Merge pull request #1848 from gilmoskowitz/i24559_xtlocks
[xtuple] / foundation-database / 440_schema.sql
1 --
2 -- PostgreSQL database dump
3 --
4
5 -- Dumped from database version 9.1.12
6 -- Dumped by pg_dump version 9.1.12
7 -- Started on 2014-03-27 11:30:47 EDT
8
9 SET statement_timeout = 0;
10 SET client_encoding = 'SQL_ASCII';
11 SET standard_conforming_strings = on;
12 SET check_function_bodies = false;
13 SET client_min_messages = warning;
14
15 --
16 -- TOC entry 6 (class 2615 OID 146565167)
17 -- Name: api; Type: SCHEMA; Schema: -; Owner: admin
18 --
19
20 CREATE SCHEMA api;
21
22
23 ALTER SCHEMA api OWNER TO admin;
24
25 --
26 -- TOC entry 7 (class 2615 OID 146565168)
27 -- Name: fixcountry; Type: SCHEMA; Schema: -; Owner: admin
28 --
29
30 CREATE SCHEMA fixcountry;
31
32
33 ALTER SCHEMA fixcountry OWNER TO admin;
34
35 --
36 -- TOC entry 8899 (class 0 OID 0)
37 -- Dependencies: 7
38 -- Name: SCHEMA fixcountry; Type: COMMENT; Schema: -; Owner: admin
39 --
40
41 COMMENT ON SCHEMA fixcountry IS 'Schema to hold contents of fixcountry';
42
43
44 --
45 -- TOC entry 9 (class 2615 OID 146565169)
46 -- Name: te; Type: SCHEMA; Schema: -; Owner: admin
47 --
48
49 CREATE SCHEMA te;
50
51
52 ALTER SCHEMA te OWNER TO admin;
53
54 --
55 -- TOC entry 8903 (class 0 OID 0)
56 -- Dependencies: 9
57 -- Name: SCHEMA te; Type: COMMENT; Schema: -; Owner: admin
58 --
59
60 COMMENT ON SCHEMA te IS 'This file is part of the xTuple ERP: PostBooks Edition, a free and open source Enterprise Resource Planning software suite, Copyright (c) 1999-2010 by OpenMFG LLC, d/b/a xTuple. It is licensed to you under the Common Public Attribution License version 1.0, the full text of which (including xTuple-specific Exhibits) is available at www.xtuple.com/CPAL.  By using this software, you agree to be bound by its terms.';
61
62
63 --
64 -- TOC entry 10 (class 2615 OID 146565170)
65 -- Name: xtdesktop; Type: SCHEMA; Schema: -; Owner: admin
66 --
67
68 CREATE SCHEMA xtdesktop;
69
70
71 ALTER SCHEMA xtdesktop OWNER TO admin;
72
73 --
74 -- TOC entry 8905 (class 0 OID 0)
75 -- Dependencies: 10
76 -- Name: SCHEMA xtdesktop; Type: COMMENT; Schema: -; Owner: admin
77 --
78
79 COMMENT ON SCHEMA xtdesktop IS 'Schema to hold contents of xtdesktop';
80
81
82 --
83 -- TOC entry 889 (class 3079 OID 11681)
84 -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: 
85 --
86
87 CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
88
89
90 --
91 -- TOC entry 8907 (class 0 OID 0)
92 -- Dependencies: 889
93 -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 
94 --
95
96 COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
97
98
99 SET search_path = public, pg_catalog;
100
101 --
102 -- TOC entry 2648 (class 1247 OID 146565173)
103 -- Dependencies: 8 165
104 -- Name: achline; Type: TYPE; Schema: public; Owner: admin
105 --
106
107 CREATE TYPE achline AS (
108         achline_checkhead_id integer,
109         achline_batch text,
110         achline_type text,
111         achline_value text
112 );
113
114
115 ALTER TYPE public.achline OWNER TO admin;
116
117 --
118 -- TOC entry 2651 (class 1247 OID 146565176)
119 -- Dependencies: 8 166
120 -- Name: apaging; Type: TYPE; Schema: public; Owner: admin
121 --
122
123 CREATE TYPE apaging AS (
124         apaging_docdate text,
125         apaging_duedate date,
126         apaging_ponumber text,
127         apaging_reference text,
128         apaging_invcnumber text,
129         apaging_docnumber text,
130         apaging_doctype text,
131         apaging_vend_id integer,
132         apaging_vend_number text,
133         apaging_vend_name text,
134         apaging_vend_vendtype_id integer,
135         apaging_vendtype_code text,
136         apaging_terms_descrip text,
137         apaging_apopen_amount numeric,
138         apaging_cur_val numeric,
139         apaging_thirty_val numeric,
140         apaging_sixty_val numeric,
141         apaging_ninety_val numeric,
142         apaging_plus_val numeric,
143         apaging_total_val numeric,
144         apaging_discdate date,
145         apaging_disc_val numeric,
146         apaging_discdays numeric,
147         apaging_discprcnt numeric
148 );
149
150
151 ALTER TYPE public.apaging OWNER TO admin;
152
153 --
154 -- TOC entry 2654 (class 1247 OID 146565179)
155 -- Dependencies: 8 167
156 -- Name: araging; Type: TYPE; Schema: public; Owner: admin
157 --
158
159 CREATE TYPE araging AS (
160         araging_docdate date,
161         araging_duedate date,
162         araging_ponumber text,
163         araging_docnumber text,
164         araging_doctype text,
165         araging_cust_id integer,
166         araging_cust_number text,
167         araging_cust_name text,
168         araging_cust_custtype_id integer,
169         araging_custtype_code text,
170         araging_terms_descrip text,
171         araging_aropen_amount numeric,
172         araging_cur_val numeric,
173         araging_thirty_val numeric,
174         araging_sixty_val numeric,
175         araging_ninety_val numeric,
176         araging_plus_val numeric,
177         araging_total_val numeric
178 );
179
180
181 ALTER TYPE public.araging OWNER TO admin;
182
183 --
184 -- TOC entry 2657 (class 1247 OID 146565182)
185 -- Dependencies: 8 168
186 -- Name: bomdata; Type: TYPE; Schema: public; Owner: admin
187 --
188
189 CREATE TYPE bomdata AS (
190         bomdata_bomwork_id integer,
191         bomdata_bomwork_parent_id integer,
192         bomdata_bomwork_level integer,
193         bomdata_bomwork_seqnumber integer,
194         bomdata_bomitem_id integer,
195         bomdata_item_id integer,
196         bomdata_item_number text,
197         bomdata_uom_name text,
198         bomdata_item_descrip1 text,
199         bomdata_item_descrip2 text,
200         bomdata_itemdescription text,
201         bomdata_batchsize numeric,
202         bomdata_qtyfxd numeric,
203         bomdata_qtyper numeric,
204         bomdata_qtyreq numeric,
205         bomdata_scrap numeric,
206         bomdata_createchild boolean,
207         bomdata_issuemethod text,
208         bomdata_effective date,
209         bomdata_expires date,
210         bomdata_expired boolean,
211         bomdata_future boolean,
212         bomdata_actunitcost numeric,
213         bomdata_stdunitcost numeric,
214         bomdata_actextendedcost numeric,
215         bomdata_stdextendedcost numeric,
216         bomdata_ecn text,
217         bomdata_char_id integer,
218         bomdata_value text,
219         bomdata_notes text,
220         bomdata_ref text
221 );
222
223
224 ALTER TYPE public.bomdata OWNER TO admin;
225
226 --
227 -- TOC entry 2660 (class 1247 OID 146565185)
228 -- Dependencies: 8 169
229 -- Name: checkdata; Type: TYPE; Schema: public; Owner: admin
230 --
231
232 CREATE TYPE checkdata AS (
233         checkdata_page integer,
234         checkdata_checknumber text,
235         checkdata_checkwords text,
236         checkdata_checkdate text,
237         checkdata_checkamount text,
238         checkdata_checkcurrsymbol text,
239         checkdata_checkcurrabbr text,
240         checkdata_checkcurrname text,
241         checkdata_checkpayto text,
242         checkdata_checkaddress text,
243         checkdata_checkmemo text,
244         checkdata_docnumber text,
245         checkdata_docreference text,
246         checkdata_docdate text,
247         checkdata_docamount text,
248         checkdata_docdiscount text,
249         checkdata_docnetamount text
250 );
251
252
253 ALTER TYPE public.checkdata OWNER TO admin;
254
255 --
256 -- TOC entry 2663 (class 1247 OID 146565188)
257 -- Dependencies: 8 170
258 -- Name: cntctdup; Type: TYPE; Schema: public; Owner: admin
259 --
260
261 CREATE TYPE cntctdup AS (
262         cntct_id integer,
263         cntct_crmacct_id integer,
264         cntct_addr_id integer,
265         cntct_first_name text,
266         cntct_last_name text,
267         cntct_honorific text,
268         cntct_initials text,
269         cntct_active boolean,
270         cntct_phone text,
271         cntct_phone2 text,
272         cntct_fax text,
273         cntct_email text,
274         cntct_webaddr text,
275         cntct_notes text,
276         cntct_title text,
277         cntct_number text,
278         cntct_middle text,
279         cntct_suffix text,
280         cntct_owner_username text,
281         cntct_name text,
282         crmacct_number text,
283         crmacct_name text,
284         addr_id integer,
285         addr_active boolean,
286         addr_line1 text,
287         addr_line2 text,
288         addr_line3 text,
289         addr_city text,
290         addr_state text,
291         addr_postalcode text,
292         addr_country text,
293         addr_notes text,
294         addr_number text,
295         cntctdup_level integer
296 );
297
298
299 ALTER TYPE public.cntctdup OWNER TO admin;
300
301 --
302 -- TOC entry 2666 (class 1247 OID 146565191)
303 -- Dependencies: 8 171
304 -- Name: flcoldata; Type: TYPE; Schema: public; Owner: admin
305 --
306
307 CREATE TYPE flcoldata AS (
308         flcoldata_column integer,
309         flcoldata_start date,
310         flcoldata_end date
311 );
312
313
314 ALTER TYPE public.flcoldata OWNER TO admin;
315
316 --
317 -- TOC entry 2669 (class 1247 OID 146565194)
318 -- Dependencies: 8 172
319 -- Name: flstmthead; Type: TYPE; Schema: public; Owner: admin
320 --
321
322 CREATE TYPE flstmthead AS (
323         flstmthead_flhead_id integer,
324         flstmthead_flcol_id integer,
325         flstmthead_period_id integer,
326         flstmthead_username text,
327         flstmthead_typedescrip1 text,
328         flstmthead_typedescrip2 text,
329         flstmthead_flhead_name text,
330         flstmthead_flcol_name text,
331         flstmthead_month text,
332         flstmthead_qtr text,
333         flstmthead_year text,
334         flstmthead_prmonth text,
335         flstmthead_prqtr text,
336         flstmthead_pryear text
337 );
338
339
340 ALTER TYPE public.flstmthead OWNER TO admin;
341
342 --
343 -- TOC entry 2672 (class 1247 OID 146565197)
344 -- Dependencies: 8 173
345 -- Name: flstmtitem; Type: TYPE; Schema: public; Owner: admin
346 --
347
348 CREATE TYPE flstmtitem AS (
349         flstmtitem_flhead_id integer,
350         flstmtitem_period_id integer,
351         flstmtitem_username text,
352         flstmtitem_order integer,
353         flstmtitem_level integer,
354         flstmtitem_subgrp integer,
355         flstmtitem_type text,
356         flstmtitem_type_id integer,
357         flstmtitem_parent_id integer,
358         flstmtitem_accnt_id integer,
359         flstmtitem_name text,
360         flstmtitem_month numeric,
361         flstmtitem_monthdb numeric,
362         flstmtitem_monthcr numeric,
363         flstmtitem_monthprcnt numeric,
364         flstmtitem_monthbudget numeric,
365         flstmtitem_monthbudgetprcnt numeric,
366         flstmtitem_monthbudgetdiff numeric,
367         flstmtitem_monthbudgetdiffprcnt numeric,
368         flstmtitem_qtr numeric,
369         flstmtitem_qtrdb numeric,
370         flstmtitem_qtrcr numeric,
371         flstmtitem_qtrprcnt numeric,
372         flstmtitem_qtrbudget numeric,
373         flstmtitem_qtrbudgetprcnt numeric,
374         flstmtitem_qtrbudgetdiff numeric,
375         flstmtitem_qtrbudgetdiffprcnt numeric,
376         flstmtitem_year numeric,
377         flstmtitem_yeardb numeric,
378         flstmtitem_yearcr numeric,
379         flstmtitem_yearprcnt numeric,
380         flstmtitem_yearbudget numeric,
381         flstmtitem_yearbudgetprcnt numeric,
382         flstmtitem_yearbudgetdiff numeric,
383         flstmtitem_yearbudgetdiffprcnt numeric,
384         flstmtitem_prmonth numeric,
385         flstmtitem_prmonthprcnt numeric,
386         flstmtitem_prmonthdiff numeric,
387         flstmtitem_prmonthdiffprcnt numeric,
388         flstmtitem_prqtr numeric,
389         flstmtitem_prqtrprcnt numeric,
390         flstmtitem_prqtrdiff numeric,
391         flstmtitem_prqtrdiffprcnt numeric,
392         flstmtitem_pryear numeric,
393         flstmtitem_pryearprcnt numeric,
394         flstmtitem_pryeardiff numeric,
395         flstmtitem_pryeardiffprcnt numeric
396 );
397
398
399 ALTER TYPE public.flstmtitem OWNER TO admin;
400
401 --
402 -- TOC entry 2675 (class 1247 OID 146565200)
403 -- Dependencies: 8 174
404 -- Name: fltrendhead; Type: TYPE; Schema: public; Owner: admin
405 --
406
407 CREATE TYPE fltrendhead AS (
408         fltrendhead_flhead_id integer,
409         fltrendhead_username text,
410         fltrendhead_typedescrip text,
411         fltrendhead_flhead_name text,
412         fltrendhead_fld1 text,
413         fltrendhead_fld2 text,
414         fltrendhead_fld3 text,
415         fltrendhead_fld4 text,
416         fltrendhead_fld5 text,
417         fltrendhead_fld6 text,
418         fltrendhead_fld7 text,
419         fltrendhead_fld8 text,
420         fltrendhead_fld9 text,
421         fltrendhead_fld10 text,
422         fltrendhead_fld11 text,
423         fltrendhead_fld12 text,
424         fltrendhead_grndttl text
425 );
426
427
428 ALTER TYPE public.fltrendhead OWNER TO admin;
429
430 --
431 -- TOC entry 2678 (class 1247 OID 146565203)
432 -- Dependencies: 8 175
433 -- Name: fltrenditem; Type: TYPE; Schema: public; Owner: admin
434 --
435
436 CREATE TYPE fltrenditem AS (
437         fltrenditem_flhead_id integer,
438         fltrenditem_username text,
439         fltrenditem_order integer,
440         fltrenditem_level integer,
441         fltrenditem_subgrp integer,
442         fltrenditem_type text,
443         fltrenditem_type_id integer,
444         fltrenditem_parent_id integer,
445         fltrenditem_accnt_id integer,
446         fltrenditem_name text,
447         fltrenditem_fld1 text,
448         fltrenditem_fld2 text,
449         fltrenditem_fld3 text,
450         fltrenditem_fld4 text,
451         fltrenditem_fld5 text,
452         fltrenditem_fld6 text,
453         fltrenditem_fld7 text,
454         fltrenditem_fld8 text,
455         fltrenditem_fld9 text,
456         fltrenditem_fld10 text,
457         fltrenditem_fld11 text,
458         fltrenditem_fld12 text,
459         fltrenditem_grndttl text
460 );
461
462
463 ALTER TYPE public.fltrenditem OWNER TO admin;
464
465 --
466 -- TOC entry 2681 (class 1247 OID 146565206)
467 -- Dependencies: 8 176
468 -- Name: freightdata; Type: TYPE; Schema: public; Owner: admin
469 --
470
471 CREATE TYPE freightdata AS (
472         freightdata_schedule text,
473         freightdata_from text,
474         freightdata_to text,
475         freightdata_shipvia text,
476         freightdata_freightclass text,
477         freightdata_weight numeric,
478         freightdata_uom text,
479         freightdata_price numeric,
480         freightdata_type text,
481         freightdata_total numeric,
482         freightdata_currency text
483 );
484
485
486 ALTER TYPE public.freightdata OWNER TO admin;
487
488 --
489 -- TOC entry 2684 (class 1247 OID 146565209)
490 -- Dependencies: 8 177
491 -- Name: itemprice; Type: TYPE; Schema: public; Owner: admin
492 --
493
494 CREATE TYPE itemprice AS (
495         itemprice_price numeric,
496         itemprice_type character(1)
497 );
498
499
500 ALTER TYPE public.itemprice OWNER TO admin;
501
502 --
503 -- TOC entry 2687 (class 1247 OID 146565212)
504 -- Dependencies: 8 178
505 -- Name: orderitemtype; Type: TYPE; Schema: public; Owner: admin
506 --
507
508 CREATE TYPE orderitemtype AS (
509         orderitem_id integer,
510         orderitem_orderhead_type text,
511         orderitem_orderhead_id integer,
512         orderitem_linenumber integer,
513         orderitem_status text,
514         orderitem_itemsite_id integer,
515         orderitem_scheddate date,
516         orderitem_qty_ordered numeric,
517         orderitem_qty_shipped numeric,
518         orderitem_qty_received numeric,
519         orderitem_qty_uom_id integer,
520         orderitem_qty_invuomratio numeric,
521         orderitem_unitcost numeric,
522         orderitem_unitcost_curr_id integer,
523         orderitem_freight numeric,
524         orderitem_freight_received numeric,
525         orderitem_freight_curr_id integer
526 );
527
528
529 ALTER TYPE public.orderitemtype OWNER TO admin;
530
531 --
532 -- TOC entry 2690 (class 1247 OID 146565215)
533 -- Dependencies: 8 179
534 -- Name: ordhead; Type: TYPE; Schema: public; Owner: admin
535 --
536
537 CREATE TYPE ordhead AS (
538         orderhead_id integer,
539         orderhead_type text,
540         orderhead_number text,
541         orderhead_status text,
542         orderhead_orderdate date,
543         orderhead_linecount integer,
544         orderhead_from_id integer,
545         orderhead_from text,
546         orderhead_to_id integer,
547         orderhead_to text,
548         orderhead_curr_id integer,
549         orderhead_agent_username text,
550         orderhead_shipvia text
551 );
552
553
554 ALTER TYPE public.ordhead OWNER TO admin;
555
556 --
557 -- TOC entry 2693 (class 1247 OID 146565218)
558 -- Dependencies: 8 180
559 -- Name: orditem; Type: TYPE; Schema: public; Owner: admin
560 --
561
562 CREATE TYPE orditem AS (
563         orderitem_id integer,
564         orderitem_orderhead_type text,
565         orderitem_orderhead_id integer,
566         orderitem_linenumber integer,
567         orderitem_status text,
568         orderitem_itemsite_id integer,
569         orderitem_scheddate date,
570         orderitem_qty_ordered numeric,
571         orderitem_qty_shipped numeric,
572         orderitem_qty_received numeric,
573         orderitem_qty_uom_id integer,
574         orderitem_qty_invuomratio numeric,
575         orderitem_unitcost numeric,
576         orderitem_unitcost_curr_id integer,
577         orderitem_freight numeric,
578         orderitem_freight_received numeric,
579         orderitem_freight_curr_id integer
580 );
581
582
583 ALTER TYPE public.orditem OWNER TO admin;
584
585 --
586 -- TOC entry 2696 (class 1247 OID 146565221)
587 -- Dependencies: 8 181
588 -- Name: reordlvl; Type: TYPE; Schema: public; Owner: admin
589 --
590
591 CREATE TYPE reordlvl AS (
592         reordlvl_itemsite_id integer,
593         reordlvl_item_id integer,
594         reordlvl_warehous_code text,
595         reordlvl_item_number text,
596         reordlvl_item_descrip text,
597         reordlvl_leadtime integer,
598         reordlvl_daysofstock integer,
599         reordlvl_curr_level numeric,
600         reordlvl_total_days numeric,
601         reordlvl_total_usage numeric,
602         reordlvl_calc_level integer
603 );
604
605
606 ALTER TYPE public.reordlvl OWNER TO admin;
607
608 --
609 -- TOC entry 2699 (class 1247 OID 146565224)
610 -- Dependencies: 8 182
611 -- Name: seqiss; Type: TYPE; Schema: public; Owner: admin
612 --
613
614 CREATE TYPE seqiss AS (
615         seqiss_number integer,
616         seqiss_time timestamp with time zone
617 );
618
619
620 ALTER TYPE public.seqiss OWNER TO admin;
621
622 --
623 -- TOC entry 2702 (class 1247 OID 146565227)
624 -- Dependencies: 8 183
625 -- Name: subtax; Type: TYPE; Schema: public; Owner: admin
626 --
627
628 CREATE TYPE subtax AS (
629         subtax_taxcode_id integer,
630         subtax_taxcode_code text,
631         subtax_taxcode_descrip text,
632         subtax_taxcode_level integer
633 );
634
635
636 ALTER TYPE public.subtax OWNER TO admin;
637
638 --
639 -- TOC entry 2705 (class 1247 OID 146565230)
640 -- Dependencies: 8 184
641 -- Name: taxassign; Type: TYPE; Schema: public; Owner: admin
642 --
643
644 CREATE TYPE taxassign AS (
645         taxassign_taxzone_id integer,
646         taxassign_taxtype_id integer,
647         taxassign_level integer,
648         taxassign_zone_code text,
649         taxassign_type_descrip text,
650         taxassign_taxclass_code text,
651         taxassign_taxclass_sequence integer
652 );
653
654
655 ALTER TYPE public.taxassign OWNER TO admin;
656
657 --
658 -- TOC entry 2708 (class 1247 OID 146565233)
659 -- Dependencies: 8 185
660 -- Name: taxdetail; Type: TYPE; Schema: public; Owner: admin
661 --
662
663 CREATE TYPE taxdetail AS (
664         taxdetail_tax_id integer,
665         taxdetail_tax_code text,
666         taxdetail_tax_descrip text,
667         taxdetail_tax_basis_tax_id integer,
668         taxdetail_taxrate_percent numeric(10,6),
669         taxdetail_taxrate_amount numeric(16,2),
670         taxdetail_level integer,
671         taxdetail_taxclass_id integer,
672         taxdetail_taxclass_code text,
673         taxdetail_taxclass_sequence integer,
674         taxdetail_tax numeric(16,6),
675         taxdetail_curr_id integer,
676         taxdetail_curr_abbr text
677 );
678
679
680 ALTER TYPE public.taxdetail OWNER TO admin;
681
682 --
683 -- TOC entry 2711 (class 1247 OID 146565236)
684 -- Dependencies: 8 186
685 -- Name: wodata; Type: TYPE; Schema: public; Owner: admin
686 --
687
688 CREATE TYPE wodata AS (
689         wodata_id integer,
690         wodata_id_type integer,
691         wodata_number integer,
692         wodata_subnumber integer,
693         wodata_itemnumber text,
694         wodata_descrip text,
695         wodata_status character(1),
696         wodata_startdate date,
697         wodata_duedate date,
698         wodata_adhoc boolean,
699         wodata_itemsite_id integer,
700         wodata_listprice numeric,
701         wodata_custprice numeric,
702         wodata_qoh numeric,
703         wodata_short numeric,
704         wodata_qtyper numeric,
705         wodata_qtyiss numeric,
706         wodata_qtyrcv numeric,
707         wodata_qtyordreq numeric,
708         wodata_qtyuom text,
709         wodata_scrap numeric,
710         wodata_setup numeric,
711         wodata_run numeric,
712         wodata_notes text,
713         wodata_ref text,
714         wodata_level integer
715 );
716
717
718 ALTER TYPE public.wodata OWNER TO admin;
719
720 --
721 -- TOC entry 2714 (class 1247 OID 146565239)
722 -- Dependencies: 8 187
723 -- Name: woinvav; Type: TYPE; Schema: public; Owner: admin
724 --
725
726 CREATE TYPE woinvav AS (
727         woinvav_itemsite_id integer,
728         woinvav_womatl_id integer,
729         woinvav_type character(1),
730         woinvav_item_wo_number text,
731         woinvav_descrip text,
732         woinvav_uomname text,
733         woinvav_qoh numeric,
734         woinvav_balance numeric,
735         woinvav_allocated numeric,
736         woinvav_ordered numeric,
737         woinvav_woavail numeric,
738         woinvav_totalavail numeric,
739         woinvav_reorderlevel numeric,
740         woinvav_level integer
741 );
742
743
744 ALTER TYPE public.woinvav OWNER TO admin;
745
746 SET search_path = xtdesktop, pg_catalog;
747
748 --
749 -- TOC entry 2717 (class 1247 OID 146565242)
750 -- Dependencies: 10 188
751 -- Name: usersonline; Type: TYPE; Schema: xtdesktop; Owner: admin
752 --
753
754 CREATE TYPE usersonline AS (
755         usr_id integer,
756         usr_username text,
757         usr_propername text,
758         usr_email text,
759         client_start timestamp with time zone,
760         query_start timestamp with time zone,
761         cnt_internal bigint,
762         cnt_external bigint,
763         client_addr inet
764 );
765
766
767 ALTER TYPE xtdesktop.usersonline OWNER TO admin;
768
769 SET search_path = api, pg_catalog;
770
771 --
772 -- TOC entry 901 (class 1255 OID 146565243)
773 -- Dependencies: 4536 6
774 -- Name: getcustnumberfrominfo(text, text, text, text, text, boolean); Type: FUNCTION; Schema: api; Owner: admin
775 --
776
777 CREATE FUNCTION getcustnumberfrominfo(text, text, text, text, text, boolean) RETURNS text
778     LANGUAGE plpgsql
779     AS $_$
780 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
781 -- See www.xtuple.com/CPAL for the full text of the software license.
782 DECLARE
783   _email        TEXT    := COALESCE(UPPER($1), '');
784   _company      TEXT    := COALESCE(UPPER($2), '');
785   _first        TEXT    := COALESCE(UPPER($3), '');
786   _last         TEXT    := COALESCE(UPPER($4), '');
787   _fullname     TEXT    := COALESCE(UPPER($5), TRIM(_first || ' ' || _last));
788   _generate     BOOLEAN := COALESCE($6, FALSE);
789   _counter      INTEGER;
790   _custcount    INTEGER := 0;
791   _custnumber   TEXT;
792   _candidate    TEXT    := '';
793   _loopmax      INTEGER := 0;
794   _minlength    INTEGER := 5;
795   _maxlength    INTEGER := 8;
796   _numformat    TEXT    := '';
797   _testme       TEXT;
798 BEGIN
799   IF (_email != '') THEN
800     SELECT count(*), cust_number INTO _custcount, _custnumber
801     FROM custinfo LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
802     WHERE (UPPER(cntct_email)=_email)
803     GROUP BY cust_number;
804     IF (NOT FOUND) THEN
805       _custcount := 0;
806     ELSIF(_custcount = 1) THEN
807       RETURN _custnumber;
808     END IF;
809   END IF;
810
811   IF (_company != '') THEN
812     SELECT count(*), cust_number INTO _custcount, _custnumber
813     FROM custinfo
814     WHERE (UPPER(cust_name)=_company)
815     GROUP BY cust_number;
816     IF (NOT FOUND) THEN
817       _custcount := 0;
818     ELSIF(_custcount = 1) THEN
819       RETURN _custnumber;
820     END IF;
821   END IF;
822
823   IF (_fullname = '' AND (_first != '' OR _last != '')) THEN
824     _fullname := TRIM(_first || ' ' || _last);
825   END IF;
826
827   IF (_custcount <= 0 AND _fullname != '') THEN
828     SELECT count(*), cust_number INTO _custcount, _custnumber
829     FROM custinfo
830     WHERE (UPPER(cust_name)=_fullname)
831     GROUP BY cust_number;
832     IF (NOT FOUND) THEN
833       _custcount := 0;
834     ELSIF(_custcount = 1) THEN
835       RETURN _custnumber;
836     END IF;
837   END IF;
838
839   IF (_custcount > 1) THEN
840     RAISE EXCEPTION 'Found % possible Customers for % and % and %',
841                     _custcount, _email, _company, _fullname;
842   END IF;
843
844   IF (_custcount <= 0 AND _generate) THEN
845     IF (_maxlength < _minlength) THEN
846       RAISE EXCEPTION 'Fix getCustNumberFromInfo: max length < min length';
847     END IF;
848
849     IF (_company != '') THEN
850       _candidate := _company;
851     ELSIF (_email != '') THEN
852       _candidate := SUBSTRING(_email FOR POSITION('@' IN _email) - 1);
853     ELSIF (_last != '') THEN
854       _candidate := _last;
855       IF (_first != '') THEN
856         _candidate := _candidate || _first;
857       END IF;
858     ELSIF (_fullname != '' AND (POSITION(' ' IN _fullname) > 0)) THEN
859       _candidate := SUBSTRING(_fullname FROM POSITION(' ' IN _fullname) + 1) ||
860                     SUBSTRING(_fullname FOR  POSITION(' ' IN _fullname) - 1);
861     END IF;
862     WHILE (POSITION(' ' IN _candidate) > 0) LOOP
863       _candidate := SUBSTRING(_candidate FOR  POSITION(' ' IN _candidate) - 1) ||
864                     SUBSTRING(_candidate FROM POSITION(' ' IN _candidate) + 1);
865     END LOOP;
866     FOR _counter IN _minlength.._maxlength LOOP
867       _testme := SUBSTRING(_candidate FOR _counter);
868       IF (NOT EXISTS(SELECT cust_number
869                      FROM custinfo
870                      WHERE (cust_number=_testme))) THEN
871         _custnumber := _testme;
872         EXIT;
873       END IF;
874     END LOOP;
875     IF (_custnumber IS NULL OR _custnumber = '') THEN
876       IF (LENGTH(_candidate) < _minlength) THEN
877         _minlength := LENGTH(_candidate);
878       END IF;
879       FOR _counter IN _minlength.._maxlength LOOP
880         _loopmax := _loopmax * 10 + 9;
881         _numformat := _numformat || '0';
882       END LOOP;
883       FOR _counter IN 1.._loopmax LOOP
884         _testme := SUBSTRING(_candidate FOR _minlength) ||
885                    TRIM(TO_CHAR(_counter, _numformat));
886         IF (NOT EXISTS(SELECT cust_number
887                        FROM custinfo
888                        WHERE (cust_number=_testme))) THEN
889           _custnumber := _testme;
890           EXIT;
891         END IF;
892       END LOOP;
893     END IF;
894     IF (_custnumber IS NULL OR _custnumber = '') THEN
895       RAISE EXCEPTION 'Could not generate a new Customer Number';
896     END IF;
897   END IF;
898
899   IF (_custnumber IS NULL OR _custnumber = '') THEN
900     RAISE EXCEPTION 'Could not find Customer Number for % and % and %',
901                     _email, _company, _fullname;
902   END IF;
903
904   RETURN _custnumber;
905 END;
906 $_$;
907
908
909 ALTER FUNCTION api.getcustnumberfrominfo(text, text, text, text, text, boolean) OWNER TO admin;
910
911 SET search_path = public, pg_catalog;
912
913 --
914 -- TOC entry 902 (class 1255 OID 146565244)
915 -- Dependencies: 4536 8
916 -- Name: formatlocationname(integer); Type: FUNCTION; Schema: public; Owner: admin
917 --
918
919 CREATE FUNCTION formatlocationname(integer) RETURNS text
920     LANGUAGE plpgsql IMMUTABLE
921     AS $_$
922 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
923 -- See www.xtuple.com/CPAL for the full text of the software license.
924 DECLARE
925   pLocationid ALIAS FOR $1;
926   _name TEXT;
927   _r RECORD;
928
929 BEGIN
930
931   SELECT location_aisle, location_rack,
932          location_bin, location_name INTO _r
933   FROM location
934   WHERE (location_id=pLocationid);
935   IF (FOUND) THEN
936     IF (_r.location_aisle IS NOT NULL) THEN
937       _name := _r.location_aisle;
938     ELSE
939       _name := '';
940     END IF;
941
942     IF (_r.location_rack IS NOT NULL) THEN
943       _name := (_name || _r.location_rack);
944     END IF;
945
946     IF (_r.location_bin IS NOT NULL) THEN
947       _name := (_name || _r.location_bin);
948     END IF;
949
950     IF (_r.location_name IS NOT NULL) THEN
951       _name := (_name || _r.location_name);
952     END IF;
953
954     RETURN _name;
955   ELSE
956     RETURN 'N/A';
957   END IF;
958
959 END;
960 $_$;
961
962
963 ALTER FUNCTION public.formatlocationname(integer) OWNER TO admin;
964
965 SET default_tablespace = '';
966
967 SET default_with_oids = false;
968
969 --
970 -- TOC entry 189 (class 1259 OID 146565245)
971 -- Dependencies: 5838 8
972 -- Name: cntslip; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
973 --
974
975 CREATE TABLE cntslip (
976     cntslip_id integer DEFAULT nextval(('"cntslip_cntslip_id_seq"'::text)::regclass) NOT NULL,
977     cntslip_cnttag_id integer,
978     cntslip_entered timestamp with time zone,
979     cntslip_posted boolean,
980     cntslip_number text,
981     cntslip_qty numeric(18,6),
982     cntslip_comments text,
983     cntslip_location_id integer,
984     cntslip_lotserial text,
985     cntslip_lotserial_expiration date,
986     cntslip_lotserial_warrpurc date,
987     cntslip_username text
988 );
989
990
991 ALTER TABLE public.cntslip OWNER TO admin;
992
993 --
994 -- TOC entry 8908 (class 0 OID 0)
995 -- Dependencies: 189
996 -- Name: TABLE cntslip; Type: COMMENT; Schema: public; Owner: admin
997 --
998
999 COMMENT ON TABLE cntslip IS 'Count Slip information';
1000
1001
1002 --
1003 -- TOC entry 190 (class 1259 OID 146565252)
1004 -- Dependencies: 5839 8
1005 -- Name: invcnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1006 --
1007
1008 CREATE TABLE invcnt (
1009     invcnt_id integer DEFAULT nextval(('invcnt_invcnt_id_seq'::text)::regclass) NOT NULL,
1010     invcnt_itemsite_id integer,
1011     invcnt_tagdate timestamp with time zone,
1012     invcnt_cntdate timestamp with time zone,
1013     invcnt_qoh_before numeric(18,6),
1014     invcnt_qoh_after numeric(18,6),
1015     invcnt_matcost numeric(16,6),
1016     invcnt_posted boolean,
1017     invcnt_postdate timestamp with time zone,
1018     invcnt_comments text,
1019     invcnt_priority boolean,
1020     invcnt_tagnumber text,
1021     invcnt_invhist_id integer,
1022     invcnt_location_id integer,
1023     invcnt_cnt_username text,
1024     invcnt_post_username text,
1025     invcnt_tag_username text
1026 );
1027
1028
1029 ALTER TABLE public.invcnt OWNER TO admin;
1030
1031 --
1032 -- TOC entry 8910 (class 0 OID 0)
1033 -- Dependencies: 190
1034 -- Name: TABLE invcnt; Type: COMMENT; Schema: public; Owner: admin
1035 --
1036
1037 COMMENT ON TABLE invcnt IS 'Count Tag information';
1038
1039
1040 --
1041 -- TOC entry 191 (class 1259 OID 146565259)
1042 -- Dependencies: 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 8
1043 -- Name: item; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1044 --
1045
1046 CREATE TABLE item (
1047     item_id integer DEFAULT nextval(('item_item_id_seq'::text)::regclass) NOT NULL,
1048     item_number text NOT NULL,
1049     item_descrip1 text NOT NULL,
1050     item_descrip2 text NOT NULL,
1051     item_classcode_id integer NOT NULL,
1052     item_picklist boolean DEFAULT true NOT NULL,
1053     item_comments text,
1054     item_sold boolean NOT NULL,
1055     item_fractional boolean NOT NULL,
1056     item_active boolean NOT NULL,
1057     item_type character(1) DEFAULT 'R'::bpchar NOT NULL,
1058     item_prodweight numeric(16,2) DEFAULT 0 NOT NULL,
1059     item_packweight numeric(16,2) DEFAULT 0 NOT NULL,
1060     item_prodcat_id integer NOT NULL,
1061     item_exclusive boolean DEFAULT false NOT NULL,
1062     item_listprice numeric(16,4) NOT NULL,
1063     item_config boolean DEFAULT false,
1064     item_extdescrip text,
1065     item_upccode text,
1066     item_maxcost numeric(16,6) DEFAULT 0 NOT NULL,
1067     item_inv_uom_id integer NOT NULL,
1068     item_price_uom_id integer NOT NULL,
1069     item_warrdays integer DEFAULT 0,
1070     item_freightclass_id integer,
1071     item_tax_recoverable boolean DEFAULT false NOT NULL,
1072     item_listcost numeric(16,6) DEFAULT 0.0 NOT NULL,
1073     CONSTRAINT item_item_number_check CHECK ((item_number <> ''::text)),
1074     CONSTRAINT item_item_type_check CHECK (((((((((((((item_type = 'P'::bpchar) OR (item_type = 'M'::bpchar)) OR (item_type = 'F'::bpchar)) OR (item_type = 'O'::bpchar)) OR (item_type = 'R'::bpchar)) OR (item_type = 'S'::bpchar)) OR (item_type = 'T'::bpchar)) OR (item_type = 'B'::bpchar)) OR (item_type = 'L'::bpchar)) OR (item_type = 'Y'::bpchar)) OR (item_type = 'C'::bpchar)) OR (item_type = 'K'::bpchar))),
1075     CONSTRAINT item_sold_check CHECK ((NOT (item_sold AND (item_prodcat_id = (-1)))))
1076 );
1077
1078
1079 ALTER TABLE public.item OWNER TO admin;
1080
1081 --
1082 -- TOC entry 8912 (class 0 OID 0)
1083 -- Dependencies: 191
1084 -- Name: TABLE item; Type: COMMENT; Schema: public; Owner: admin
1085 --
1086
1087 COMMENT ON TABLE item IS 'Item information';
1088
1089
1090 --
1091 -- TOC entry 8913 (class 0 OID 0)
1092 -- Dependencies: 191
1093 -- Name: COLUMN item.item_maxcost; Type: COMMENT; Schema: public; Owner: admin
1094 --
1095
1096 COMMENT ON COLUMN item.item_maxcost IS 'Maximum cost for item.  Used to constrain purchase order price.';
1097
1098
1099 --
1100 -- TOC entry 8914 (class 0 OID 0)
1101 -- Dependencies: 191
1102 -- Name: COLUMN item.item_listcost; Type: COMMENT; Schema: public; Owner: admin
1103 --
1104
1105 COMMENT ON COLUMN item.item_listcost IS 'List cost for item.  Basis for markup pricing.';
1106
1107
1108 --
1109 -- TOC entry 192 (class 1259 OID 146565279)
1110 -- Dependencies: 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 8
1111 -- Name: itemsite; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1112 --
1113
1114 CREATE TABLE itemsite (
1115     itemsite_id integer DEFAULT nextval(('itemsite_itemsite_id_seq'::text)::regclass) NOT NULL,
1116     itemsite_item_id integer NOT NULL,
1117     itemsite_warehous_id integer,
1118     itemsite_qtyonhand numeric(18,6) NOT NULL,
1119     itemsite_reorderlevel numeric(18,6) NOT NULL,
1120     itemsite_ordertoqty numeric(18,6) NOT NULL,
1121     itemsite_cyclecountfreq integer NOT NULL,
1122     itemsite_datelastcount date,
1123     itemsite_datelastused date,
1124     itemsite_loccntrl boolean NOT NULL,
1125     itemsite_safetystock numeric(18,6) NOT NULL,
1126     itemsite_minordqty numeric(18,6) NOT NULL,
1127     itemsite_multordqty numeric(18,6) NOT NULL,
1128     itemsite_leadtime integer NOT NULL,
1129     itemsite_abcclass character(1),
1130     itemsite_issuemethod character(1),
1131     itemsite_controlmethod character(1),
1132     itemsite_active boolean NOT NULL,
1133     itemsite_plancode_id integer NOT NULL,
1134     itemsite_costcat_id integer NOT NULL,
1135     itemsite_eventfence integer NOT NULL,
1136     itemsite_sold boolean NOT NULL,
1137     itemsite_stocked boolean NOT NULL,
1138     itemsite_freeze boolean DEFAULT false NOT NULL,
1139     itemsite_location_id integer NOT NULL,
1140     itemsite_useparams boolean NOT NULL,
1141     itemsite_useparamsmanual boolean NOT NULL,
1142     itemsite_soldranking integer DEFAULT 1,
1143     itemsite_createpr boolean,
1144     itemsite_location text,
1145     itemsite_location_comments text,
1146     itemsite_notes text,
1147     itemsite_perishable boolean NOT NULL,
1148     itemsite_nnqoh numeric(18,6) DEFAULT 0 NOT NULL,
1149     itemsite_autoabcclass boolean NOT NULL,
1150     itemsite_ordergroup integer DEFAULT 1 NOT NULL,
1151     itemsite_disallowblankwip boolean DEFAULT false NOT NULL,
1152     itemsite_maxordqty numeric(18,6) DEFAULT 0.0 NOT NULL,
1153     itemsite_mps_timefence integer DEFAULT 0 NOT NULL,
1154     itemsite_createwo boolean DEFAULT false NOT NULL,
1155     itemsite_warrpurc boolean DEFAULT false NOT NULL,
1156     itemsite_autoreg boolean DEFAULT false,
1157     itemsite_costmethod character(1) NOT NULL,
1158     itemsite_value numeric(12,2) NOT NULL,
1159     itemsite_ordergroup_first boolean DEFAULT false NOT NULL,
1160     itemsite_supply_itemsite_id integer,
1161     itemsite_planning_type character(1) DEFAULT 'M'::bpchar NOT NULL,
1162     itemsite_wosupply boolean DEFAULT false NOT NULL,
1163     itemsite_posupply boolean DEFAULT false NOT NULL,
1164     itemsite_lsseq_id integer,
1165     itemsite_cosdefault character(1),
1166     itemsite_createsopr boolean DEFAULT false,
1167     itemsite_createsopo boolean DEFAULT false,
1168     itemsite_dropship boolean DEFAULT false,
1169     itemsite_recvlocation_id integer DEFAULT (-1) NOT NULL,
1170     itemsite_issuelocation_id integer DEFAULT (-1) NOT NULL,
1171     itemsite_location_dist boolean DEFAULT false NOT NULL,
1172     itemsite_recvlocation_dist boolean DEFAULT false NOT NULL,
1173     itemsite_issuelocation_dist boolean DEFAULT false NOT NULL,
1174     CONSTRAINT itemsite_itemsite_abcclass_check CHECK (((((itemsite_abcclass = 'A'::bpchar) OR (itemsite_abcclass = 'B'::bpchar)) OR (itemsite_abcclass = 'C'::bpchar)) OR (itemsite_abcclass = 'T'::bpchar))),
1175     CONSTRAINT itemsite_itemsite_controlmethod_check CHECK (((((itemsite_controlmethod = 'N'::bpchar) OR (itemsite_controlmethod = 'R'::bpchar)) OR (itemsite_controlmethod = 'S'::bpchar)) OR (itemsite_controlmethod = 'L'::bpchar))),
1176     CONSTRAINT itemsite_itemsite_costmethod_check CHECK (((((itemsite_costmethod = 'N'::bpchar) OR (itemsite_costmethod = 'A'::bpchar)) OR (itemsite_costmethod = 'S'::bpchar)) OR (itemsite_costmethod = 'J'::bpchar))),
1177     CONSTRAINT itemsite_itemsite_ordergroup_check CHECK ((itemsite_ordergroup > 0))
1178 );
1179
1180
1181 ALTER TABLE public.itemsite OWNER TO admin;
1182
1183 --
1184 -- TOC entry 8916 (class 0 OID 0)
1185 -- Dependencies: 192
1186 -- Name: TABLE itemsite; Type: COMMENT; Schema: public; Owner: admin
1187 --
1188
1189 COMMENT ON TABLE itemsite IS 'Item Site information';
1190
1191
1192 --
1193 -- TOC entry 8917 (class 0 OID 0)
1194 -- Dependencies: 192
1195 -- Name: COLUMN itemsite.itemsite_lsseq_id; Type: COMMENT; Schema: public; Owner: admin
1196 --
1197
1198 COMMENT ON COLUMN itemsite.itemsite_lsseq_id IS 'Foreign key reference for automatic lot/serial numbering';
1199
1200
1201 --
1202 -- TOC entry 8918 (class 0 OID 0)
1203 -- Dependencies: 192
1204 -- Name: COLUMN itemsite.itemsite_createsopr; Type: COMMENT; Schema: public; Owner: admin
1205 --
1206
1207 COMMENT ON COLUMN itemsite.itemsite_createsopr IS 'Used to flag Sales items that create P/Rs';
1208
1209
1210 --
1211 -- TOC entry 8919 (class 0 OID 0)
1212 -- Dependencies: 192
1213 -- Name: COLUMN itemsite.itemsite_createsopo; Type: COMMENT; Schema: public; Owner: admin
1214 --
1215
1216 COMMENT ON COLUMN itemsite.itemsite_createsopo IS 'Used to flag Sales items that create P/Os';
1217
1218
1219 --
1220 -- TOC entry 8920 (class 0 OID 0)
1221 -- Dependencies: 192
1222 -- Name: COLUMN itemsite.itemsite_dropship; Type: COMMENT; Schema: public; Owner: admin
1223 --
1224
1225 COMMENT ON COLUMN itemsite.itemsite_dropship IS 'Used to flag Sales items to drop ship';
1226
1227
1228 --
1229 -- TOC entry 193 (class 1259 OID 146565312)
1230 -- Dependencies: 5881 5882 5883 5884 5885 5886 8
1231 -- Name: whsinfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1232 --
1233
1234 CREATE TABLE whsinfo (
1235     warehous_id integer DEFAULT nextval(('warehous_warehous_id_seq'::text)::regclass) NOT NULL,
1236     warehous_code text NOT NULL,
1237     warehous_descrip text,
1238     warehous_fob text,
1239     warehous_active boolean,
1240     warehous_counttag_prefix text,
1241     warehous_counttag_number integer,
1242     warehous_bol_prefix text,
1243     warehous_bol_number integer,
1244     warehous_shipping boolean,
1245     warehous_useslips boolean,
1246     warehous_usezones boolean,
1247     warehous_aislesize integer,
1248     warehous_aislealpha boolean,
1249     warehous_racksize integer,
1250     warehous_rackalpha boolean,
1251     warehous_binsize integer,
1252     warehous_binalpha boolean,
1253     warehous_locationsize integer,
1254     warehous_locationalpha boolean,
1255     warehous_enforcearbl boolean,
1256     warehous_default_accnt_id integer,
1257     warehous_shipping_commission numeric(8,4) DEFAULT 0.00,
1258     warehous_cntct_id integer,
1259     warehous_addr_id integer,
1260     warehous_transit boolean DEFAULT false NOT NULL,
1261     warehous_shipform_id integer,
1262     warehous_shipvia_id integer,
1263     warehous_shipcomments text,
1264     warehous_costcat_id integer,
1265     warehous_sitetype_id integer,
1266     warehous_taxzone_id integer,
1267     warehous_sequence integer DEFAULT 0 NOT NULL,
1268     CONSTRAINT whsinfo_check CHECK (((warehous_transit AND (warehous_costcat_id IS NOT NULL)) OR (NOT warehous_transit))),
1269     CONSTRAINT whsinfo_warehous_code_check CHECK ((warehous_code <> ''::text))
1270 );
1271
1272
1273 ALTER TABLE public.whsinfo OWNER TO admin;
1274
1275 --
1276 -- TOC entry 8922 (class 0 OID 0)
1277 -- Dependencies: 193
1278 -- Name: TABLE whsinfo; Type: COMMENT; Schema: public; Owner: admin
1279 --
1280
1281 COMMENT ON TABLE whsinfo IS 'Warehouse information';
1282
1283
1284 SET search_path = api, pg_catalog;
1285
1286 --
1287 -- TOC entry 194 (class 1259 OID 146565324)
1288 -- Dependencies: 8469 6
1289 -- Name: physinvcount; Type: VIEW; Schema: api; Owner: admin
1290 --
1291
1292 CREATE VIEW physinvcount AS
1293     SELECT whsinfo.warehous_code AS site, item.item_number, invcnt.invcnt_tagnumber AS tag_number, cntslip.cntslip_qty AS quantity, public.formatlocationname(cntslip.cntslip_location_id) AS location, cntslip.cntslip_lotserial AS lotserial, cntslip.cntslip_comments AS comment FROM ((((public.invcnt JOIN public.itemsite ON ((itemsite.itemsite_id = invcnt.invcnt_itemsite_id))) JOIN public.whsinfo ON ((whsinfo.warehous_id = itemsite.itemsite_warehous_id))) JOIN public.item ON ((item.item_id = itemsite.itemsite_item_id))) LEFT JOIN public.cntslip ON ((cntslip.cntslip_cnttag_id = invcnt.invcnt_id)));
1294
1295
1296 ALTER TABLE api.physinvcount OWNER TO admin;
1297
1298 --
1299 -- TOC entry 8924 (class 0 OID 0)
1300 -- Dependencies: 194
1301 -- Name: VIEW physinvcount; Type: COMMENT; Schema: api; Owner: admin
1302 --
1303
1304 COMMENT ON VIEW physinvcount IS 'Physical Inventory Count Tag and Slip';
1305
1306
1307 --
1308 -- TOC entry 906 (class 1255 OID 146565329)
1309 -- Dependencies: 2740 4536 6
1310 -- Name: insertphysinvcount(physinvcount); Type: FUNCTION; Schema: api; Owner: admin
1311 --
1312
1313 CREATE FUNCTION insertphysinvcount(physinvcount) RETURNS boolean
1314     LANGUAGE plpgsql
1315     AS $_$
1316 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
1317 -- See www.xtuple.com/CPAL for the full text of the software license.
1318 DECLARE
1319   pNEW ALIAS FOR $1;
1320   _itemid INTEGER;
1321   _type TEXT;
1322   _siteid INTEGER;
1323   _itemsiteid INTEGER;
1324   _controlmethod TEXT;
1325   _loccntrl BOOLEAN;
1326   _locationid INTEGER;
1327   _lsid INTEGER;
1328   _invcntid INTEGER;
1329   _cntslipid INTEGER;
1330   _result INTEGER;
1331
1332 BEGIN
1333
1334   -- Check Item
1335   SELECT item_id, item_type INTO _itemid, _type
1336   FROM item
1337   WHERE (item_number=UPPER(pNEW.item_number));
1338   IF (NOT FOUND OR _type IN ('F', 'R', 'L','J')) THEN
1339     SELECT item_id, item_type INTO _itemid, _type
1340     FROM item
1341     WHERE (item_upccode=pNEW.item_number);
1342     IF (NOT FOUND OR _type IN ('F', 'R', 'L','J')) THEN
1343       RAISE EXCEPTION 'Function insertPhysInvCount failed because Item % not found or invalid type', pNEW.item_number;
1344     END IF;
1345   END IF;
1346
1347   -- Check Site
1348   SELECT warehous_id INTO _siteid
1349   FROM whsinfo
1350   WHERE (warehous_code=COALESCE(pNEW.site, (SELECT warehous_code
1351                                             FROM usrpref,whsinfo
1352                                             WHERE (usrpref_username=getEffectiveXtUser())
1353                                               AND (usrpref_name='PreferredWarehouse')
1354                                               AND (warehous_id=CAST(usrpref_value AS INTEGER)))));
1355   IF (NOT FOUND) THEN
1356     RAISE EXCEPTION 'Function insertPhysInvCount failed because Site % not found', pNEW.site;
1357   END IF;
1358
1359   -- Check Itemsite
1360   SELECT itemsite_id, itemsite_controlmethod, itemsite_loccntrl INTO _itemsiteid, _controlmethod, _loccntrl
1361   FROM itemsite
1362   WHERE (itemsite_item_id=_itemid)
1363     AND (itemsite_warehous_id=_siteid);
1364   IF (NOT FOUND) THEN
1365     RAISE EXCEPTION 'Function insertPhysInvCount failed because Itemsite %, % not found', pNEW.site, pNEW.item_number;
1366   END IF;
1367   IF (_controlmethod = 'N') THEN
1368     RAISE EXCEPTION 'Function insertPhysInvCount failed because Itemsite %, % not inventory control method', pNEW.site, pNEW.item_number;
1369   END IF;
1370   IF (_controlmethod IN ('L', 'S') AND COALESCE(pNEW.lotserial, '') = '') THEN
1371     RAISE EXCEPTION 'Function insertPhysInvCount failed because Itemsite %, % lot/serial controlled and lotserial not provided', pNEW.site, pNEW.item_number;
1372   END IF;
1373   IF (_controlmethod = 'S') THEN
1374     -- Check for unique serial id
1375     SELECT ls_id INTO _lsid
1376     FROM ls
1377     WHERE (ls_number=pNEW.lotserial);
1378     IF (FOUND) THEN
1379       RAISE EXCEPTION 'Function insertPhysInvCount failed because Serial %, %, % not unique', pNEW.site, pNEW.item_number, pNEW.lotserial;
1380     END IF;
1381   END IF;
1382   IF (_loccntrl) THEN
1383     IF (pNEW.location IS NULL) THEN
1384       RAISE EXCEPTION 'Function insertPhysInvCount failed because Itemsite %, % multi location and location not provided', pNEW.site, pNEW.item_number;
1385     ELSE
1386       -- Check Location
1387       SELECT location_id INTO _locationid
1388       FROM location
1389       WHERE (location_id=getLocationId(pNEW.site, pNEW.location));
1390       IF (NOT FOUND) THEN
1391         RAISE EXCEPTION 'Function insertPhysInvCount failed because Location %, % not found', pNEW.site, pNEW.location;
1392       END IF;
1393     END IF;
1394   END IF;
1395
1396   -- Create Count Tag
1397   SELECT CreateCountTag(_itemsiteid, pNEW.comment, FALSE, FALSE) INTO _invcntid;
1398   IF (_invcntid <= 0) THEN
1399     RAISE EXCEPTION 'Function insertPhysInvCount failed because CreateCountTag failed for Itemsite %, %', pNEW.site, pNEW.item_number;
1400   END IF;
1401
1402   -- Create Count Slip
1403   INSERT INTO cntslip
1404   ( cntslip_cnttag_id,
1405     cntslip_username, cntslip_entered, cntslip_posted,
1406     cntslip_number, cntslip_qty,
1407     cntslip_location_id, cntslip_lotserial,
1408     cntslip_lotserial_expiration,
1409     cntslip_lotserial_warrpurc,
1410     cntslip_comments )
1411   VALUES
1412   ( _invcntid,
1413     getEffectiveXtUser(), CURRENT_TIMESTAMP, FALSE,
1414     'N/A', pNEW.quantity,
1415     COALESCE(_locationid, -1), pNEW.lotserial,
1416     NULL,
1417     NULL,
1418     pNEW.comment )
1419   RETURNING cntslip_id INTO _cntslipid;
1420
1421   -- Post Count Slip
1422   SELECT postCountSlip(_cntslipid) INTO _result;
1423   IF (_result < 0) THEN
1424     RAISE EXCEPTION 'Function insertPhysInvCount failed because postCountSlip failed for Itemsite %, %, %', pNEW.site, pNEW.item_number, _result;
1425   END IF;
1426
1427   RETURN TRUE;
1428 END;
1429 $_$;
1430
1431
1432 ALTER FUNCTION api.insertphysinvcount(physinvcount) OWNER TO admin;
1433
1434 SET search_path = public, pg_catalog;
1435
1436 --
1437 -- TOC entry 907 (class 1255 OID 146565330)
1438 -- Dependencies: 4536 8
1439 -- Name: basecurrid(); Type: FUNCTION; Schema: public; Owner: admin
1440 --
1441
1442 CREATE FUNCTION basecurrid() RETURNS integer
1443     LANGUAGE plpgsql IMMUTABLE
1444     AS $$
1445 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
1446 -- See www.xtuple.com/CPAL for the full text of the software license.
1447 DECLARE
1448   returnVal INTEGER;
1449 BEGIN
1450   SELECT curr_id INTO returnVal
1451     FROM curr_symbol
1452    WHERE curr_base = TRUE;
1453   IF NOT FOUND THEN
1454     RAISE EXCEPTION 'No base currency found';
1455   END IF;
1456   RETURN returnVal;
1457 END;
1458 $$;
1459
1460
1461 ALTER FUNCTION public.basecurrid() OWNER TO admin;
1462
1463 --
1464 -- TOC entry 908 (class 1255 OID 146565331)
1465 -- Dependencies: 4536 8
1466 -- Name: formatglaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
1467 --
1468
1469 CREATE FUNCTION formatglaccount(integer) RETURNS text
1470     LANGUAGE plpgsql IMMUTABLE
1471     AS $_$
1472 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
1473 -- See www.xtuple.com/CPAL for the full text of the software license.
1474 DECLARE
1475   pAccntid ALIAS FOR $1;
1476   _accnt RECORD;
1477
1478 BEGIN
1479
1480   SELECT COALESCE(accnt_company, '') AS accnt_company,
1481          COALESCE(accnt_profit, '') AS accnt_profit,
1482          accnt_number,
1483          COALESCE(accnt_sub, '') AS accnt_sub INTO _accnt
1484   FROM accnt
1485   WHERE (accnt_id=pAccntid);
1486
1487   IF (NOT FOUND) THEN
1488     RETURN 'Error';
1489   END IF;
1490
1491   RETURN formatGlAccount(_accnt.accnt_company, _accnt.accnt_profit, _accnt.accnt_number, _accnt.accnt_sub);
1492
1493 END;
1494 $_$;
1495
1496
1497 ALTER FUNCTION public.formatglaccount(integer) OWNER TO admin;
1498
1499 --
1500 -- TOC entry 909 (class 1255 OID 146565332)
1501 -- Dependencies: 4536 8
1502 -- Name: formatsolinenumber(integer); Type: FUNCTION; Schema: public; Owner: admin
1503 --
1504
1505 CREATE FUNCTION formatsolinenumber(integer) RETURNS text
1506     LANGUAGE plpgsql
1507     AS $_$
1508 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
1509 -- See www.xtuple.com/CPAL for the full text of the software license.
1510 DECLARE
1511   pSoitemid ALIAS FOR $1;
1512   _r RECORD;
1513
1514 BEGIN
1515
1516   SELECT coitem_linenumber, coitem_subnumber
1517     INTO _r
1518     FROM coitem
1519    WHERE(coitem_id=pSoitemid);
1520
1521   IF(NOT FOUND) THEN
1522     RETURN NULL;
1523   END IF;
1524
1525   IF(COALESCE(_r.coitem_subnumber, 0) > 0) THEN
1526     RETURN _r.coitem_linenumber || '.' || _r.coitem_subnumber;
1527   END IF;
1528
1529   RETURN _r.coitem_linenumber; 
1530 END;
1531 $_$;
1532
1533
1534 ALTER FUNCTION public.formatsolinenumber(integer) OWNER TO admin;
1535
1536 --
1537 -- TOC entry 910 (class 1255 OID 146565333)
1538 -- Dependencies: 4536 8
1539 -- Name: geteffectivextuser(); Type: FUNCTION; Schema: public; Owner: admin
1540 --
1541
1542 CREATE FUNCTION geteffectivextuser() RETURNS text
1543     LANGUAGE plpgsql STABLE
1544     AS $$
1545 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
1546 -- See www.xtuple.com/CPAL for the full text of the software license.
1547 BEGIN
1548 /*
1549   The default return value of this function is simply
1550   the user currently connected.
1551   
1552   Overload this function from another schema 
1553   to implement specific user handling from an external 
1554   application that uses connection pooling. 
1555   Use setEffectiveXtUser(text) to create a temporary table that 
1556   inserts user data that can in turn be used as a lookup 
1557   reference for an over loaded version of this function like so:
1558   
1559   SELECT effective_value
1560   FROM effective_user
1561   WHERE effective_key = 'username'
1562 */
1563
1564   RETURN CURRENT_USER;
1565
1566 END;
1567 $$;
1568
1569
1570 ALTER FUNCTION public.geteffectivextuser() OWNER TO admin;
1571
1572 --
1573 -- TOC entry 911 (class 1255 OID 146565334)
1574 -- Dependencies: 4536 8
1575 -- Name: getitemtaxtype(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
1576 --
1577
1578 CREATE FUNCTION getitemtaxtype(integer, integer) RETURNS integer
1579     LANGUAGE plpgsql
1580     AS $_$
1581 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
1582 -- See www.xtuple.com/CPAL for the full text of the software license.
1583 DECLARE
1584   pItemid ALIAS FOR $1;
1585   pTaxzoneid ALIAS FOR $2;
1586   _taxtypeid INTEGER;
1587 BEGIN
1588   SELECT itemtax_taxtype_id
1589     INTO _taxtypeid
1590     FROM itemtax
1591    WHERE ((itemtax_item_id=pItemid)
1592      AND  (itemtax_taxzone_id=pTaxzoneid));
1593   IF (NOT FOUND) THEN
1594     SELECT itemtax_taxtype_id
1595       INTO _taxtypeid
1596       FROM itemtax
1597      WHERE ((itemtax_item_id=pItemid)
1598        AND  (itemtax_taxzone_id IS NULL));
1599     IF (NOT FOUND) THEN
1600       RETURN NULL;
1601     END IF;
1602   END IF;
1603
1604   RETURN _taxtypeid;
1605 END;
1606 $_$;
1607
1608
1609 ALTER FUNCTION public.getitemtaxtype(integer, integer) OWNER TO admin;
1610
1611 --
1612 -- TOC entry 195 (class 1259 OID 146565335)
1613 -- Dependencies: 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 8
1614 -- Name: cohead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1615 --
1616
1617 CREATE TABLE cohead (
1618     cohead_id integer DEFAULT nextval(('cohead_cohead_id_seq'::text)::regclass) NOT NULL,
1619     cohead_number text NOT NULL,
1620     cohead_cust_id integer NOT NULL,
1621     cohead_custponumber text,
1622     cohead_type character(1),
1623     cohead_orderdate date,
1624     cohead_warehous_id integer,
1625     cohead_shipto_id integer,
1626     cohead_shiptoname text,
1627     cohead_shiptoaddress1 text,
1628     cohead_shiptoaddress2 text,
1629     cohead_shiptoaddress3 text,
1630     cohead_shiptoaddress4 text,
1631     cohead_shiptoaddress5 text,
1632     cohead_salesrep_id integer NOT NULL,
1633     cohead_terms_id integer NOT NULL,
1634     cohead_fob text,
1635     cohead_shipvia text,
1636     cohead_shiptocity text,
1637     cohead_shiptostate text,
1638     cohead_shiptozipcode text,
1639     cohead_freight numeric(16,4) NOT NULL,
1640     cohead_misc numeric(16,4) DEFAULT 0 NOT NULL,
1641     cohead_imported boolean DEFAULT false,
1642     cohead_ordercomments text,
1643     cohead_shipcomments text,
1644     cohead_shiptophone text,
1645     cohead_shipchrg_id integer,
1646     cohead_shipform_id integer,
1647     cohead_billtoname text,
1648     cohead_billtoaddress1 text,
1649     cohead_billtoaddress2 text,
1650     cohead_billtoaddress3 text,
1651     cohead_billtocity text,
1652     cohead_billtostate text,
1653     cohead_billtozipcode text,
1654     cohead_misc_accnt_id integer,
1655     cohead_misc_descrip text,
1656     cohead_commission numeric(16,4),
1657     cohead_miscdate date,
1658     cohead_holdtype character(1),
1659     cohead_packdate date,
1660     cohead_prj_id integer,
1661     cohead_wasquote boolean DEFAULT false NOT NULL,
1662     cohead_lastupdated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
1663     cohead_shipcomplete boolean DEFAULT false NOT NULL,
1664     cohead_created timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone,
1665     cohead_creator text DEFAULT geteffectivextuser(),
1666     cohead_quote_number text,
1667     cohead_billtocountry text,
1668     cohead_shiptocountry text,
1669     cohead_curr_id integer DEFAULT basecurrid(),
1670     cohead_calcfreight boolean DEFAULT false NOT NULL,
1671     cohead_shipto_cntct_id integer,
1672     cohead_shipto_cntct_honorific text,
1673     cohead_shipto_cntct_first_name text,
1674     cohead_shipto_cntct_middle text,
1675     cohead_shipto_cntct_last_name text,
1676     cohead_shipto_cntct_suffix text,
1677     cohead_shipto_cntct_phone text,
1678     cohead_shipto_cntct_title text,
1679     cohead_shipto_cntct_fax text,
1680     cohead_shipto_cntct_email text,
1681     cohead_billto_cntct_id integer,
1682     cohead_billto_cntct_honorific text,
1683     cohead_billto_cntct_first_name text,
1684     cohead_billto_cntct_middle text,
1685     cohead_billto_cntct_last_name text,
1686     cohead_billto_cntct_suffix text,
1687     cohead_billto_cntct_phone text,
1688     cohead_billto_cntct_title text,
1689     cohead_billto_cntct_fax text,
1690     cohead_billto_cntct_email text,
1691     cohead_taxzone_id integer,
1692     cohead_taxtype_id integer,
1693     cohead_ophead_id integer,
1694     cohead_status character(1) DEFAULT 'O'::bpchar NOT NULL,
1695     cohead_saletype_id integer,
1696     cohead_shipzone_id integer,
1697     CONSTRAINT cohead_check CHECK (((cohead_misc = (0)::numeric) OR ((cohead_misc <> (0)::numeric) AND (cohead_misc_accnt_id IS NOT NULL)))),
1698     CONSTRAINT cohead_cohead_number_check CHECK ((cohead_number <> ''::text))
1699 );
1700
1701
1702 ALTER TABLE public.cohead OWNER TO admin;
1703
1704 --
1705 -- TOC entry 8926 (class 0 OID 0)
1706 -- Dependencies: 195
1707 -- Name: TABLE cohead; Type: COMMENT; Schema: public; Owner: admin
1708 --
1709
1710 COMMENT ON TABLE cohead IS 'Sales Order header information';
1711
1712
1713 --
1714 -- TOC entry 8927 (class 0 OID 0)
1715 -- Dependencies: 195
1716 -- Name: COLUMN cohead.cohead_saletype_id; Type: COMMENT; Schema: public; Owner: admin
1717 --
1718
1719 COMMENT ON COLUMN cohead.cohead_saletype_id IS 'Associated sale type for sales order.';
1720
1721
1722 --
1723 -- TOC entry 8928 (class 0 OID 0)
1724 -- Dependencies: 195
1725 -- Name: COLUMN cohead.cohead_shipzone_id; Type: COMMENT; Schema: public; Owner: admin
1726 --
1727
1728 COMMENT ON COLUMN cohead.cohead_shipzone_id IS 'Associated shipping zone for sales order.';
1729
1730
1731 --
1732 -- TOC entry 196 (class 1259 OID 146565354)
1733 -- Dependencies: 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 8
1734 -- Name: coitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1735 --
1736
1737 CREATE TABLE coitem (
1738     coitem_id integer DEFAULT nextval(('coitem_coitem_id_seq'::text)::regclass) NOT NULL,
1739     coitem_cohead_id integer,
1740     coitem_linenumber integer NOT NULL,
1741     coitem_itemsite_id integer,
1742     coitem_status character(1),
1743     coitem_scheddate date,
1744     coitem_promdate date,
1745     coitem_qtyord numeric(18,6) NOT NULL,
1746     coitem_unitcost numeric(16,6) NOT NULL,
1747     coitem_price numeric(16,4) NOT NULL,
1748     coitem_custprice numeric(16,4) NOT NULL,
1749     coitem_qtyshipped numeric(18,6) NOT NULL,
1750     coitem_order_id integer,
1751     coitem_memo text,
1752     coitem_imported boolean DEFAULT false,
1753     coitem_qtyreturned numeric(18,6),
1754     coitem_closedate timestamp with time zone,
1755     coitem_custpn text,
1756     coitem_order_type character(1),
1757     coitem_close_username text,
1758     coitem_lastupdated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
1759     coitem_substitute_item_id integer,
1760     coitem_created timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone,
1761     coitem_creator text DEFAULT geteffectivextuser(),
1762     coitem_prcost numeric(16,6),
1763     coitem_qty_uom_id integer NOT NULL,
1764     coitem_qty_invuomratio numeric(20,10) NOT NULL,
1765     coitem_price_uom_id integer NOT NULL,
1766     coitem_price_invuomratio numeric(20,10) NOT NULL,
1767     coitem_warranty boolean DEFAULT false NOT NULL,
1768     coitem_cos_accnt_id integer,
1769     coitem_qtyreserved numeric(18,6) DEFAULT 0.0 NOT NULL,
1770     coitem_subnumber integer DEFAULT 0 NOT NULL,
1771     coitem_firm boolean DEFAULT false NOT NULL,
1772     coitem_taxtype_id integer,
1773     coitem_rev_accnt_id integer,
1774     coitem_pricemode character(1) DEFAULT 'D'::bpchar NOT NULL,
1775     CONSTRAINT coitem_coitem_status_check CHECK ((((coitem_status = 'O'::bpchar) OR (coitem_status = 'C'::bpchar)) OR (coitem_status = 'X'::bpchar))),
1776     CONSTRAINT valid_coitem_pricemode CHECK ((coitem_pricemode = ANY (ARRAY['D'::bpchar, 'M'::bpchar])))
1777 );
1778
1779
1780 ALTER TABLE public.coitem OWNER TO admin;
1781
1782 --
1783 -- TOC entry 8930 (class 0 OID 0)
1784 -- Dependencies: 196
1785 -- Name: TABLE coitem; Type: COMMENT; Schema: public; Owner: admin
1786 --
1787
1788 COMMENT ON TABLE coitem IS 'Sales Order Line Item information';
1789
1790
1791 --
1792 -- TOC entry 8931 (class 0 OID 0)
1793 -- Dependencies: 196
1794 -- Name: COLUMN coitem.coitem_pricemode; Type: COMMENT; Schema: public; Owner: admin
1795 --
1796
1797 COMMENT ON COLUMN coitem.coitem_pricemode IS 'Pricing mode for sales order item.  Valid values are D-discount, and M-markup';
1798
1799
1800 --
1801 -- TOC entry 197 (class 1259 OID 146565372)
1802 -- Dependencies: 5912 5913 5914 5915 5916 5917 5918 5919 8
1803 -- Name: pohead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1804 --
1805
1806 CREATE TABLE pohead (
1807     pohead_id integer DEFAULT nextval(('pohead_pohead_id_seq'::text)::regclass) NOT NULL,
1808     pohead_status character(1),
1809     pohead_number text NOT NULL,
1810     pohead_orderdate date,
1811     pohead_vend_id integer,
1812     pohead_fob text,
1813     pohead_shipvia text,
1814     pohead_comments text,
1815     pohead_freight numeric(16,2) DEFAULT 0,
1816     pohead_printed boolean DEFAULT false,
1817     pohead_terms_id integer,
1818     pohead_warehous_id integer,
1819     pohead_vendaddr_id integer,
1820     pohead_agent_username text,
1821     pohead_curr_id integer DEFAULT basecurrid(),
1822     pohead_saved boolean DEFAULT true NOT NULL,
1823     pohead_taxzone_id integer,
1824     pohead_taxtype_id integer,
1825     pohead_dropship boolean DEFAULT false,
1826     pohead_vend_cntct_id integer,
1827     pohead_vend_cntct_honorific text,
1828     pohead_vend_cntct_first_name text,
1829     pohead_vend_cntct_middle text,
1830     pohead_vend_cntct_last_name text,
1831     pohead_vend_cntct_suffix text,
1832     pohead_vend_cntct_phone text,
1833     pohead_vend_cntct_title text,
1834     pohead_vend_cntct_fax text,
1835     pohead_vend_cntct_email text,
1836     pohead_vendaddress1 text,
1837     pohead_vendaddress2 text,
1838     pohead_vendaddress3 text,
1839     pohead_vendcity text,
1840     pohead_vendstate text,
1841     pohead_vendzipcode text,
1842     pohead_vendcountry text,
1843     pohead_shipto_cntct_id integer,
1844     pohead_shipto_cntct_honorific text,
1845     pohead_shipto_cntct_first_name text,
1846     pohead_shipto_cntct_middle text,
1847     pohead_shipto_cntct_last_name text,
1848     pohead_shipto_cntct_suffix text,
1849     pohead_shipto_cntct_phone text,
1850     pohead_shipto_cntct_title text,
1851     pohead_shipto_cntct_fax text,
1852     pohead_shipto_cntct_email text,
1853     pohead_shiptoaddress_id integer,
1854     pohead_shiptoaddress1 text,
1855     pohead_shiptoaddress2 text,
1856     pohead_shiptoaddress3 text,
1857     pohead_shiptocity text,
1858     pohead_shiptostate text,
1859     pohead_shiptozipcode text,
1860     pohead_shiptocountry text,
1861     pohead_cohead_id integer,
1862     pohead_released date,
1863     pohead_shiptoname text,
1864     CONSTRAINT pohead_pohead_number_check CHECK ((pohead_number <> ''::text)),
1865     CONSTRAINT pohead_pohead_status_check CHECK ((((pohead_status = 'U'::bpchar) OR (pohead_status = 'O'::bpchar)) OR (pohead_status = 'C'::bpchar)))
1866 );
1867
1868
1869 ALTER TABLE public.pohead OWNER TO admin;
1870
1871 --
1872 -- TOC entry 8933 (class 0 OID 0)
1873 -- Dependencies: 197
1874 -- Name: TABLE pohead; Type: COMMENT; Schema: public; Owner: admin
1875 --
1876
1877 COMMENT ON TABLE pohead IS 'Purchase Order header information';
1878
1879
1880 --
1881 -- TOC entry 198 (class 1259 OID 146565386)
1882 -- Dependencies: 5920 5921 5922 5923 5924 5925 5926 5927 5928 8
1883 -- Name: poitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1884 --
1885
1886 CREATE TABLE poitem (
1887     poitem_id integer DEFAULT nextval(('poitem_poitem_id_seq'::text)::regclass) NOT NULL,
1888     poitem_status character(1),
1889     poitem_pohead_id integer,
1890     poitem_linenumber integer,
1891     poitem_duedate date,
1892     poitem_itemsite_id integer,
1893     poitem_vend_item_descrip text,
1894     poitem_vend_uom text,
1895     poitem_invvenduomratio numeric(20,10),
1896     poitem_qty_ordered numeric(18,6) NOT NULL,
1897     poitem_qty_received numeric(18,6) DEFAULT 0.0 NOT NULL,
1898     poitem_qty_returned numeric(18,6) DEFAULT 0.0 NOT NULL,
1899     poitem_qty_vouchered numeric(18,6) DEFAULT 0.0 NOT NULL,
1900     poitem_unitprice numeric(16,6),
1901     poitem_vend_item_number text,
1902     poitem_comments text,
1903     poitem_qty_toreceive numeric(18,6),
1904     poitem_expcat_id integer,
1905     poitem_itemsrc_id integer,
1906     poitem_freight numeric(16,4) DEFAULT 0.0 NOT NULL,
1907     poitem_freight_received numeric(16,4) DEFAULT 0.0 NOT NULL,
1908     poitem_freight_vouchered numeric(16,4) DEFAULT 0.0 NOT NULL,
1909     poitem_prj_id integer,
1910     poitem_stdcost numeric(16,6),
1911     poitem_bom_rev_id integer,
1912     poitem_boo_rev_id integer,
1913     poitem_manuf_name text,
1914     poitem_manuf_item_number text,
1915     poitem_manuf_item_descrip text,
1916     poitem_taxtype_id integer,
1917     poitem_tax_recoverable boolean DEFAULT true NOT NULL,
1918     poitem_rlsd_duedate date,
1919     poitem_order_id integer,
1920     poitem_order_type character(1),
1921     CONSTRAINT poitem_poitem_status_check CHECK ((((poitem_status = 'U'::bpchar) OR (poitem_status = 'O'::bpchar)) OR (poitem_status = 'C'::bpchar)))
1922 );
1923
1924
1925 ALTER TABLE public.poitem OWNER TO admin;
1926
1927 --
1928 -- TOC entry 8935 (class 0 OID 0)
1929 -- Dependencies: 198
1930 -- Name: TABLE poitem; Type: COMMENT; Schema: public; Owner: admin
1931 --
1932
1933 COMMENT ON TABLE poitem IS 'Purchase Order Line Item information';
1934
1935
1936 --
1937 -- TOC entry 199 (class 1259 OID 146565401)
1938 -- Dependencies: 5930 5931 8
1939 -- Name: taxtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1940 --
1941
1942 CREATE TABLE taxtype (
1943     taxtype_id integer NOT NULL,
1944     taxtype_name text NOT NULL,
1945     taxtype_descrip text,
1946     taxtype_sys boolean DEFAULT false NOT NULL,
1947     CONSTRAINT taxtype_taxtype_name_check CHECK ((taxtype_name <> ''::text))
1948 );
1949
1950
1951 ALTER TABLE public.taxtype OWNER TO admin;
1952
1953 --
1954 -- TOC entry 8937 (class 0 OID 0)
1955 -- Dependencies: 199
1956 -- Name: TABLE taxtype; Type: COMMENT; Schema: public; Owner: admin
1957 --
1958
1959 COMMENT ON TABLE taxtype IS 'The list of Tax Types';
1960
1961
1962 --
1963 -- TOC entry 200 (class 1259 OID 146565409)
1964 -- Dependencies: 5933 5934 8
1965 -- Name: uom; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
1966 --
1967
1968 CREATE TABLE uom (
1969     uom_id integer NOT NULL,
1970     uom_name text NOT NULL,
1971     uom_descrip text,
1972     uom_item_weight boolean DEFAULT false NOT NULL,
1973     CONSTRAINT uom_uom_name_check CHECK ((uom_name <> ''::text))
1974 );
1975
1976
1977 ALTER TABLE public.uom OWNER TO admin;
1978
1979 --
1980 -- TOC entry 8939 (class 0 OID 0)
1981 -- Dependencies: 200
1982 -- Name: TABLE uom; Type: COMMENT; Schema: public; Owner: admin
1983 --
1984
1985 COMMENT ON TABLE uom IS 'Unit of Measure information';
1986
1987
1988 SET search_path = api, pg_catalog;
1989
1990 --
1991 -- TOC entry 201 (class 1259 OID 146565417)
1992 -- Dependencies: 8470 6
1993 -- Name: salesline; Type: VIEW; Schema: api; Owner: admin
1994 --
1995
1996 CREATE VIEW salesline AS
1997     SELECT (cohead.cohead_number)::character varying AS order_number, (public.formatsolinenumber(coitem.coitem_id))::character varying AS line_number, l.item_number, coitem.coitem_custpn AS customer_pn, s.item_number AS substitute_for, whsinfo.warehous_code AS sold_from_site, coitem.coitem_status AS status, coitem.coitem_qtyord AS qty_ordered, q.uom_name AS qty_uom, coitem.coitem_price AS net_unit_price, p.uom_name AS price_uom, coitem.coitem_scheddate AS scheduled_date, coitem.coitem_promdate AS promise_date, coitem.coitem_warranty AS warranty, COALESCE((SELECT taxtype.taxtype_name FROM public.taxtype WHERE (taxtype.taxtype_id = public.getitemtaxtype(l.item_id, cohead.cohead_taxzone_id))), 'None'::text) AS tax_type, CASE WHEN (coitem.coitem_price = (0)::numeric) THEN '100'::text WHEN (coitem.coitem_custprice = (0)::numeric) THEN 'N/A'::text ELSE (round((((1)::numeric - (coitem.coitem_price / coitem.coitem_custprice)) * (100)::numeric), 4))::text END AS discount_pct_from_list, CASE WHEN (coitem.coitem_order_id = (-1)) THEN false ELSE true END AS create_order, CASE WHEN (coitem.coitem_order_id = (-1)) THEN ''::text ELSE ((pohead.pohead_number || '-'::text) || poitem.poitem_linenumber) END AS create_po, coitem.coitem_prcost AS overwrite_po_price, coitem.coitem_memo AS notes, CASE WHEN (coitem.coitem_cos_accnt_id IS NOT NULL) THEN public.formatglaccount(coitem.coitem_cos_accnt_id) ELSE NULL::text END AS alternate_cos_account, CASE WHEN (coitem.coitem_rev_accnt_id IS NOT NULL) THEN public.formatglaccount(coitem.coitem_rev_accnt_id) ELSE NULL::text END AS alternate_rev_account FROM public.cohead, (((public.coitem LEFT JOIN public.itemsite isb ON ((coitem.coitem_substitute_item_id = isb.itemsite_id))) LEFT JOIN public.item s ON ((isb.itemsite_item_id = s.item_id))) LEFT JOIN (public.poitem JOIN public.pohead ON ((poitem.poitem_pohead_id = pohead.pohead_id))) ON ((poitem.poitem_id = coitem.coitem_order_id))), public.itemsite il, public.item l, public.whsinfo, public.uom q, public.uom p WHERE ((((((cohead.cohead_id = coitem.coitem_cohead_id) AND (coitem.coitem_itemsite_id = il.itemsite_id)) AND (il.itemsite_item_id = l.item_id)) AND (il.itemsite_warehous_id = whsinfo.warehous_id)) AND (coitem.coitem_qty_uom_id = q.uom_id)) AND (coitem.coitem_price_uom_id = p.uom_id)) ORDER BY cohead.cohead_number, coitem.coitem_linenumber, coitem.coitem_subnumber;
1998
1999
2000 ALTER TABLE api.salesline OWNER TO admin;
2001
2002 --
2003 -- TOC entry 8941 (class 0 OID 0)
2004 -- Dependencies: 201
2005 -- Name: VIEW salesline; Type: COMMENT; Schema: api; Owner: admin
2006 --
2007
2008 COMMENT ON VIEW salesline IS 'Sales Order Line Item';
2009
2010
2011 --
2012 -- TOC entry 912 (class 1255 OID 146565422)
2013 -- Dependencies: 2767 4536 6
2014 -- Name: insertsalesline(salesline); Type: FUNCTION; Schema: api; Owner: admin
2015 --
2016
2017 CREATE FUNCTION insertsalesline(salesline) RETURNS boolean
2018     LANGUAGE plpgsql
2019     AS $_$
2020 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2021 -- See www.xtuple.com/CPAL for the full text of the software license.
2022 DECLARE
2023   pNEW ALIAS FOR $1;
2024   _r RECORD;
2025
2026 BEGIN
2027
2028   IF (NOT EXISTS (SELECT cohead_id FROM cohead WHERE cohead_number=pNEW.order_number)) THEN
2029     RAISE EXCEPTION 'Function insertSalesLine failed because Sales Order % not found', pNEW.order_number;
2030   END IF;
2031
2032   IF (NOT EXISTS (SELECT item_id FROM item WHERE item_number=pNEW.item_number)) THEN
2033     RAISE EXCEPTION 'Function insertSalesLine failed because Item Number % not found', pNEW.item_number;
2034   END IF;
2035
2036   SELECT * INTO _r
2037   FROM cohead, itemsite, item, whsinfo
2038   WHERE ((cohead_number=pNEW.order_number)
2039   AND (itemsite_warehous_id=warehous_id
2040   AND (itemsite_item_id=item_id)
2041   AND (itemsite_active)
2042   AND (item_number=pNEW.item_number)
2043   AND (warehous_active)
2044   AND (warehous_id=COALESCE(getWarehousId(pNEW.sold_from_site,'ALL'),cohead_warehous_id,fetchprefwarehousid()))));
2045
2046   IF (NOT FOUND) THEN
2047     RAISE EXCEPTION 'Function insertSalesLine failed with unknown failure to retrieve Sales Order';
2048   END IF;
2049
2050   INSERT INTO coitem (
2051     coitem_cohead_id,
2052     coitem_linenumber,
2053     coitem_itemsite_id,
2054     coitem_status,
2055     coitem_scheddate,
2056     coitem_promdate,
2057     coitem_qtyord,
2058     coitem_qty_uom_id,
2059     coitem_qty_invuomratio,
2060     coitem_qtyshipped,
2061     coitem_unitcost,
2062     coitem_price,
2063     coitem_price_uom_id,
2064     coitem_price_invuomratio,
2065     coitem_custprice,
2066     coitem_order_id,
2067     coitem_memo,
2068     coitem_imported,
2069     coitem_qtyreturned,
2070     coitem_custpn,
2071     coitem_order_type,
2072     coitem_substitute_item_id,
2073     coitem_prcost,
2074     coitem_taxtype_id,
2075     coitem_warranty,
2076     coitem_cos_accnt_id,
2077     coitem_rev_accnt_id)
2078   VALUES (
2079     _r.cohead_id,
2080     pNEW.line_number::INTEGER,
2081     _r.itemsite_id,
2082     pNEW.status,
2083     pNEW.scheduled_date,
2084     pNEW.promise_date,
2085     pNEW.qty_ordered,
2086     COALESCE(getUomId(pNEW.qty_uom),_r.item_inv_uom_id),
2087     itemuomtouomratio(_r.item_id,COALESCE(getUomId(pNEW.qty_uom),_r.item_inv_uom_id),_r.item_inv_uom_id),
2088     0,
2089     stdCost(_r.item_id),
2090     COALESCE(pNEW.net_unit_price,itemPrice(_r.item_id,_r.cohead_cust_id,
2091              _r.cohead_shipto_id,pNEW.qty_ordered,_r.cohead_curr_id,_r.cohead_orderdate)),
2092     COALESCE(getUomId(pNEW.price_uom),_r.item_price_uom_id),
2093     itemuomtouomratio(_r.item_id,COALESCE(getUomId(pNEW.price_uom),_r.item_price_uom_id),_r.item_price_uom_id),
2094     itemPrice(_r.item_id, _r.cohead_cust_id, _r.cohead_shipto_id,
2095               pNEW.qty_ordered, _r.item_inv_uom_id, _r.item_price_uom_id,
2096               _r.cohead_curr_id,_r.cohead_orderdate,
2097               CASE WHEN (fetchMetricText('soPriceEffective') = 'ScheduleDate') THEN pNEW.scheduled_date
2098                    WHEN (fetchMetricText('soPriceEffective') = 'OrderDate') THEN _r.cohead_orderdate
2099                    ELSE CURRENT_DATE END,
2100               NULL)
2101     -1,
2102     pNEW.notes,
2103     true,
2104     0,
2105     pNEW.customer_pn,
2106     CASE
2107       WHEN ((pNEW.create_order  AND (_r.item_type = 'M')) OR 
2108            ((pNEW.create_order IS NULL) AND _r.itemsite_createwo)) THEN
2109         'W'
2110       WHEN ((pNEW.create_order AND (_r.item_type = 'P')) OR 
2111            ((pNEW.create_order IS NULL) AND _r.itemsite_createsopr)) THEN
2112         'R'
2113       WHEN ((pNEW.create_order AND (_r.item_type = 'P') AND (_r.itemsite_createsopo)) OR 
2114            ((pNEW.create_order IS NULL) AND _r.itemsite_createsopo)) THEN
2115         'P'
2116     END,
2117     getitemid(pNEW.substitute_for),
2118     pNEW.overwrite_po_price,
2119     COALESCE(getTaxTypeId(pNEW.tax_type), getItemTaxType(_r.itemsite_item_id, _r.cohead_taxzone_id)),
2120     pNEW.warranty,
2121     getGlAccntId(pNEW.alternate_cos_account),
2122     getGlAccntId(pNEW.alternate_rev_account)
2123     );
2124
2125   RETURN TRUE;
2126 END;
2127 $_$;
2128
2129
2130 ALTER FUNCTION api.insertsalesline(salesline) OWNER TO admin;
2131
2132 SET search_path = public, pg_catalog;
2133
2134 --
2135 -- TOC entry 914 (class 1255 OID 146565423)
2136 -- Dependencies: 4536 8
2137 -- Name: _accntdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
2138 --
2139
2140 CREATE FUNCTION _accntdeletetrigger() RETURNS trigger
2141     LANGUAGE plpgsql
2142     AS $$
2143 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2144 -- See www.xtuple.com/CPAL for the full text of the software license.
2145 DECLARE
2146   _accntnum     TEXT := formatGLAccount(OLD.accnt_id);
2147   _check INTEGER;
2148 BEGIN
2149 -- This trigger is to protect against accounts that are in use
2150
2151 --  Check to see if the passed accnt is used in a Cost Category
2152   SELECT costcat_id INTO _check
2153   FROM costcat
2154   WHERE ( (costcat_asset_accnt_id=OLD.accnt_id)
2155      OR   (costcat_liability_accnt_id=OLD.accnt_id)
2156      OR   (costcat_adjustment_accnt_id=OLD.accnt_id)
2157      OR   (costcat_purchprice_accnt_id=OLD.accnt_id)
2158      OR   (costcat_laboroverhead_accnt_id=OLD.accnt_id)
2159      OR   (costcat_scrap_accnt_id=OLD.accnt_id)
2160      OR   (costcat_invcost_accnt_id=OLD.accnt_id)
2161      OR   (costcat_wip_accnt_id=OLD.accnt_id)
2162      OR   (costcat_shipasset_accnt_id=OLD.accnt_id)
2163      OR   (costcat_mfgscrap_accnt_id=OLD.accnt_id)
2164      OR   (costcat_transform_accnt_id=OLD.accnt_id)
2165      OR   (costcat_freight_accnt_id=OLD.accnt_id) )
2166   LIMIT 1;
2167   IF (FOUND) THEN
2168     RAISE EXCEPTION 'Can not delete, used in Cost Category';
2169   END IF;
2170
2171 --  Check to see if the passed accnt is used in a Sales Account Assignment
2172   SELECT salesaccnt_id INTO _check
2173   FROM salesaccnt
2174   WHERE ( (salesaccnt_sales_accnt_id=OLD.accnt_id)
2175      OR   (salesaccnt_credit_accnt_id=OLD.accnt_id)
2176      OR   (salesaccnt_cos_accnt_id=OLD.accnt_id) )
2177   LIMIT 1;
2178   IF (FOUND) THEN
2179     RAISE EXCEPTION 'Can not delete, used in Sales Account Assignment';
2180   END IF;
2181
2182 --  Check to see if the passed accnt is used in a A/R Account Assignment
2183   SELECT araccnt_id INTO _check
2184   FROM araccnt
2185   WHERE ( (araccnt_freight_accnt_id=OLD.accnt_id)
2186      OR   (araccnt_ar_accnt_id=OLD.accnt_id)
2187      OR   (araccnt_prepaid_accnt_id=OLD.accnt_id) )
2188   LIMIT 1;
2189   IF (FOUND) THEN
2190     RAISE EXCEPTION 'Can not delete, used in A/R Account Assignment';
2191   END IF;
2192
2193 --  Check to see if the passed accnt is used in a Warehouse
2194   SELECT warehous_id INTO _check
2195   FROM whsinfo
2196   WHERE (warehous_default_accnt_id=OLD.accnt_id)
2197   LIMIT 1;
2198   IF (FOUND) THEN
2199     RAISE EXCEPTION 'Can not delete, used in Site';
2200   END IF;
2201
2202 --  Check to see if the passed accnt is used in a Bank Account
2203   SELECT bankaccnt_id INTO _check
2204   FROM bankaccnt
2205   WHERE (bankaccnt_accnt_id=OLD.accnt_id)
2206   LIMIT 1;
2207   IF (FOUND) THEN
2208     RAISE EXCEPTION 'Can not delete, used in Bank Account';
2209   END IF;
2210
2211 --  Check to see if the passed accnt is used in an Expense Category
2212   SELECT expcat_id INTO _check
2213   FROM expcat
2214   WHERE ( (expcat_exp_accnt_id=OLD.accnt_id)
2215      OR   (expcat_liability_accnt_id=OLD.accnt_id)
2216      OR   (expcat_purchprice_accnt_id=OLD.accnt_id)
2217      OR   (expcat_freight_accnt_id=OLD.accnt_id) )
2218   LIMIT 1;
2219   IF (FOUND) THEN
2220     RAISE EXCEPTION 'Can not delete, used in Expense Category';
2221   END IF;
2222
2223 --  Check to see if the passed accnt is used in a Tax Code
2224   SELECT tax_id INTO _check
2225   FROM tax
2226   WHERE (tax_sales_accnt_id=OLD.accnt_id)
2227   LIMIT 1;
2228   IF (FOUND) THEN
2229     RAISE EXCEPTION 'Can not delete, used in Tax Code';
2230   END IF;
2231
2232 --  Check to see if the passed accnt is used in a Standard Journal Item
2233   SELECT stdjrnlitem_id INTO _check
2234   FROM stdjrnlitem
2235   WHERE (stdjrnlitem_accnt_id=OLD.accnt_id)
2236   LIMIT 1;
2237   IF (FOUND) THEN
2238     RAISE EXCEPTION 'Can not delete, used in Standard Journal Item';
2239   END IF;
2240
2241 --  Check to see if the passed accnt is used in a A/P Account Assignment
2242   SELECT apaccnt_ap_accnt_id INTO _check
2243   FROM apaccnt
2244   WHERE ( (apaccnt_ap_accnt_id=OLD.accnt_id)
2245      OR   (apaccnt_prepaid_accnt_id=OLD.accnt_id)
2246      OR   (apaccnt_discount_accnt_id=OLD.accnt_id) )
2247   LIMIT 1;
2248   IF (FOUND) THEN
2249     RAISE EXCEPTION 'Can not delete, used in A/P Account Assignment';
2250   END IF;
2251
2252 --  Check to see if the passed accnt is used in an A/R Open Item record
2253   SELECT aropen_accnt_id INTO _check
2254     FROM aropen
2255    WHERE (aropen_accnt_id=OLD.accnt_id)
2256    LIMIT 1;
2257   IF (FOUND) THEN
2258     RAISE EXCEPTION 'Can not delete, used in A/R Open Item';
2259   END IF;
2260
2261 --  Check to see if the passed accnt has been used in the G/L
2262   SELECT gltrans_accnt_id INTO _check
2263   FROM gltrans
2264   WHERE (gltrans_accnt_id=OLD.accnt_id)
2265   LIMIT 1;
2266   IF (FOUND) THEN
2267     RAISE EXCEPTION 'Can not delete, used in G/L Transaction';
2268   END IF;
2269
2270   SELECT sltrans_accnt_id INTO _check
2271   FROM sltrans
2272   WHERE (sltrans_accnt_id=OLD.accnt_id)
2273   LIMIT 1;
2274   IF (FOUND) THEN
2275     RAISE EXCEPTION 'Can not delete, used in G/L Journal Transaction';
2276   END IF;
2277
2278   SELECT glseries_accnt_id INTO _check
2279   FROM glseries
2280   WHERE (glseries_accnt_id=OLD.accnt_id)
2281   LIMIT 1;
2282   IF (FOUND) THEN
2283     RAISE EXCEPTION 'Can not delete, used in G/L Series';
2284   END IF;
2285
2286   SELECT trialbal_accnt_id INTO _check
2287   FROM trialbal
2288   WHERE (trialbal_accnt_id=OLD.accnt_id)
2289     AND (trialbal_beginning != 0 OR trialbal_ending != 0)
2290   LIMIT 1;
2291   IF (FOUND) THEN
2292     RAISE EXCEPTION 'Can not delete, used in Trial Balance';
2293   END IF;
2294
2295   SELECT cashrcptmisc_accnt_id INTO _check
2296   FROM cashrcptmisc
2297   WHERE (cashrcptmisc_accnt_id=OLD.accnt_id)
2298   LIMIT 1;
2299   IF (FOUND) THEN
2300     RAISE EXCEPTION 'Can not delete, used in Cash Receipt Misc. Application';
2301   END IF;
2302
2303   -- TODO: everything above here should be replaced by fkeys
2304   IF (OLD.accnt_id = fetchMetricValue('DefaultAPAccount')) THEN
2305     RAISE EXCEPTION 'Cannot delete the default A/P Account [xtuple: accnt, -1, %]',
2306                     _accntnum;
2307   ELSIF (OLD.accnt_id = fetchMetricValue('DefaultARAccount')) THEN
2308     RAISE EXCEPTION 'Cannot delete the default A/R Account [xtuple: accnt, -2, %]',
2309                     _accntnum;
2310   END IF;
2311
2312   RETURN OLD;
2313 END;
2314 $$;
2315
2316
2317 ALTER FUNCTION public._accntdeletetrigger() OWNER TO admin;
2318
2319 --
2320 -- TOC entry 915 (class 1255 OID 146565424)
2321 -- Dependencies: 4536 8
2322 -- Name: _accnttrigger(); Type: FUNCTION; Schema: public; Owner: admin
2323 --
2324
2325 CREATE FUNCTION _accnttrigger() RETURNS trigger
2326     LANGUAGE plpgsql
2327     AS $$
2328 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2329 -- See www.xtuple.com/CPAL for the full text of the software license.
2330 DECLARE
2331   ffSub BOOLEAN;
2332   ffProfit BOOLEAN;
2333   result INTEGER;
2334 BEGIN
2335   SELECT (metric_value='t')
2336     INTO ffSub
2337     FROM metric
2338    WHERE(metric_name='GLFFSubaccounts')
2339    LIMIT 1;
2340   ffSub := COALESCE(ffSub, false);
2341
2342   SELECT (metric_value='t')
2343     INTO ffProfit
2344     FROM metric
2345    WHERE(metric_name='GLFFProfitCenters')
2346    LIMIT 1;
2347   ffProfit := COALESCE(ffSub, false);
2348
2349   IF (NEW.accnt_sub IS NOT NULL AND ffSub = false) THEN
2350     SELECT subaccnt_id
2351       INTO result
2352       FROM subaccnt
2353      WHERE(subaccnt_number=NEW.accnt_sub)
2354      LIMIT 1;
2355     IF (NOT FOUND) THEN
2356       RAISE EXCEPTION 'You must supply a valid Sub Account Number.';
2357     END IF;
2358   END IF;
2359
2360   IF (NEW.accnt_profit IS NOT NULL AND ffProfit = false) THEN
2361     SELECT prftcntr_id
2362       INTO result
2363       FROM prftcntr
2364      WHERE(prftcntr_number=NEW.accnt_profit)
2365      LIMIT 1;
2366     IF (NOT FOUND) THEN
2367       RAISE EXCEPTION 'You must supply a valid Profit Center Number.';
2368     END IF;
2369   END IF;
2370
2371   IF (TG_OP = 'UPDATE') THEN
2372     IF ((NEW.accnt_type != OLD.accnt_type) AND
2373         (SELECT (count(*) > 0) FROM gltrans WHERE (gltrans_accnt_id=NEW.accnt_id))) THEN
2374       RAISE EXCEPTION 'You may not change the account type of an account that has transaction history';
2375     END IF;
2376   END IF;
2377
2378   NEW.accnt_name := formatGlAccount(NEW.accnt_company, NEW.accnt_profit, NEW.accnt_number, NEW.accnt_sub);
2379
2380   RETURN NEW;
2381 END;
2382 $$;
2383
2384
2385 ALTER FUNCTION public._accnttrigger() OWNER TO admin;
2386
2387 --
2388 -- TOC entry 916 (class 1255 OID 146565425)
2389 -- Dependencies: 4536 8
2390 -- Name: _accntuniquetrigger(); Type: FUNCTION; Schema: public; Owner: admin
2391 --
2392
2393 CREATE FUNCTION _accntuniquetrigger() RETURNS trigger
2394     LANGUAGE plpgsql
2395     AS $$
2396 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2397 -- See www.xtuple.com/CPAL for the full text of the software license.
2398 DECLARE
2399 BEGIN
2400   -- This trigger is to protect against id collision on inherited tables since there is no way 
2401   -- to enforce that with regular constraints.  It should be applied to accnt and any table that 
2402   -- inherits accnt.
2403   IF (SELECT (count(accnt_id) > 0) FROM accnt WHERE (accnt_id = NEW.accnt_id)) THEN
2404     RAISE EXCEPTION 'Can not create record on account with duplicate key %.', NEW.accnt_id;
2405   END IF;
2406   
2407   RETURN NEW;
2408 END;
2409 $$;
2410
2411
2412 ALTER FUNCTION public._accntuniquetrigger() OWNER TO admin;
2413
2414 --
2415 -- TOC entry 917 (class 1255 OID 146565426)
2416 -- Dependencies: 4536 8
2417 -- Name: _addrtrigger(); Type: FUNCTION; Schema: public; Owner: admin
2418 --
2419
2420 CREATE FUNCTION _addrtrigger() RETURNS trigger
2421     LANGUAGE plpgsql
2422     AS $$
2423 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
2424 -- See www.xtuple.com/CPAL for the full text of the software license.
2425   DECLARE
2426     _uses       INTEGER := 0;
2427
2428   BEGIN
2429
2430     IF (TG_OP = 'INSERT') THEN
2431       --- clear the number from the issue cache
2432       PERFORM clearNumberIssue('AddressNumber', NEW.addr_number);
2433     ELSE
2434       SELECT count(*) INTO _uses
2435       FROM cntct
2436       WHERE ((cntct_addr_id=OLD.addr_id)
2437         AND   cntct_active);
2438     END IF;
2439
2440     IF (TG_OP = 'UPDATE') THEN
2441       IF (OLD.addr_active AND NOT NEW.addr_active AND _uses > 0) THEN
2442         RAISE EXCEPTION 'Cannot inactivate Address with Active Contacts (%)',
2443                         _uses;
2444       END IF;
2445     ELSIF (TG_OP = 'DELETE') THEN
2446       IF (_uses > 0) THEN
2447         RAISE EXCEPTION 'Cannot Delete Address with Active Contacts (%)',
2448                         _uses;
2449       END IF;
2450
2451       UPDATE cntct SET cntct_addr_id = NULL
2452       WHERE ((cntct_addr_id=OLD.addr_id)
2453         AND  (NOT cntct_active));
2454
2455       RETURN OLD;
2456     END IF;
2457
2458     RETURN NEW;
2459   END;
2460 $$;
2461
2462
2463 ALTER FUNCTION public._addrtrigger() OWNER TO admin;
2464
2465 --
2466 -- TOC entry 918 (class 1255 OID 146565427)
2467 -- Dependencies: 4536 8
2468 -- Name: _alarmbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
2469 --
2470
2471 CREATE FUNCTION _alarmbeforetrigger() RETURNS trigger
2472     LANGUAGE plpgsql
2473     AS $$
2474 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
2475 -- See www.xtuple.com/CPAL for the full text of the software license.
2476   BEGIN
2477     PERFORM clearNumberIssue('AlarmNumber', NEW.alarm_number);
2478
2479     RETURN NEW;
2480   END;
2481 $$;
2482
2483
2484 ALTER FUNCTION public._alarmbeforetrigger() OWNER TO admin;
2485
2486 --
2487 -- TOC entry 919 (class 1255 OID 146565428)
2488 -- Dependencies: 4536 8
2489 -- Name: _apapplytrigger(); Type: FUNCTION; Schema: public; Owner: admin
2490 --
2491
2492 CREATE FUNCTION _apapplytrigger() RETURNS trigger
2493     LANGUAGE plpgsql
2494     AS $$
2495 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2496 -- See www.xtuple.com/CPAL for the full text of the software license.
2497 DECLARE
2498   _tpaid NUMERIC;
2499
2500 BEGIN
2501
2502 -- get the exchange rate for the doc date
2503   IF (TG_OP = 'INSERT') THEN
2504     SELECT currtocurr(NEW.apapply_curr_id,apopen_curr_id,NEW.apapply_amount,NEW.apapply_postdate) 
2505       INTO _tpaid
2506     FROM apopen
2507     WHERE ( apopen_id=NEW.apapply_target_apopen_id );
2508     IF (FOUND) THEN
2509       NEW.apapply_target_paid := _tpaid;
2510     ELSE
2511       RAISE EXCEPTION 'Error calculating paid amount on application';
2512     END IF;
2513   END IF;
2514
2515   RETURN NEW;
2516
2517 END;
2518
2519 $$;
2520
2521
2522 ALTER FUNCTION public._apapplytrigger() OWNER TO admin;
2523
2524 --
2525 -- TOC entry 920 (class 1255 OID 146565429)
2526 -- Dependencies: 4536 8
2527 -- Name: _apopentrigger(); Type: FUNCTION; Schema: public; Owner: admin
2528 --
2529
2530 CREATE FUNCTION _apopentrigger() RETURNS trigger
2531     LANGUAGE plpgsql
2532     AS $$
2533 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2534 -- See www.xtuple.com/CPAL for the full text of the software license.
2535 DECLARE
2536   _currrate NUMERIC;
2537
2538 BEGIN
2539
2540 -- get the base exchange rate for the doc date
2541   IF (TG_OP = 'INSERT' AND NEW.apopen_curr_rate IS NULL) THEN
2542     SELECT curr_rate INTO _currrate
2543     FROM curr_rate
2544     WHERE ( (NEW.apopen_curr_id=curr_id)
2545     AND ( NEW.apopen_docdate BETWEEN curr_effective 
2546                                  AND curr_expires) );
2547     IF (FOUND) THEN
2548       NEW.apopen_curr_rate := _currrate;
2549     ELSE
2550       RAISE EXCEPTION 'Currency exchange rate not found';
2551     END IF;
2552   END IF;
2553
2554   NEW.apopen_open := NEW.apopen_amount > NEW.apopen_paid;
2555
2556   IF (TG_OP = 'INSERT') THEN
2557     IF (NEW.apopen_open=FALSE) THEN
2558       NEW.apopen_status='C';
2559     ELSE
2560       NEW.apopen_status='O';
2561     END IF;
2562
2563      --- clear the number from the issue cache
2564     PERFORM clearNumberIssue('APMemoNumber', NEW.apopen_docnumber);
2565   END IF;
2566   
2567   IF (TG_OP = 'UPDATE') THEN
2568     IF ((OLD.apopen_open=TRUE) AND (NEW.apopen_open=FALSE)) THEN
2569       NEW.apopen_status='C';
2570       IF (NEW.apopen_closedate IS NULL) THEN
2571         NEW.apopen_closedate=CURRENT_DATE;
2572       END IF;
2573     END IF;
2574     
2575     IF ((OLD.apopen_open=FALSE) AND (NEW.apopen_open=TRUE)) THEN
2576       NEW.apopen_status='O';
2577       NEW.apopen_closedate=NULL;
2578     END IF;
2579   END IF;
2580
2581   RETURN NEW;
2582
2583 END;
2584
2585 $$;
2586
2587
2588 ALTER FUNCTION public._apopentrigger() OWNER TO admin;
2589
2590 --
2591 -- TOC entry 913 (class 1255 OID 146565430)
2592 -- Dependencies: 4536 8
2593 -- Name: _arapplytrigger(); Type: FUNCTION; Schema: public; Owner: admin
2594 --
2595
2596 CREATE FUNCTION _arapplytrigger() RETURNS trigger
2597     LANGUAGE plpgsql
2598     AS $$
2599 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2600 -- See www.xtuple.com/CPAL for the full text of the software license.
2601 DECLARE
2602   _tpaid NUMERIC;
2603
2604 BEGIN
2605
2606 -- get the exchange rate for the doc date
2607   IF (TG_OP = 'INSERT') THEN
2608     IF (NEW.arapply_target_doctype != 'K') THEN 
2609       SELECT round(currtocurr(NEW.arapply_curr_id,aropen_curr_id,NEW.arapply_applied,NEW.arapply_postdate),2) 
2610         INTO NEW.arapply_target_paid
2611       FROM aropen
2612       WHERE ( aropen_id=NEW.arapply_target_aropen_id );
2613     ELSE
2614       SELECT round(currtocurr(NEW.arapply_curr_id,aropen_curr_id,NEW.arapply_applied,NEW.arapply_postdate),2) 
2615         INTO NEW.arapply_target_paid
2616       FROM aropen
2617       WHERE ( aropen_id=NEW.arapply_source_aropen_id );
2618     END IF;
2619     IF NOT FOUND THEN
2620       NEW.arapply_target_paid := NEW.arapply_applied;
2621     END IF;
2622   END IF;
2623
2624   RETURN NEW;
2625
2626 END;
2627
2628 $$;
2629
2630
2631 ALTER FUNCTION public._arapplytrigger() OWNER TO admin;
2632
2633 --
2634 -- TOC entry 903 (class 1255 OID 146565431)
2635 -- Dependencies: 4536 8
2636 -- Name: _aropenaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
2637 --
2638
2639 CREATE FUNCTION _aropenaftertrigger() RETURNS trigger
2640     LANGUAGE plpgsql
2641     AS $$
2642 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2643 -- See www.xtuple.com/CPAL for the full text of the software license.
2644 DECLARE
2645   _openAmount NUMERIC;
2646   _lateCount INTEGER := 0;
2647   _graceDays INTEGER;
2648   _checkLate BOOLEAN := false;
2649   _checkLimit BOOLEAN := false;
2650   _id INTEGER;
2651 BEGIN
2652
2653   IF (TG_OP = 'INSERT') THEN
2654     _id := NEW.aropen_id;
2655   ELSE
2656     _id := OLD.aropen_id;
2657   END IF;
2658 -- If metric is set then auto close any associated incidents when AR is closed
2659   IF (fetchMetricBool('AutoCloseARIncident')) THEN
2660     IF (NEW.aropen_open = FALSE) THEN
2661       UPDATE incdt SET incdt_status='L' WHERE (incdt_aropen_id=_id);
2662     END IF;
2663   END IF;
2664
2665   RETURN NEW;
2666
2667 END;
2668 $$;
2669
2670
2671 ALTER FUNCTION public._aropenaftertrigger() OWNER TO admin;
2672
2673 --
2674 -- TOC entry 904 (class 1255 OID 146565432)
2675 -- Dependencies: 4536 8
2676 -- Name: _aropentrigger(); Type: FUNCTION; Schema: public; Owner: admin
2677 --
2678
2679 CREATE FUNCTION _aropentrigger() RETURNS trigger
2680     LANGUAGE plpgsql
2681     AS $$
2682 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2683 -- See www.xtuple.com/CPAL for the full text of the software license.
2684 DECLARE
2685   _openAmount NUMERIC;
2686   _p RECORD;
2687   _lateCount INTEGER := 0;
2688   _graceDays INTEGER;
2689   _checkLate BOOLEAN := false;
2690   _checkLimit BOOLEAN := false;
2691   _id INTEGER;
2692   _currRate NUMERIC;
2693 BEGIN
2694   -- Checks
2695   -- Start with privileges
2696   IF ( (NOT checkPrivilege('MaintainARMemos')) AND
2697        (NOT checkPrivilege('PostMiscInvoices')) AND
2698        (NOT checkPrivilege('PostARDocuments')) ) THEN
2699     RAISE EXCEPTION 'You do not have privileges to maintain A/R Memos.';
2700   END IF;
2701
2702   IF ( (NEW.aropen_docnumber IS NULL) OR (LENGTH(NEW.aropen_docnumber) = 0) ) THEN
2703     RAISE EXCEPTION 'You must enter a valid Document # for this A/R Memo.';
2704   END IF;
2705
2706   IF ( (NEW.aropen_amount IS NOT NULL) AND (NEW.aropen_amount < 0) ) THEN
2707     RAISE EXCEPTION 'You must enter a positive Amount for this A/R Memo.';
2708   END IF;
2709
2710   IF (TG_OP IN ('INSERT', 'UPDATE') AND NEW.aropen_cust_id < 0) THEN
2711     RAISE NOTICE 'Fixing deprecated use of negative aropen_cust_id';
2712     NEW.aropen_cust_id := NULL;
2713   END IF;
2714
2715   IF (TG_OP IN ('INSERT', 'UPDATE') AND NEW.aropen_salesrep_id < 0) THEN
2716     RAISE NOTICE 'Fixing deprecated use of negative aropen_salesrep_id';
2717     NEW.aropen_salesrep_id := NULL;
2718   END IF;
2719
2720   IF (TG_OP = 'INSERT') THEN
2721     SELECT aropen_id INTO _id
2722     FROM aropen
2723     WHERE ( (aropen_doctype=NEW.aropen_doctype)
2724       AND   (aropen_docnumber=NEW.aropen_docnumber) )
2725     LIMIT 1;
2726     IF (FOUND) THEN
2727       RAISE EXCEPTION 'This Document Type/Number already exists. You may not enter a duplicate A/R Memo.';
2728     END IF;
2729
2730     --- clear the number from the issue cache if applicable
2731     PERFORM clearNumberIssue('ARMemoNumber', NEW.aropen_docnumber);
2732   END IF;
2733
2734 -- Determine the number of late invoices
2735   IF ( SELECT (metric_value='t')
2736          FROM metric
2737         WHERE(metric_name='AutoCreditWarnLateCustomers')) THEN
2738     _checkLate := true;
2739
2740     SELECT COALESCE(metric_value::integer, _graceDays)
2741       INTO _graceDays
2742       FROM metric
2743      WHERE(metric_name='DefaultAutoCreditWarnGraceDays');
2744     IF (NOT FOUND) THEN
2745       _graceDays := 30;
2746     END IF;
2747     SELECT COALESCE(cust_gracedays, _graceDays)
2748       INTO _graceDays
2749       FROM custinfo
2750      WHERE(cust_id=NEW.aropen_cust_id);
2751     IF (NOT FOUND) THEN
2752       _graceDays := 30;
2753     END IF;
2754
2755     SELECT count(aropen_id)
2756       INTO _lateCount
2757       FROM aropen
2758      WHERE((NEW.aropen_cust_id = aropen_cust_id)
2759        AND (aropen_open)
2760        AND (aropen_amount > aropen_paid)
2761        AND (aropen_doctype IN ('I', 'D'))
2762        AND (aropen_duedate < (CURRENT_DATE - _graceDays)));
2763
2764   --  Adjust _lateCount if late invoice being paid
2765     IF ( (NEW.aropen_paid = NEW.aropen_amount)
2766      AND (NEW.aropen_doctype IN ('I', 'D'))
2767      AND (NEW.aropen_duedate < (CURRENT_DATE - _graceDays))) THEN
2768       _lateCount := _lateCount - 1;
2769     END IF;
2770   END IF;
2771
2772 -- get the base exchange rate for the doc date
2773   IF (TG_OP = 'INSERT' AND NEW.aropen_curr_rate IS NULL) THEN
2774     SELECT curr_rate INTO _currrate
2775       FROM curr_rate
2776     WHERE ( (NEW.aropen_curr_id=curr_id)
2777       AND ( NEW.aropen_docdate BETWEEN curr_effective 
2778                                    AND curr_expires) );
2779     IF (FOUND) THEN
2780       NEW.aropen_curr_rate := _currrate;
2781     ELSE
2782       RAISE EXCEPTION 'Currency exchange rate not found';
2783     END IF;
2784   END IF;
2785
2786 --  Close this aropen if it is paid
2787   IF (NEW.aropen_paid = NEW.aropen_amount) THEN
2788     NEW.aropen_open=FALSE;
2789
2790 --  Remove any aropenalloc regards that reference this aropen item
2791     DELETE FROM aropenalloc WHERE (aropenalloc_aropen_id=NEW.aropen_id);
2792   END IF;
2793
2794   IF (TG_OP = 'INSERT') THEN
2795     IF (NEW.aropen_open=FALSE) 
2796     AND (NEW.aropen_closedate IS NULL) THEN
2797       NEW.aropen_closedate=current_date;
2798     END IF;
2799   END IF;
2800   
2801   IF (TG_OP = 'UPDATE') THEN
2802     IF ((OLD.aropen_open=TRUE) 
2803     AND (NEW.aropen_open=FALSE) 
2804     AND (NEW.aropen_closedate IS NULL)) THEN
2805       NEW.aropen_closedate=current_date;
2806     END IF;
2807   END IF;
2808
2809 --  Only check if the customer in question has a non-zero Credit Limit
2810   SELECT cust_id, cust_creditlmt, cust_creditstatus,
2811          cust_autoupdatestatus, cust_autoholdorders INTO _p
2812   FROM custinfo
2813   WHERE (cust_id=NEW.aropen_cust_id);
2814   IF (_p.cust_creditlmt > 0) THEN
2815     _checkLimit := true;
2816
2817     SELECT COALESCE(SUM( CASE WHEN (aropen_doctype IN ('I', 'D')) THEN (aropen_amount - aropen_paid)
2818                      ELSE ((aropen_amount - aropen_paid) * -1)
2819                 END ), 0.0) INTO _openAmount
2820     FROM aropen AS current
2821     WHERE ( (current.aropen_cust_id=NEW.aropen_cust_id)
2822      AND (current.aropen_open)
2823      AND (current.aropen_id <> NEW.aropen_id) );
2824
2825 --  Add in the value of the current aropen item
2826     IF (NEW.aropen_doctype IN ('I', 'D')) THEN
2827       _openAmount := (_openAmount + (NEW.aropen_amount - NEW.aropen_paid));
2828     ELSE
2829       _openAmount := (_openAmount - (NEW.aropen_amount - NEW.aropen_paid));
2830     END IF;
2831   ELSE
2832     _openAmount := 0;
2833   END IF;
2834
2835   IF (_checkLimit OR _checkLate) THEN
2836 --  Handle a Customer that is going under its credit limit
2837     IF ((_p.cust_creditlmt >= _openAmount) AND (_lateCount <= 0)) THEN
2838
2839 --  Handle the Customer Status
2840       IF ( (_p.cust_autoupdatestatus) AND (_p.cust_creditstatus='W') ) THEN
2841         UPDATE custinfo
2842         SET cust_creditstatus='G'
2843         WHERE (cust_id=NEW.aropen_cust_id);
2844       END IF;
2845
2846 --  Handle the open Sales Orders
2847       IF (_p.cust_autoholdorders) THEN
2848         UPDATE cohead
2849         SET cohead_holdtype='N'
2850         FROM coitem
2851         WHERE ( (coitem_cohead_id=cohead_id)
2852          AND (cohead_holdtype='C')
2853          AND (coitem_status='O')
2854          AND (cohead_cust_id=_p.cust_id) );
2855       END IF;
2856
2857 --  Handle a Customer that is going over its credit limit
2858     ELSIF ((_p.cust_creditlmt < _openAmount) OR (_lateCount > 0)) THEN
2859
2860 --  Handle the Customer Status
2861       IF ( (_p.cust_autoupdatestatus) AND (_p.cust_creditstatus = 'G') ) THEN
2862         UPDATE custinfo
2863         SET cust_creditstatus='W'
2864         WHERE (cust_id=NEW.aropen_cust_id);
2865       END IF;
2866
2867 --  Handle the open Sales Orders
2868       IF (_p.cust_autoholdorders) THEN
2869         UPDATE cohead
2870         SET cohead_holdtype='C'
2871         FROM coitem
2872         WHERE ( (coitem_cohead_id=cohead_id)
2873          AND (cohead_holdtype='N')
2874          AND (coitem_status='O')
2875          AND (cohead_cust_id=_p.cust_id) );
2876       END IF;
2877
2878     END IF;
2879
2880   END IF;
2881
2882   RETURN NEW;
2883
2884 END;
2885 $$;
2886
2887
2888 ALTER FUNCTION public._aropentrigger() OWNER TO admin;
2889
2890 --
2891 -- TOC entry 921 (class 1255 OID 146565434)
2892 -- Dependencies: 4536 8
2893 -- Name: _bomheadtrigger(); Type: FUNCTION; Schema: public; Owner: admin
2894 --
2895
2896 CREATE FUNCTION _bomheadtrigger() RETURNS trigger
2897     LANGUAGE plpgsql
2898     AS $$
2899 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2900 -- See www.xtuple.com/CPAL for the full text of the software license.
2901 DECLARE
2902   _revid INTEGER;
2903   _check TEXT;
2904 BEGIN
2905 -- Privilege Checks
2906   IF (NOT checkPrivilege('MaintainBOMs')) THEN
2907     RAISE EXCEPTION 'You do not have privileges to maintain Bills of Material.';
2908   END IF;
2909   
2910   RETURN NEW;
2911 END;
2912 $$;
2913
2914
2915 ALTER FUNCTION public._bomheadtrigger() OWNER TO admin;
2916
2917 --
2918 -- TOC entry 922 (class 1255 OID 146565435)
2919 -- Dependencies: 4536 8
2920 -- Name: _bomitemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
2921 --
2922
2923 CREATE FUNCTION _bomitemaftertrigger() RETURNS trigger
2924     LANGUAGE plpgsql
2925     AS $$
2926 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
2927 -- See www.xtuple.com/CPAL for the full text of the software license.
2928 DECLARE
2929
2930 BEGIN
2931
2932   IF ( SELECT fetchMetricBool('ItemChangeLog') ) THEN
2933     IF (TG_OP = 'INSERT') THEN
2934       PERFORM postComment('ChangeLog', 'BMI', NEW.bomitem_id, ('Created BOM Item Sequence ' || NEW.bomitem_seqnumber::TEXT));
2935
2936     ELSIF (TG_OP = 'UPDATE') THEN
2937       IF (NEW.bomitem_effective <> OLD.bomitem_effective) THEN
2938         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2939                              ( 'Effective Date Changed from ' || formatDate(OLD.bomitem_effective, 'Always') ||
2940                                ' to ' || formatDate(NEW.bomitem_effective, 'Always' ) ) );
2941       END IF;
2942
2943       IF (NEW.bomitem_expires <> OLD.bomitem_expires) THEN
2944         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2945                              ( 'Expiration Date Changed from ' || formatDate(OLD.bomitem_expires, 'Never') ||
2946                                ' to ' || formatDate(NEW.bomitem_expires, 'Never' ) ) );
2947       END IF;
2948
2949       IF (NEW.bomitem_qtyfxd <> OLD.bomitem_qtyfxd) THEN
2950         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2951                              ( 'Fixed Qty. Changed from ' || formatQtyPer(OLD.bomitem_qtyfxd) ||
2952                                ' to ' || formatQtyPer(NEW.bomitem_qtyfxd ) ) );
2953       END IF;
2954
2955       IF (NEW.bomitem_qtyper <> OLD.bomitem_qtyper) THEN
2956         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2957                              ( 'Qty. Per Changed from ' || formatQtyPer(OLD.bomitem_qtyper) ||
2958                                ' to ' || formatQtyPer(NEW.bomitem_qtyper ) ) );
2959       END IF;
2960
2961       IF (NEW.bomitem_scrap <> OLD.bomitem_scrap) THEN
2962         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2963                              ( 'Scrap % Changed from ' || formatPrcnt(OLD.bomitem_scrap) ||
2964                                ' to ' || formatPrcnt(NEW.bomitem_scrap ) ) );
2965       END IF;
2966
2967       IF (NEW.bomitem_issuemethod <> OLD.bomitem_issuemethod) THEN
2968         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2969                              ( 'Issue Method Changed from ' || (CASE WHEN(OLD.bomitem_issuemethod='S') THEN 'Push'
2970                                                                      WHEN(OLD.bomitem_issuemethod='L') THEN 'Pull'
2971                                                                      WHEN(OLD.bomitem_issuemethod='M') THEN 'Mixed'
2972                                                                      ELSE OLD.bomitem_issuemethod END) ||
2973                                ' to ' || (CASE WHEN(NEW.bomitem_issuemethod='S') THEN 'Push'
2974                                                WHEN(NEW.bomitem_issuemethod='L') THEN 'Pull'
2975                                                WHEN(NEW.bomitem_issuemethod='M') THEN 'Mixed'
2976                                                ELSE NEW.bomitem_issuemethod END) ) );
2977       END IF;
2978
2979       IF (NEW.bomitem_ecn <> OLD.bomitem_ecn) THEN
2980         PERFORM postComment( 'ChangeLog', 'BMI', NEW.bomitem_id,
2981                              ( 'ECN Changed from ' || OLD.bomitem_ecn ||
2982                                ' to ' || NEW.bomitem_ecn ) );
2983       END IF;
2984
2985       IF (OLD.bomitem_createwo <> NEW.bomitem_createwo) THEN
2986         IF (NEW.bomitem_createwo) THEN
2987           PERFORM postComment('ChangeLog', 'BMI', NEW.bomitem_id, 'Create Child W/O activated');
2988         ELSE
2989           PERFORM postComment('ChangeLog', 'BMI', NEW.bomitem_id, 'Create Child W/O deactivated');
2990         END IF;
2991       END IF;
2992
2993       IF (OLD.bomitem_issuewo <> NEW.bomitem_issuewo) THEN
2994         IF (NEW.bomitem_issuewo) THEN
2995           PERFORM postComment('ChangeLog', 'BMI', NEW.bomitem_id, 'Issue Child W/O activated');
2996         ELSE
2997           PERFORM postComment('ChangeLog', 'BMI', NEW.bomitem_id, 'Issue Child W/O deactivated');
2998         END IF;
2999       END IF;
3000
3001     END IF;
3002   END IF;
3003
3004   IF (TG_OP = 'DELETE') THEN
3005     DELETE FROM comment
3006      WHERE ( (comment_source='BMI')
3007        AND   (comment_source_id=OLD.bomitem_id) );
3008
3009     RETURN OLD;
3010   END IF;
3011
3012   RETURN NEW;
3013 END;
3014 $$;
3015
3016
3017 ALTER FUNCTION public._bomitemaftertrigger() OWNER TO admin;
3018
3019 --
3020 -- TOC entry 923 (class 1255 OID 146565436)
3021 -- Dependencies: 4536 8
3022 -- Name: _bomitembeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
3023 --
3024
3025 CREATE FUNCTION _bomitembeforedeletetrigger() RETURNS trigger
3026     LANGUAGE plpgsql
3027     AS $$
3028 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3029 -- See www.xtuple.com/CPAL for the full text of the software license.
3030 DECLARE
3031 BEGIN
3032
3033   DELETE FROM comment
3034    WHERE ( (comment_source='BMI')
3035      AND   (comment_source_id=OLD.bomitem_id) );
3036
3037   RETURN OLD;
3038 END;
3039 $$;
3040
3041
3042 ALTER FUNCTION public._bomitembeforedeletetrigger() OWNER TO admin;
3043
3044 --
3045 -- TOC entry 924 (class 1255 OID 146565437)
3046 -- Dependencies: 4536 8
3047 -- Name: _bomitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
3048 --
3049
3050 CREATE FUNCTION _bomitembeforetrigger() RETURNS trigger
3051     LANGUAGE plpgsql
3052     AS $$
3053 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3054 -- See www.xtuple.com/CPAL for the full text of the software license.
3055 DECLARE
3056   _bomworksetid INTEGER;
3057   _bomworkid INTEGER;
3058   _seqNumber INTEGER;
3059   _parentItem RECORD;
3060 BEGIN
3061
3062   -- Privilege Checks
3063   IF (NOT checkPrivilege('MaintainBOMs')) THEN
3064     RAISE EXCEPTION 'You do not have privileges to maintain Bills of Material.';
3065   END IF;
3066
3067   -- Cache Parent Item
3068    SELECT * INTO _parentItem
3069    FROM item
3070    WHERE (item_id=NEW.bomitem_parent_item_id);
3071
3072   IF (TG_OP = 'INSERT') THEN
3073     --  Make sure that the parent and component are not the same
3074     IF (NEW.bomitem_parent_item_id = NEW.bomitem_item_id) THEN
3075       RAISE EXCEPTION 'BOM Item Parent and Component Item cannot be the same. [xtuple: createBOMItem, -1]';
3076     END IF;
3077
3078     --  Make sure that the parent is not used in the component at some level
3079     SELECT indentedWhereUsed(NEW.bomitem_parent_item_id) INTO _bomworksetid;
3080     SELECT bomwork_id INTO _bomworkid
3081     FROM bomwork
3082     WHERE ((bomwork_set_id=_bomworksetid)
3083       AND  (bomwork_item_id=NEW.bomitem_item_id))
3084     LIMIT 1;
3085     IF (FOUND) THEN
3086       PERFORM deleteBOMWorkset(_bomworksetid);
3087       RAISE EXCEPTION 'BOM Item Parent is used by Component, BOM is recursive. [xtuple: createBOMItem, -2]';
3088     END IF;
3089
3090     PERFORM deleteBOMWorkset(_bomworksetid);
3091
3092     -- Set defaults
3093     NEW.bomitem_rev_id := COALESCE(NEW.bomitem_rev_id, -1);
3094     NEW.bomitem_booitem_seq_id := COALESCE(NEW.bomitem_booitem_seq_id, -1);
3095     NEW.bomitem_schedatwooper := COALESCE(NEW.bomitem_schedatwooper, FALSE);
3096     IF (NEW.bomitem_seqnumber IS NULL) THEN
3097       --  Grab the next Sequence Number, if any
3098       SELECT MAX(bomitem_seqnumber) INTO _seqNumber
3099       FROM bomitem(NEW.bomitem_parent_item_id,NEW.bomitem_rev_id);
3100       IF (_seqNumber IS NOT NULL) THEN
3101         NEW.bomitem_seqnumber := (_seqNumber + 10);
3102       ELSE
3103         NEW.bomitem_seqnumber := 10;
3104       END IF;
3105     END IF;
3106   END IF; -- end Insert specific
3107
3108   IF (TG_OP = 'UPDATE') THEN
3109     -- Disallow changes that would compromise revision control integrity
3110     IF (NEW.bomitem_parent_item_id != OLD.bomitem_parent_item_id) THEN
3111       RAISE EXCEPTION 'Parent Item ID may not be changed.';
3112     END IF;
3113
3114     IF (NEW.bomitem_item_id != OLD.bomitem_item_id) THEN
3115       RAISE EXCEPTION 'Item ID may not be changed.';
3116     END IF;
3117
3118     IF ((fetchMetricBool('RevControl')) AND (OLD.bomitem_rev_id > -1)) THEN
3119       IF (SELECT (rev_status = 'I') FROM rev WHERE (rev_id=OLD.bomitem_rev_id)) THEN
3120         RAISE EXCEPTION 'Bill of material is Inactive and may not be modified';
3121       END IF;
3122     END IF;
3123   END IF; -- end Update specific
3124
3125   -- Check for valid UOM
3126   IF (SELECT (count(*) != 1)
3127       FROM
3128              (SELECT uom_id
3129                 FROM item JOIN uom ON (item_inv_uom_id=uom_id)
3130                 WHERE(item_id=NEW.bomitem_item_id)
3131               UNION 
3132               SELECT uom_id
3133                 FROM item JOIN itemuomconv ON (itemuomconv_item_id=item_id)
3134                           JOIN uom ON (itemuomconv_to_uom_id=uom_id),
3135                      itemuom, uomtype 
3136                WHERE((itemuomconv_from_uom_id=item_inv_uom_id)
3137                  AND (item_id=NEW.bomitem_item_id) 
3138                  AND (itemuom_itemuomconv_id=itemuomconv_id) 
3139                  AND (uomtype_id=itemuom_uomtype_id) 
3140                  AND (uomtype_name='MaterialIssue'))
3141               UNION 
3142               SELECT uom_id
3143                 FROM item JOIN itemuomconv ON (itemuomconv_item_id=item_id)
3144                           JOIN uom ON (itemuomconv_from_uom_id=uom_id),
3145                      itemuom, uomtype 
3146                WHERE((itemuomconv_to_uom_id=item_inv_uom_id)
3147                  AND (item_id=NEW.bomitem_item_id) 
3148                  AND (itemuom_itemuomconv_id=itemuomconv_id) 
3149                  AND (uomtype_id=itemuom_uomtype_id) 
3150                  AND (uomtype_name='MaterialIssue'))) AS data
3151         WHERE (uom_id=NEW.bomitem_uom_id)) THEN
3152     RAISE EXCEPTION 'Unit of Measure Invalid for Material Issue.';
3153   END IF;
3154
3155 -- Disallow configuration parameters if parent is not a job item
3156    IF (NEW.bomitem_char_id IS NOT NULL) THEN
3157      IF (NOT _parentItem.item_config) THEN
3158        RAISE EXCEPTION 'Configuration characteristics may only be defined for Configured Items';
3159      END IF;
3160    END IF;
3161
3162   -- Kit items must be sold and not kits themselves
3163   IF (_parentItem.item_type = 'K') THEN
3164     IF (SELECT (COUNT(item_id) = 0)
3165           FROM item
3166          WHERE ((item_id=NEW.bomitem_item_id)
3167            AND (item_sold)
3168            AND (item_type != 'K'))) THEN
3169        RAISE EXCEPTION 'Bill of Material Items for kits must be sold and not kits themselves';
3170      END IF;
3171    END IF;
3172
3173   -- Over ride logic to disallow invalid data
3174   IF (NEW.bomitem_createwo) THEN
3175     IF (SELECT (item_type != 'M') 
3176           FROM item 
3177          WHERE (item_id=NEW.bomitem_item_id)) THEN
3178       NEW.bomitem_createwo := FALSE;
3179     END IF;
3180     IF (NEW.bomitem_booitem_seq_id = -1) THEN
3181       NEW.bomitem_schedatwooper := FALSE;
3182     END IF;
3183   END IF;
3184
3185   NEW.bomitem_moddate := COALESCE(NEW.bomitem_moddate, CURRENT_DATE);
3186
3187   RETURN NEW;
3188 END;
3189 $$;
3190
3191
3192 ALTER FUNCTION public._bomitembeforetrigger() OWNER TO admin;
3193
3194 --
3195 -- TOC entry 925 (class 1255 OID 146565439)
3196 -- Dependencies: 4536 8
3197 -- Name: _bomitemsubtrigger(); Type: FUNCTION; Schema: public; Owner: admin
3198 --
3199
3200 CREATE FUNCTION _bomitemsubtrigger() RETURNS trigger
3201     LANGUAGE plpgsql
3202     AS $$
3203 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3204 -- See www.xtuple.com/CPAL for the full text of the software license.
3205 BEGIN
3206
3207 -- Privilege Checks
3208   IF (NOT checkPrivilege('MaintainBOMs')) THEN
3209     RAISE EXCEPTION 'You do not have privileges to maintain Bills of Material.';
3210   END IF;
3211
3212   IF (TG_OP = 'DELETE') THEN
3213     RETURN OLD;
3214   ELSE
3215     RETURN NEW;
3216   END IF;
3217
3218 END;
3219 $$;
3220
3221
3222 ALTER FUNCTION public._bomitemsubtrigger() OWNER TO admin;
3223
3224 --
3225 -- TOC entry 926 (class 1255 OID 146565440)
3226 -- Dependencies: 4536 8
3227 -- Name: _cashrcptitemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
3228 --
3229
3230 CREATE FUNCTION _cashrcptitemaftertrigger() RETURNS trigger
3231     LANGUAGE plpgsql
3232     AS $$
3233 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3234 -- See www.xtuple.com/CPAL for the full text of the software license.
3235 DECLARE
3236   _total      NUMERIC;
3237
3238 BEGIN
3239
3240   -- Checks
3241   -- Total Over Application Warning
3242   SELECT (cashrcpt_amount - SUM(COALESCE(cashrcptitem_amount, 0))) INTO _total
3243   FROM cashrcptitem JOIN cashrcpt ON (cashrcpt_id=cashrcptitem_cashrcpt_id)
3244   WHERE (cashrcptitem_cashrcpt_id=NEW.cashrcptitem_cashrcpt_id)
3245   GROUP BY cashrcpt_amount;
3246   IF (_total < 0.0) THEN
3247     RAISE WARNING 'Warning -- the Cash Receipt has been over applied.';
3248   END IF;
3249   
3250   RETURN NEW;
3251
3252 END;
3253 $$;
3254
3255
3256 ALTER FUNCTION public._cashrcptitemaftertrigger() OWNER TO admin;
3257
3258 --
3259 -- TOC entry 927 (class 1255 OID 146565441)
3260 -- Dependencies: 4536 8
3261 -- Name: _cashrcptitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
3262 --
3263
3264 CREATE FUNCTION _cashrcptitemtrigger() RETURNS trigger
3265     LANGUAGE plpgsql
3266     AS $$
3267 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3268 -- See www.xtuple.com/CPAL for the full text of the software license.
3269 DECLARE
3270   _check      BOOLEAN;
3271   _openAmount NUMERIC;
3272
3273 BEGIN
3274
3275   -- Checks
3276   -- Start with Privileges
3277   IF (TG_OP = 'INSERT') THEN
3278     SELECT checkPrivilege('MaintainCashReceipts') INTO _check;
3279     IF NOT (_check) THEN
3280       RAISE EXCEPTION 'You do not have privileges to add a new Cash Receipt Application.';
3281     END IF;
3282   ELSE
3283     SELECT checkPrivilege('MaintainCashReceipts') INTO _check;
3284     IF NOT (_check) THEN
3285       RAISE EXCEPTION 'You do not have privileges to alter a Cash Receipt Application.';
3286     END IF;
3287   END IF;
3288
3289   -- Over Application
3290   SELECT round(currToCurr(aropen_curr_id, cashrcpt_curr_id,
3291                aropen_amount - aropen_paid, cashrcpt_distdate) -
3292                COALESCE((SELECT SUM(cashrcptitem_amount)
3293                            FROM cashrcptitem, cashrcpt
3294                            WHERE ((cashrcpt_id=cashrcptitem_cashrcpt_id)
3295                              AND  (NOT cashrcpt_void)
3296                              AND  (NOT cashrcpt_posted)
3297                              AND  (cashrcpt_id != NEW.cashrcptitem_cashrcpt_id)
3298                              AND  (cashrcptitem_aropen_id=NEW.cashrcptitem_aropen_id))), 0),2) INTO _openAmount
3299   FROM aropen, cashrcpt
3300   WHERE ( (aropen_id=NEW.cashrcptitem_aropen_id)
3301     AND   (cashrcpt_id=NEW.cashrcptitem_cashrcpt_id) );
3302   IF (NEW.cashrcptitem_amount > _openAmount) THEN
3303     RAISE EXCEPTION 'You may not apply more than the balance of this item.';
3304   END IF;
3305
3306
3307   RETURN NEW;
3308
3309 END;
3310 $$;
3311
3312
3313 ALTER FUNCTION public._cashrcptitemtrigger() OWNER TO admin;
3314
3315 --
3316 -- TOC entry 928 (class 1255 OID 146565442)
3317 -- Dependencies: 4536 8
3318 -- Name: _cashrcptmisctrigger(); Type: FUNCTION; Schema: public; Owner: admin
3319 --
3320
3321 CREATE FUNCTION _cashrcptmisctrigger() RETURNS trigger
3322     LANGUAGE plpgsql
3323     AS $$
3324 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3325 -- See www.xtuple.com/CPAL for the full text of the software license.
3326 DECLARE
3327   _check      BOOLEAN;
3328
3329 BEGIN
3330
3331   -- Checks
3332   -- Start with Privileges
3333   IF (TG_OP = 'INSERT') THEN
3334     SELECT checkPrivilege('MaintainCashReceipts') INTO _check;
3335     IF NOT (_check) THEN
3336       RAISE EXCEPTION 'You do not have privileges to add a new Cash Receipt Misc. Application.';
3337     END IF;
3338   ELSE
3339     SELECT checkPrivilege('MaintainCashReceipts') INTO _check;
3340     IF NOT (_check) THEN
3341       RAISE EXCEPTION 'You do not have privileges to alter a Cash Receipt Misc. Application.';
3342     END IF;
3343   END IF;
3344
3345   -- Account is required
3346   IF (NEW.cashrcptmisc_accnt_id IS NULL) THEN
3347     RAISE EXCEPTION 'You must supply a valid GL Account.';
3348   END IF;
3349
3350   -- Amount is required
3351   IF (COALESCE(NEW.cashrcptmisc_amount, 0) = 0) THEN
3352     RAISE EXCEPTION 'You must supply a valid Amount.';
3353   END IF;
3354
3355   RETURN NEW;
3356
3357 END;
3358 $$;
3359
3360
3361 ALTER FUNCTION public._cashrcptmisctrigger() OWNER TO admin;
3362
3363 --
3364 -- TOC entry 929 (class 1255 OID 146565443)
3365 -- Dependencies: 4536 8
3366 -- Name: _cashrcpttrigger(); Type: FUNCTION; Schema: public; Owner: admin
3367 --
3368
3369 CREATE FUNCTION _cashrcpttrigger() RETURNS trigger
3370     LANGUAGE plpgsql
3371     AS $$
3372 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3373 -- See www.xtuple.com/CPAL for the full text of the software license.
3374 DECLARE
3375   _check      BOOLEAN;
3376   _checkId    INTEGER;
3377   _currId     INTEGER;
3378   _bankCurrId INTEGER;
3379   _currrate   NUMERIC;
3380
3381 BEGIN
3382
3383   -- Checks
3384   -- Start with privileges
3385   IF (TG_OP = 'INSERT') THEN
3386     SELECT checkPrivilege('MaintainCashReceipts') INTO _check;
3387     IF NOT (_check) THEN
3388       RAISE EXCEPTION 'You do not have privileges to add new Cash Receipts.';
3389     END IF;
3390   ELSE
3391     SELECT checkPrivilege('MaintainCashReceipts') INTO _check;
3392     IF NOT (_check) THEN
3393       RAISE EXCEPTION 'You do not have privileges to alter a Cash Receipt.';
3394     END IF;
3395   END IF;
3396
3397   -- Currency must be same as Bank Currency
3398   IF (TG_OP = 'INSERT') THEN
3399     _currId = COALESCE(NEW.cashrcpt_curr_id, basecurrid());
3400
3401      --- clear the number from the issue cache
3402     PERFORM clearNumberIssue('CashRcptNumber', NEW.cashrcpt_number);
3403   ELSE
3404     _currId = NEW.cashrcpt_curr_id;
3405   END IF;
3406
3407 -- get the base exchange rate for the dist date
3408   IF (NEW.cashrcpt_curr_rate IS NULL) THEN
3409     SELECT curr_rate INTO _currrate
3410     FROM curr_rate
3411     WHERE ( (NEW.cashrcpt_curr_id=curr_id)
3412       AND ( NEW.cashrcpt_distdate BETWEEN curr_effective 
3413                                  AND curr_expires) );
3414     IF (FOUND) THEN
3415       NEW.cashrcpt_curr_rate := _currrate;
3416     ELSE
3417       RAISE EXCEPTION 'Currency exchange rate not found';
3418     END IF;
3419   END IF;
3420
3421   -- Create CashReceiptPosted Event
3422   IF (TG_OP = 'UPDATE') THEN
3423     IF (OLD.cashrcpt_posted=FALSE AND NEW.cashrcpt_posted=TRUE) THEN
3424       PERFORM postEvent('CashReceiptPosted', NULL, NEW.cashrcpt_id,
3425                         NULL,
3426                         (cust_number || '-' ||
3427                         NEW.cashrcpt_docnumber || ' ' ||
3428                         currConcat(NEW.cashrcpt_curr_id) ||
3429                         formatMoney(NEW.cashrcpt_amount)),
3430                         NULL, NULL, NULL, NULL)
3431       FROM custinfo
3432       WHERE (cust_id=NEW.cashrcpt_cust_id);
3433     END IF;
3434   END IF;
3435
3436   RETURN NEW;
3437
3438 END;
3439 $$;
3440
3441
3442 ALTER FUNCTION public._cashrcpttrigger() OWNER TO admin;
3443
3444 --
3445 -- TOC entry 931 (class 1255 OID 146565444)
3446 -- Dependencies: 4536 8
3447 -- Name: _ccardtrigger(); Type: FUNCTION; Schema: public; Owner: admin
3448 --
3449
3450 CREATE FUNCTION _ccardtrigger() RETURNS trigger
3451     LANGUAGE plpgsql
3452     AS $$
3453 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3454 -- See www.xtuple.com/CPAL for the full text of the software license.
3455 DECLARE
3456
3457 BEGIN
3458
3459   New.ccard_lastupdated := current_timestamp;
3460   New.ccard_last_updated_by_username := getEffectiveXtUser();
3461
3462   IF (TG_OP = 'UPDATE') THEN
3463     INSERT INTO ccardaud
3464          VALUES (nextval('ccardaud_ccardaud_id_seq'), NEW.ccard_id,
3465                  OLD.ccard_seq, NEW.ccard_seq, OLD.ccard_cust_id, NEW.ccard_cust_id,
3466                  OLD.ccard_active, NEW.ccard_active, OLD.ccard_name, NEW.ccard_name,
3467                  OLD.ccard_address1, NEW.ccard_address1, OLD.ccard_address2,
3468                  NEW.ccard_address2, OLD.ccard_city, NEW.ccard_city, OLD.ccard_state,
3469                  NEW.ccard_state, OLD.ccard_zip, NEW.ccard_zip, OLD.ccard_country,
3470                  NEW.ccard_country, OLD.ccard_number, NEW.ccard_number, OLD.ccard_debit,
3471                  NEW.ccard_debit, OLD.ccard_month_expired, NEW.ccard_month_expired,
3472                  OLD.ccard_year_expired, NEW.ccard_year_expired, OLD.ccard_type, NEW.ccard_type);
3473   ELSE
3474 -- We are inserting a record, therefore no old values
3475     INSERT INTO ccardaud
3476          VALUES (nextval('ccardaud_ccardaud_id_seq'), NEW.ccard_id,
3477                  NULL, NEW.ccard_seq, NULL, NEW.ccard_cust_id, NULL,
3478                  NEW.ccard_active, NULL, NEW.ccard_name, NULL,
3479                  NEW.ccard_address1, NULL, NEW.ccard_address2, NULL,
3480                  NEW.ccard_city, NULL, NEW.ccard_state, NULL,
3481                  NEW.ccard_zip, NULL, NEW.ccard_country, NULL,
3482                  NEW.ccard_number, NULL, NEW.ccard_debit, NULL,
3483                  NEW.ccard_month_expired, NULL, NEW.ccard_year_expired, NULL,
3484                  NEW.ccard_type);
3485   END IF;
3486
3487   RETURN NEW;
3488
3489 END;
3490 $$;
3491
3492
3493 ALTER FUNCTION public._ccardtrigger() OWNER TO admin;
3494
3495 --
3496 -- TOC entry 932 (class 1255 OID 146565445)
3497 -- Dependencies: 4536 8
3498 -- Name: _charasshistorytrigger(); Type: FUNCTION; Schema: public; Owner: admin
3499 --
3500
3501 CREATE FUNCTION _charasshistorytrigger() RETURNS trigger
3502     LANGUAGE plpgsql
3503     AS $$
3504 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3505 -- See www.xtuple.com/CPAL for the full text of the software license.
3506 BEGIN
3507   IF(TG_OP = 'DELETE') THEN
3508     IF (OLD.charass_target_type = 'INCDT') THEN
3509       INSERT INTO incdthist
3510             (incdthist_incdt_id, incdthist_descrip)
3511       VALUES(OLD.charass_target_id,
3512              ('Characteristic ' || 
3513                COALESCE((SELECT char_name 
3514                            FROM char
3515                           WHERE (char_id=OLD.charass_char_id)), '')
3516               || ' Deleted: "' || 
3517               COALESCE(OLD.charass_value,'')
3518               || '"') );
3519     END IF;
3520     RETURN OLD;
3521   ELSIF (NEW.charass_target_type = 'INCDT') THEN
3522     IF (TG_OP = 'INSERT') THEN
3523       INSERT INTO incdthist
3524             (incdthist_incdt_id, incdthist_descrip)
3525       VALUES(NEW.charass_target_id,
3526              ('Characteristic ' || 
3527                COALESCE((SELECT char_name 
3528                            FROM char
3529                           WHERE (char_id=NEW.charass_char_id)), '')
3530               || ' Added: "' || 
3531               COALESCE(NEW.charass_value,'')
3532               || '"') );
3533     ELSIF (TG_OP = 'UPDATE') THEN
3534       IF (COALESCE(NEW.charass_value,'') <> COALESCE(OLD.charass_value,'')) THEN
3535         INSERT INTO incdthist
3536               (incdthist_incdt_id, incdthist_descrip)
3537         VALUES(NEW.charass_target_id,
3538                ('Characteristic ' || 
3539                  COALESCE((SELECT char_name 
3540                              FROM char
3541                             WHERE (char_id=NEW.charass_char_id)), '')
3542                 || ' Changed: "' || 
3543                 COALESCE(OLD.charass_value,'')
3544                 || '" -> "' ||
3545                 COALESCE(NEW.charass_value,'')
3546                 || '"') );
3547       END IF;
3548     END IF;
3549   END IF;
3550   RETURN NEW;
3551 END;
3552 $$;
3553
3554
3555 ALTER FUNCTION public._charasshistorytrigger() OWNER TO admin;
3556
3557 --
3558 -- TOC entry 933 (class 1255 OID 146565446)
3559 -- Dependencies: 4536 8
3560 -- Name: _charasstrigger(); Type: FUNCTION; Schema: public; Owner: admin
3561 --
3562
3563 CREATE FUNCTION _charasstrigger() RETURNS trigger
3564     LANGUAGE plpgsql
3565     AS $$
3566 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3567 -- See www.xtuple.com/CPAL for the full text of the software license.
3568 BEGIN
3569
3570 -- Privilege Checks
3571    IF (NEW.charass_target_type = 'I' AND NOT checkPrivilege('MaintainItemMasters')) THEN
3572      RAISE EXCEPTION 'You do not have privileges to maintain Items.';
3573    END IF;
3574
3575    IF (NEW.charass_target_type = 'C' AND NOT checkPrivilege('MaintainCustomerMasters')) THEN
3576      RAISE EXCEPTION 'You do not have privileges to maintain Customers.';
3577    END IF;
3578
3579 -- Data check
3580   IF (NEW.charass_char_id IS NULL) THEN
3581         RAISE EXCEPTION 'You must supply a valid Characteristic ID.';
3582   END IF;
3583
3584 -- Default Logic
3585   IF (NEW.charass_default) THEN
3586     UPDATE charass
3587     SET charass_default = false 
3588     WHERE ((charass_target_id=NEW.charass_target_id)
3589     AND  (charass_target_type=NEW.charass_target_type)
3590     AND  (charass_char_id=NEW.charass_char_id)
3591     AND  (charass_id <> NEW.charass_ID));
3592   END IF;
3593
3594 -- Incident update
3595   IF (NEW.charass_target_type = 'INCDT') THEN
3596     UPDATE incdt SET incdt_updated = now() WHERE incdt_id = NEW.charass_target_id;
3597   END IF;
3598   
3599   RETURN NEW;
3600 END;
3601 $$;
3602
3603
3604 ALTER FUNCTION public._charasstrigger() OWNER TO admin;
3605
3606 --
3607 -- TOC entry 934 (class 1255 OID 146565447)
3608 -- Dependencies: 4536 8
3609 -- Name: _charbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
3610 --
3611
3612 CREATE FUNCTION _charbeforetrigger() RETURNS trigger
3613     LANGUAGE plpgsql
3614     AS $$
3615 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3616 -- See www.xtuple.com/CPAL for the full text of the software license.
3617 BEGIN
3618   IF (NOT checkPrivilege('MaintainCharacteristics')) THEN
3619     RAISE EXCEPTION 'You do not have privileges to maintain Characteristics.';
3620   END IF;
3621
3622   RETURN NEW;
3623 END;
3624 $$;
3625
3626
3627 ALTER FUNCTION public._charbeforetrigger() OWNER TO admin;
3628
3629 --
3630 -- TOC entry 935 (class 1255 OID 146565448)
3631 -- Dependencies: 4536 8
3632 -- Name: _charopttrigger(); Type: FUNCTION; Schema: public; Owner: admin
3633 --
3634
3635 CREATE FUNCTION _charopttrigger() RETURNS trigger
3636     LANGUAGE plpgsql
3637     AS $$
3638 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3639 -- See www.xtuple.com/CPAL for the full text of the software license.
3640 BEGIN
3641   IF (NOT checkPrivilege('MaintainCharacteristics')) THEN
3642     RAISE EXCEPTION 'You do not have privileges to maintain Characteristic options.';
3643   END IF;
3644
3645   IF (TG_OP = 'UPDATE') THEN
3646     UPDATE charass SET
3647       charass_value = NEW.charopt_value
3648     WHERE ((charass_char_id=NEW.charopt_char_id)
3649       AND (charass_value=OLD.charopt_value));
3650   END IF;
3651
3652   IF (TG_OP = 'DELETE') THEN
3653     IF (SELECT (count(charass_id) > 0)
3654         FROM charass
3655         WHERE ((charass_char_id=OLD.charopt_char_id)
3656          AND (charass_value=OLD.charopt_value))) THEN
3657        RAISE EXCEPTION 'This characteristic option value is in use and can not be deleted.';
3658     END IF;
3659   END IF;
3660   
3661   RETURN NEW;
3662 END;
3663 $$;
3664
3665
3666 ALTER FUNCTION public._charopttrigger() OWNER TO admin;
3667
3668 --
3669 -- TOC entry 938 (class 1255 OID 146565449)
3670 -- Dependencies: 4536 8
3671 -- Name: _checkheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
3672 --
3673
3674 CREATE FUNCTION _checkheadbeforetrigger() RETURNS trigger
3675     LANGUAGE plpgsql
3676     AS $$
3677 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3678 -- See www.xtuple.com/CPAL for the full text of the software license.
3679 DECLARE 
3680   _amount NUMERIC;
3681   _currrate NUMERIC;
3682
3683 BEGIN
3684
3685 -- get the base exchange rate for the check date
3686   IF (TG_OP = 'INSERT' AND NEW.checkhead_curr_rate IS NULL) THEN
3687     SELECT curr_rate INTO _currrate
3688     FROM curr_rate
3689     WHERE ( (NEW.checkhead_curr_id=curr_id)
3690       AND ( NEW.checkhead_checkdate BETWEEN curr_effective 
3691                                    AND curr_expires) );
3692     IF (FOUND) THEN
3693       NEW.checkhead_curr_rate := _currrate;
3694     ELSE
3695       RAISE EXCEPTION 'Currency exchange rate not found';
3696     END IF;
3697   END IF;
3698
3699   IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
3700     IF (NOT EXISTS (SELECT checkrecip_id
3701                     FROM checkrecip
3702                     WHERE ((checkrecip_type=NEW.checkhead_recip_type)
3703                       AND  (checkrecip_id=NEW.checkhead_recip_id)) )) THEN
3704       RAISE EXCEPTION 'Cannot verify recipient for check % (type %  id %)',
3705                       NEW.checkhead_number, NEW.checkhead_recip_type,
3706                       NEW.checkhead_recip_id;
3707     END IF;
3708
3709     IF (NEW.checkhead_journalnumber IS NOT NULL
3710         AND NOT EXISTS (SELECT jrnluse_number
3711                         FROM jrnluse
3712                         WHERE (jrnluse_number=NEW.checkhead_journalnumber))
3713         ) THEN
3714       RAISE EXCEPTION 'Journal Number % does not exist and cannot be used for check %.',
3715                       NEW.checkhead_journalnumber, NEW.checkhead_number;
3716     END IF;
3717   END IF;
3718
3719   RETURN NEW;
3720 END;
3721 $$;
3722
3723
3724 ALTER FUNCTION public._checkheadbeforetrigger() OWNER TO admin;
3725
3726 --
3727 -- TOC entry 939 (class 1255 OID 146565450)
3728 -- Dependencies: 4536 8
3729 -- Name: _cmheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
3730 --
3731
3732 CREATE FUNCTION _cmheadbeforetrigger() RETURNS trigger
3733     LANGUAGE plpgsql
3734     AS $$
3735 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3736 -- See www.xtuple.com/CPAL for the full text of the software license.
3737 DECLARE
3738   _check BOOLEAN;
3739   _id INTEGER;
3740 BEGIN
3741   -- Checks
3742   -- Start with privileges
3743   SELECT checkPrivilege('MaintainCreditMemos') INTO _check;
3744   IF ( (TG_OP = 'INSERT') OR (TG_OP = 'DELETE') ) THEN
3745     IF NOT (_check) THEN
3746       RAISE EXCEPTION 'You do not have privileges to maintain Credit Memos.';
3747     END IF;
3748   END IF;
3749   IF (TG_OP = 'UPDATE') THEN
3750     IF ((OLD.cmhead_printed = NEW.cmhead_printed) AND NOT (_check) ) THEN
3751       RAISE EXCEPTION 'You do not have privileges to maintain Credit Memos.';
3752     END IF;
3753   END IF;
3754
3755   IF (TG_OP = 'DELETE') THEN
3756     DELETE FROM cmheadtax
3757     WHERE (taxhist_parent_id=OLD.cmhead_id);
3758
3759     RETURN OLD;
3760   END IF;
3761
3762   IF ( (NEW.cmhead_number IS NULL) OR (LENGTH(NEW.cmhead_number) = 0) ) THEN
3763     RAISE EXCEPTION 'You must enter a valid Memo # for this Credit Memo.';
3764   END IF;
3765
3766   IF (TG_OP = 'INSERT') THEN
3767     SELECT cmhead_id INTO _id
3768     FROM cmhead
3769     WHERE (cmhead_number=NEW.cmhead_number);
3770     IF (FOUND) THEN
3771       RAISE EXCEPTION 'The Memo # is already in use.';
3772     END IF;
3773
3774     IF (fetchMetricText('CMNumberGeneration') IN ('A','O')) THEN
3775       --- clear the number from the issue cache
3776       PERFORM clearNumberIssue('CmNumber', NEW.cmhead_number);
3777     ELSIF (fetchMetricText('CMNumberGeneration') = 'S') THEN
3778       --- clear the number from the issue cache
3779       PERFORM clearNumberIssue('SoNumber', NEW.cmhead_number);
3780     END IF;
3781   END IF;
3782
3783   IF (NEW.cmhead_cust_id IS NOT NULL) THEN
3784     SELECT cust_id INTO _id
3785     FROM custinfo
3786     WHERE (cust_id=NEW.cmhead_cust_id);
3787     IF (NOT FOUND) THEN
3788       RAISE EXCEPTION 'You must enter a valid Customer # for this Credit Memo.';
3789     END IF;
3790   END IF;
3791
3792   IF ( (NEW.cmhead_misc > 0) AND (NEW.cmhead_misc_accnt_id = -1) ) THEN
3793     RAISE EXCEPTION 'You may not enter a Misc. Charge without indicating the G/L Sales Account.';
3794   END IF;
3795
3796   RETURN NEW;
3797 END;
3798 $$;
3799
3800
3801 ALTER FUNCTION public._cmheadbeforetrigger() OWNER TO admin;
3802
3803 --
3804 -- TOC entry 940 (class 1255 OID 146565451)
3805 -- Dependencies: 4536 8
3806 -- Name: _cmheadtrigger(); Type: FUNCTION; Schema: public; Owner: admin
3807 --
3808
3809 CREATE FUNCTION _cmheadtrigger() RETURNS trigger
3810     LANGUAGE plpgsql
3811     AS $$
3812 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3813 -- See www.xtuple.com/CPAL for the full text of the software license.
3814 BEGIN
3815   IF (TG_OP = 'DELETE') THEN
3816     -- If this was created by a return, then reset the return
3817     IF (OLD.cmhead_rahead_id IS NOT NULL) THEN
3818       UPDATE rahead SET
3819         rahead_headcredited=false
3820       WHERE (rahead_id=OLD.cmhead_rahead_id);
3821       DELETE FROM rahist
3822       WHERE ((rahist_rahead_id=OLD.cmhead_rahead_id)
3823       AND (rahist_source='CM')
3824       AND (rahist_source_id=OLD.cmhead_id));
3825     END IF;
3826     RETURN OLD;
3827   END IF;
3828
3829 -- Insert new row
3830   IF (TG_OP = 'INSERT') THEN
3831
3832   -- Calculate Freight Tax
3833     IF (NEW.cmhead_freight <> 0) THEN
3834       PERFORM calculateTaxHist( 'cmheadtax',
3835                                 NEW.cmhead_id,
3836                                 NEW.cmhead_taxzone_id,
3837                                 getFreightTaxtypeId(),
3838                                 NEW.cmhead_docdate,
3839                                 NEW.cmhead_curr_id,
3840                                 NEW.cmhead_freight * -1 );
3841     END IF;
3842   END IF;
3843
3844 -- Update row
3845   IF (TG_OP = 'UPDATE') THEN
3846
3847     IF ( (NEW.cmhead_freight <> OLD.cmhead_freight) OR
3848          (COALESCE(NEW.cmhead_taxzone_id,-1) <> COALESCE(OLD.cmhead_taxzone_id,-1)) OR
3849          (NEW.cmhead_docdate <> OLD.cmhead_docdate) OR
3850          (NEW.cmhead_curr_id <> OLD.cmhead_curr_id) ) THEN
3851   -- Calculate cmhead Tax
3852       PERFORM calculateTaxHist( 'cmheadtax',
3853                                 NEW.cmhead_id,
3854                                 NEW.cmhead_taxzone_id,
3855                                 getFreightTaxtypeId(),
3856                                 NEW.cmhead_docdate,
3857                                 NEW.cmhead_curr_id,
3858                                 NEW.cmhead_freight * -1 );
3859     END IF;
3860
3861     IF ( (COALESCE(NEW.cmhead_taxzone_id,-1) <> COALESCE(OLD.cmhead_taxzone_id,-1)) OR
3862          (NEW.cmhead_docdate <> OLD.cmhead_docdate) OR
3863          (NEW.cmhead_curr_id <> OLD.cmhead_curr_id) ) THEN
3864   -- Calculate cmitem Tax
3865       IF (COALESCE(NEW.cmhead_taxzone_id,-1) <> COALESCE(OLD.cmhead_taxzone_id,-1)) THEN
3866     -- Cmitem trigger will calculate tax
3867         UPDATE cmitem SET cmitem_taxtype_id=getItemTaxType(itemsite_item_id,NEW.cmhead_taxzone_id)
3868         FROM itemsite 
3869         WHERE ((itemsite_id=cmitem_itemsite_id)
3870           AND (cmitem_cmhead_id=NEW.cmhead_id));
3871       ELSE
3872         PERFORM calculateTaxHist( 'cmitemtax',
3873                                   cmitem_id,
3874                                   NEW.cmhead_taxzone_id,
3875                                   cmitem_taxtype_id,
3876                                   NEW.cmhead_docdate,
3877                                   NEW.cmhead_curr_id,
3878                                   (cmitem_qtycredit * cmitem_qty_invuomratio) *
3879                                   (cmitem_unitprice / cmitem_price_invuomratio) * -1)
3880         FROM cmitem
3881         WHERE (cmitem_cmhead_id = NEW.cmhead_id);
3882       END IF;
3883     END IF;
3884
3885   END IF;
3886
3887
3888   RETURN NEW;
3889 END;
3890 $$;
3891
3892
3893 ALTER FUNCTION public._cmheadtrigger() OWNER TO admin;
3894
3895 --
3896 -- TOC entry 941 (class 1255 OID 146565452)
3897 -- Dependencies: 4536 8
3898 -- Name: _cmitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
3899 --
3900
3901 CREATE FUNCTION _cmitembeforetrigger() RETURNS trigger
3902     LANGUAGE plpgsql
3903     AS $$
3904 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3905 -- See www.xtuple.com/CPAL for the full text of the software license.
3906 DECLARE
3907   _check BOOLEAN;
3908   _id INTEGER;
3909 BEGIN
3910   -- Checks
3911   -- Start with privileges
3912   SELECT checkPrivilege('MaintainCreditMemos') INTO _check;
3913   IF NOT (_check) THEN
3914     RAISE EXCEPTION 'You do not have privileges to maintain Credit Memos.';
3915   END IF;
3916
3917   IF (TG_OP = 'DELETE') THEN
3918     DELETE FROM cmitemtax
3919     WHERE (taxhist_parent_id=OLD.cmitem_id);
3920
3921     RETURN OLD;
3922   END IF;
3923
3924   IF (TG_OP = 'INSERT') THEN
3925     IF ( (NEW.cmitem_qtycredit IS NULL) OR (NEW.cmitem_qtycredit = 0) ) THEN
3926       RAISE EXCEPTION 'Quantity to Credit must be greater than zero.';
3927     END IF;
3928     SELECT cmitem_id INTO _id
3929     FROM cmitem
3930     WHERE ( (cmitem_cmhead_id=NEW.cmitem_cmhead_id) AND (cmitem_linenumber=NEW.cmitem_linenumber) );
3931     IF (FOUND) THEN
3932       RAISE EXCEPTION 'The Memo Line Number is already in use.';
3933     END IF;
3934   END IF;
3935
3936   RETURN NEW;
3937 END;
3938 $$;
3939
3940
3941 ALTER FUNCTION public._cmitembeforetrigger() OWNER TO admin;
3942
3943 --
3944 -- TOC entry 942 (class 1255 OID 146565453)
3945 -- Dependencies: 4536 8
3946 -- Name: _cmitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
3947 --
3948
3949 CREATE FUNCTION _cmitemtrigger() RETURNS trigger
3950     LANGUAGE plpgsql
3951     AS $$
3952 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
3953 -- See www.xtuple.com/CPAL for the full text of the software license.
3954 DECLARE
3955   _ext NUMERIC;
3956   _r RECORD;
3957
3958 BEGIN
3959   IF (TG_OP = 'DELETE') THEN
3960
3961 --  If this was created by a return, reset return values
3962     IF (OLD.cmitem_raitem_id) IS NOT NULL THEN
3963       _ext := ROUND((OLD.cmitem_qtycredit * OLD.cmitem_qty_invuomratio) *  (OLD.cmitem_unitprice / OLD.cmitem_price_invuomratio),2);
3964       UPDATE raitem SET
3965         raitem_status = 'O',
3966         raitem_qtycredited = raitem_qtycredited-OLD.cmitem_qtycredit,
3967         raitem_amtcredited = raitem_amtcredited-_ext
3968       WHERE (raitem_id=OLD.cmitem_raitem_id);
3969     END IF;
3970     RETURN OLD;
3971   END IF;
3972
3973 -- Cache Credit Memo Head
3974   SELECT * INTO _r
3975   FROM cmhead
3976   WHERE (cmhead_id=NEW.cmitem_cmhead_id);
3977   IF (NOT FOUND) THEN
3978     RAISE EXCEPTION 'Credit Memo head not found';
3979   END IF;
3980
3981 -- Insert new row
3982   IF (TG_OP = 'INSERT') THEN
3983
3984   -- Calculate Tax
3985       PERFORM calculateTaxHist( 'cmitemtax',
3986                                 NEW.cmitem_id,
3987                                 COALESCE(_r.cmhead_taxzone_id, -1),
3988                                 NEW.cmitem_taxtype_id,
3989                                 COALESCE(_r.cmhead_docdate, CURRENT_DATE),
3990                                 COALESCE(_r.cmhead_curr_id, -1),
3991                                 (NEW.cmitem_qtycredit * NEW.cmitem_qty_invuomratio) *
3992                                 (NEW.cmitem_unitprice / NEW.cmitem_price_invuomratio) * -1);
3993   END IF;
3994
3995 -- Update row
3996   IF (TG_OP = 'UPDATE') THEN
3997
3998   -- Calculate Tax
3999     IF ( (NEW.cmitem_qtycredit <> OLD.cmitem_qtycredit) OR
4000          (NEW.cmitem_qty_invuomratio <> OLD.cmitem_qty_invuomratio) OR
4001          (NEW.cmitem_unitprice <> OLD.cmitem_unitprice) OR
4002          (NEW.cmitem_price_invuomratio <> OLD.cmitem_price_invuomratio) OR
4003          (COALESCE(NEW.cmitem_taxtype_id, -1) <> COALESCE(OLD.cmitem_taxtype_id, -1)) ) THEN
4004       PERFORM calculateTaxHist( 'cmitemtax',
4005                                 NEW.cmitem_id,
4006                                 COALESCE(_r.cmhead_taxzone_id, -1),
4007                                 NEW.cmitem_taxtype_id,
4008                                 COALESCE(_r.cmhead_docdate, CURRENT_DATE),
4009                                 COALESCE(_r.cmhead_curr_id, -1),
4010                                 (NEW.cmitem_qtycredit * NEW.cmitem_qty_invuomratio) *
4011                                 (NEW.cmitem_unitprice / NEW.cmitem_price_invuomratio) * -1);
4012     END IF;
4013   END IF;
4014
4015
4016   RETURN NEW;
4017 END;
4018 $$;
4019
4020
4021 ALTER FUNCTION public._cmitemtrigger() OWNER TO admin;
4022
4023 --
4024 -- TOC entry 943 (class 1255 OID 146565454)
4025 -- Dependencies: 4536 8
4026 -- Name: _cntcttrigger(); Type: FUNCTION; Schema: public; Owner: admin
4027 --
4028
4029 CREATE FUNCTION _cntcttrigger() RETURNS trigger
4030     LANGUAGE plpgsql
4031     AS $$
4032 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4033 -- See www.xtuple.com/CPAL for the full text of the software license.
4034 BEGIN
4035
4036   NEW.cntct_name := formatCntctName(NULL, NEW.cntct_first_name, NEW.cntct_middle, NEW.cntct_last_name, NEW.cntct_suffix);
4037   NEW.cntct_email := lower(NEW.cntct_email);
4038
4039   IF (TG_OP = 'INSERT') THEN
4040     --- clear the number from the issue cache
4041     PERFORM clearNumberIssue('ContactNumber', NEW.cntct_number);
4042   END IF;
4043   
4044   RETURN NEW;
4045 END;
4046 $$;
4047
4048
4049 ALTER FUNCTION public._cntcttrigger() OWNER TO admin;
4050
4051 --
4052 -- TOC entry 947 (class 1255 OID 146565455)
4053 -- Dependencies: 4536 8
4054 -- Name: _cntcttriggerafter(); Type: FUNCTION; Schema: public; Owner: admin
4055 --
4056
4057 CREATE FUNCTION _cntcttriggerafter() RETURNS trigger
4058     LANGUAGE plpgsql
4059     AS $$
4060 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4061 -- See www.xtuple.com/CPAL for the full text of the software license.
4062 DECLARE
4063   _cntctemlid INTEGER;
4064   _rows INTEGER;
4065 BEGIN
4066   IF (TG_OP = 'INSERT') THEN
4067     IF(length(coalesce(NEW.cntct_email,'')) > 0) THEN
4068       INSERT INTO cntcteml (
4069         cntcteml_cntct_id, cntcteml_primary, cntcteml_email )
4070       VALUES (
4071         NEW.cntct_id, true, NEW.cntct_email );
4072     END IF;
4073     PERFORM postComment('ChangeLog', 'T', NEW.cntct_id,
4074                         ('Created by ' || getEffectiveXtUser()));
4075   ELSIF (TG_OP = 'UPDATE') THEN
4076     IF (OLD.cntct_email != NEW.cntct_email) THEN
4077       SELECT cntcteml_id INTO _cntctemlid
4078       FROM cntcteml
4079       WHERE ((cntcteml_cntct_id=NEW.cntct_id)
4080         AND (cntcteml_email=NEW.cntct_email));
4081
4082       GET DIAGNOSTICS _rows = ROW_COUNT;
4083       IF (_rows = 0) THEN
4084         UPDATE cntcteml SET
4085           cntcteml_primary=false
4086         WHERE ((cntcteml_cntct_id=NEW.cntct_id)
4087          AND (cntcteml_primary=true));
4088        
4089         INSERT INTO cntcteml (
4090           cntcteml_cntct_id, cntcteml_primary, cntcteml_email )
4091         VALUES (
4092           NEW.cntct_id, true, NEW.cntct_email ); 
4093       ELSE
4094         UPDATE cntcteml SET
4095           cntcteml_primary=false
4096         WHERE ((cntcteml_cntct_id=NEW.cntct_id)
4097          AND (cntcteml_primary=true));
4098
4099         UPDATE cntcteml SET
4100           cntcteml_primary=true
4101         WHERE (cntcteml_id=_cntctemlid);
4102       END IF;
4103     END IF;
4104   ELSIF (TG_OP = 'DELETE') THEN
4105       DELETE FROM comment
4106        WHERE (comment_source_id=OLD.cntct_id AND comment_source = 'T');
4107       DELETE FROM docass
4108        WHERE (docass_source_id=OLD.cntct_id AND docass_source_type = 'T')
4109           OR (docass_target_id=OLD.cntct_id AND docass_target_type = 'T');
4110       
4111       RETURN OLD;
4112   END IF;
4113
4114   RETURN NEW;
4115 END;
4116 $$;
4117
4118
4119 ALTER FUNCTION public._cntcttriggerafter() OWNER TO admin;
4120
4121 --
4122 -- TOC entry 948 (class 1255 OID 146565456)
4123 -- Dependencies: 4536 8
4124 -- Name: _cntcttriggerbeforedelete(); Type: FUNCTION; Schema: public; Owner: admin
4125 --
4126
4127 CREATE FUNCTION _cntcttriggerbeforedelete() RETURNS trigger
4128     LANGUAGE plpgsql
4129     AS $$
4130 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4131 -- See www.xtuple.com/CPAL for the full text of the software license.
4132 BEGIN
4133   IF (TG_OP = 'DELETE') THEN
4134     DELETE FROM cntctaddr WHERE cntctaddr_cntct_id=OLD.cntct_id;
4135     DELETE FROM cntctdata WHERE cntctdata_cntct_id=OLD.cntct_id;
4136     DELETE FROM cntcteml  WHERE cntcteml_cntct_id=OLD.cntct_id;
4137     DELETE FROM docass WHERE docass_source_id = OLD.cntct_id AND docass_source_type = 'T';
4138     DELETE FROM docass WHERE docass_target_id = OLD.cntct_id AND docass_target_type = 'T';
4139
4140     -- these have denormalized cntct info so it should be ok to update them
4141     UPDATE cohead SET cohead_billto_cntct_id=NULL
4142      WHERE cohead_billto_cntct_id=OLD.cntct_id;
4143     UPDATE cohead SET cohead_shipto_cntct_id=NULL
4144      WHERE cohead_shipto_cntct_id=OLD.cntct_id;
4145
4146     UPDATE pohead SET pohead_vend_cntct_id=NULL
4147      WHERE pohead_vend_cntct_id=OLD.cntct_id;
4148     UPDATE pohead SET pohead_shipto_cntct_id=NULL
4149      WHERE pohead_shipto_cntct_id=OLD.cntct_id;
4150
4151     UPDATE quhead SET quhead_billto_cntct_id=NULL
4152      WHERE quhead_billto_cntct_id=OLD.cntct_id;
4153     UPDATE quhead SET quhead_shipto_cntct_id=NULL
4154      WHERE quhead_shipto_cntct_id=OLD.cntct_id;
4155
4156     IF (fetchMetricBool('MultiWhs')) THEN
4157       UPDATE tohead SET tohead_destcntct_id=NULL
4158        WHERE tohead_destcntct_id=OLD.cntct_id;
4159       UPDATE tohead SET tohead_srccntct_id=NULL
4160        WHERE tohead_srccntct_id=OLD.cntct_id;
4161     END IF;
4162
4163   END IF;
4164   RETURN OLD;
4165 END;
4166 $$;
4167
4168
4169 ALTER FUNCTION public._cntcttriggerbeforedelete() OWNER TO admin;
4170
4171 --
4172 -- TOC entry 949 (class 1255 OID 146565457)
4173 -- Dependencies: 4536 8
4174 -- Name: _cntsliptrigger(); Type: FUNCTION; Schema: public; Owner: admin
4175 --
4176
4177 CREATE FUNCTION _cntsliptrigger() RETURNS trigger
4178     LANGUAGE plpgsql
4179     AS $$
4180 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4181 -- See www.xtuple.com/CPAL for the full text of the software license.
4182 DECLARE
4183   _p RECORD;
4184   _comments TEXT;
4185   _temp TEXT;
4186
4187 BEGIN
4188   IF (TG_OP = 'DELETE') THEN
4189     SELECT itemsite_loccntrl, itemsite_controlmethod,
4190            cntslip_posted, cntslip_lotserial, cntslip_comments,
4191            cntslip_number, cntslip_qty INTO _p
4192       FROM cntslip, invcnt, itemsite
4193      WHERE ( (cntslip_cnttag_id=invcnt_id)
4194        AND   (invcnt_itemsite_id=itemsite_id)
4195        AND   (cntslip_id=OLD.cntslip_id) );
4196
4197     IF(_p.cntslip_posted) THEN
4198       SELECT ( '
4199 Count Slip #' || _p.cntslip_number ||
4200              ' deleted ' || formatQty(_p.cntslip_qty) ) INTO _comments;
4201
4202 --  Add the Location name if the itemsite is MLC
4203       IF (_p.itemsite_loccntrl) THEN
4204         SELECT ( ', Location:' || location_name ) INTO _temp
4205           FROM location, cntslip
4206          WHERE ( (cntslip_location_id=location_id)
4207            AND   (cntslip_id=OLD.cntslip_id) );
4208   
4209         _comments := (_comments || _temp);
4210       END IF;
4211   
4212 --  Add the Lot/Serial if the itemsite is Lot or Serial controlled
4213       IF (_p.itemsite_controlmethod = 'L') THEN
4214         _comments := (_comments || ( ', Lot #:' || _p.cntslip_lotserial));
4215       ELSIF (_p.itemsite_controlmethod = 'S') THEN
4216         _comments := (_comments || ( ', Serial #:' || _p.cntslip_lotserial));
4217       END IF;
4218   
4219       _comments := (_comments || ' ' || _p.cntslip_comments);
4220   
4221       UPDATE invcnt
4222          SET invcnt_qoh_after = ( COALESCE(invcnt_qoh_after, 0) - cntslip_qty),
4223              invcnt_comments = (invcnt_comments || _comments)
4224         FROM cntslip
4225        WHERE ( (cntslip_cnttag_id=invcnt_id)
4226          AND   (NOT invcnt_posted)
4227          AND   (cntslip_id=OLD.cntslip_id) );
4228
4229     END IF;
4230
4231     RETURN OLD;
4232   END IF;
4233
4234   RETURN NEW;
4235 END;
4236 $$;
4237
4238
4239 ALTER FUNCTION public._cntsliptrigger() OWNER TO admin;
4240
4241 --
4242 -- TOC entry 950 (class 1255 OID 146565458)
4243 -- Dependencies: 4536 8
4244 -- Name: _cobillbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
4245 --
4246
4247 CREATE FUNCTION _cobillbeforetrigger() RETURNS trigger
4248     LANGUAGE plpgsql
4249     AS $$
4250 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4251 -- See www.xtuple.com/CPAL for the full text of the software license.
4252 DECLARE
4253
4254 BEGIN
4255   IF (TG_OP = 'DELETE') THEN
4256     DELETE FROM cobilltax
4257     WHERE (taxhist_parent_id=OLD.cobill_id);
4258
4259     RETURN OLD;
4260   END IF;
4261
4262   RETURN NEW;
4263 END;
4264 $$;
4265
4266
4267 ALTER FUNCTION public._cobillbeforetrigger() OWNER TO admin;
4268
4269 --
4270 -- TOC entry 951 (class 1255 OID 146565459)
4271 -- Dependencies: 4536 8
4272 -- Name: _cobilltrigger(); Type: FUNCTION; Schema: public; Owner: admin
4273 --
4274
4275 CREATE FUNCTION _cobilltrigger() RETURNS trigger
4276     LANGUAGE plpgsql
4277     AS $$
4278 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4279 -- See www.xtuple.com/CPAL for the full text of the software license.
4280 DECLARE
4281   _r RECORD;
4282
4283 BEGIN
4284   IF (TG_OP = 'DELETE') THEN
4285     RETURN OLD;
4286   END IF;
4287
4288 -- Cache Billing Head
4289   SELECT * INTO _r
4290   FROM cobmisc
4291   WHERE (cobmisc_id=NEW.cobill_cobmisc_id);
4292   IF (NOT FOUND) THEN
4293     RAISE EXCEPTION 'Billing head not found';
4294   END IF;
4295
4296 -- Insert new row
4297   IF (TG_OP = 'INSERT') THEN
4298
4299   -- Calculate Tax
4300       PERFORM calculateTaxHist( 'cobilltax',
4301                                 NEW.cobill_id,
4302                                 COALESCE(_r.cobmisc_taxzone_id, -1),
4303                                 NEW.cobill_taxtype_id,
4304                                 COALESCE(_r.cobmisc_shipdate, CURRENT_DATE),
4305                                 COALESCE(_r.cobmisc_curr_id, -1),
4306                                 (NEW.cobill_qty * coitem_qty_invuomratio) *
4307                                 (coitem_price / coitem_price_invuomratio) )
4308       FROM coitem
4309       WHERE (coitem_id=NEW.cobill_coitem_id);
4310   END IF;
4311
4312 -- Update row
4313   IF (TG_OP = 'UPDATE') THEN
4314
4315   -- Calculate Tax
4316     IF ( (NEW.cobill_qty <> OLD.cobill_qty) OR
4317          (NEW.cobill_taxtype_id <> OLD.cobill_taxtype_id) ) THEN
4318       PERFORM calculateTaxHist( 'cobilltax',
4319                                 NEW.cobill_id,
4320                                 COALESCE(_r.cobmisc_taxzone_id, -1),
4321                                 NEW.cobill_taxtype_id,
4322                                 COALESCE(_r.cobmisc_shipdate, CURRENT_DATE),
4323                                 COALESCE(_r.cobmisc_curr_id, -1),
4324                                 (NEW.cobill_qty * coitem_qty_invuomratio) *
4325                                 (coitem_price / coitem_price_invuomratio) )
4326       FROM coitem
4327       WHERE (coitem_id=NEW.cobill_coitem_id);
4328     END IF;
4329   END IF;
4330
4331   RETURN NEW;
4332 END;
4333 $$;
4334
4335
4336 ALTER FUNCTION public._cobilltrigger() OWNER TO admin;
4337
4338 --
4339 -- TOC entry 936 (class 1255 OID 146565460)
4340 -- Dependencies: 4536 8
4341 -- Name: _cobmiscbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
4342 --
4343
4344 CREATE FUNCTION _cobmiscbeforetrigger() RETURNS trigger
4345     LANGUAGE plpgsql
4346     AS $$
4347 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4348 -- See www.xtuple.com/CPAL for the full text of the software license.
4349 DECLARE
4350
4351 BEGIN
4352   IF (TG_OP = 'DELETE') THEN
4353     DELETE FROM cobmisctax
4354     WHERE (taxhist_parent_id=OLD.cobmisc_id);
4355
4356     RETURN OLD;
4357   END IF;
4358
4359   RETURN NEW;
4360 END;
4361 $$;
4362
4363
4364 ALTER FUNCTION public._cobmiscbeforetrigger() OWNER TO admin;
4365
4366 --
4367 -- TOC entry 937 (class 1255 OID 146565461)
4368 -- Dependencies: 4536 8
4369 -- Name: _cobmisctrigger(); Type: FUNCTION; Schema: public; Owner: admin
4370 --
4371
4372 CREATE FUNCTION _cobmisctrigger() RETURNS trigger
4373     LANGUAGE plpgsql
4374     AS $$
4375 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4376 -- See www.xtuple.com/CPAL for the full text of the software license.
4377 BEGIN
4378   IF (TG_OP = 'DELETE') THEN
4379     -- Something can go here
4380     RETURN OLD;
4381   END IF;
4382
4383 -- Insert new row
4384   IF (TG_OP = 'INSERT') THEN
4385
4386   -- Calculate Freight Tax
4387     IF (NEW.cobmisc_freight <> 0) THEN
4388       PERFORM calculateTaxHist( 'cobmisctax',
4389                                 NEW.cobmisc_id,
4390                                 NEW.cobmisc_taxzone_id,
4391                                 getFreightTaxtypeId(),
4392                                 NEW.cobmisc_invcdate,
4393                                 NEW.cobmisc_curr_id,
4394                                 NEW.cobmisc_freight );
4395     END IF;
4396   END IF;
4397
4398 -- Update row
4399   IF (TG_OP = 'UPDATE') THEN
4400
4401   -- Calculate Tax
4402     IF (COALESCE(NEW.cobmisc_taxzone_id,-1) <> COALESCE(OLD.cobmisc_taxzone_id,-1)) THEN
4403       UPDATE cobill SET cobill_taxtype_id=getItemTaxType(itemsite_item_id,NEW.cobmisc_taxzone_id)
4404       FROM coitem
4405         JOIN itemsite ON (coitem_itemsite_id=itemsite_id)
4406       WHERE ((coitem_id=cobill_coitem_id)
4407        AND (cobill_cobmisc_id=NEW.cobmisc_id));
4408     END IF;
4409     
4410     IF ( (NEW.cobmisc_freight <> OLD.cobmisc_freight) OR
4411          (COALESCE(NEW.cobmisc_taxzone_id,-1) <> COALESCE(OLD.cobmisc_taxzone_id,-1)) OR
4412          (NEW.cobmisc_invcdate <> OLD.cobmisc_invcdate) OR
4413          (NEW.cobmisc_curr_id <> OLD.cobmisc_curr_id) ) THEN
4414       PERFORM calculateTaxHist( 'cobmisctax',
4415                                 NEW.cobmisc_id,
4416                                 NEW.cobmisc_taxzone_id,
4417                                 getFreightTaxtypeId(),
4418                                 NEW.cobmisc_invcdate,
4419                                 NEW.cobmisc_curr_id,
4420                                 NEW.cobmisc_freight );
4421       PERFORM calculateTaxHist( 'cobilltax',
4422                                 cobill_id,
4423                                 NEW.cobmisc_taxzone_id,
4424                                 cobill_taxtype_id,
4425                                 NEW.cobmisc_invcdate,
4426                                 NEW.cobmisc_curr_id,
4427                                 (cobill_qty * coitem_qty_invuomratio) *
4428                                 (coitem_price / coitem_price_invuomratio) )
4429       FROM cobill JOIN coitem ON (coitem_id = cobill_coitem_id)
4430       WHERE (cobill_cobmisc_id = NEW.cobmisc_id);
4431     END IF;
4432   END IF;
4433
4434   RETURN NEW;
4435 END;
4436 $$;
4437
4438
4439 ALTER FUNCTION public._cobmisctrigger() OWNER TO admin;
4440
4441 --
4442 -- TOC entry 944 (class 1255 OID 146565462)
4443 -- Dependencies: 4536 8
4444 -- Name: _commenttrigger(); Type: FUNCTION; Schema: public; Owner: admin
4445 --
4446
4447 CREATE FUNCTION _commenttrigger() RETURNS trigger
4448     LANGUAGE plpgsql
4449     AS $$
4450 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4451 -- See www.xtuple.com/CPAL for the full text of the software license.
4452 BEGIN
4453   IF (NEW.comment_cmnttype_id IS NULL) THEN
4454         RAISE EXCEPTION 'You must supply a valid Comment Type ID.';
4455   ELSIF (NEW.comment_source = 'INCDT') THEN
4456     UPDATE incdt SET incdt_updated = now() WHERE incdt_id = NEW.comment_source_id;
4457   END IF;
4458
4459   RETURN NEW;
4460 END;
4461 $$;
4462
4463
4464 ALTER FUNCTION public._commenttrigger() OWNER TO admin;
4465
4466 --
4467 -- TOC entry 952 (class 1255 OID 146565463)
4468 -- Dependencies: 4536 8
4469 -- Name: _companytrigger(); Type: FUNCTION; Schema: public; Owner: admin
4470 --
4471
4472 CREATE FUNCTION _companytrigger() RETURNS trigger
4473     LANGUAGE plpgsql
4474     AS $$
4475 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4476 -- See www.xtuple.com/CPAL for the full text of the software license.
4477 DECLARE
4478   _used BOOLEAN := false;
4479
4480 BEGIN
4481   IF (NEW.company_external AND NOT OLD.company_external) THEN
4482     IF EXISTS(SELECT accnt_id
4483               FROM accnt, company, (
4484                   SELECT DISTINCT apaccnt_ap_accnt_id AS test_accnt_id FROM apaccnt
4485                   UNION SELECT DISTINCT apaccnt_discount_accnt_id FROM apaccnt
4486                   UNION SELECT DISTINCT apaccnt_prepaid_accnt_id FROM apaccnt
4487                   UNION SELECT DISTINCT apopen_accnt_id FROM apopen
4488                   UNION SELECT DISTINCT araccnt_ar_accnt_id FROM araccnt
4489                   UNION SELECT DISTINCT araccnt_deferred_accnt_id FROM araccnt
4490                   UNION SELECT DISTINCT araccnt_freight_accnt_id FROM araccnt
4491                   UNION SELECT DISTINCT araccnt_prepaid_accnt_id FROM araccnt
4492                   UNION SELECT DISTINCT aropen_accnt_id FROM aropen
4493                   UNION SELECT DISTINCT bankaccnt_accnt_id FROM bankaccnt
4494                   UNION SELECT DISTINCT bankaccnt_rec_accnt_id FROM bankaccnt
4495                   UNION SELECT DISTINCT budgitem_accnt_id FROM budgitem
4496                   UNION SELECT DISTINCT cashrcptmisc_accnt_id FROM cashrcptmisc
4497                   UNION SELECT DISTINCT cmhead_misc_accnt_id FROM cmhead
4498                   UNION SELECT DISTINCT cobmisc_misc_accnt_id FROM cobmisc
4499                   UNION SELECT DISTINCT cohead_misc_accnt_id FROM cohead
4500                   UNION SELECT DISTINCT coitem_cos_accnt_id FROM coitem
4501                   UNION SELECT DISTINCT costcat_adjustment_accnt_id FROM costcat
4502                   UNION SELECT DISTINCT costcat_asset_accnt_id FROM costcat
4503                   UNION SELECT DISTINCT costcat_freight_accnt_id FROM costcat
4504                   UNION SELECT DISTINCT costcat_invcost_accnt_id FROM costcat
4505                   UNION SELECT DISTINCT costcat_laboroverhead_accnt_id FROM costcat
4506                   UNION SELECT DISTINCT costcat_liability_accnt_id FROM costcat
4507                   UNION SELECT DISTINCT costcat_matusage_accnt_id FROM costcat
4508                   UNION SELECT DISTINCT costcat_mfgscrap_accnt_id FROM costcat
4509                   UNION SELECT DISTINCT costcat_purchprice_accnt_id FROM costcat
4510                   UNION SELECT DISTINCT costcat_scrap_accnt_id FROM costcat
4511                   UNION SELECT DISTINCT costcat_shipasset_accnt_id FROM costcat
4512                   UNION SELECT DISTINCT costcat_toliability_accnt_id FROM costcat
4513                   UNION SELECT DISTINCT costcat_transform_accnt_id FROM costcat
4514                   UNION SELECT DISTINCT costcat_wip_accnt_id FROM costcat
4515                   UNION SELECT DISTINCT costelem_exp_accnt_id FROM costelem
4516                   UNION SELECT DISTINCT expcat_exp_accnt_id FROM expcat
4517                   UNION SELECT DISTINCT expcat_freight_accnt_id FROM expcat
4518                   UNION SELECT DISTINCT expcat_liability_accnt_id FROM expcat
4519                   UNION SELECT DISTINCT expcat_purchprice_accnt_id FROM expcat
4520                   UNION SELECT DISTINCT glseries_accnt_id FROM glseries
4521                   UNION SELECT DISTINCT gltrans_accnt_id FROM gltrans
4522                   UNION SELECT DISTINCT invchead_misc_accnt_id FROM invchead
4523                   UNION SELECT DISTINCT quhead_misc_accnt_id FROM quhead
4524                   UNION SELECT DISTINCT salesaccnt_cor_accnt_id FROM salesaccnt
4525                   UNION SELECT DISTINCT salesaccnt_cos_accnt_id FROM salesaccnt
4526                   UNION SELECT DISTINCT salesaccnt_cow_accnt_id FROM salesaccnt
4527                   UNION SELECT DISTINCT salesaccnt_credit_accnt_id FROM salesaccnt
4528                   UNION SELECT DISTINCT salesaccnt_returns_accnt_id FROM salesaccnt
4529                   UNION SELECT DISTINCT salesaccnt_sales_accnt_id FROM salesaccnt
4530                   UNION SELECT DISTINCT salescat_ar_accnt_id FROM salescat
4531                   UNION SELECT DISTINCT salescat_prepaid_accnt_id FROM salescat
4532                   UNION SELECT DISTINCT salescat_sales_accnt_id FROM salescat
4533                   UNION SELECT DISTINCT stdjrnlitem_accnt_id FROM stdjrnlitem
4534                   UNION SELECT DISTINCT tax_sales_accnt_id FROM tax
4535                   UNION SELECT DISTINCT taxauth_accnt_id FROM taxauth
4536                   UNION SELECT DISTINCT vodist_accnt_id FROM vodist
4537                   UNION SELECT DISTINCT warehous_default_accnt_id FROM whsinfo
4538                 ) AS dummy
4539               WHERE ((accnt_id=test_accnt_id)
4540                 AND  (accnt_company=company_number)
4541                 AND  (accnt_company=NEW.company_number))
4542     ) THEN
4543       RAISE EXCEPTION 'Cannot make Company % External because it is used in the local database.',
4544                       NEW.company_number;
4545     ELSIF (fetchMetricBool('EnableReturnAuth')) THEN
4546       IF EXISTS(SELECT accnt_id
4547               FROM accnt, company, (
4548                   SELECT DISTINCT rahead_misc_accnt_id AS test_accnt_id FROM rahead
4549                   UNION SELECT DISTINCT raitem_cos_accnt_id FROM raitem
4550                 ) AS dummy
4551               WHERE ((accnt_id=test_accnt_id)
4552                 AND  (accnt_company=company_number)
4553                 AND  (accnt_company=NEW.company_number))
4554       ) THEN
4555         RAISE EXCEPTION 'Cannot make Company % External because it is used in the local database.',
4556                         NEW.company_number;
4557       END IF;
4558     END IF;
4559   END IF;
4560
4561   RETURN NEW;
4562 END;
4563 $$;
4564
4565
4566 ALTER FUNCTION public._companytrigger() OWNER TO admin;
4567
4568 --
4569 -- TOC entry 953 (class 1255 OID 146565464)
4570 -- Dependencies: 4536 8
4571 -- Name: _contrctaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
4572 --
4573
4574 CREATE FUNCTION _contrctaftertrigger() RETURNS trigger
4575     LANGUAGE plpgsql
4576     AS $$
4577 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4578 -- See www.xtuple.com/CPAL for the full text of the software license.
4579 DECLARE
4580
4581 BEGIN
4582
4583   -- synchronize contract effectivity with item source effectivity
4584   IF (NEW.contrct_effective <> OLD.contrct_effective) THEN
4585     UPDATE itemsrc SET itemsrc_effective=NEW.contrct_effective
4586     WHERE itemsrc_contrct_id=NEW.contrct_id;
4587   END IF;
4588
4589   IF (NEW.contrct_expires <> OLD.contrct_expires) THEN
4590     UPDATE itemsrc SET itemsrc_expires=NEW.contrct_expires
4591     WHERE itemsrc_contrct_id=NEW.contrct_id;
4592   END IF;
4593
4594   RETURN NEW;
4595 END;
4596 $$;
4597
4598
4599 ALTER FUNCTION public._contrctaftertrigger() OWNER TO admin;
4600
4601 --
4602 -- TOC entry 954 (class 1255 OID 146565465)
4603 -- Dependencies: 4536 8
4604 -- Name: _crmacctaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
4605 --
4606
4607 CREATE FUNCTION _crmacctaftertrigger() RETURNS trigger
4608     LANGUAGE plpgsql
4609     AS $$
4610 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4611 -- See www.xtuple.com/CPAL for the full text of the software license.
4612 DECLARE
4613   _cmnttypeid INTEGER;
4614   _gotpriv    BOOLEAN;
4615
4616 BEGIN
4617   /* update _number and _name separately to propagate just what changed.
4618      the priv manipulation allows targeted updates of crmaccount-maintained data
4619      (note: grantPriv() == false if the user already had the priv, true if this
4620      call granted the priv).
4621    */
4622   IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
4623     IF (NEW.crmacct_cust_id IS NOT NULL) THEN
4624       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainCustomerMasters');
4625       UPDATE custinfo SET cust_number = NEW.crmacct_number
4626       WHERE ((cust_id=NEW.crmacct_cust_id)
4627         AND  (cust_number!=NEW.crmacct_number));
4628       UPDATE custinfo SET cust_name = NEW.crmacct_name
4629       WHERE ((cust_id=NEW.crmacct_cust_id)
4630         AND  (cust_name!=NEW.crmacct_name));
4631       IF (_gotpriv) THEN
4632         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainCustomerMasters');
4633       END IF;
4634     END IF;
4635
4636     IF (NEW.crmacct_emp_id IS NOT NULL) THEN
4637       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainEmployees');
4638       UPDATE emp SET emp_code = NEW.crmacct_number
4639       WHERE ((emp_id=NEW.crmacct_emp_id)
4640         AND  (emp_code!=NEW.crmacct_number));
4641       UPDATE emp SET emp_name = NEW.crmacct_name
4642       WHERE ((emp_id=NEW.crmacct_emp_id)
4643         AND  (emp_name!=NEW.crmacct_name));
4644       IF (_gotpriv) THEN
4645         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainEmployees');
4646       END IF;
4647     END IF;
4648
4649     IF (NEW.crmacct_prospect_id IS NOT NULL) THEN
4650       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainProspectMasters');
4651       UPDATE prospect SET prospect_number = NEW.crmacct_number
4652       WHERE ((prospect_id=NEW.crmacct_prospect_id)
4653         AND  (prospect_number!=NEW.crmacct_number));
4654       UPDATE prospect SET prospect_name = NEW.crmacct_name
4655       WHERE ((prospect_id=NEW.crmacct_prospect_id)
4656         AND  (prospect_name!=NEW.crmacct_name));
4657       IF (_gotpriv) THEN
4658         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainProspectMasters');
4659       END IF;
4660     END IF;
4661
4662     IF (NEW.crmacct_salesrep_id IS NOT NULL) THEN
4663       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainSalesReps');
4664       UPDATE salesrep SET salesrep_number = NEW.crmacct_number
4665       WHERE ((salesrep_id=NEW.crmacct_salesrep_id)
4666         AND  (salesrep_number!=NEW.crmacct_number));
4667       UPDATE salesrep SET salesrep_name = NEW.crmacct_name
4668       WHERE ((salesrep_id=NEW.crmacct_salesrep_id)
4669         AND  (salesrep_name!=NEW.crmacct_name));
4670       IF (_gotpriv) THEN
4671         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainSalesReps');
4672       END IF;
4673     END IF;
4674
4675     IF (NEW.crmacct_taxauth_id IS NOT NULL) THEN
4676       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainTaxAuthorities');
4677       UPDATE taxauth SET taxauth_code = NEW.crmacct_number
4678       WHERE ((taxauth_id=NEW.crmacct_taxauth_id)
4679         AND  (taxauth_code!=NEW.crmacct_number));
4680       UPDATE taxauth SET taxauth_name = NEW.crmacct_name
4681       WHERE ((taxauth_id=NEW.crmacct_taxauth_id)
4682         AND  (taxauth_name!=NEW.crmacct_name));
4683       IF (_gotpriv) THEN
4684         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainTaxAuthorities');
4685       END IF;
4686     END IF;
4687
4688     IF (NEW.crmacct_vend_id IS NOT NULL) THEN
4689       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainVendors');
4690       UPDATE vendinfo SET vend_number = NEW.crmacct_number
4691       WHERE ((vend_id=NEW.crmacct_vend_id)
4692         AND  (vend_number!=NEW.crmacct_number));
4693       UPDATE vendinfo SET vend_name = NEW.crmacct_name
4694       WHERE ((vend_id=NEW.crmacct_vend_id)
4695         AND  (vend_name!=NEW.crmacct_name));
4696       IF (_gotpriv) THEN
4697         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainVendors');
4698       END IF;
4699     END IF;
4700
4701     -- Link Primary and Secondary Contacts to this Account if they are not already
4702     IF (NEW.crmacct_cntct_id_1 IS NOT NULL) THEN
4703       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainAllContacts');
4704       UPDATE cntct SET cntct_crmacct_id = NEW.crmacct_id
4705        WHERE cntct_id=NEW.crmacct_cntct_id_1;
4706       IF (_gotpriv) THEN
4707         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainAllContacts');
4708       END IF;
4709     END IF;
4710
4711     IF (NEW.crmacct_cntct_id_2 IS NOT NULL) THEN
4712       _gotpriv := grantPriv(getEffectiveXtUser(), 'MaintainAllContacts');
4713       UPDATE cntct SET cntct_crmacct_id = NEW.crmacct_id
4714        WHERE cntct_id=NEW.crmacct_cntct_id_2;
4715       IF (_gotpriv) THEN
4716         PERFORM revokePriv(getEffectiveXtUser(), 'MaintainAllContacts');
4717       END IF;
4718     END IF;
4719
4720     -- cannot have fkey references to system catalogs so enforce them here
4721     IF (NEW.crmacct_usr_username IS NOT NULL) THEN
4722       IF (NOT EXISTS(SELECT usr_username
4723                        FROM usr
4724                       WHERE usr_username=NEW.crmacct_usr_username)) THEN
4725         RAISE EXCEPTION 'User % does not exist so this CRM Account Number is invalid.',
4726                         NEW.crmacct_usr_username;
4727       END IF;
4728       IF (TG_OP = 'UPDATE') THEN
4729         -- reminder: this evaluates to false if either is NULL
4730         IF (NEW.crmacct_usr_username != OLD.crmacct_usr_username) THEN
4731           RAISE EXCEPTION 'Cannot change the user name for %',
4732                           OLD.crmacct_usr_username;
4733         END IF;
4734       END IF;
4735       UPDATE usrpref SET usrpref_value = NEW.crmacct_name
4736       WHERE ((usrpref_username=NEW.crmacct_usr_username)
4737         AND  (usrpref_name='propername')
4738         AND  (usrpref_value!=NEW.crmacct_name));
4739     END IF;
4740
4741   ELSIF (TG_OP = 'DELETE') THEN
4742     IF (OLD.crmacct_cust_id IS NOT NULL) THEN
4743       RAISE EXCEPTION 'Cannot delete CRM Account because it is a Customer [xtuple: deleteCrmAccount, -1]';
4744     END IF;
4745
4746     IF (OLD.crmacct_emp_id IS NOT NULL) THEN
4747       RAISE EXCEPTION 'Cannot delete CRM Account because it is an Employee [xtuple: deleteCrmAccount, -7]';
4748     END IF;
4749
4750     IF (OLD.crmacct_prospect_id IS NOT NULL) THEN
4751       RAISE EXCEPTION 'Cannot delete CRM Account because it is a Prospect [xtuple: deleteCrmAccount, -3]';
4752     END IF;
4753
4754     DELETE FROM salesrep WHERE salesrep_id  = OLD.crmacct_salesrep_id;
4755     IF (OLD.crmacct_salesrep_id IS NOT NULL) THEN
4756       RAISE EXCEPTION 'Cannot delete CRM Account because it is a Sales Rep [xtuple: deleteCrmAccount, -6]';
4757     END IF;
4758
4759     IF (OLD.crmacct_taxauth_id IS NOT NULL) THEN
4760       RAISE EXCEPTION 'Cannot delete CRM Account because it is a Tax Authority [xtuple: deleteCrmAccount, -5]';
4761     END IF;
4762
4763     IF (EXISTS(SELECT usename
4764                  FROM pg_user
4765                 WHERE usename=OLD.crmacct_usr_username)) THEN
4766       RAISE EXCEPTION 'Cannot delete CRM Account because it is a User [xtuple: deleteCrmAccount, -8]';
4767     END IF;
4768
4769     IF (OLD.crmacct_vend_id IS NOT NULL) THEN
4770       RAISE EXCEPTION 'Cannot delete CRM Account because it is a Vendor [xtuple: deleteCrmAccount, -2]';
4771     END IF;
4772
4773     DELETE FROM imageass
4774      WHERE (imageass_source_id=OLD.crmacct_id) AND (imageass_source='CRMA');
4775     DELETE FROM url
4776      WHERE (url_source_id=OLD.crmacct_id)      AND (url_source='CRMA');
4777
4778   END IF;
4779
4780   SELECT cmnttype_id INTO _cmnttypeid
4781     FROM cmnttype
4782    WHERE (cmnttype_name='ChangeLog');
4783   IF (_cmnttypeid IS NOT NULL) THEN
4784     IF (TG_OP = 'INSERT') THEN
4785       PERFORM postComment(_cmnttypeid, 'CRMA', NEW.crmacct_id,
4786                           ('Created by ' || getEffectiveXtUser()));
4787
4788     ELSIF (TG_OP = 'DELETE') THEN
4789       PERFORM postComment(_cmnttypeid, 'CRMA', OLD.crmacct_id,
4790                           'Deleted "' || OLD.crmacct_number || '"');
4791     END IF;
4792   END IF;
4793
4794   IF (TG_OP = 'DELETE') THEN
4795     RETURN OLD;
4796   END IF;
4797
4798   RETURN NEW;
4799 END;
4800 $$;
4801
4802
4803 ALTER FUNCTION public._crmacctaftertrigger() OWNER TO admin;
4804
4805 --
4806 -- TOC entry 955 (class 1255 OID 146565467)
4807 -- Dependencies: 4536 8
4808 -- Name: _crmacctbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
4809 --
4810
4811 CREATE FUNCTION _crmacctbeforetrigger() RETURNS trigger
4812     LANGUAGE plpgsql
4813     AS $$
4814 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
4815 -- See www.xtuple.com/CPAL for the full text of the software license.
4816 DECLARE
4817   _count        INTEGER;
4818 BEGIN
4819   -- disallow reusing crmacct_numbers
4820   IF (TG_OP IN ('INSERT', 'UPDATE')) THEN
4821     IF (TG_OP = 'INSERT' AND fetchMetricText('CRMAccountNumberGeneration') IN ('A','O')) THEN
4822       PERFORM clearNumberIssue('CRMAccountNumber', NEW.crmacct_number);
4823     END IF;
4824
4825     NEW.crmacct_usr_username := LOWER(TRIM(NEW.crmacct_usr_username));
4826     IF (NEW.crmacct_usr_username = '') THEN
4827       NEW.crmacct_usr_username = NULL;
4828     END IF;
4829
4830     NEW.crmacct_owner_username := LOWER(TRIM(NEW.crmacct_owner_username));
4831     IF (COALESCE(NEW.crmacct_owner_username, '') = '') THEN
4832       NEW.crmacct_owner_username = getEffectiveXtUser();
4833     END IF;
4834
4835     IF (NEW.crmacct_competitor_id < 0) THEN
4836       NEW.crmacct_competitor_id := NULL;
4837     END IF;
4838     IF (NEW.crmacct_partner_id < 0) THEN
4839       NEW.crmacct_partner_id := NULL;
4840     END IF;
4841
4842     NEW.crmacct_number = UPPER(NEW.crmacct_number);
4843
4844     IF (TG_OP = 'UPDATE') THEN
4845       -- TODO: why not ALTER USER OLD.crmacct_number RENAME TO LOWER(NEW.crmacct_number)?
4846       IF (NEW.crmacct_number != UPPER(OLD.crmacct_number) AND
4847           NEW.crmacct_usr_username IS NOT NULL            AND
4848           UPPER(NEW.crmacct_usr_username) != NEW.crmacct_number) THEN
4849         RAISE EXCEPTION 'The CRM Account % is associated with a system User so the number cannot be changed.',
4850                         NEW.crmacct_number;
4851       END IF;
4852     END IF;
4853
4854   ELSIF (TG_OP = 'DELETE') THEN
4855     UPDATE cntct SET cntct_crmacct_id = NULL
4856      WHERE cntct_crmacct_id = OLD.crmacct_id;
4857
4858     DELETE FROM docass WHERE docass_source_id = OLD.crmacct_id AND docass_source_type = 'CRMA';
4859     DELETE FROM docass WHERE docass_target_id = OLD.crmacct_id AND docass_target_type = 'CRMA';
4860
4861     GET DIAGNOSTICS _count = ROW_COUNT;
4862     RAISE DEBUG 'updated % contacts', _count;
4863
4864     RETURN OLD;
4865
4866   END IF;
4867
4868   RETURN NEW;
4869 END;
4870 $$;
4871
4872
4873 ALTER FUNCTION public._crmacctbeforetrigger() OWNER TO admin;
4874
4875 --
4876 -- TOC entry 956 (class 1255 OID 146565468)
4877 -- Dependencies: 4536 8
4878 -- Name: _custaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
4879 --
4880
4881 CREATE FUNCTION _custaftertrigger() RETURNS trigger
4882     LANGUAGE plpgsql
4883     AS $$
4884 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
4885 -- See www.xtuple.com/CPAL for the full text of the software license.
4886 DECLARE
4887   _cmnttypeid INTEGER;
4888   _whsId      INTEGER := -1;
4889
4890 BEGIN
4891
4892   IF (TG_OP = 'INSERT') THEN
4893     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
4894     LOOP
4895       UPDATE crmacct SET crmacct_cust_id=NEW.cust_id,
4896                          crmacct_name=NEW.cust_name,
4897                          crmacct_prospect_id=NULL
4898       WHERE crmacct_number=NEW.cust_number;
4899       IF (FOUND) THEN
4900         DELETE FROM prospect WHERE prospect_id=NEW.cust_id;
4901         EXIT;
4902       END IF;
4903       BEGIN
4904         INSERT INTO crmacct(crmacct_number,  crmacct_name,    crmacct_active,
4905                             crmacct_type,    crmacct_cust_id, crmacct_cntct_id_1,
4906                             crmacct_cntct_id_2
4907                   ) VALUES (NEW.cust_number, NEW.cust_name,   NEW.cust_active,
4908                             'O',             NEW.cust_id,     NEW.cust_cntct_id,
4909                             NEW.cust_corrcntct_id);
4910         EXIT;
4911       EXCEPTION WHEN unique_violation THEN
4912             -- do nothing, and loop to try the UPDATE again
4913       END;
4914     END LOOP;
4915
4916     PERFORM updateCharAssignment('C', NEW.cust_id, char_id, charass_value)
4917        FROM custtype
4918        JOIN charass ON (custtype_id=charass_target_id AND charass_target_type='CT')
4919        JOIN char ON (charass_char_id=char_id)
4920        WHERE ((custtype_id=NEW.cust_custtype_id)
4921           AND (custtype_char)
4922           AND (charass_default));
4923
4924   ELSIF (TG_OP = 'UPDATE') THEN
4925     UPDATE crmacct SET crmacct_number = NEW.cust_number
4926     WHERE ((crmacct_cust_id=NEW.cust_id)
4927       AND  (crmacct_number!=NEW.cust_number));
4928
4929     UPDATE crmacct SET crmacct_name = NEW.cust_name
4930     WHERE ((crmacct_cust_id=NEW.cust_id)
4931       AND  (crmacct_name!=NEW.cust_name));
4932   END IF;
4933
4934   IF (TG_OP = 'INSERT') THEN
4935     PERFORM postEvent('NewCustomer', 'C', NEW.cust_id,
4936                       NULL, NEW.cust_number,
4937                       NULL, NULL, NULL, NULL);
4938   END IF;
4939
4940   IF (fetchMetricBool('CustomerChangeLog')) THEN
4941     SELECT cmnttype_id INTO _cmnttypeid
4942       FROM cmnttype
4943      WHERE (cmnttype_name='ChangeLog');
4944
4945     IF (_cmnttypeid IS NOT NULL) THEN
4946       IF (TG_OP = 'INSERT') THEN
4947         PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id, 'Created');
4948
4949       ELSIF (TG_OP = 'UPDATE') THEN
4950
4951         IF (OLD.cust_number <> NEW.cust_number) THEN
4952           PERFORM postComment( _cmnttypeid, 'C', NEW.cust_id,
4953                               ('Number changed from "' || OLD.cust_number ||
4954                                '" to "' || NEW.cust_number || '"') );
4955         END IF;
4956
4957         IF (OLD.cust_name <> NEW.cust_name) THEN
4958           PERFORM postComment( _cmnttypeid, 'C', NEW.cust_id,
4959                               ('Name changed from "' || OLD.cust_name ||
4960                                '" to "' || NEW.cust_name || '"') );
4961         END IF;
4962
4963         IF (OLD.cust_active <> NEW.cust_active) THEN
4964           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
4965                               CASE WHEN NEW.cust_active THEN 'Activated'
4966                                    ELSE 'Deactivated' END);
4967         END IF;
4968
4969         IF (OLD.cust_discntprcnt <> NEW.cust_discntprcnt) THEN
4970           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
4971                               ('Discount changed from "' ||
4972                                formatprcnt(OLD.cust_discntprcnt) || '%" to "' ||
4973                                formatprcnt(NEW.cust_discntprcnt) || '%"') );
4974         END IF;
4975
4976         IF (OLD.cust_creditlmt <> NEW.cust_creditlmt) THEN
4977           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
4978                               ('Credit Limit changed from ' || formatMoney(OLD.cust_creditlmt) ||
4979                                ' to ' || formatMoney(NEW.cust_creditlmt)));
4980         END IF;
4981
4982         IF (OLD.cust_creditstatus <> NEW.cust_creditstatus) THEN
4983           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
4984                               ('Credit Status Changed from "' ||
4985                                CASE OLD.cust_creditstatus
4986                                     WHEN 'G' THEN 'In Good Standing'
4987                                     WHEN 'W' THEN 'Credit Warning'
4988                                     WHEN 'H' THEN 'Credit Hold'
4989                                     ELSE 'Unknown/Error'
4990                                END || '" to "' ||
4991                                CASE NEW.cust_creditstatus
4992                                     WHEN 'G' THEN 'In Good Standing'
4993                                     WHEN 'W' THEN 'Credit Warning'
4994                                     WHEN 'H' THEN 'Credit Hold'
4995                                     ELSE 'Unknown/Error'
4996                                END || '"') );
4997         END IF;
4998
4999         IF (OLD.cust_custtype_id <> NEW.cust_custtype_id) THEN
5000           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
5001                               ('Customer type changed from "' ||
5002                                (SELECT custtype_code FROM custtype
5003                                  WHERE custtype_id = OLD.cust_custtype_id) || '" to "' ||
5004                                (SELECT custtype_code FROM custtype
5005                                  WHERE custtype_id = NEW.cust_custtype_id) || '"') );
5006         END IF;
5007
5008         IF (COALESCE(OLD.cust_gracedays,-1) <> COALESCE(NEW.cust_gracedays,-1)) THEN
5009           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
5010                               ('Grace Days changed from "' ||
5011                                COALESCE(TEXT(OLD.cust_gracedays), 'Default') ||
5012                                '" to "' ||
5013                                COALESCE(TEXT(NEW.cust_gracedays), 'Default') || '"'));
5014         END IF;
5015
5016         IF (OLD.cust_terms_id <> NEW.cust_terms_id) THEN
5017           PERFORM postComment(_cmnttypeid, 'C', NEW.cust_id,
5018                               ('Terms changed from "' ||
5019                                (SELECT terms_code FROM terms
5020                                  WHERE terms_id = OLD.cust_terms_id) || '" to "' ||
5021                                (SELECT terms_code FROM terms
5022                                  WHERE terms_id = NEW.cust_terms_id) || '"'));
5023         END IF;
5024
5025       END IF;
5026     END IF;
5027   END IF;
5028
5029   RETURN NEW;
5030 END;
5031 $$;
5032
5033
5034 ALTER FUNCTION public._custaftertrigger() OWNER TO admin;
5035
5036 --
5037 -- TOC entry 957 (class 1255 OID 146565469)
5038 -- Dependencies: 4536 8
5039 -- Name: _custinfoafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5040 --
5041
5042 CREATE FUNCTION _custinfoafterdeletetrigger() RETURNS trigger
5043     LANGUAGE plpgsql
5044     AS $$
5045 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
5046 -- See www.xtuple.com/CPAL for the full text of the software license.
5047 BEGIN
5048   -- handle transitory state when converting customer to prospect
5049   IF EXISTS(SELECT quhead_id
5050               FROM quhead
5051              WHERE (quhead_cust_id=OLD.cust_id) AND
5052      NOT EXISTS(SELECT prospect_id
5053                   FROM prospect
5054                  WHERE prospect_id=OLD.cust_id)) THEN
5055     RAISE EXCEPTION '[xtuple: deleteCustomer, -8]';
5056   END IF;
5057
5058   IF EXISTS(SELECT invchead_id
5059               FROM invchead
5060              WHERE (invchead_cust_id=OLD.cust_id)) THEN
5061     RAISE EXCEPTION '[xtuple: deleteCustomer, -7]';
5062   END IF;
5063   -- end TODO
5064
5065   IF EXISTS(SELECT checkhead_recip_id
5066               FROM checkhead
5067              WHERE ((checkhead_recip_id=OLD.cust_id)
5068                AND  (checkhead_recip_type='C'))) THEN
5069     RAISE EXCEPTION '[xtuple: deleteCustomer, -6]';
5070   END IF;
5071
5072   DELETE FROM taxreg
5073    WHERE ((taxreg_rel_type='C')
5074      AND  (taxreg_rel_id=OLD.cust_id));
5075
5076   DELETE FROM ipsass
5077    WHERE (ipsass_cust_id=OLD.cust_id);
5078
5079   DELETE FROM docass WHERE docass_source_id = OLD.cust_id AND docass_source_type = 'C';
5080   DELETE FROM docass WHERE docass_target_id = OLD.cust_id AND docass_target_type = 'C';
5081
5082   IF (fetchMetricBool('CustomerChangeLog')) THEN
5083     PERFORM postComment(cmnttype_id, 'C', OLD.cust_id,
5084                         ('Deleted "' || OLD.cust_number || '"'))
5085       FROM cmnttype
5086      WHERE (cmnttype_name='ChangeLog');
5087   END IF;
5088
5089   RETURN OLD;
5090 END;
5091 $$;
5092
5093
5094 ALTER FUNCTION public._custinfoafterdeletetrigger() OWNER TO admin;
5095
5096 --
5097 -- TOC entry 958 (class 1255 OID 146565470)
5098 -- Dependencies: 4536 8
5099 -- Name: _custinfobeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5100 --
5101
5102 CREATE FUNCTION _custinfobeforedeletetrigger() RETURNS trigger
5103     LANGUAGE plpgsql
5104     AS $$
5105 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
5106 -- See www.xtuple.com/CPAL for the full text of the software license.
5107 BEGIN
5108   IF NOT (checkPrivilege('MaintainCustomerMasters')) THEN
5109     RAISE EXCEPTION 'You do not have privileges to maintain Customers.';
5110   END IF;
5111
5112   UPDATE crmacct SET crmacct_cust_id = NULL
5113    WHERE crmacct_cust_id = OLD.cust_id;
5114
5115   RETURN OLD;
5116 END;
5117 $$;
5118
5119
5120 ALTER FUNCTION public._custinfobeforedeletetrigger() OWNER TO admin;
5121
5122 --
5123 -- TOC entry 960 (class 1255 OID 146565471)
5124 -- Dependencies: 4536 8
5125 -- Name: _custtrigger(); Type: FUNCTION; Schema: public; Owner: admin
5126 --
5127
5128 CREATE FUNCTION _custtrigger() RETURNS trigger
5129     LANGUAGE plpgsql
5130     AS $$
5131 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
5132 -- See www.xtuple.com/CPAL for the full text of the software license.
5133 BEGIN
5134   IF NOT (checkPrivilege('MaintainCustomerMasters') OR
5135           checkPrivilege('PostMiscInvoices')) THEN
5136     RAISE EXCEPTION 'You do not have privileges to maintain Customers.';
5137   END IF;
5138
5139   IF (NEW.cust_number IS NULL) THEN
5140         RAISE EXCEPTION 'You must supply a valid Customer Number.';
5141   END IF;
5142
5143   IF (LENGTH(COALESCE(NEW.cust_name,''))=0) THEN
5144         RAISE EXCEPTION 'You must supply a valid Customer Name.';
5145   END IF;
5146
5147   IF (NEW.cust_custtype_id IS NULL) THEN
5148         RAISE EXCEPTION 'You must supply a valid Customer Type ID.';
5149   END IF;
5150
5151   IF (NEW.cust_salesrep_id IS NULL) THEN
5152         RAISE EXCEPTION 'You must supply a valid Sales Rep ID.';
5153   END IF;
5154
5155   IF (NEW.cust_terms_id IS NULL) THEN
5156         RAISE EXCEPTION 'You must supply a valid Terms Code ID.';
5157   END IF;
5158
5159   IF (TG_OP = 'INSERT' AND fetchMetricText('CRMAccountNumberGeneration') IN ('A','O')) THEN
5160     PERFORM clearNumberIssue('CRMAccountNumber', NEW.cust_number);
5161   END IF;
5162
5163   NEW.cust_number := UPPER(NEW.cust_number);
5164
5165   RETURN NEW;
5166 END;
5167 $$;
5168
5169
5170 ALTER FUNCTION public._custtrigger() OWNER TO admin;
5171
5172 --
5173 -- TOC entry 961 (class 1255 OID 146565472)
5174 -- Dependencies: 4536 8
5175 -- Name: _custtypeafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5176 --
5177
5178 CREATE FUNCTION _custtypeafterdeletetrigger() RETURNS trigger
5179     LANGUAGE plpgsql
5180     AS $$
5181 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5182 -- See www.xtuple.com/CPAL for the full text of the software license.
5183 BEGIN
5184   IF (SELECT fetchMetricValue('DefaultCustType') = OLD.custtype_id) THEN
5185     RAISE EXCEPTION 'Cannot delete the default Customer Type [xtuple: custtype, -1, %]',
5186                     OLD.custtype_code;
5187   END IF;
5188
5189   RETURN OLD;
5190 END;
5191 $$;
5192
5193
5194 ALTER FUNCTION public._custtypeafterdeletetrigger() OWNER TO admin;
5195
5196 --
5197 -- TOC entry 962 (class 1255 OID 146565473)
5198 -- Dependencies: 4536 8
5199 -- Name: _custtypetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5200 --
5201
5202 CREATE FUNCTION _custtypetrigger() RETURNS trigger
5203     LANGUAGE plpgsql
5204     AS $$
5205 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5206 -- See www.xtuple.com/CPAL for the full text of the software license.
5207 DECLARE
5208   _check      BOOLEAN;
5209   _code       TEXT;
5210
5211 BEGIN
5212
5213 --  Checks
5214   IF (TG_OP IN ('INSERT','UPDATE')) THEN
5215
5216     IF (LENGTH(COALESCE(NEW.custtype_code, ''))=0) THEN
5217       RAISE EXCEPTION 'You must supply a valid Customer Type Code.';
5218     END IF;
5219
5220     SELECT custtype_code INTO _code
5221     FROM custtype
5222     WHERE ( (UPPER(custtype_code)=UPPER(NEW.custtype_code))
5223       AND (custtype_id<>NEW.custtype_id) );
5224     IF (FOUND) THEN
5225       RAISE EXCEPTION 'The Customer Type Code entered cannot be used as it is in use.';
5226     END IF;
5227
5228   END IF;
5229
5230   RETURN NEW;
5231 END;
5232 $$;
5233
5234
5235 ALTER FUNCTION public._custtypetrigger() OWNER TO admin;
5236
5237 --
5238 -- TOC entry 963 (class 1255 OID 146565474)
5239 -- Dependencies: 4536 8
5240 -- Name: _docasstrigger(); Type: FUNCTION; Schema: public; Owner: admin
5241 --
5242
5243 CREATE FUNCTION _docasstrigger() RETURNS trigger
5244     LANGUAGE plpgsql
5245     AS $$
5246 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5247 -- See www.xtuple.com/CPAL for the full text of the software license.
5248 BEGIN
5249   IF (NEW.docass_source_type = 'INCDT') THEN
5250     UPDATE incdt SET incdt_updated = now() WHERE incdt_id = NEW.docass_source_id;
5251   END IF;
5252
5253   RETURN NEW;
5254 END;
5255 $$;
5256
5257
5258 ALTER FUNCTION public._docasstrigger() OWNER TO admin;
5259
5260 --
5261 -- TOC entry 964 (class 1255 OID 146565475)
5262 -- Dependencies: 4536 8
5263 -- Name: _empafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5264 --
5265
5266 CREATE FUNCTION _empafterdeletetrigger() RETURNS trigger
5267     LANGUAGE plpgsql
5268     AS $$
5269 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5270 -- See www.xtuple.com/CPAL for the full text of the software license.
5271 BEGIN
5272   IF (fetchMetricBool('EmployeeChangeLog')) THEN
5273     PERFORM postComment(cmnttype_id, 'EMP', OLD.emp_id,
5274                         ('Deleted "' || OLD.emp_code || '"'))
5275       FROM cmnttype
5276      WHERE (cmnttype_name='ChangeLog');
5277   END IF;
5278
5279   RETURN OLD;
5280 END;
5281 $$;
5282
5283
5284 ALTER FUNCTION public._empafterdeletetrigger() OWNER TO admin;
5285
5286 --
5287 -- TOC entry 965 (class 1255 OID 146565476)
5288 -- Dependencies: 4536 8
5289 -- Name: _empaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
5290 --
5291
5292 CREATE FUNCTION _empaftertrigger() RETURNS trigger
5293     LANGUAGE plpgsql
5294     AS $$
5295 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5296 -- See www.xtuple.com/CPAL for the full text of the software license.
5297 DECLARE
5298   _cmnttypeid     INTEGER;
5299   _newcrmacctname TEXT;
5300
5301 BEGIN
5302
5303   IF (TG_OP = 'INSERT') THEN
5304     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
5305     LOOP
5306       UPDATE crmacct SET crmacct_emp_id=NEW.emp_id,
5307                          crmacct_name=NEW.emp_name
5308        WHERE crmacct_number=NEW.emp_code;
5309       IF (FOUND) THEN
5310         EXIT;
5311       END IF;
5312       BEGIN
5313         INSERT INTO crmacct(crmacct_number,  crmacct_name,    crmacct_active,
5314                             crmacct_type,    crmacct_emp_id,  crmacct_cntct_id_1
5315                   ) VALUES (NEW.emp_code,    NEW.emp_name,    NEW.emp_active, 
5316                             'I',             NEW.emp_id,      NEW.emp_cntct_id);
5317         EXIT;
5318       EXCEPTION WHEN unique_violation THEN
5319             -- do nothing, and loop to try the UPDATE again
5320       END;
5321     END LOOP;
5322
5323     /* TODO: default characteristic assignments based on empgrp? */
5324
5325   ELSIF (TG_OP = 'UPDATE') THEN
5326     UPDATE crmacct SET crmacct_number = NEW.emp_code
5327     WHERE ((crmacct_emp_id=NEW.emp_id)
5328       AND  (crmacct_number!=NEW.emp_code));
5329
5330     UPDATE crmacct SET crmacct_name = NEW.emp_name
5331     WHERE ((crmacct_emp_id=NEW.emp_id)
5332       AND  (crmacct_name!=NEW.emp_name));
5333   END IF;
5334
5335   IF (fetchMetricBool('EmployeeChangeLog')) THEN
5336     SELECT cmnttype_id INTO _cmnttypeid
5337       FROM cmnttype
5338      WHERE (cmnttype_name='ChangeLog');
5339
5340     IF (_cmnttypeid IS NOT NULL) THEN
5341       IF (TG_OP = 'INSERT') THEN
5342         PERFORM postComment(_cmnttypeid, 'EMP', NEW.emp_id, 'Created');
5343
5344       ELSIF (TG_OP = 'UPDATE') THEN
5345
5346         IF (OLD.emp_number <> NEW.emp_number) THEN
5347           PERFORM postComment(_cmnttypeid, 'EMP', NEW.emp_id,
5348                               ('Number Changed from "' || OLD.emp_number ||
5349                                '" to "' || NEW.emp_number || '"'));
5350         END IF;
5351
5352         IF (OLD.emp_code <> NEW.emp_code) THEN
5353           PERFORM postComment(_cmnttypeid, 'EMP', NEW.emp_id,
5354                               ('Code Changed from "' || OLD.emp_code ||
5355                                '" to "' || NEW.emp_code || '"'));
5356         END IF;
5357
5358         IF (OLD.emp_active <> NEW.emp_active) THEN
5359           PERFORM postComment(_cmnttypeid, 'EMP', NEW.emp_id,
5360                               CASE WHEN NEW.emp_active THEN 'Activated'
5361                                    ELSE 'Deactivated' END);
5362         END IF;
5363
5364         IF (COALESCE(OLD.emp_dept_id, -1) <> COALESCE(NEW.emp_dept_id, -1)) THEN
5365           PERFORM postComment(_cmnttypeid, 'EMP', NEW.emp_id,
5366                               ('Department Changed from "' ||
5367                                COALESCE((SELECT dept_number FROM dept
5368                                           WHERE dept_id=OLD.emp_dept_id), '')
5369                                || '" to "' ||
5370                                COALESCE((SELECT dept_number FROM dept
5371                                           WHERE dept_id=NEW.emp_dept_id), '') || '"'));
5372         END IF;
5373
5374         IF (COALESCE(OLD.emp_shift_id, -1) <> COALESCE(NEW.emp_shift_id, -1)) THEN
5375           PERFORM postComment(_cmnttypeid, 'EMP', NEW.emp_id,
5376                               ('Shift Changed from "' ||
5377                                COALESCE((SELECT shift_number FROM shift
5378                                           WHERE shift_id=OLD.emp_shift_id), '')
5379                                || '" to "' ||
5380                                COALESCE((SELECT shift_number FROM shift
5381                                           WHERE shift_id=NEW.emp_shift_id), '') || '"'));
5382         END IF;
5383
5384       END IF;
5385     END IF;
5386   END IF;
5387
5388   RETURN NEW;
5389 END;
5390 $$;
5391
5392
5393 ALTER FUNCTION public._empaftertrigger() OWNER TO admin;
5394
5395 --
5396 -- TOC entry 966 (class 1255 OID 146565477)
5397 -- Dependencies: 4536 8
5398 -- Name: _empbeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5399 --
5400
5401 CREATE FUNCTION _empbeforedeletetrigger() RETURNS trigger
5402     LANGUAGE plpgsql
5403     AS $$
5404 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5405 -- See www.xtuple.com/CPAL for the full text of the software license.
5406 BEGIN
5407   IF NOT (checkPrivilege('MaintainEmployees')) THEN
5408     RAISE EXCEPTION 'You do not have privileges to maintain Employees.';
5409   END IF;
5410
5411   UPDATE crmacct SET crmacct_emp_id = NULL
5412    WHERE crmacct_emp_id = OLD.emp_id;
5413
5414   UPDATE salesrep SET salesrep_emp_id = NULL
5415    WHERE salesrep_emp_id = OLD.emp_id;
5416
5417   DELETE FROM docass WHERE docass_source_id = OLD.emp_id AND docass_source_type = 'EMP';
5418   DELETE FROM docass WHERE docass_target_id = OLD.emp_id AND docass_target_type = 'EMP';
5419
5420   RETURN OLD;
5421 END;
5422 $$;
5423
5424
5425 ALTER FUNCTION public._empbeforedeletetrigger() OWNER TO admin;
5426
5427 --
5428 -- TOC entry 967 (class 1255 OID 146565478)
5429 -- Dependencies: 4536 8
5430 -- Name: _empbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5431 --
5432
5433 CREATE FUNCTION _empbeforetrigger() RETURNS trigger
5434     LANGUAGE plpgsql
5435     AS $$
5436 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5437 -- See www.xtuple.com/CPAL for the full text of the software license.
5438 BEGIN
5439
5440   IF NOT (checkPrivilege('MaintainEmployees')) THEN
5441     RAISE EXCEPTION 'You do not have privileges to maintain Employees.';
5442   END IF;
5443
5444   IF (NEW.emp_code IS NULL) THEN
5445     RAISE EXCEPTION 'You must supply a valid Employee Code.';
5446   END IF;
5447
5448   IF (NEW.emp_number IS NULL) THEN
5449     RAISE EXCEPTION 'You must supply a valid Employee Number.';
5450   END IF;
5451
5452   IF (NEW.emp_id = NEW.emp_mgr_emp_id) THEN
5453     RAISE EXCEPTION 'An Employee may not be his or her own Manager.';
5454   END IF;
5455
5456   -- ERROR:  cannot use column references in default expression
5457   IF (NEW.emp_name IS NULL) THEN
5458     NEW.emp_name = COALESCE(formatCntctName(NEW.emp_cntct_id), NEW.emp_number);
5459   END IF;
5460
5461   IF (TG_OP = 'INSERT' AND fetchMetricText('CRMAccountNumberGeneration') IN ('A','O')) THEN
5462     PERFORM clearNumberIssue('CRMAccountNumber', NEW.emp_number);
5463   END IF;
5464
5465   NEW.emp_code := UPPER(NEW.emp_code);
5466
5467   -- deprecated column emp_username
5468   IF (TG_OP = 'UPDATE' AND
5469       LOWER(NEW.emp_username) != LOWER(NEW.emp_code) AND
5470       EXISTS(SELECT 1
5471                FROM crmacct
5472               WHERE crmacct_emp_id = NEW.emp_id
5473                 AND crmacct_usr_username IS NOT NULL)) THEN
5474     NEW.emp_username = LOWER(NEW.emp_code);
5475   END IF;
5476
5477   RETURN NEW;
5478 END;
5479 $$;
5480
5481
5482 ALTER FUNCTION public._empbeforetrigger() OWNER TO admin;
5483
5484 --
5485 -- TOC entry 968 (class 1255 OID 146565479)
5486 -- Dependencies: 4536 8
5487 -- Name: _evntlogafterinserttrigger(); Type: FUNCTION; Schema: public; Owner: admin
5488 --
5489
5490 CREATE FUNCTION _evntlogafterinserttrigger() RETURNS trigger
5491     LANGUAGE plpgsql
5492     AS $$
5493 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5494 -- See www.xtuple.com/CPAL for the full text of the software license.
5495 DECLARE
5496   _r RECORD;
5497
5498 BEGIN
5499
5500   IF (NEW.evntlog_username = 'autopilot') THEN
5501     SELECT * INTO _r FROM evnttype WHERE (evnttype_id=NEW.evntlog_evnttype_id);
5502     IF (_r.evnttype_name = 'SoCreated') THEN
5503       PERFORM createPrjToSale(NEW.evntlog_ord_id);
5504     END IF;
5505   END IF;
5506
5507   RETURN NEW;
5508 END;
5509 $$;
5510
5511
5512 ALTER FUNCTION public._evntlogafterinserttrigger() OWNER TO admin;
5513
5514 --
5515 -- TOC entry 969 (class 1255 OID 146565480)
5516 -- Dependencies: 4536 8
5517 -- Name: _gltransaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
5518 --
5519
5520 CREATE FUNCTION _gltransaltertrigger() RETURNS trigger
5521     LANGUAGE plpgsql
5522     AS $$
5523 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5524 -- See www.xtuple.com/CPAL for the full text of the software license.
5525 DECLARE
5526   _externalCompany      BOOLEAN := false;
5527   _updated BOOLEAN := false;
5528 BEGIN
5529   IF(TG_OP='DELETE') THEN
5530     RAISE EXCEPTION 'You may not delete G/L Transactions once they have been created.';
5531   ELSIF (TG_OP = 'UPDATE') THEN
5532     SELECT company_external INTO _externalCompany
5533     FROM company JOIN accnt ON (company_number=accnt_company)
5534     WHERE (accnt_id=NEW.gltrans_accnt_id);
5535     IF (_externalCompany) THEN
5536       RAISE EXCEPTION 'Transactions are not allowed for G/L Accounts with External Company segments.';
5537     END IF;
5538
5539     IF(OLD.gltrans_id != NEW.gltrans_id) THEN
5540       _updated := true;
5541     ELSIF(OLD.gltrans_date != NEW.gltrans_date) THEN
5542       _updated := true;
5543     ELSIF(OLD.gltrans_accnt_id != NEW.gltrans_accnt_id) THEN
5544       _updated := true;
5545     ELSIF(OLD.gltrans_amount != NEW.gltrans_amount) THEN
5546       _updated := true;
5547     ELSIF(OLD.gltrans_username != NEW.gltrans_username) THEN
5548       _updated := true;
5549     ELSIF( (OLD.gltrans_sequence IS NULL     AND NEW.gltrans_sequence IS NOT NULL)
5550         OR (OLD.gltrans_sequence IS NOT NULL AND NEW.gltrans_sequence IS NULL)
5551         OR (COALESCE(OLD.gltrans_sequence,0) != COALESCE(NEW.gltrans_sequence,0)) ) THEN
5552       _updated := true;
5553     ELSIF( (OLD.gltrans_created IS NULL     AND NEW.gltrans_created IS NOT NULL)
5554         OR (OLD.gltrans_created IS NOT NULL AND NEW.gltrans_created IS NULL)
5555         OR (COALESCE(OLD.gltrans_created,now()) != COALESCE(NEW.gltrans_created,now())) ) THEN
5556       _updated := true;
5557     ELSIF( (OLD.gltrans_source IS NULL     AND NEW.gltrans_source IS NOT NULL)
5558         OR (OLD.gltrans_source IS NOT NULL AND NEW.gltrans_source IS NULL)
5559         OR (COALESCE(OLD.gltrans_source,'') != COALESCE(NEW.gltrans_source,'')) ) THEN
5560       _updated := true;
5561     ELSIF( (OLD.gltrans_docnumber IS NULL     AND NEW.gltrans_docnumber IS NOT NULL)
5562         OR (OLD.gltrans_docnumber IS NOT NULL AND NEW.gltrans_docnumber IS NULL)
5563         OR (COALESCE(OLD.gltrans_docnumber,'') != COALESCE(NEW.gltrans_docnumber,'')) ) THEN
5564       _updated := true;
5565     ELSIF( (OLD.gltrans_doctype IS NULL     AND NEW.gltrans_doctype IS NOT NULL)
5566         OR (OLD.gltrans_doctype IS NOT NULL AND NEW.gltrans_doctype IS NULL)
5567         OR (COALESCE(OLD.gltrans_doctype,'') != COALESCE(NEW.gltrans_doctype,'')) ) THEN
5568       _updated := true;
5569     END IF;
5570
5571     IF(_updated) THEN
5572       RAISE EXCEPTION 'You may not alter some G/L Transaction fields once they have been created.';
5573     END IF;
5574   ELSE
5575     RAISE EXCEPTION 'trigger for gltrans table called in unexpected state.';
5576   END IF;
5577   RETURN NEW;
5578 END;
5579 $$;
5580
5581
5582 ALTER FUNCTION public._gltransaltertrigger() OWNER TO admin;
5583
5584 --
5585 -- TOC entry 970 (class 1255 OID 146565481)
5586 -- Dependencies: 4536 8
5587 -- Name: _gltransinserttrigger(); Type: FUNCTION; Schema: public; Owner: admin
5588 --
5589
5590 CREATE FUNCTION _gltransinserttrigger() RETURNS trigger
5591     LANGUAGE plpgsql
5592     AS $$
5593 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5594 -- See www.xtuple.com/CPAL for the full text of the software license.
5595 DECLARE
5596   _reqNotes BOOLEAN;
5597   _externalCompany      BOOLEAN := false;
5598 BEGIN
5599   -- Checks
5600   -- Start with privileges
5601   IF ((NEW.gltrans_doctype='JE') AND (NOT checkPrivilege('PostJournalEntries'))) THEN
5602       RAISE EXCEPTION 'You do not have privileges to create a Journal Entry.';
5603   END IF;
5604
5605   SELECT company_external INTO _externalCompany
5606   FROM company JOIN accnt ON (company_number=accnt_company)
5607   WHERE (accnt_id=NEW.gltrans_accnt_id);
5608   IF (_externalCompany) THEN
5609     RAISE EXCEPTION 'Transactions are not allowed for G/L Accounts with External Company segments.';
5610   END IF;
5611   -- RAISE NOTICE '_gltransInsertTrigger(): company_external = %', _externalCompany;
5612
5613   SELECT metric_value='t'
5614     INTO _reqNotes
5615     FROM metric
5616    WHERE(metric_name='MandatoryGLEntryNotes');
5617   IF (_reqNotes IS NULL) THEN
5618     _reqNotes := false;
5619   END IF;
5620   IF ((NEW.gltrans_doctype='JE') AND _reqNotes AND (TRIM(BOTH FROM COALESCE(NEW.gltrans_notes,''))='')) THEN
5621       RAISE EXCEPTION 'Notes are required for Journal Entries.';
5622   END IF;
5623   
5624   RETURN NEW;
5625 END;
5626 $$;
5627
5628
5629 ALTER FUNCTION public._gltransinserttrigger() OWNER TO admin;
5630
5631 --
5632 -- TOC entry 971 (class 1255 OID 146565482)
5633 -- Dependencies: 4536 8
5634 -- Name: _grpprivtrigger(); Type: FUNCTION; Schema: public; Owner: admin
5635 --
5636
5637 CREATE FUNCTION _grpprivtrigger() RETURNS trigger
5638     LANGUAGE plpgsql
5639     AS $$
5640 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5641 -- See www.xtuple.com/CPAL for the full text of the software license.
5642 DECLARE
5643   _check BOOLEAN;
5644   _returnVal INTEGER;
5645 BEGIN
5646   -- This looks like a candidate for a foreign key but isn't.
5647   -- fkeys don't work if the foreign key value resides in a child of the 
5648   -- table and not the table itself.
5649   IF ((TG_OP = 'UPDATE' OR TG_OP = 'INSERT') AND
5650       (NOT EXISTS(SELECT priv_id
5651                   FROM priv
5652                   WHERE (priv_id=NEW.grppriv_priv_id)))) THEN
5653     RAISE EXCEPTION 'Privilege id % does not exist or is part of a disabled package.',
5654                 NEW.grppriv_priv_id;
5655     RETURN OLD;
5656
5657   ELSIF (TG_OP = 'DELETE') THEN
5658     RETURN OLD;
5659   END IF;
5660
5661   RETURN NEW;
5662 END;
5663 $$;
5664
5665
5666 ALTER FUNCTION public._grpprivtrigger() OWNER TO admin;
5667
5668 --
5669 -- TOC entry 972 (class 1255 OID 146565483)
5670 -- Dependencies: 4536 8
5671 -- Name: _imageasstrigger(); Type: FUNCTION; Schema: public; Owner: admin
5672 --
5673
5674 CREATE FUNCTION _imageasstrigger() RETURNS trigger
5675     LANGUAGE plpgsql
5676     AS $$
5677 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5678 -- See www.xtuple.com/CPAL for the full text of the software license.
5679 BEGIN
5680   IF (NEW.imageass_source = 'INCDT') THEN
5681     UPDATE incdt SET incdt_updated = now() WHERE incdt_id = NEW.imageass_source_id;
5682   END IF;
5683
5684   RETURN NEW;
5685 END;
5686 $$;
5687
5688
5689 ALTER FUNCTION public._imageasstrigger() OWNER TO admin;
5690
5691 --
5692 -- TOC entry 973 (class 1255 OID 146565484)
5693 -- Dependencies: 4536 8
5694 -- Name: _incdtbeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5695 --
5696
5697 CREATE FUNCTION _incdtbeforedeletetrigger() RETURNS trigger
5698     LANGUAGE plpgsql
5699     AS $$
5700 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5701 -- See www.xtuple.com/CPAL for the full text of the software license.
5702 DECLARE
5703   _recurid     INTEGER;
5704   _newparentid INTEGER;
5705 BEGIN
5706   IF (TG_OP = 'DELETE') THEN
5707     SELECT recur_id INTO _recurid
5708       FROM recur
5709      WHERE ((recur_parent_id=OLD.incdt_id)
5710         AND (recur_parent_type='INCDT'));
5711
5712      IF (_recurid IS NOT NULL) THEN
5713        SELECT MIN(incdt_id) INTO _newparentid
5714          FROM incdt
5715         WHERE ((incdt_recurring_incdt_id=OLD.inctd_id)
5716            AND (incdt_id!=OLD.incdt_id));
5717
5718       -- client is responsible for warning about deleting a recurring incdt
5719       IF (_newparentid IS NULL) THEN
5720         DELETE FROM recur WHERE recur_id=_recurid;
5721       ELSE
5722         UPDATE recur SET recur_parent_id=_newparentid
5723          WHERE recur_id=_recurid;
5724       END IF;
5725     END IF;
5726
5727     RETURN OLD;
5728   END IF;
5729
5730   RETURN NEW;
5731 END;
5732 $$;
5733
5734
5735 ALTER FUNCTION public._incdtbeforedeletetrigger() OWNER TO admin;
5736
5737 --
5738 -- TOC entry 974 (class 1255 OID 146565485)
5739 -- Dependencies: 4536 8
5740 -- Name: _incdtbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
5741 --
5742
5743 CREATE FUNCTION _incdtbeforetrigger() RETURNS trigger
5744     LANGUAGE plpgsql
5745     AS $$
5746 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5747 -- See www.xtuple.com/CPAL for the full text of the software license.
5748 DECLARE
5749   _rec          RECORD;
5750   _check        BOOLEAN;
5751   _crmacct      INTEGER;
5752
5753 BEGIN
5754
5755   IF(TG_OP = 'DELETE') THEN
5756     _rec := OLD;
5757   ELSE
5758     _rec := NEW;
5759   END IF;
5760
5761   -- Set the incident number if blank
5762   IF (TG_OP = 'INSERT') THEN
5763     IF (NEW.incdt_number IS NULL) THEN
5764       SELECT fetchIncidentNumber() INTO NEW.incdt_number;
5765     END IF;
5766
5767     --- clear the number from the issue cache
5768     PERFORM clearNumberIssue('IncidentNumber', NEW.incdt_number);
5769   END IF;
5770
5771   -- Description is required
5772   IF (LENGTH(COALESCE(NEW.incdt_summary,''))=0) THEN
5773     RAISE EXCEPTION 'You must supply a valid Incident Description.';
5774   END IF;
5775   
5776   -- CRM Account is required
5777   IF (NEW.incdt_crmacct_id IS NULL) THEN
5778     RAISE EXCEPTION 'You must supply a valid CRM Account.';
5779   END IF;
5780
5781   -- Contact is required
5782   IF (NEW.incdt_cntct_id IS NULL) THEN
5783     RAISE EXCEPTION 'You must supply a valid Contact.';
5784   END IF;
5785
5786   NEW.incdt_updated := now();
5787
5788   RETURN NEW;
5789 END;
5790 $$;
5791
5792
5793 ALTER FUNCTION public._incdtbeforetrigger() OWNER TO admin;
5794
5795 --
5796 -- TOC entry 975 (class 1255 OID 146565486)
5797 -- Dependencies: 4536 8
5798 -- Name: _incdttrigger(); Type: FUNCTION; Schema: public; Owner: admin
5799 --
5800
5801 CREATE FUNCTION _incdttrigger() RETURNS trigger
5802     LANGUAGE plpgsql
5803     AS $$
5804 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
5805 -- See www.xtuple.com/CPAL for the full text of the software license.
5806 DECLARE
5807   _r            RECORD;
5808   _counter      INTEGER :=  0;
5809   _whsId        INTEGER := -1;
5810   _evntType     TEXT;
5811   _cmnttypeid   INTEGER := -1;
5812   _cmntid       INTEGER := -1;
5813 BEGIN
5814
5815   SELECT cmnttype_id INTO _cmnttypeid
5816     FROM cmnttype
5817     WHERE (cmnttype_name='Notes to Comment');
5818   IF NOT FOUND OR _cmnttypeid IS NULL THEN
5819     _cmnttypeid := -1;
5820   END IF;
5821
5822   IF (TG_OP = 'DELETE') THEN
5823 --  This should never happen
5824     RETURN OLD;
5825   ELSIF (TG_OP = 'INSERT') THEN
5826     INSERT INTO incdthist
5827           (incdthist_incdt_id,
5828            incdthist_change, incdthist_target_id,
5829            incdthist_descrip)
5830     VALUES(NEW.incdt_id,
5831            'N', NULL,
5832            'Incident Added');
5833
5834     _evntType = 'NewIncident';
5835
5836     IF (_cmnttypeid <> -1 AND COALESCE(NEW.incdt_descrip, '') <> '') THEN
5837       PERFORM postComment(_cmnttypeid, 'INCDT', NEW.incdt_id, NEW.incdt_descrip);
5838     END IF;
5839   ELSIF (TG_OP = 'UPDATE') THEN
5840     _evntType = 'UpdatedIncident';
5841
5842     IF (COALESCE(NEW.incdt_cntct_id,-1) <> COALESCE(OLD.incdt_cntct_id,-1)) THEN
5843       INSERT INTO incdthist
5844             (incdthist_incdt_id,
5845              incdthist_change, incdthist_target_id,
5846              incdthist_descrip)
5847       VALUES(NEW.incdt_id,
5848              'C', NEW.incdt_cntct_id,
5849              ('Contact Changed: "' ||
5850                COALESCE((SELECT cntct_first_name || ' ' || cntct_last_name
5851                            FROM cntct
5852                           WHERE (cntct_id=OLD.incdt_cntct_id)), '')
5853               || '" -> "' ||
5854                COALESCE((SELECT cntct_first_name || ' ' || cntct_last_name
5855                            FROM cntct
5856                           WHERE (cntct_id=NEW.incdt_cntct_id)), '')
5857               || '"') );
5858     END IF;
5859
5860     IF (COALESCE(NEW.incdt_summary,'') <> COALESCE(OLD.incdt_summary,'')) THEN
5861       INSERT INTO incdthist
5862             (incdthist_incdt_id,
5863              incdthist_descrip)
5864       VALUES(NEW.incdt_id,
5865              ('Description Updated: "' ||
5866                COALESCE(OLD.incdt_summary, '') ||
5867               '" -> "' ||
5868                COALESCE(NEW.incdt_summary, '') ||
5869               '"') );
5870     END IF;
5871
5872     IF (COALESCE(NEW.incdt_descrip,'') <> COALESCE(OLD.incdt_descrip,'')) THEN
5873       INSERT INTO incdthist
5874             (incdthist_incdt_id,
5875              incdthist_descrip)
5876       VALUES(NEW.incdt_id,
5877              ('Notes Updated: "' ||
5878                substr(COALESCE(OLD.incdt_descrip, ''), 1, 20) ||
5879               '..." -> "' ||
5880                substr(COALESCE(NEW.incdt_descrip, ''), 1, 20) ||
5881               '..."') );
5882
5883       IF (_cmnttypeid <> -1) THEN
5884         -- find an existing comment
5885         SELECT comment_id
5886           INTO _cmntid
5887           FROM comment
5888          WHERE comment_source = 'INCDT'
5889            AND comment_source_id = NEW.incdt_id
5890            -- back out change for 21068
5891            -- AND comment_user = getEffectiveXtUser()
5892            AND comment_cmnttype_id = _cmnttypeid;
5893         IF FOUND THEN
5894           UPDATE comment SET comment_text = NEW.incdt_descrip
5895           WHERE comment_id = _cmntid;
5896         ELSE
5897           PERFORM postComment(_cmnttypeid, 'INCDT', NEW.incdt_id, NEW.incdt_descrip);
5898         END IF;
5899       END IF;
5900     END IF;
5901
5902     IF (NEW.incdt_status <> OLD.incdt_status) THEN
5903       INSERT INTO incdthist
5904             (incdthist_incdt_id,
5905              incdthist_change, incdthist_target_id,
5906              incdthist_descrip)
5907       VALUES(NEW.incdt_id,
5908              'S', NULL,
5909              ('Status Changed: ' ||
5910               CASE WHEN(OLD.incdt_status='N') THEN 'New'
5911                    WHEN(OLD.incdt_status='F') THEN 'Feedback'
5912                    WHEN(OLD.incdt_status='C') THEN 'Confirmed'
5913                    WHEN(OLD.incdt_status='A') THEN 'Assigned'
5914                    WHEN(OLD.incdt_status='R') THEN 'Resolved'
5915                    WHEN(OLD.incdt_status='L') THEN 'Closed'
5916                    ELSE OLD.incdt_status
5917               END
5918               || ' -> ' ||
5919               CASE WHEN(NEW.incdt_status='N') THEN 'New'
5920                    WHEN(NEW.incdt_status='F') THEN 'Feedback'
5921                    WHEN(NEW.incdt_status='C') THEN 'Confirmed'
5922                    WHEN(NEW.incdt_status='A') THEN 'Assigned'
5923                    WHEN(NEW.incdt_status='R') THEN 'Resolved'
5924                    WHEN(NEW.incdt_status='L') THEN 'Closed'
5925                    ELSE NEW.incdt_status
5926               END
5927               ) );
5928       IF (NEW.incdt_status = 'L') THEN
5929         _evntType = 'ClosedIncident';
5930       ELSIF (OLD.incdt_status = 'L') THEN
5931         _evntType = 'ReopenedIncident';
5932       END IF;
5933     END IF;
5934
5935     IF (COALESCE(NEW.incdt_assigned_username,'') <> COALESCE(OLD.incdt_assigned_username,'')) THEN
5936       INSERT INTO incdthist
5937             (incdthist_incdt_id,
5938              incdthist_change, incdthist_target_id,
5939              incdthist_descrip)
5940       VALUES(NEW.incdt_id,
5941              'A', NULL,
5942              ('Assigned to: "' ||
5943                COALESCE(OLD.incdt_assigned_username, '') ||
5944               '" -> "' ||
5945                COALESCE(NEW.incdt_assigned_username, '') ||
5946               '"') );
5947     END IF;
5948
5949     IF (COALESCE(NEW.incdt_incdtcat_id,-1) <> COALESCE(OLD.incdt_incdtcat_id,-1)) THEN
5950       INSERT INTO incdthist
5951             (incdthist_incdt_id,
5952              incdthist_change, incdthist_target_id,
5953              incdthist_descrip)
5954       VALUES(NEW.incdt_id,
5955              'T', NEW.incdt_incdtcat_id,
5956              ('Category Changed: ' ||
5957                COALESCE((SELECT incdtcat_name
5958                            FROM incdtcat
5959                           WHERE (incdtcat_id=OLD.incdt_incdtcat_id)), '')
5960               || ' -> ' ||
5961                COALESCE((SELECT incdtcat_name
5962                            FROM incdtcat
5963                           WHERE (incdtcat_id=NEW.incdt_incdtcat_id)), '')
5964               || '') );
5965     END IF;
5966
5967     IF (COALESCE(NEW.incdt_incdtseverity_id,-1) <> COALESCE(OLD.incdt_incdtseverity_id,-1)) THEN
5968       INSERT INTO incdthist
5969             (incdthist_incdt_id,
5970              incdthist_change, incdthist_target_id,
5971              incdthist_descrip)
5972       VALUES(NEW.incdt_id,
5973              'V', NEW.incdt_incdtseverity_id,
5974              ('Severity Changed: ' ||
5975                COALESCE((SELECT incdtseverity_name
5976                            FROM incdtseverity
5977                           WHERE (incdtseverity_id=OLD.incdt_incdtseverity_id)), '')
5978               || ' -> ' ||
5979                COALESCE((SELECT incdtseverity_name
5980                            FROM incdtseverity
5981                           WHERE (incdtseverity_id=NEW.incdt_incdtseverity_id)), '')
5982               || '') );
5983     END IF;
5984
5985     IF (COALESCE(NEW.incdt_incdtpriority_id,-1) <> COALESCE(OLD.incdt_incdtpriority_id,-1)) THEN
5986       INSERT INTO incdthist
5987             (incdthist_incdt_id,
5988              incdthist_change, incdthist_target_id,
5989              incdthist_descrip)
5990       VALUES(NEW.incdt_id,
5991              'P', NEW.incdt_incdtpriority_id,
5992              ('Priority Changed: ' ||
5993                COALESCE((SELECT incdtpriority_name
5994                            FROM incdtpriority
5995                           WHERE (incdtpriority_id=OLD.incdt_incdtpriority_id)), '')
5996               || ' -> ' ||
5997                COALESCE((SELECT incdtpriority_name
5998                            FROM incdtpriority
5999                           WHERE (incdtpriority_id=NEW.incdt_incdtpriority_id)), '')
6000               || '') );
6001     END IF;
6002
6003     IF (COALESCE(NEW.incdt_incdtresolution_id,-1) <> COALESCE(OLD.incdt_incdtresolution_id,-1)) THEN
6004       INSERT INTO incdthist
6005             (incdthist_incdt_id,
6006              incdthist_change, incdthist_target_id,
6007              incdthist_descrip)
6008       VALUES(NEW.incdt_id,
6009              'E', NEW.incdt_incdtresolution_id,
6010              ('Resolution Changed: ' ||
6011                COALESCE((SELECT incdtresolution_name
6012                            FROM incdtresolution
6013                           WHERE (incdtresolution_id=OLD.incdt_incdtresolution_id)), '')
6014               || ' -> ' ||
6015                COALESCE((SELECT incdtresolution_name
6016                            FROM incdtresolution
6017                           WHERE (incdtresolution_id=NEW.incdt_incdtresolution_id)), '')
6018               || '') );
6019     END IF;
6020   END IF;
6021
6022     PERFORM postEvent(_evntType, 'IC', NEW.incdt_id,
6023                       NULL, NEW.incdt_number::TEXT,
6024                       NULL, NULL, NULL, NULL);
6025
6026   RETURN NEW;
6027   END;
6028 $$;
6029
6030
6031 ALTER FUNCTION public._incdttrigger() OWNER TO admin;
6032
6033 --
6034 -- TOC entry 976 (class 1255 OID 146565487)
6035 -- Dependencies: 4536 8
6036 -- Name: _invcheadaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
6037 --
6038
6039 CREATE FUNCTION _invcheadaftertrigger() RETURNS trigger
6040     LANGUAGE plpgsql
6041     AS $$
6042 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6043 -- See www.xtuple.com/CPAL for the full text of the software license.
6044   DECLARE
6045     _cmnttypeid INTEGER;
6046     _cohead_id INTEGER;
6047
6048   BEGIN
6049 --  Create a comment entry when on a Sales Order when an Invoice is Posted for that order
6050
6051 --  Cache the cmnttype_id for ChangeLog
6052     SELECT cmnttype_id INTO _cmnttypeid
6053     FROM cmnttype
6054     WHERE (cmnttype_name='ChangeLog');
6055     IF (FOUND) THEN
6056       IF (TG_OP = 'UPDATE') THEN
6057         IF ((OLD.invchead_posted != NEW.invchead_posted) AND NEW.invchead_posted) THEN
6058           SELECT cohead_id INTO _cohead_id
6059           FROM cohead
6060           WHERE (cohead_number = OLD.invchead_ordernumber);
6061           IF (FOUND) THEN
6062             PERFORM postComment( _cmnttypeid, 'S', _cohead_id,
6063                                  ('Invoice, ' || NEW.invchead_invcnumber || ', posted for this order') );
6064           END IF;
6065         END IF;
6066       END IF;
6067     END IF;
6068   RETURN NEW;
6069   END;
6070 $$;
6071
6072
6073 ALTER FUNCTION public._invcheadaftertrigger() OWNER TO admin;
6074
6075 --
6076 -- TOC entry 977 (class 1255 OID 146565488)
6077 -- Dependencies: 4536 8
6078 -- Name: _invcheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
6079 --
6080
6081 CREATE FUNCTION _invcheadbeforetrigger() RETURNS trigger
6082     LANGUAGE plpgsql
6083     AS $$
6084 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6085 -- See www.xtuple.com/CPAL for the full text of the software license.
6086 DECLARE
6087   _recurid     INTEGER;
6088   _newparentid INTEGER;
6089
6090 BEGIN
6091   IF (TG_OP = 'UPDATE') THEN
6092     IF (OLD.invchead_posted
6093       AND ((OLD.invchead_invcnumber != NEW.invchead_invcnumber)
6094         OR (OLD.invchead_invcdate != NEW.invchead_invcdate)
6095         OR (OLD.invchead_terms_id != NEW.invchead_terms_id)
6096         OR (OLD.invchead_salesrep_id != NEW.invchead_salesrep_id)
6097         OR (OLD.invchead_commission != NEW.invchead_commission)
6098         OR (OLD.invchead_taxzone_id != NEW.invchead_taxzone_id)
6099         OR (OLD.invchead_shipchrg_id != NEW.invchead_shipchrg_id)
6100         OR (OLD.invchead_prj_id != NEW.invchead_prj_id)
6101         OR (OLD.invchead_misc_accnt_id != NEW.invchead_misc_accnt_id)
6102         OR (OLD.invchead_misc_amount != NEW.invchead_misc_amount)
6103         OR (OLD.invchead_freight != NEW.invchead_freight))) THEN
6104       RAISE EXCEPTION 'Edit not allow on Posted Invoice.';
6105     END IF;
6106   END IF;
6107   
6108   IF (TG_OP = 'DELETE') THEN
6109     DELETE FROM invcheadtax
6110     WHERE (taxhist_parent_id=OLD.invchead_id);
6111
6112     SELECT recur_id INTO _recurid
6113       FROM recur
6114      WHERE ((recur_parent_id=OLD.invchead_id)
6115         AND (recur_parent_type='I'));
6116     IF (_recurid IS NOT NULL) THEN
6117       SELECT invchead_id INTO _newparentid
6118         FROM invchead
6119        WHERE ((invchead_recurring_invchead_id=OLD.invchead_id)
6120           AND (invchead_id!=OLD.invchead_id))
6121        ORDER BY invchead_invcdate
6122        LIMIT 1;
6123
6124       IF (_newparentid IS NULL) THEN
6125         DELETE FROM recur WHERE recur_id=_recurid;
6126       ELSE
6127         UPDATE recur SET recur_parent_id=_newparentid
6128          WHERE recur_id=_recurid;
6129         UPDATE invchead SET invchead_recurring_invchead_id=_newparentid
6130          WHERE invchead_recurring_invchead_id=OLD.invchead_id
6131            AND invchead_id!=OLD.invchead_id;
6132       END IF;
6133     END IF;
6134
6135     RETURN OLD;
6136   END IF;
6137
6138   RETURN NEW;
6139 END;
6140 $$;
6141
6142
6143 ALTER FUNCTION public._invcheadbeforetrigger() OWNER TO admin;
6144
6145 --
6146 -- TOC entry 978 (class 1255 OID 146565489)
6147 -- Dependencies: 4536 8
6148 -- Name: _invcheadtrigger(); Type: FUNCTION; Schema: public; Owner: admin
6149 --
6150
6151 CREATE FUNCTION _invcheadtrigger() RETURNS trigger
6152     LANGUAGE plpgsql
6153     AS $$
6154 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6155 -- See www.xtuple.com/CPAL for the full text of the software license.
6156 BEGIN
6157   IF (TG_OP = 'DELETE') THEN
6158     -- Something can go here
6159     RETURN OLD;
6160   END IF;
6161
6162 -- Insert new row
6163   IF (TG_OP = 'INSERT') THEN
6164
6165   -- Calculate Freight Tax
6166     IF (NEW.invchead_freight <> 0) THEN
6167       PERFORM calculateTaxHist( 'invcheadtax',
6168                                 NEW.invchead_id,
6169                                 NEW.invchead_taxzone_id,
6170                                 getFreightTaxtypeId(),
6171                                 NEW.invchead_invcdate,
6172                                 NEW.invchead_curr_id,
6173                                 NEW.invchead_freight );
6174     END IF;
6175
6176     --- clear the number from the issue cache
6177     PERFORM clearNumberIssue('InvcNumber', NEW.invchead_invcnumber);
6178   END IF;
6179
6180 -- Update row
6181   IF (TG_OP = 'UPDATE') THEN
6182
6183     IF ( (NEW.invchead_freight <> OLD.invchead_freight) OR
6184          (COALESCE(NEW.invchead_taxzone_id,-1) <> COALESCE(OLD.invchead_taxzone_id,-1)) OR
6185          (NEW.invchead_invcdate <> OLD.invchead_invcdate) OR
6186          (NEW.invchead_curr_id <> OLD.invchead_curr_id) ) THEN
6187   -- Calculate invchead Tax
6188       PERFORM calculateTaxHist( 'invcheadtax',
6189                                 NEW.invchead_id,
6190                                 NEW.invchead_taxzone_id,
6191                                 getFreightTaxtypeId(),
6192                                 NEW.invchead_invcdate,
6193                                 NEW.invchead_curr_id,
6194                                 NEW.invchead_freight );
6195     END IF;
6196
6197     IF ( (COALESCE(NEW.invchead_taxzone_id,-1) <> COALESCE(OLD.invchead_taxzone_id,-1)) OR
6198          (NEW.invchead_invcdate <> OLD.invchead_invcdate) OR
6199          (NEW.invchead_curr_id <> OLD.invchead_curr_id) ) THEN
6200   -- Calculate invcitem Tax
6201       IF (COALESCE(NEW.invchead_taxzone_id,-1) <> COALESCE(OLD.invchead_taxzone_id,-1)) THEN
6202
6203         UPDATE invcitem SET invcitem_taxtype_id=getItemTaxType(invcitem_item_id,NEW.invchead_taxzone_id)
6204         WHERE (invcitem_invchead_id=NEW.invchead_id);
6205
6206         PERFORM calculateTaxHist( 'invcitemtax',
6207                                   invcitem_id,
6208                                   NEW.invchead_taxzone_id,
6209                                   invcitem_taxtype_id,
6210                                   NEW.invchead_invcdate,
6211                                   NEW.invchead_curr_id,
6212                                   (invcitem_billed * invcitem_qty_invuomratio) *
6213                                   (invcitem_price / invcitem_price_invuomratio) )
6214         FROM invcitem
6215         WHERE (invcitem_invchead_id = NEW.invchead_id);
6216       END IF;
6217     END IF;
6218
6219   END IF;
6220
6221   RETURN NEW;
6222 END;
6223 $$;
6224
6225
6226 ALTER FUNCTION public._invcheadtrigger() OWNER TO admin;
6227
6228 --
6229 -- TOC entry 979 (class 1255 OID 146565490)
6230 -- Dependencies: 4536 8
6231 -- Name: _invcitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
6232 --
6233
6234 CREATE FUNCTION _invcitembeforetrigger() RETURNS trigger
6235     LANGUAGE plpgsql
6236     AS $$
6237 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6238 -- See www.xtuple.com/CPAL for the full text of the software license.
6239 DECLARE
6240   _itemfractional BOOLEAN;
6241
6242 BEGIN
6243   IF (TG_OP = 'DELETE') THEN
6244     DELETE FROM invcitemtax
6245     WHERE (taxhist_parent_id=OLD.invcitem_id);
6246
6247     RETURN OLD;
6248   END IF;
6249
6250   IF (TG_OP IN ('UPDATE','DELETE')) THEN
6251     IF (SELECT COUNT(invchead_id) > 0
6252         FROM invchead
6253         WHERE ((invchead_id=OLD.invcitem_invchead_id)
6254           AND (invchead_posted))) THEN
6255       RAISE EXCEPTION 'Edit not allowed on Posted Invoices.';
6256     END IF;
6257   END IF;
6258
6259   -- If regular Item then enforce item_fractional
6260   IF (COALESCE(NEW.invcitem_item_id, -1) <> -1) THEN
6261     SELECT itemuomfractionalbyuom(NEW.invcitem_item_id, NEW.invcitem_qty_uom_id) INTO _itemfractional;
6262     IF (NOT _itemfractional) THEN
6263       IF (TRUNC(NEW.invcitem_ordered) <> NEW.invcitem_ordered) THEN
6264         RAISE EXCEPTION 'Item does not support fractional quantities';
6265       END IF;
6266       IF (TRUNC(NEW.invcitem_billed) <> NEW.invcitem_billed) THEN
6267         RAISE EXCEPTION 'Item does not support fractional quantities';
6268       END IF;
6269     END IF;
6270   END IF;
6271
6272   RETURN NEW;
6273 END;
6274 $$;
6275
6276
6277 ALTER FUNCTION public._invcitembeforetrigger() OWNER TO admin;
6278
6279 --
6280 -- TOC entry 980 (class 1255 OID 146565491)
6281 -- Dependencies: 4536 8
6282 -- Name: _invcitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
6283 --
6284
6285 CREATE FUNCTION _invcitemtrigger() RETURNS trigger
6286     LANGUAGE plpgsql
6287     AS $$
6288 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6289 -- See www.xtuple.com/CPAL for the full text of the software license.
6290 DECLARE
6291   _r RECORD;
6292
6293 BEGIN
6294   IF (TG_OP = 'DELETE') THEN
6295     RETURN OLD;
6296   END IF;
6297
6298 -- Cache Invoice Head
6299   SELECT * INTO _r
6300   FROM invchead
6301   WHERE (invchead_id=NEW.invcitem_invchead_id);
6302   IF (NOT FOUND) THEN
6303     RAISE EXCEPTION 'Invoice head not found';
6304   END IF;
6305
6306 -- Insert new row
6307   IF (TG_OP = 'INSERT') THEN
6308
6309   -- Calculate Tax
6310       PERFORM calculateTaxHist( 'invcitemtax',
6311                                 NEW.invcitem_id,
6312                                 COALESCE(_r.invchead_taxzone_id, -1),
6313                                 NEW.invcitem_taxtype_id,
6314                                 COALESCE(_r.invchead_invcdate, CURRENT_DATE),
6315                                 COALESCE(_r.invchead_curr_id, -1),
6316                                 (NEW.invcitem_billed * NEW.invcitem_qty_invuomratio) *
6317                                 (NEW.invcitem_price / NEW.invcitem_price_invuomratio) );
6318   END IF;
6319
6320 -- Update row
6321   IF (TG_OP = 'UPDATE') THEN
6322
6323   -- Calculate Tax
6324     IF ( (NEW.invcitem_billed <> OLD.invcitem_billed) OR
6325          (NEW.invcitem_qty_invuomratio <> OLD.invcitem_qty_invuomratio) OR
6326          (NEW.invcitem_price <> OLD.invcitem_price) OR
6327          (NEW.invcitem_price_invuomratio <> OLD.invcitem_price_invuomratio) OR
6328          (COALESCE(NEW.invcitem_taxtype_id, -1) <> COALESCE(OLD.invcitem_taxtype_id, -1)) ) THEN
6329       PERFORM calculateTaxHist( 'invcitemtax',
6330                                 NEW.invcitem_id,
6331                                 COALESCE(_r.invchead_taxzone_id, -1),
6332                                 NEW.invcitem_taxtype_id,
6333                                 COALESCE(_r.invchead_invcdate, CURRENT_DATE),
6334                                 COALESCE(_r.invchead_curr_id, -1),
6335                                 (NEW.invcitem_billed * NEW.invcitem_qty_invuomratio) *
6336                                 (NEW.invcitem_price / NEW.invcitem_price_invuomratio) );
6337     END IF;
6338   END IF;
6339
6340   RETURN NEW;
6341 END;
6342 $$;
6343
6344
6345 ALTER FUNCTION public._invcitemtrigger() OWNER TO admin;
6346
6347 --
6348 -- TOC entry 981 (class 1255 OID 146565492)
6349 -- Dependencies: 4536 8
6350 -- Name: _ipsassbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
6351 --
6352
6353 CREATE FUNCTION _ipsassbeforetrigger() RETURNS trigger
6354     LANGUAGE plpgsql
6355     AS $$
6356 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6357 -- See www.xtuple.com/CPAL for the full text of the software license.
6358 BEGIN
6359
6360   --  Checks
6361   IF NOT (checkPrivilege('MaintainPricingSchedules')) THEN
6362     RAISE EXCEPTION 'You do not have privileges to maintain Price Schedules.';
6363   END IF;
6364
6365   -- Business logic, disallow invalid combinations
6366   IF (TG_OP IN ('INSERT','UPDATE')) THEN
6367     IF (LENGTH(COALESCE(NEW.ipsass_custtype_pattern,'')) != 0) THEN
6368       new.ipsass_cust_id                =       -1;
6369       new.ipsass_custtype_id            =       -1;
6370       new.ipsass_shipto_id              =       -1;
6371       new.ipsass_shipto_pattern =       '';
6372     ELSIF (COALESCE(NEW.ipsass_custtype_id,-1) > -1) THEN
6373       new.ipsass_cust_id                =       -1;
6374       new.ipsass_shipto_id              =       -1;
6375       new.ipsass_shipto_pattern =       '';
6376       new.ipsass_custtype_pattern       =       '';
6377     ELSIF (LENGTH(COALESCE(NEW.ipsass_shipto_pattern,'')) != 0) THEN
6378       new.ipsass_custtype_id            =       -1;
6379       new.ipsass_shipto_id              =       -1;
6380       new.ipsass_custtype_pattern       =       '';
6381     ELSE
6382       new.ipsass_shipto_id              =       COALESCE(NEW.ipsass_shipto_id,-1);
6383       new.ipsass_custtype_id            =       -1;
6384       new.ipsass_shipto_pattern =       '';
6385       new.ipsass_custtype_pattern       =       '';
6386     END IF;
6387
6388     RETURN NEW;
6389   ELSE
6390     RETURN OLD;
6391   END IF;
6392   
6393 END;
6394 $$;
6395
6396
6397 ALTER FUNCTION public._ipsassbeforetrigger() OWNER TO admin;
6398
6399 --
6400 -- TOC entry 982 (class 1255 OID 146565493)
6401 -- Dependencies: 4536 8
6402 -- Name: _ipsheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
6403 --
6404
6405 CREATE FUNCTION _ipsheadbeforetrigger() RETURNS trigger
6406     LANGUAGE plpgsql
6407     AS $$
6408 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6409 -- See www.xtuple.com/CPAL for the full text of the software license.
6410 BEGIN
6411
6412   --  Checks
6413   IF NOT (checkPrivilege('MaintainPricingSchedules')) THEN
6414     RAISE EXCEPTION 'You do not have privileges to maintain Price Schedules.';
6415   END IF;
6416
6417   IF (TG_OP IN ('INSERT','UPDATE')) THEN
6418     RETURN NEW;
6419   ELSE
6420     RETURN OLD;
6421   END IF;
6422 END;
6423 $$;
6424
6425
6426 ALTER FUNCTION public._ipsheadbeforetrigger() OWNER TO admin;
6427
6428 --
6429 -- TOC entry 984 (class 1255 OID 146565494)
6430 -- Dependencies: 4536 8
6431 -- Name: _ipsitemcharbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
6432 --
6433
6434 CREATE FUNCTION _ipsitemcharbeforetrigger() RETURNS trigger
6435     LANGUAGE plpgsql
6436     AS $$
6437 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6438 -- See www.xtuple.com/CPAL for the full text of the software license.
6439 BEGIN
6440
6441   --  Checks
6442   IF NOT (checkPrivilege('MaintainPricingSchedules')) THEN
6443     RAISE EXCEPTION 'You do not have privileges to maintain Price Schedules.';
6444   END IF;
6445   
6446   IF (TG_OP IN ('INSERT','UPDATE')) THEN
6447     IF (SELECT (COUNT(item_id)=0)
6448         FROM ipsiteminfo JOIN item ON (item_id=ipsitem_item_id) 
6449         WHERE ((ipsitem_id=NEW.ipsitemchar_ipsitem_id)
6450         AND (item_config))) THEN
6451       RAISE EXCEPTION 'Characteristic prices may only be set on configured items.';
6452     ELSIF (SELECT (COUNT(item_id)=0)
6453         FROM ipsiteminfo JOIN item ON (item_id=ipsitem_item_id)
6454                          JOIN charass ON (charass_target_id=item_id AND charass_target_type='I') 
6455         WHERE ((ipsitem_id=NEW.ipsitemchar_ipsitem_id)
6456         AND (charass_char_id=NEW.ipsitemchar_char_id)
6457         AND (charass_value=NEW.ipsitemchar_value))) THEN
6458       RAISE EXCEPTION 'No characteristic with matching value exists for this item.';
6459     END IF;
6460     RETURN NEW;
6461   ELSE
6462     RETURN OLD;
6463   END IF;
6464 END;
6465 $$;
6466
6467
6468 ALTER FUNCTION public._ipsitemcharbeforetrigger() OWNER TO admin;
6469
6470 --
6471 -- TOC entry 985 (class 1255 OID 146565495)
6472 -- Dependencies: 4536 8
6473 -- Name: _ipsiteminfobeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
6474 --
6475
6476 CREATE FUNCTION _ipsiteminfobeforetrigger() RETURNS trigger
6477     LANGUAGE plpgsql
6478     AS $$
6479 BEGIN
6480
6481   --  Checks
6482   IF NOT (checkPrivilege('MaintainPricingSchedules')) THEN
6483     RAISE EXCEPTION 'You do not have privileges to maintain Price Schedules.';
6484   END IF;
6485   
6486   IF (TG_OP IN ('INSERT','UPDATE')) THEN
6487     RETURN NEW;
6488   ELSE
6489     RETURN OLD;
6490   END IF;
6491 END;
6492 $$;
6493
6494
6495 ALTER FUNCTION public._ipsiteminfobeforetrigger() OWNER TO admin;
6496
6497 --
6498 -- TOC entry 986 (class 1255 OID 146565496)
6499 -- Dependencies: 4536 8
6500 -- Name: _itemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
6501 --
6502
6503 CREATE FUNCTION _itemaftertrigger() RETURNS trigger
6504     LANGUAGE plpgsql
6505     AS $$
6506 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6507 -- See www.xtuple.com/CPAL for the full text of the software license.
6508 DECLARE
6509   _cmnttypeid INTEGER;
6510
6511 BEGIN
6512 -- Privilege Checks
6513    IF (NOT checkPrivilege('MaintainItemMasters')) THEN
6514      RAISE EXCEPTION 'You do not have privileges to maintain Items.';
6515    END IF;
6516    
6517 -- Integrity checks
6518   IF (TG_OP = 'UPDATE') THEN
6519     IF ((OLD.item_type <> NEW.item_type) AND (NEW.item_type = 'L')) THEN
6520       IF (SELECT COUNT(*) != 0 FROM bomitem WHERE (bomitem_item_id = OLD.item_id)) THEN
6521         RAISE EXCEPTION 'This item is part of one or more Bills of Materials and cannot be a Planning Item.';
6522       END IF;
6523     END IF;
6524
6525     IF ((OLD.item_type <> NEW.item_type) AND
6526        (NEW.item_type IN ('R','S','T'))) THEN
6527       IF (SELECT COUNT(*) != 0
6528         FROM itemsite
6529         WHERE ((itemsite_item_id=OLD.item_id)
6530         AND (itemsite_qtyonhand + qtyallocated(itemsite_id,startoftime(),endoftime()) +
6531            qtyordered(itemsite_id,startoftime(),endoftime()) > 0 ))) THEN
6532           RAISE EXCEPTION 'Item type not allowed when there are itemsites with quantities with on hand quantities or pending inventory activity for this item.';
6533       END IF;
6534     END IF;
6535 -- If type changed remove costs and deactivate item sites
6536     IF (NEW.item_type <> OLD.item_type) THEN
6537       PERFORM updateCost(itemcost_id, 0) FROM itemcost WHERE (itemcost_item_id=OLD.item_id);
6538       UPDATE itemsite SET itemsite_active=false WHERE (itemsite_item_id=OLD.item_id);
6539       IF (NEW.item_type = 'R') THEN
6540         UPDATE itemsite SET itemsite_controlmethod='N' WHERE (itemsite_item_id=OLD.item_id);
6541       END IF;
6542     END IF;
6543   END IF;
6544
6545   IF ( SELECT (metric_value='t')
6546        FROM metric
6547        WHERE (metric_name='ItemChangeLog') ) THEN
6548
6549 --  Cache the cmnttype_id for ChangeLog
6550     SELECT cmnttype_id INTO _cmnttypeid
6551     FROM cmnttype
6552     WHERE (cmnttype_name='ChangeLog');
6553     IF (FOUND) THEN
6554       IF (TG_OP = 'INSERT') THEN
6555         PERFORM postComment(_cmnttypeid, 'I', NEW.item_id, 'Created');
6556
6557       ELSIF (TG_OP = 'UPDATE') THEN
6558         IF (OLD.item_active <> NEW.item_active) THEN
6559           IF (NEW.item_active) THEN
6560             PERFORM postComment(_cmnttypeid, 'I', NEW.item_id, 'Activated');
6561           ELSE
6562             PERFORM postComment(_cmnttypeid, 'I', NEW.item_id, 'Deactivated');
6563           END IF;
6564         END IF;
6565
6566         IF (OLD.item_descrip1 <> NEW.item_descrip1) THEN
6567           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6568                                ( 'Description 1 Changed from "' || OLD.item_descrip1 ||
6569                                  '" to "' || NEW.item_descrip1 || '"' ) );
6570         END IF;
6571
6572         IF (OLD.item_descrip2 <> NEW.item_descrip2) THEN
6573           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6574                                ( 'Description 2 Changed from "' || OLD.item_descrip2 ||
6575                                  '" to "' || NEW.item_descrip2 || '"' ) );
6576         END IF;
6577
6578         IF (OLD.item_inv_uom_id <> NEW.item_inv_uom_id) THEN
6579           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6580                                ( 'Inventory UOM Changed from "' ||
6581                                  (SELECT uom_name FROM uom WHERE uom_id=OLD.item_inv_uom_id) ||
6582                                  '" (' || CAST(OLD.item_inv_uom_id AS TEXT) ||
6583                                  ') to "' ||
6584                                  (SELECT uom_name FROM uom WHERE uom_id=NEW.item_inv_uom_id) ||
6585                                  '" (' || CAST(NEW.item_inv_uom_id AS TEXT) || ')' ) );
6586         END IF;
6587
6588         IF (OLD.item_sold <> NEW.item_sold) THEN
6589           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6590                                CASE WHEN (NEW.item_sold) THEN 'Sold Changed from FALSE to TRUE'
6591                                     ELSE 'Sold Changed from TRUE to FALSE'
6592                                END );
6593         END IF;
6594
6595         IF (OLD.item_picklist <> NEW.item_picklist) THEN
6596           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6597                                CASE WHEN (NEW.item_picklist) THEN 'Pick List Changed from FALSE to TRUE'
6598                                     ELSE 'Pick List Changed from TRUE to FALSE'
6599                                END );
6600         END IF;
6601
6602         IF (OLD.item_fractional <> NEW.item_fractional) THEN
6603           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6604                                CASE WHEN (NEW.item_fractional) THEN 'Fractional Changed from FALSE to TRUE'
6605                                     ELSE 'Fractional Changed from TRUE to FALSE'
6606                                END );
6607         END IF;
6608
6609         IF (OLD.item_exclusive <> NEW.item_exclusive) THEN
6610           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6611                                CASE WHEN (NEW.item_exclusive) THEN 'Exclusive Changed from FALSE to TRUE'
6612                                     ELSE 'Exclusive Changed from TRUE to FALSE'
6613                                END );
6614         END IF;
6615         IF (OLD.item_config <> NEW.item_config) THEN
6616           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6617                                CASE WHEN (NEW.item_config) THEN 'Configured Changed from FALSE to TRUE'
6618                                     ELSE 'Configured Changed from TRUE to FALSE'
6619                                END );
6620         END IF;
6621
6622         IF (OLD.item_listprice <> NEW.item_listprice) THEN
6623           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6624                                ( 'List Price Changed from "' || formatSalesPrice(OLD.item_listprice) ||
6625                                  '" to "' || formatSalesPrice(NEW.item_listprice) || '"' ) );
6626         END IF;
6627
6628 -- Add New stuff
6629
6630         IF (OLD.item_type <> NEW.item_type) THEN
6631           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6632                                ( 'Type Changed from "' || OLD.item_type ||
6633                                  '" to "' || NEW.item_type || '"' ) );
6634         END IF;
6635
6636         IF (OLD.item_price_uom_id <> NEW.item_price_uom_id) THEN
6637           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6638                                ( 'Price UOM Changed from "' ||
6639                                  (SELECT uom_name FROM uom WHERE uom_id=OLD.item_price_uom_id) ||
6640                                  '" (' || CAST(OLD.item_price_uom_id AS TEXT) ||
6641                                  ') to "' ||
6642                                  (SELECT uom_name FROM uom WHERE uom_id=NEW.item_price_uom_id) ||
6643                                  '" (' || CAST(NEW.item_price_uom_id AS TEXT) || ')' ) );
6644         END IF;
6645
6646         IF (OLD.item_classcode_id <> NEW.item_classcode_id) THEN
6647           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6648                                ( 'Class Code Changed from "' ||
6649                                  (SELECT classcode_code || '-' || classcode_descrip FROM classcode WHERE classcode_id=OLD.item_classcode_id) ||
6650                                  '" (' || CAST(OLD.item_classcode_id AS TEXT) ||
6651                                  ') to "' ||
6652                                  (SELECT classcode_code || '-' || classcode_descrip FROM classcode WHERE classcode_id=NEW.item_classcode_id) ||
6653                                  '" (' || CAST(NEW.item_classcode_id AS TEXT) || ')' ) );
6654         END IF;
6655
6656         IF (OLD.item_freightclass_id <> NEW.item_freightclass_id) THEN
6657           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6658                                ( 'Freight Class Changed from "' ||
6659                                  (SELECT freightclass_code || '-' || freightclass_descrip FROM freightclass WHERE freightclass_id=OLD.item_freightclass_id) ||
6660                                  '" (' || CAST(OLD.item_freightclass_id AS TEXT) ||
6661                                  ') to "' ||
6662                                  (SELECT freightclass_code || '-' || freightclass_descrip FROM freightclass WHERE freightclass_id=NEW.item_freightclass_id) ||
6663                                  '" (' || CAST(NEW.item_freightclass_id AS TEXT) || ')' ) );
6664         END IF;
6665
6666         IF (OLD.item_prodcat_id <> NEW.item_prodcat_id) THEN
6667           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6668                                ( 'Product Category Changed from "' ||
6669                                  (SELECT prodcat_code || '-' || prodcat_descrip FROM prodcat WHERE prodcat_id=OLD.item_prodcat_id) ||
6670                                  '" (' || CAST(OLD.item_prodcat_id AS TEXT) ||
6671                                  ') to "' ||
6672                                  (SELECT prodcat_code || '-' || prodcat_descrip FROM prodcat WHERE prodcat_id=NEW.item_prodcat_id) ||
6673                                  '" (' || CAST(NEW.item_prodcat_id AS TEXT) || ')' ) );
6674         END IF;
6675
6676         IF (OLD.item_upccode <> NEW.item_upccode) THEN
6677           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6678                                ( 'UPC Code Changed from "' || OLD.item_upccode ||
6679                                  '" to "' || NEW.item_upccode || '"' ) );
6680         END IF;
6681
6682         IF (OLD.item_prodweight <> NEW.item_prodweight) THEN
6683           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6684                                ( 'Product Weight Changed from "' || formatWeight(OLD.item_prodweight) ||
6685                                  '" to "' || formatWeight(NEW.item_prodweight) || '"' ) );
6686         END IF;
6687
6688         IF (OLD.item_packweight <> NEW.item_packweight) THEN
6689           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6690                                ( 'Packaging Weight Changed from "' || formatWeight(OLD.item_packweight) ||
6691                                  '" to "' || formatWeight(NEW.item_packweight) || '"' ) );
6692         END IF;
6693
6694         IF (OLD.item_maxcost <> NEW.item_maxcost) THEN
6695           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6696                                ( 'Maximum Desired Cost Changed from "' || formatCost(OLD.item_maxcost) ||
6697                                  '" to "' || formatCost(NEW.item_maxcost) || '"' ) );
6698         END IF;
6699
6700         IF (OLD.item_listcost <> NEW.item_listcost) THEN
6701           PERFORM postComment( _cmnttypeid, 'I', NEW.item_id,
6702                                ( 'List Cost Changed from "' || formatCost(OLD.item_listcost) ||
6703                                  '" to "' || formatCost(NEW.item_listcost) || '"' ) );
6704         END IF;
6705 -- End changes
6706
6707       END IF;
6708     END IF;
6709   END IF;
6710
6711   IF (TG_OP = 'DELETE') THEN
6712     DELETE FROM imageass WHERE ((imageass_source_id=OLD.item_id) AND (imageass_source='I'));
6713     DELETE FROM url WHERE ((url_source_id=OLD.item_id) AND (url_source='I'));
6714     DELETE FROM docass WHERE docass_source_id = OLD.item_id AND docass_source_type = 'I';
6715     DELETE FROM docass WHERE docass_target_id = OLD.item_id AND docass_target_type = 'I';
6716
6717     RETURN OLD;
6718   END IF;
6719   
6720   RETURN NEW;
6721
6722 END;
6723 $$;
6724
6725
6726 ALTER FUNCTION public._itemaftertrigger() OWNER TO admin;
6727
6728 --
6729 -- TOC entry 987 (class 1255 OID 146565498)
6730 -- Dependencies: 4536 8
6731 -- Name: _itemaliastrigger(); Type: FUNCTION; Schema: public; Owner: admin
6732 --
6733
6734 CREATE FUNCTION _itemaliastrigger() RETURNS trigger
6735     LANGUAGE plpgsql
6736     AS $$
6737 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
6738 -- See www.xtuple.com/CPAL for the full text of the software license.
6739 BEGIN
6740
6741 -- Privilege Checks
6742    IF (NOT checkPrivilege('MaintainItemMasters')) THEN
6743      RAISE EXCEPTION 'You do not have privileges to maintain Item Aliases.';
6744    END IF;
6745   
6746   RETURN NEW;
6747 END;
6748 $$;
6749
6750
6751 ALTER FUNCTION public._itemaliastrigger() OWNER TO admin;
6752
6753 --
6754 -- TOC entry 988 (class 1255 OID 146565499)
6755 -- Dependencies: 4536 8
6756 -- Name: _itemcostaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
6757 --
6758
6759 CREATE FUNCTION _itemcostaftertrigger() RETURNS trigger
6760     LANGUAGE plpgsql
6761     AS $$
6762 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6763 -- See www.xtuple.com/CPAL for the full text of the software license.
6764 DECLARE
6765   _itemNumber TEXT;
6766   _maxCost NUMERIC;
6767   _oldStdCost NUMERIC;
6768   _oldActCost NUMERIC;
6769   _actualCost NUMERIC;
6770   _standardCost NUMERIC;
6771   
6772 BEGIN
6773
6774 --  Create Event if Standard or Actual Cost is greater than Max Cost
6775
6776 IF NOT EXISTS(SELECT 1 
6777      FROM evntnot
6778        JOIN evnttype ON (evnttype_id = evntnot_evnttype_id)
6779        JOIN usrpref ON (evntnot_username = usrpref_username)
6780      WHERE
6781           evnttype_name = 'CostExceedsMaxDesired'
6782           AND usrpref_name = 'active' 
6783           AND usrpref_value = 't')     
6784    THEN
6785      RETURN NEW;     
6786 END IF; 
6787
6788   SELECT item_number, item_maxcost, actcost(item_id), stdcost(item_id) INTO _itemNumber, _maxCost, _actualCost, _standardCost
6789   FROM item
6790   WHERE (item_id=NEW.itemcost_item_id);
6791
6792   IF (_maxCost > 0.0) THEN
6793    -- IF (_standardCost > _maxCost) 
6794       IF NOT EXISTS(SELECT 1 --COUNT(evntlog_id) 
6795                     FROM
6796                       evntlog, evnttype
6797                       WHERE evntlog_evnttype_id = evnttype_id 
6798                       AND evntlog_number LIKE 
6799                           (_itemNumber || ' -Standard- New:' || '%')
6800                    
6801                       AND (evntlog_dispatched IS NULL)
6802                       AND CAST(evntlog_evnttime AS DATE) = current_date
6803                      
6804                       ) 
6805                       AND (_standardCost > _maxCost) THEN
6806                                
6807                        
6808       IF (TG_OP = 'INSERT') THEN
6809         _oldStdCost := 0;
6810         _oldActCost := 0;
6811       ELSE
6812         _oldStdCost := OLD.itemcost_stdcost;
6813         _oldActCost := OLD.itemcost_stdcost;
6814       END IF; 
6815       PERFORM postEvent('CostExceedsMaxDesired', NULL, NEW.itemcost_item_id,
6816                         itemsite_warehous_id,
6817                         (_itemNumber || ' -Standard- ' || 
6818                          'New: ' || formatCost(_standardCost) ||
6819                          ' Max: '|| formatCost(_MaxCost)),
6820                         NEW.itemcost_stdcost, _oldStdCost,
6821                         NULL, NULL)
6822       FROM itemsite
6823       WHERE (itemsite_item_id=NEW.itemcost_item_id);
6824     END IF;
6825        IF NOT EXISTS(
6826                      SELECT 1 FROM
6827                       evntlog, evnttype
6828                       WHERE evntlog_evnttype_id = evnttype_id 
6829                       AND evntlog_number LIKE 
6830                           (_itemNumber || ' -Actual- New:' || '%')
6831
6832                       AND (evntlog_dispatched IS NULL)
6833                       AND CAST(evntlog_evnttime AS DATE) = current_date
6834                       )
6835
6836                  AND  (_actualCost > _maxCost)
6837           THEN
6838                             
6839       PERFORM postEvent('CostExceedsMaxDesired', NULL, NEW.itemcost_item_id,
6840                         itemsite_warehous_id,
6841                         (_itemNumber || ' -Actual- ' || 
6842                          'New: ' || formatCost(_actualCost) ||
6843                          ' Max: '|| formatCost(_MaxCost)),
6844                         NEW.itemcost_actcost, _oldActCost,
6845                         NULL, NULL)
6846       FROM itemsite
6847       WHERE (itemsite_item_id=NEW.itemcost_item_id);
6848     END IF;
6849   END IF;
6850
6851   RETURN NEW;
6852
6853 END;
6854 $$;
6855
6856
6857 ALTER FUNCTION public._itemcostaftertrigger() OWNER TO admin;
6858
6859 --
6860 -- TOC entry 989 (class 1255 OID 146565500)
6861 -- Dependencies: 4536 8
6862 -- Name: _itemcosttrigger(); Type: FUNCTION; Schema: public; Owner: admin
6863 --
6864
6865 CREATE FUNCTION _itemcosttrigger() RETURNS trigger
6866     LANGUAGE plpgsql
6867     AS $$
6868 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6869 -- See www.xtuple.com/CPAL for the full text of the software license.
6870 BEGIN
6871
6872   --Privilege Checks
6873   IF ( (TG_OP = 'INSERT') AND (NOT checkPrivilege('CreateCosts')) AND (NOT checkPrivilege('PostVouchers')) ) THEN
6874     RAISE EXCEPTION 'You do not have privileges to enter Item Costs.';
6875   END IF;
6876
6877   IF ( (TG_OP = 'UPDATE') AND (NOT checkPrivilege('EnterActualCosts')) AND (NOT checkPrivilege('PostVouchers')) AND (NOT checkPrivilege('UpdateActualCosts')) AND (NOT checkPrivilege('PostActualCosts')) AND (NOT checkPrivilege('PostStandardCosts')) ) THEN
6878     RAISE EXCEPTION 'You do not have privileges to update Item Costs.';
6879   END IF;
6880
6881   IF ( (TG_OP = 'DELETE') AND (NOT checkPrivilege('DeleteCosts')) ) THEN
6882     RAISE EXCEPTION 'You do not have privileges to delete Item Costs.';
6883   END IF;
6884
6885   IF (TG_OP = 'UPDATE') THEN
6886     IF (NEW.itemcost_actcost <> OLD.itemcost_actcost OR
6887         NEW.itemcost_curr_id <> OLD.itemcost_curr_id) THEN
6888       INSERT INTO costhist
6889       ( costhist_item_id, costhist_costelem_id, costhist_type,
6890         costhist_lowlevel, costhist_username, costhist_date,
6891         costhist_oldcost, costhist_newcost,
6892         costhist_oldcurr_id, costhist_newcurr_id )
6893       VALUES
6894       ( NEW.itemcost_item_id, NEW.itemcost_costelem_id, 'A',
6895         NEW.itemcost_lowlevel, getEffectiveXtUser(), CURRENT_TIMESTAMP,
6896         OLD.itemcost_actcost, NEW.itemcost_actcost,
6897         OLD.itemcost_curr_id, NEW.itemcost_curr_id );
6898     END IF;
6899
6900     IF (NEW.itemcost_stdcost <> OLD.itemcost_stdcost) THEN
6901       INSERT INTO costhist
6902       ( costhist_item_id, costhist_costelem_id, costhist_type,
6903         costhist_lowlevel, costhist_username, costhist_date,
6904         costhist_oldcost, costhist_newcost,
6905         costhist_oldcurr_id, costhist_newcurr_id )
6906       VALUES
6907       ( NEW.itemcost_item_id, NEW.itemcost_costelem_id, 'S',
6908         NEW.itemcost_lowlevel, getEffectiveXtUser(), CURRENT_TIMESTAMP,
6909         OLD.itemcost_stdcost, NEW.itemcost_stdcost,
6910         baseCurrId(), baseCurrId() );
6911     END IF;
6912
6913     RETURN NEW;
6914
6915   ELSIF (TG_OP = 'INSERT') THEN
6916     INSERT INTO costhist
6917     ( costhist_item_id, costhist_costelem_id, costhist_type,
6918       costhist_lowlevel, costhist_username, costhist_date,
6919       costhist_oldcost, costhist_newcost,
6920       costhist_oldcurr_id, costhist_newcurr_id )
6921     VALUES
6922     ( NEW.itemcost_item_id, NEW.itemcost_costelem_id, 'N',
6923       NEW.itemcost_lowlevel, getEffectiveXtUser(), CURRENT_TIMESTAMP,
6924       0, NEW.itemcost_actcost,
6925       baseCurrId(), NEW.itemcost_curr_id );
6926
6927     RETURN NEW;
6928
6929   ELSIF (TG_OP = 'DELETE') THEN
6930     INSERT INTO costhist
6931     ( costhist_item_id, costhist_costelem_id, costhist_type,
6932       costhist_lowlevel, costhist_username, costhist_date,
6933       costhist_oldcost, costhist_newcost,
6934       costhist_oldcurr_id, costhist_newcurr_id )
6935     VALUES
6936     ( OLD.itemcost_item_id, OLD.itemcost_costelem_id, 'D',
6937       OLD.itemcost_lowlevel, getEffectiveXtUser(), CURRENT_TIMESTAMP,
6938       OLD.itemcost_stdcost, 0,
6939       OLD.itemcost_curr_id, baseCurrId() );
6940
6941     RETURN OLD;
6942   END IF;
6943
6944 END;
6945 $$;
6946
6947
6948 ALTER FUNCTION public._itemcosttrigger() OWNER TO admin;
6949
6950 --
6951 -- TOC entry 990 (class 1255 OID 146565501)
6952 -- Dependencies: 4536 8
6953 -- Name: _itemsiteaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
6954 --
6955
6956 CREATE FUNCTION _itemsiteaftertrigger() RETURNS trigger
6957     LANGUAGE plpgsql
6958     AS $$
6959 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
6960 -- See www.xtuple.com/CPAL for the full text of the software license.
6961 DECLARE
6962   _state INTEGER;
6963   _wasLocationControl BOOLEAN;
6964   _isLocationControl BOOLEAN;
6965   _wasLotSerial BOOLEAN;
6966   _isLotSerial BOOLEAN;
6967   _wasPerishable BOOLEAN;
6968   _isPerishable BOOLEAN;
6969   _qty NUMERIC;
6970   _maint BOOLEAN;
6971   _cost NUMERIC;
6972   _variance NUMERIC;
6973   _application TEXT;
6974
6975 BEGIN
6976 -- Cache Application
6977   SELECT fetchMetricText('Application') INTO _application;
6978
6979 -- Check if we are doing maintenance
6980   IF (TG_OP = 'INSERT') THEN
6981     _maint := TRUE;
6982   ELSIF (TG_OP = 'UPDATE') THEN
6983     IF ((OLD.itemsite_item_id           != NEW.itemsite_item_id)
6984      OR (OLD.itemsite_warehous_id       != NEW.itemsite_warehous_id)
6985      OR (OLD.itemsite_reorderlevel      != NEW.itemsite_reorderlevel)
6986      OR (OLD.itemsite_ordertoqty        != NEW.itemsite_ordertoqty)
6987      OR (OLD.itemsite_cyclecountfreq    != NEW.itemsite_cyclecountfreq)
6988      OR (OLD.itemsite_planning_type     != NEW.itemsite_planning_type)
6989      OR (OLD.itemsite_posupply          != NEW.itemsite_posupply)
6990      OR (OLD.itemsite_wosupply          != NEW.itemsite_wosupply)
6991      OR (OLD.itemsite_loccntrl          != NEW.itemsite_loccntrl)
6992      OR (OLD.itemsite_safetystock       != NEW.itemsite_safetystock)
6993      OR (OLD.itemsite_minordqty         != NEW.itemsite_minordqty)
6994      OR (OLD.itemsite_multordqty        != NEW.itemsite_multordqty)
6995      OR (OLD.itemsite_leadtime          != NEW.itemsite_leadtime)
6996      OR (OLD.itemsite_abcclass          != NEW.itemsite_abcclass)
6997      OR (OLD.itemsite_controlmethod     != NEW.itemsite_controlmethod)
6998      OR (OLD.itemsite_active            != NEW.itemsite_active)
6999      OR (OLD.itemsite_plancode_id       != NEW.itemsite_plancode_id)
7000      OR (OLD.itemsite_costcat_id        != NEW.itemsite_costcat_id)
7001      OR (OLD.itemsite_eventfence        != NEW.itemsite_eventfence)
7002      OR (OLD.itemsite_sold              != NEW.itemsite_sold)
7003      OR (OLD.itemsite_stocked           != NEW.itemsite_stocked)
7004      OR (OLD.itemsite_location_id       != NEW.itemsite_location_id)
7005      OR (OLD.itemsite_recvlocation_id   != NEW.itemsite_recvlocation_id)
7006      OR (OLD.itemsite_issuelocation_id  != NEW.itemsite_issuelocation_id)
7007      OR (OLD.itemsite_location_dist     != NEW.itemsite_location_dist)
7008      OR (OLD.itemsite_recvlocation_dist != NEW.itemsite_recvlocation_dist)
7009      OR (OLD.itemsite_issuelocation_dist != NEW.itemsite_issuelocation_dist)
7010      OR (OLD.itemsite_useparams         != NEW.itemsite_useparams)
7011      OR (OLD.itemsite_useparamsmanual   != NEW.itemsite_useparamsmanual)
7012      OR (OLD.itemsite_soldranking       != NEW.itemsite_soldranking)
7013      OR (OLD.itemsite_createpr          != NEW.itemsite_createpr)
7014      OR (OLD.itemsite_location          != NEW.itemsite_location)
7015      OR (OLD.itemsite_location_comments != NEW.itemsite_location_comments)
7016      OR (OLD.itemsite_notes             != NEW.itemsite_notes)
7017      OR (OLD.itemsite_perishable        != NEW.itemsite_perishable)
7018      OR (OLD.itemsite_autoabcclass      != NEW.itemsite_autoabcclass)
7019      OR (OLD.itemsite_ordergroup        != NEW.itemsite_ordergroup)
7020      OR (OLD.itemsite_disallowblankwip  != NEW.itemsite_disallowblankwip)
7021      OR (OLD.itemsite_maxordqty         != NEW.itemsite_maxordqty)
7022      OR (OLD.itemsite_mps_timefence     != NEW.itemsite_mps_timefence)
7023      OR (OLD.itemsite_createwo          != NEW.itemsite_createwo)
7024      OR (OLD.itemsite_warrpurc          != NEW.itemsite_warrpurc)
7025      OR (OLD.itemsite_costmethod        != NEW.itemsite_costmethod)
7026      OR (OLD.itemsite_autoreg           != NEW.itemsite_autoreg)
7027      OR (OLD.itemsite_lsseq_id          != NEW.itemsite_lsseq_id) ) THEN
7028       IF (OLD.itemsite_item_id != NEW.itemsite_item_id) THEN
7029         RAISE EXCEPTION 'The item number on an itemsite may not be changed.';
7030       ELSIF (OLD.itemsite_warehous_id != NEW.itemsite_warehous_id) THEN
7031         RAISE EXCEPTION 'The warehouse code on an itemsite may not be changed.';
7032       END IF;
7033       _maint := TRUE;
7034     END IF;
7035   ELSE
7036     _maint := FALSE;
7037   END IF;
7038
7039   IF (_maint) THEN -- Begin Maintenance
7040 -- Privilege Checks
7041     IF ( NOT checkPrivilege('MaintainItemSites') ) THEN
7042        RAISE EXCEPTION 'You do not have privileges to maintain Item Sites.';
7043     END IF;
7044     
7045 -- Override values to avoid invalid data combinations
7046     IF (NOT NEW.itemsite_posupply) THEN
7047       UPDATE itemsite SET
7048         itemsite_createpr = FALSE
7049       WHERE (itemsite_id=NEW.itemsite_id);
7050     END IF;
7051     IF (NOT NEW.itemsite_wosupply) THEN
7052       UPDATE itemsite SET
7053         itemsite_createwo = FALSE
7054       WHERE (itemsite_id=NEW.itemsite_id);
7055     END IF;
7056
7057     IF (NEW.itemsite_controlmethod NOT IN ('S','L')) THEN
7058       UPDATE itemsite SET
7059         itemsite_perishable = FALSE,
7060         itemsite_warrpurc = FALSE,
7061         itemsite_autoreg = FALSE,
7062         itemsite_lsseq_id = NULL
7063       WHERE (itemsite_id=NEW.itemsite_id);
7064     END IF;
7065
7066     IF (NOT NEW.itemsite_loccntrl) THEN
7067       UPDATE itemsite SET
7068         itemsite_disallowblankwip = FALSE
7069       WHERE (itemsite_id=NEW.itemsite_id);
7070     END IF;
7071
7072     IF (NOT NEW.itemsite_useparams) THEN
7073       UPDATE itemsite SET
7074         itemsite_reorderlevel    = 0,
7075         itemsite_ordertoqty      = 0,
7076         itemsite_minordqty       = 0,
7077         itemsite_maxordqty       = 0,
7078         itemsite_multordqty      = 0,
7079         itemsite_useparamsmanual = FALSE
7080       WHERE (itemsite_id = NEW.itemsite_id);
7081     END IF;
7082     
7083 -- Integrity check
7084
7085     -- Both insert and update
7086     IF ( (NEW.itemsite_controlmethod IN ('S', 'L')) AND
7087          (NEW.itemsite_location_dist OR NEW.itemsite_recvlocation_dist OR NEW.itemsite_issuelocation_dist) ) THEN
7088       RAISE EXCEPTION 'You cannot auto-distribute Lot/Serial controlled Item Sites.';
7089     END IF;
7090
7091     IF (TG_OP = 'INSERT') THEN
7092       -- Handle MLC logic
7093       IF ( (NEW.itemsite_loccntrl) AND (NEW.itemsite_warehous_id IS NOT NULL) ) THEN
7094         IF (SELECT count(*)=0
7095             FROM location
7096             WHERE ((location_warehous_id=NEW.itemsite_warehous_id)
7097             AND ( (NOT location_restrict) OR
7098                 ( (location_restrict) AND
7099                 (location_id IN ( SELECT locitem_location_id
7100                                   FROM locitem
7101                                   WHERE (locitem_item_id=NEW.itemsite_item_id) ) ) ) ))) THEN
7102           RAISE EXCEPTION 'You must first create at least one valid
7103                           Location for this Item Site before it may be
7104                           multiply located.';
7105         END IF;
7106       END IF;
7107
7108       --This could be made a table constraint later, but do not want to create a big problem
7109       --for users with problematic legacy data over a relatively trivial problem for now,
7110       --so we will just check moving forword.
7111       IF (NEW.itemsite_stocked AND NEW.itemsite_reorderlevel<=0) THEN
7112         RAISE EXCEPTION 'Stocked items must have postive reorder level specified.';
7113       END IF;
7114     END IF;
7115
7116     IF (TG_OP = 'UPDATE') THEN
7117       --This could be made a table constraint later, but do not want to create a big problem
7118       --for users with problematic legacy data over a relatively trivial problem for now,
7119       --so we will just check moving forword.
7120       IF ((NEW.itemsite_stocked)
7121         AND (NEW.itemsite_stocked != OLD.itemsite_stocked) --Avoid checking unless explicitly changed
7122         AND (NEW.itemsite_reorderlevel<=0)) THEN
7123         RAISE EXCEPTION 'Stocked items must have postive reorder level specified.';
7124       END IF;
7125     END IF;
7126   
7127     IF (TG_OP = 'UPDATE') THEN
7128   
7129 -- Integrity check
7130       IF (NOT OLD.itemsite_loccntrl AND NEW.itemsite_loccntrl) THEN
7131         IF (SELECT count(*)=0
7132           FROM location
7133           WHERE ((location_warehous_id=NEW.itemsite_warehous_id)
7134           AND ( (NOT location_restrict) OR
7135               ( (location_restrict) AND
7136               (location_id IN ( SELECT locitem_location_id
7137                                 FROM locitem
7138                                 WHERE (locitem_item_id=NEW.itemsite_item_id) ) ) ) ))) THEN
7139            RAISE EXCEPTION 'You must first create at least one valid
7140                           Location for this Item Site before it may be
7141                           multiply located.';
7142         END IF;
7143       END IF;
7144    
7145 -- Update detail records based on control method changes 
7146       _wasLocationControl := OLD.itemsite_loccntrl;
7147       _isLocationControl := NEW.itemsite_loccntrl;
7148       _wasLotSerial := OLD.itemsite_controlmethod IN ('S','L');
7149       _isLotSerial := NEW.itemsite_controlmethod IN ('S','L'); 
7150       _wasPerishable := OLD.itemsite_perishable;
7151       _isPerishable := NEW.itemsite_perishable;
7152       _state := 0;
7153     
7154       IF ( (_wasLocationControl) AND (_isLocationControl) ) THEN
7155         _state := 10;
7156       ELSIF ( (NOT _wasLocationControl) AND (NOT _isLocationControl) ) THEN
7157         _state := 20;
7158       ELSIF ( (NOT _wasLocationControl) AND (_isLocationControl) ) THEN
7159         _state := 30;
7160       ELSIF ( (_wasLocationControl) AND (NOT _isLocationControl) ) THEN
7161         _state := 40;
7162       END IF;
7163
7164       IF ( (_wasLotSerial) AND (_isLotSerial) ) THEN
7165         _state := _state + 1;
7166       ELSIF ( (NOT _wasLotSerial) AND (NOT _isLotSerial) ) THEN
7167         _state := _state + 2;
7168       ELSIF ( (NOT _wasLotSerial) AND (_isLotSerial) ) THEN
7169         _state := _state + 3;
7170       ELSIF ( (_wasLotSerial) AND (NOT _isLotSerial) ) THEN
7171         _state := _state + 4;
7172       END IF;
7173
7174       IF ( (_application = 'Standard') AND (_state IN (41, 43, 14, 34, 24, 42, 44)) ) THEN
7175         -- Check for Reservations
7176         IF (SELECT COUNT(*) > 0
7177             FROM itemloc JOIN reserve ON (reserve_supply_id=itemloc_id AND reserve_supply_type='I')
7178             WHERE (itemloc_itemsite_id=OLD.itemsite_id)) THEN
7179           RAISE EXCEPTION 'Sales Order Reservations by Location exist for this Item Site';
7180         END IF;
7181       END IF;
7182
7183       IF (_state IN (41, 43)) THEN
7184         PERFORM consolidateLotSerial(OLD.itemsite_id);
7185       ELSIF (_state IN (14, 34)) THEN
7186         PERFORM consolidateLocations(OLD.itemsite_id);
7187       ELSIF (_state IN (24, 42, 44)) THEN
7188
7189         RAISE NOTICE 'Deleting item site detail records,';
7190
7191         SELECT SUM(itemloc_qty) INTO _qty
7192         FROM itemloc, location
7193         WHERE ((itemloc_location_id=location_id)
7194         AND (NOT location_netable) 
7195         AND (itemloc_itemsite_id=OLD.itemsite_id));
7196
7197         IF (_qty != 0) THEN
7198           UPDATE itemsite
7199           SET itemsite_qtyonhand = itemsite_qtyonhand + _qty,
7200             itemsite_nnqoh = itemsite_nnqoh - _qty
7201           WHERE (itemsite_id=OLD.itemsite_id);
7202         END IF;
7203
7204         DELETE FROM itemloc
7205         WHERE (itemloc_itemsite_id=OLD.itemsite_id);
7206       END IF;
7207
7208      IF (NEW.itemsite_qtyonhand != 0) THEN
7209 --  Handle detail creation
7210 --  Create itemloc records if they do not exist
7211        IF (_state IN (23, 32, 33)) THEN
7212           INSERT INTO itemloc 
7213             ( itemloc_itemsite_id, itemloc_location_id,
7214               itemloc_expiration, itemloc_qty )
7215             VALUES
7216             ( NEW.itemsite_id, -1,
7217               endOfTime(), NEW.itemsite_qtyonhand );
7218         END IF;
7219
7220 --  Handle Location distribution
7221         IF (_state IN (31, 32, 33, 34)) THEN
7222           IF (SELECT (COUNT(*)=1)
7223               FROM location
7224               WHERE ((location_id=NEW.itemsite_location_id)
7225               AND (location_warehous_id=NEW.itemsite_warehous_id)
7226               AND ( (NOT location_restrict) OR
7227                   ( (location_restrict) AND
7228                   (location_id IN ( SELECT locitem_location_id
7229                                     FROM locitem
7230                                     WHERE (locitem_item_id=NEW.itemsite_item_id) ) ) ) ))) THEN
7231            PERFORM initialDistribution(NEW.itemsite_id, NEW.itemsite_location_id);
7232           ELSE
7233             RAISE EXCEPTION 'A valid default location must be selected to distribute existing inventory to.';
7234           END IF;
7235         END IF;
7236
7237 --  Handle Lot/Serial distribution
7238         IF ( (_state = 13) OR (_state = 23) OR (_state = 33) OR (_state = 43) ) THEN
7239           RAISE NOTICE 'You should now use the Reassign Lot/Serial # window to assign Lot/Serial #s.';
7240         END IF;
7241       END IF;  
7242       IF (OLD.itemsite_costmethod='A' AND NEW.itemsite_costmethod='S') THEN
7243         -- TODO: Average costing cost method change
7244         SELECT stdcost(NEW.itemsite_item_id) * NEW.itemsite_qtyonhand
7245           INTO _cost;
7246         _variance := _cost - NEW.itemsite_value;
7247         NEW.itemsite_value := _cost;
7248         IF(_variance <> 0.0) THEN
7249           PERFORM insertGLTransaction( 'P/D', '', '', 'Itemsite converted from Average to Standard cost.',
7250                                        costcat_invcost_accnt_id, costcat_asset_accnt_id, NEW.itemsite_id,
7251                                       _variance, CURRENT_DATE )
7252              FROM costcat
7253             WHERE(costcat_id=NEW.itemsite_costcat_id);
7254           UPDATE itemsite SET itemsite_value = _cost WHERE (itemsite_id = NEW.itemsite_id);
7255         END IF;
7256       END IF;
7257     END IF;
7258
7259 --  Handle Perishable
7260     IF ( (_application = 'Standard') AND (_wasPerishable) AND (NOT _isPerishable) ) THEN
7261       UPDATE itemloc SET itemloc_expiration = endOfTime()
7262       WHERE (itemloc_itemsite_id = OLD.itemsite_id);
7263       PERFORM consolidateLotSerial(OLD.itemsite_id);
7264     END IF;
7265
7266 --  If Planning Type changed to None then delete all Planned Orders
7267     IF ( (_application = 'Standard') AND (TG_OP = 'UPDATE') ) THEN
7268       IF (NEW.itemsite_planning_type = 'N' AND OLD.itemsite_planning_type <> 'N') THEN
7269         PERFORM deletePlannedOrder(planord_id, TRUE)
7270         FROM planord
7271         WHERE (planord_itemsite_id=NEW.itemsite_id);
7272       END IF;
7273     END IF;
7274     
7275   END IF;  -- End Maintenance
7276
7277   RETURN NEW;
7278
7279 END;
7280 $$;
7281
7282
7283 ALTER FUNCTION public._itemsiteaftertrigger() OWNER TO admin;
7284
7285 --
7286 -- TOC entry 991 (class 1255 OID 146565503)
7287 -- Dependencies: 4536 8
7288 -- Name: _itemsitetrigger(); Type: FUNCTION; Schema: public; Owner: admin
7289 --
7290
7291 CREATE FUNCTION _itemsitetrigger() RETURNS trigger
7292     LANGUAGE plpgsql
7293     AS $$
7294 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7295 -- See www.xtuple.com/CPAL for the full text of the software license.
7296 DECLARE
7297   _cmnttypeid INTEGER;
7298   _r RECORD;
7299
7300 BEGIN
7301
7302   -- Cache some information
7303   SELECT item_type INTO _r
7304   FROM item
7305   WHERE (item_id=NEW.itemsite_item_id);
7306  
7307 -- Override values to avoid invalid data combinations
7308   IF (_r.item_type IN ('J','R','S')) THEN
7309     NEW.itemsite_planning_type := 'N';
7310   END IF;
7311
7312   IF (_r.item_type = 'L') THEN
7313     NEW.itemsite_planning_type := 'S';
7314   END IF;
7315
7316   IF (TG_OP = 'UPDATE') THEN
7317     IF ( (NEW.itemsite_qtyonhand <> OLD.itemsite_qtyonhand) ) THEN
7318       IF (OLD.itemsite_freeze) THEN
7319         NEW.itemsite_qtyonhand := OLD.itemsite_qtyonhand;
7320       ELSE
7321         NEW.itemsite_datelastused := CURRENT_DATE;
7322       END IF;
7323
7324       IF ( (NEW.itemsite_qtyonhand < 0) AND (OLD.itemsite_qtyonhand >= 0) AND (NEW.itemsite_eventfence > 0) ) THEN
7325         PERFORM postEvent('QOHBelowZero', 'I', NEW.itemsite_id,
7326                           warehous_id,
7327                           (item_number || '/' || warehous_code),
7328                           NULL, NULL, NULL, NULL)
7329         FROM item, whsinfo
7330         WHERE (item_id=NEW.itemsite_item_id)
7331           AND (warehous_id=NEW.itemsite_warehous_id);
7332       END IF;
7333     END IF;
7334     IF ( (NEW.itemsite_value <> OLD.itemsite_value) AND (OLD.itemsite_freeze) ) THEN
7335       NEW.itemsite_value := OLD.itemsite_value;
7336     END IF;
7337   END IF;
7338
7339   IF (NEW.itemsite_qtyonhand < 0 AND NEW.itemsite_costmethod = 'A') THEN
7340     RAISE EXCEPTION 'Itemsite (%) is set to use average costing and is not allowed to have a negative quantity on hand.', NEW.itemsite_id;
7341   ELSIF (NEW.itemsite_value < 0 AND NEW.itemsite_costmethod = 'A') THEN
7342     RAISE EXCEPTION 'This transaction results in a negative itemsite value.  Itemsite (%) is set to use average costing and is not allowed to have a negative value.', NEW.itemsite_id;
7343   END IF;
7344
7345 --  Handle the ChangeLog
7346   IF ( SELECT (metric_value='t')
7347        FROM metric
7348        WHERE (metric_name='ItemSiteChangeLog') ) THEN
7349
7350 --  Cache the cmnttype_id for ChangeLog
7351     SELECT cmnttype_id INTO _cmnttypeid
7352     FROM cmnttype
7353     WHERE (cmnttype_name='ChangeLog');
7354     IF (FOUND) THEN
7355       IF (TG_OP = 'INSERT') THEN
7356         PERFORM postComment(_cmnttypeid, 'IS', NEW.itemsite_id, 'Created');
7357
7358       ELSIF (TG_OP = 'UPDATE') THEN
7359
7360         IF (OLD.itemsite_plancode_id <> NEW.itemsite_plancode_id) THEN
7361           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7362                                ( 'Planner Code Changed from "' || oldplancode.plancode_code ||
7363                                  '" to "' || newplancode.plancode_code || '"' ) )
7364           FROM plancode AS oldplancode, plancode AS newplancode
7365           WHERE ( (oldplancode.plancode_id=OLD.itemsite_plancode_id)
7366            AND (newplancode.plancode_id=NEW.itemsite_plancode_id) );
7367         END IF;
7368
7369         IF (NEW.itemsite_reorderlevel <> OLD.itemsite_reorderlevel) THEN
7370           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7371                                ( 'Reorder Level Changed from ' || formatQty(OLD.itemsite_reorderlevel) ||
7372                                  ' to ' || formatQty(NEW.itemsite_reorderlevel ) ) );
7373         END IF;
7374
7375         IF (NEW.itemsite_ordertoqty <> OLD.itemsite_ordertoqty) THEN
7376           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7377                                ( 'Order Up To Changed from ' || formatQty(OLD.itemsite_ordertoqty) ||
7378                                  ' to ' || formatQty(NEW.itemsite_ordertoqty ) ) );
7379         END IF;
7380
7381         IF (NEW.itemsite_leadtime <> OLD.itemsite_leadtime) THEN
7382           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7383                                ( 'Itemsite Leadtime Changed from ' || formatQty(OLD.itemsite_leadtime) ||
7384                                  ' to ' || formatQty(NEW.itemsite_leadtime ) ) );
7385         END IF;
7386
7387         IF (NEW.itemsite_abcclass <> OLD.itemsite_abcclass) THEN
7388           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7389                                ( 'Itemsite ABC Class Changed from ' || COALESCE(OLD.itemsite_abcclass, 'None') ||
7390                                  ' to ' || COALESCE(NEW.itemsite_abcclass,'None') ) );
7391         END IF;
7392
7393         IF (NEW.itemsite_controlmethod <> OLD.itemsite_controlmethod) THEN
7394           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7395                                ( 'Itemsite Control Method Changed from ' || COALESCE(OLD.itemsite_controlmethod,'None') ||
7396                                  ' to ' || COALESCE(NEW.itemsite_controlmethod,'None') ) );
7397         END IF;
7398
7399         IF (OLD.itemsite_sold <> NEW.itemsite_sold) THEN
7400           PERFORM postComment( _cmnttypeid, 'IS', NEW.itemsite_id,
7401             CASE WHEN (NEW.itemsite_sold) THEN 'Sold Changed from FALSE to TRUE'
7402                                           ELSE 'Sold Changed from TRUE to FALSE'
7403             END );
7404         END IF;
7405
7406         IF (OLD.itemsite_active <> NEW.itemsite_active) THEN
7407           IF (NEW.itemsite_active) THEN
7408             PERFORM postComment(_cmnttypeid, 'IS', NEW.itemsite_id, 'Activated');
7409           ELSE
7410             PERFORM postComment(_cmnttypeid, 'IS', NEW.itemsite_id, 'Deactivated');
7411           END IF;
7412         END IF;
7413
7414       END IF;
7415     END IF;
7416   END IF;
7417
7418   RETURN NEW;
7419
7420 END;
7421 $$;
7422
7423
7424 ALTER FUNCTION public._itemsitetrigger() OWNER TO admin;
7425
7426 --
7427 -- TOC entry 992 (class 1255 OID 146565504)
7428 -- Dependencies: 4536 8
7429 -- Name: _itemsrcaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
7430 --
7431
7432 CREATE FUNCTION _itemsrcaftertrigger() RETURNS trigger
7433     LANGUAGE plpgsql
7434     AS $$
7435 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7436 -- See www.xtuple.com/CPAL for the full text of the software license.
7437 BEGIN
7438
7439 -- Privilege Checks
7440   IF (NOT checkPrivilege('MaintainItemSources')) THEN
7441     RAISE EXCEPTION 'You do not have privileges to maintain Item Sources.';
7442   END IF;
7443
7444 -- Set default to false for other item sources of this item
7445   IF (COALESCE(NEW.itemsrc_default, FALSE) = TRUE) THEN
7446     UPDATE itemsrc SET itemsrc_default = FALSE
7447     WHERE ( (itemsrc_item_id = NEW.itemsrc_item_id)
7448       AND (itemsrc_id <> NEW.itemsrc_id) );
7449   END IF;
7450
7451   RETURN NEW;
7452 END;
7453 $$;
7454
7455
7456 ALTER FUNCTION public._itemsrcaftertrigger() OWNER TO admin;
7457
7458 --
7459 -- TOC entry 993 (class 1255 OID 146565505)
7460 -- Dependencies: 4536 8
7461 -- Name: _itemsrcptrigger(); Type: FUNCTION; Schema: public; Owner: admin
7462 --
7463
7464 CREATE FUNCTION _itemsrcptrigger() RETURNS trigger
7465     LANGUAGE plpgsql
7466     AS $$
7467 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7468 -- See www.xtuple.com/CPAL for the full text of the software license.
7469 BEGIN
7470
7471 -- Privilege Checks
7472    IF (NOT checkPrivilege('MaintainItemSources')) THEN
7473      RAISE EXCEPTION 'You do not have privileges to maintain Item Sources.';
7474    END IF;
7475
7476 -- Set defaults
7477    NEW.itemsrcp_curr_id := COALESCE(NEW.itemsrcp_curr_id,basecurrid());
7478   
7479   RETURN NEW;
7480 END;
7481 $$;
7482
7483
7484 ALTER FUNCTION public._itemsrcptrigger() OWNER TO admin;
7485
7486 --
7487 -- TOC entry 994 (class 1255 OID 146565506)
7488 -- Dependencies: 4536 8
7489 -- Name: _itemsrctrigger(); Type: FUNCTION; Schema: public; Owner: admin
7490 --
7491
7492 CREATE FUNCTION _itemsrctrigger() RETURNS trigger
7493     LANGUAGE plpgsql
7494     AS $$
7495 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7496 -- See www.xtuple.com/CPAL for the full text of the software license.
7497 BEGIN
7498
7499 -- Privilege Checks
7500    IF (NOT checkPrivilege('MaintainItemSources')) THEN
7501      RAISE EXCEPTION 'You do not have privileges to maintain Item Sources.';
7502    END IF;
7503
7504 -- Set defaults
7505    NEW.itemsrc_invvendoruomratio        := COALESCE(NEW.itemsrc_invvendoruomratio,1);
7506    NEW.itemsrc_minordqty                := COALESCE(NEW.itemsrc_minordqty,0);
7507    NEW.itemsrc_multordqty               := COALESCE(NEW.itemsrc_multordqty,0);
7508    NEW.itemsrc_active                   := COALESCE(NEW.itemsrc_active,true);
7509    NEW.itemsrc_leadtime                 := COALESCE(NEW.itemsrc_leadtime,0);
7510    NEW.itemsrc_ranking                  := COALESCE(NEW.itemsrc_ranking,1);
7511   
7512   RETURN NEW;
7513 END;
7514 $$;
7515
7516
7517 ALTER FUNCTION public._itemsrctrigger() OWNER TO admin;
7518
7519 --
7520 -- TOC entry 995 (class 1255 OID 146565507)
7521 -- Dependencies: 4536 8
7522 -- Name: _itemsubtrigger(); Type: FUNCTION; Schema: public; Owner: admin
7523 --
7524
7525 CREATE FUNCTION _itemsubtrigger() RETURNS trigger
7526     LANGUAGE plpgsql
7527     AS $$
7528 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7529 -- See www.xtuple.com/CPAL for the full text of the software license.
7530 BEGIN
7531
7532 -- Privilege Checks
7533    IF (NOT checkPrivilege('MaintainItemMasters')) THEN
7534      RAISE EXCEPTION 'You do not have privileges to maintain Item Substitutes.';
7535    END IF;
7536   
7537   RETURN NEW;
7538 END;
7539 $$;
7540
7541
7542 ALTER FUNCTION public._itemsubtrigger() OWNER TO admin;
7543
7544 --
7545 -- TOC entry 996 (class 1255 OID 146565508)
7546 -- Dependencies: 4536 8
7547 -- Name: _itemtaxtrigger(); Type: FUNCTION; Schema: public; Owner: admin
7548 --
7549
7550 CREATE FUNCTION _itemtaxtrigger() RETURNS trigger
7551     LANGUAGE plpgsql
7552     AS $$
7553 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7554 -- See www.xtuple.com/CPAL for the full text of the software license.
7555 BEGIN
7556
7557 -- Privilege Checks
7558    IF (NOT checkPrivilege('MaintainItemMasters')) THEN
7559      RAISE EXCEPTION 'You do not have privileges to maintain Items.';
7560    END IF;
7561   
7562   RETURN NEW;
7563 END;
7564 $$;
7565
7566
7567 ALTER FUNCTION public._itemtaxtrigger() OWNER TO admin;
7568
7569 --
7570 -- TOC entry 997 (class 1255 OID 146565509)
7571 -- Dependencies: 4536 8
7572 -- Name: _itemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
7573 --
7574
7575 CREATE FUNCTION _itemtrigger() RETURNS trigger
7576     LANGUAGE plpgsql
7577     AS $$
7578 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7579 -- See www.xtuple.com/CPAL for the full text of the software license.
7580 BEGIN
7581  
7582 -- Override values to avoid invalid data combinations
7583   IF (NEW.item_type IN ('R','S','O','L','B')) THEN
7584     NEW.item_picklist := FALSE;
7585   END IF;
7586
7587   IF (NEW.item_type IN ('F','S','O','L','B')) THEN
7588     NEW.item_picklist := FALSE;
7589     NEW.item_sold := FALSE;
7590     NEW.item_prodcat_id := -1;
7591     NEW.item_exclusive := false;
7592     NEW.item_listprice := 0;
7593     NEW.item_upccode := '';
7594     NEW.item_prodweight := 0;
7595     NEW.item_packweight := 0;
7596   END IF;
7597
7598   IF (NEW.item_type NOT IN ('M','R')) THEN
7599     NEW.item_config := false;
7600   END IF;
7601
7602   RETURN NEW;
7603
7604 END;
7605 $$;
7606
7607
7608 ALTER FUNCTION public._itemtrigger() OWNER TO admin;
7609
7610 --
7611 -- TOC entry 998 (class 1255 OID 146565510)
7612 -- Dependencies: 4536 8
7613 -- Name: _itemuomconvtrigger(); Type: FUNCTION; Schema: public; Owner: admin
7614 --
7615
7616 CREATE FUNCTION _itemuomconvtrigger() RETURNS trigger
7617     LANGUAGE plpgsql
7618     AS $$
7619 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7620 -- See www.xtuple.com/CPAL for the full text of the software license.
7621 BEGIN
7622
7623 -- Privilege Checks
7624    IF (NOT checkPrivilege('MaintainItemMasters')) THEN
7625      RAISE EXCEPTION 'You do not have privileges to maintain Items.';
7626    END IF;
7627   
7628   RETURN NEW;
7629 END;
7630 $$;
7631
7632
7633 ALTER FUNCTION public._itemuomconvtrigger() OWNER TO admin;
7634
7635 --
7636 -- TOC entry 999 (class 1255 OID 146565511)
7637 -- Dependencies: 4536 8
7638 -- Name: _locationaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
7639 --
7640
7641 CREATE FUNCTION _locationaftertrigger() RETURNS trigger
7642     LANGUAGE plpgsql
7643     AS $$
7644 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7645 -- See www.xtuple.com/CPAL for the full text of the software license.
7646 DECLARE
7647   _itemloc    RECORD;
7648
7649 BEGIN
7650
7651   -- Maintain itemsite_qtyonhand and itemsite_nnqoh when location_netable changes
7652   IF (TG_OP = 'UPDATE') THEN
7653     IF (OLD.location_netable <> NEW.location_netable) THEN
7654       FOR _itemloc IN SELECT * FROM itemloc WHERE (itemloc_location_id=NEW.location_id) LOOP
7655         IF (NEW.location_netable) THEN
7656           UPDATE itemsite SET itemsite_qtyonhand = itemsite_qtyonhand + _itemloc.itemloc_qty,
7657                               itemsite_nnqoh = itemsite_nnqoh - _itemloc.itemloc_qty
7658           WHERE (itemsite_id=_itemloc.itemloc_itemsite_id);
7659         ELSE
7660           UPDATE itemsite SET itemsite_qtyonhand = itemsite_qtyonhand - _itemloc.itemloc_qty,
7661                               itemsite_nnqoh = itemsite_nnqoh + _itemloc.itemloc_qty
7662           WHERE (itemsite_id=_itemloc.itemloc_itemsite_id);
7663         END IF;
7664       END LOOP;
7665     END IF;
7666   END IF;
7667   
7668   RETURN NEW;
7669
7670 END;
7671 $$;
7672
7673
7674 ALTER FUNCTION public._locationaftertrigger() OWNER TO admin;
7675
7676 --
7677 -- TOC entry 1000 (class 1255 OID 146565512)
7678 -- Dependencies: 4536 8
7679 -- Name: _locationtrigger(); Type: FUNCTION; Schema: public; Owner: admin
7680 --
7681
7682 CREATE FUNCTION _locationtrigger() RETURNS trigger
7683     LANGUAGE plpgsql
7684     AS $$
7685 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7686 -- See www.xtuple.com/CPAL for the full text of the software license.
7687 DECLARE
7688   _check      BOOLEAN;
7689   _checkId    INTEGER;
7690
7691 BEGIN
7692
7693   -- Checks
7694   -- Start with privileges
7695   IF (TG_OP = 'INSERT') THEN
7696     SELECT checkPrivilege('MaintainLocations') INTO _check;
7697     IF NOT (_check) THEN
7698       RAISE EXCEPTION 'You do not have privileges to add new Locations.';
7699     END IF;
7700   ELSE
7701     SELECT checkPrivilege('MaintainLocations') INTO _check;
7702     IF NOT (_check) THEN
7703       RAISE EXCEPTION 'You do not have privileges to alter a Location.';
7704     END IF;
7705   END IF;
7706
7707   -- Code is required
7708   IF ( (LENGTH(COALESCE(NEW.location_name,''))=0) AND
7709        (LENGTH(COALESCE(NEW.location_aisle,''))=0) AND
7710        (LENGTH(COALESCE(NEW.location_rack,''))=0) AND
7711        (LENGTH(COALESCE(NEW.location_bin,''))=0) ) THEN
7712     RAISE EXCEPTION 'You must supply a valid Location Identifier.';
7713   END IF;
7714   
7715   -- Site is required
7716   IF (NEW.location_warehous_id IS NULL) THEN
7717     RAISE EXCEPTION 'You must supply a valid Site.';
7718   END IF;
7719
7720   -- Location Identifier must be unique
7721   SELECT location_id INTO _checkId
7722   FROM location
7723   WHERE ( (UPPER(location_name)=UPPER(NEW.location_name))
7724     AND   (UPPER(location_aisle)=UPPER(NEW.location_aisle))
7725     AND   (UPPER(location_rack)=UPPER(NEW.location_rack))
7726     AND   (UPPER(location_bin)=UPPER(NEW.location_bin))
7727     AND   (location_warehous_id=NEW.location_warehous_id)
7728     AND   (location_id<>NEW.location_id) );
7729   IF (FOUND) THEN
7730     RAISE EXCEPTION 'You must supply a unique Location Identifier for this Site.';
7731   END IF;
7732   
7733   RETURN NEW;
7734
7735 END;
7736 $$;
7737
7738
7739 ALTER FUNCTION public._locationtrigger() OWNER TO admin;
7740
7741 --
7742 -- TOC entry 1001 (class 1255 OID 146565513)
7743 -- Dependencies: 4536 8
7744 -- Name: _metasqlaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
7745 --
7746
7747 CREATE FUNCTION _metasqlaltertrigger() RETURNS trigger
7748     LANGUAGE plpgsql
7749     AS $$
7750 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7751 -- See www.xtuple.com/CPAL for the full text of the software license.
7752 BEGIN
7753   IF (NOT (isDBA() OR checkPrivilege('MaintainMetaSQL'))) THEN
7754     RAISE EXCEPTION '% does not have privileges to maintain MetaSQL statements in %.%',
7755                 getEffectiveXtUser(), TG_TABLE_SCHEMA, TG_TABLE_NAME;
7756   END IF;
7757
7758   IF ((TG_OP = 'UPDATE' OR TG_OP = 'DELETE')
7759       AND NEW.metasql_grade <= 0
7760       AND NOT isDBA()) THEN
7761     RAISE EXCEPTION 'You may not alter grade 0 metasql queries except using the xTuple Updater utility';
7762   END IF;
7763
7764   IF (TG_OP = 'DELETE') THEN
7765     RETURN OLD;
7766   END IF;
7767
7768   RETURN NEW;
7769 END;
7770
7771 $$;
7772
7773
7774 ALTER FUNCTION public._metasqlaltertrigger() OWNER TO admin;
7775
7776 --
7777 -- TOC entry 1002 (class 1255 OID 146565514)
7778 -- Dependencies: 4536 8
7779 -- Name: _metasqltrigger(); Type: FUNCTION; Schema: public; Owner: admin
7780 --
7781
7782 CREATE FUNCTION _metasqltrigger() RETURNS trigger
7783     LANGUAGE plpgsql
7784     AS $$
7785 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7786 -- See www.xtuple.com/CPAL for the full text of the software license.
7787 BEGIN
7788
7789   NEW.metasql_lastuser          := getEffectiveXtUser();
7790   NEW.metasql_lastupdate        := current_date;
7791   RETURN NEW;
7792
7793 END;
7794
7795 $$;
7796
7797
7798 ALTER FUNCTION public._metasqltrigger() OWNER TO admin;
7799
7800 --
7801 -- TOC entry 1004 (class 1255 OID 146565515)
7802 -- Dependencies: 4536 8
7803 -- Name: _opheadaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
7804 --
7805
7806 CREATE FUNCTION _opheadaftertrigger() RETURNS trigger
7807     LANGUAGE plpgsql
7808     AS $$
7809 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7810 -- See www.xtuple.com/CPAL for the full text of the software license.
7811 DECLARE
7812   _cmnttypeid INTEGER;
7813 BEGIN
7814   IF (TG_OP = 'DELETE') THEN
7815     DELETE FROM docass WHERE docass_source_id = OLD.ophead_id AND docass_source_type = 'OPP';
7816     DELETE FROM docass WHERE docass_target_id = OLD.ophead_id AND docass_target_type = 'OPP';
7817   END IF;
7818   
7819   --  Comments
7820   IF ( SELECT (metric_value='t') FROM metric WHERE (metric_name='OpportunityChangeLog') ) THEN
7821
7822     --  Cache the cmnttype_id for ChangeLog
7823     SELECT cmnttype_id INTO _cmnttypeid
7824     FROM cmnttype
7825     WHERE (cmnttype_name='ChangeLog');
7826     IF (FOUND) THEN
7827       IF (TG_OP = 'INSERT') THEN
7828         PERFORM postComment(_cmnttypeid, 'OPP', NEW.ophead_id, 'Created');
7829
7830         --- clear the number from the issue cache
7831         PERFORM clearNumberIssue('OpportunityNumber', NEW.ophead_number);
7832       ELSIF (TG_OP = 'UPDATE') THEN
7833         IF (OLD.ophead_active <> NEW.ophead_active) THEN
7834           IF (NEW.ophead_active) THEN
7835             PERFORM postComment(_cmnttypeid, 'OPP', NEW.ophead_id, 'Activated');
7836           ELSE
7837             PERFORM postComment(_cmnttypeid, 'OPP', NEW.ophead_id, 'Deactivated');
7838           END IF;
7839         END IF;
7840
7841         IF (OLD.ophead_name <> NEW.ophead_name) THEN
7842           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7843                                ( 'Name Changed from "' || OLD.ophead_name ||
7844                                  '" to "' || NEW.ophead_name || '"' ) );
7845         END IF;
7846
7847         IF (OLD.ophead_owner_username <> NEW.ophead_owner_username) THEN
7848           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7849                                ( 'Owner Name Changed from "' || OLD.ophead_owner_username ||
7850                                  '" to "' || NEW.ophead_owner_username || '"' ) );
7851         END IF;
7852
7853         IF (OLD.ophead_probability_prcnt <> NEW.ophead_probability_prcnt) THEN
7854           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7855                                ( 'Probability % Changed from "' || OLD.ophead_probability_prcnt ||
7856                                  '" to "' || NEW.ophead_probability_prcnt || '"' ) );
7857         END IF;
7858
7859         IF (OLD.ophead_amount <> NEW.ophead_amount) THEN
7860           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7861                                ( 'Amount Changed from "' || OLD.ophead_amount ||
7862                                  '" to "' || NEW.ophead_amount || '"' ) );
7863         END IF;
7864
7865         IF (OLD.ophead_target_date <> NEW.ophead_target_date) THEN
7866           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7867                                ( 'Target Date Changed from "' || OLD.ophead_target_date ||
7868                                  '" to "' || NEW.ophead_target_date || '"' ) );
7869         END IF;
7870
7871         IF (OLD.ophead_actual_date <> NEW.ophead_actual_date) THEN
7872           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7873                                ( 'Actual Date Changed from "' || OLD.ophead_actual_date ||
7874                                  '" to "' || NEW.ophead_actual_date || '"' ) );
7875         END IF;
7876
7877         IF (OLD.ophead_crmacct_id <> NEW.ophead_crmacct_id) THEN
7878           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7879                                ( 'CRM Account Changed from "' ||
7880                                  (SELECT crmacct_name FROM crmacct WHERE crmacct_id=OLD.ophead_crmacct_id) ||
7881                                  '" (' || OLD.ophead_crmacct_id ||
7882                                  ') to "' ||
7883                                  (SELECT crmacct_name FROM crmacct WHERE crmacct_id=NEW.ophead_crmacct_id) ||
7884                                  '" (' || NEW.ophead_crmacct_id || ')' ) );
7885         END IF;
7886
7887         IF (OLD.ophead_curr_id <> NEW.ophead_curr_id) THEN
7888           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7889                                ( 'Currency Changed from "' ||
7890                                  (SELECT curr_name FROM curr_symbol WHERE curr_id=OLD.ophead_curr_id) ||
7891                                  '" (' || OLD.ophead_curr_id ||
7892                                  ') to "' ||
7893                                  (SELECT curr_name FROM curr_symbol WHERE curr_id=NEW.ophead_curr_id) ||
7894                                  '" (' || NEW.ophead_curr_id || ')' ) );
7895         END IF;
7896
7897         IF (OLD.ophead_opstage_id <> NEW.ophead_opstage_id) THEN
7898           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7899                                ( 'Stage Changed from "' ||
7900                                  (SELECT opstage_name FROM opstage WHERE opstage_id=OLD.ophead_opstage_id) ||
7901                                  '" (' || OLD.ophead_opstage_id ||
7902                                  ') to "' ||
7903                                  (SELECT opstage_name FROM opstage WHERE opstage_id=NEW.ophead_opstage_id) ||
7904                                  '" (' || NEW.ophead_opstage_id || ')' ) );
7905         END IF;
7906
7907         IF (OLD.ophead_opsource_id <> NEW.ophead_opsource_id) THEN
7908           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7909                                ( 'Source Changed from "' ||
7910                                  (SELECT opsource_name FROM opsource WHERE opsource_id=OLD.ophead_opsource_id) ||
7911                                  '" (' || OLD.ophead_opsource_id ||
7912                                  ') to "' ||
7913                                  (SELECT opsource_name FROM opsource WHERE opsource_id=NEW.ophead_opsource_id) ||
7914                                  '" (' || NEW.ophead_opsource_id || ')' ) );
7915         END IF;
7916
7917         IF (OLD.ophead_optype_id <> NEW.ophead_optype_id) THEN
7918           PERFORM postComment( _cmnttypeid, 'OPP', NEW.ophead_id,
7919                                ( 'Type Changed from "' ||
7920                                  (SELECT optype_name FROM optype WHERE optype_id=OLD.ophead_optype_id) ||
7921                                  '" (' || OLD.ophead_optype_id ||
7922                                  ') to "' ||
7923                                  (SELECT optype_name FROM optype WHERE optype_id=NEW.ophead_optype_id) ||
7924                                  '" (' || NEW.ophead_optype_id || ')' ) );
7925         END IF;
7926
7927       END IF;
7928     END IF;
7929   END IF;
7930
7931   RETURN NEW;
7932 END;
7933 $$;
7934
7935
7936 ALTER FUNCTION public._opheadaftertrigger() OWNER TO admin;
7937
7938 --
7939 -- TOC entry 1005 (class 1255 OID 146565516)
7940 -- Dependencies: 4536 8
7941 -- Name: _opheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
7942 --
7943
7944 CREATE FUNCTION _opheadbeforetrigger() RETURNS trigger
7945     LANGUAGE plpgsql
7946     AS $$
7947 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7948 -- See www.xtuple.com/CPAL for the full text of the software license.
7949 DECLARE
7950   _rec record;
7951   _check boolean;
7952   _test text;
7953 BEGIN
7954
7955   IF(TG_OP = 'DELETE') THEN
7956     _rec := OLD;
7957   ELSE
7958     _rec := NEW;
7959   END IF;
7960
7961   --  Auto inactivate
7962   IF (TG_OP = 'UPDATE') THEN
7963     IF ( (NEW.ophead_opstage_id != OLD.ophead_opstage_id) AND
7964          (SELECT opstage_opinactive FROM opstage WHERE opstage_id=NEW.ophead_opstage_id) ) THEN
7965       NEW.ophead_active := FALSE;
7966     END IF;
7967   END IF;
7968
7969   IF (TG_OP = 'INSERT') THEN
7970     IF (SELECT opstage_opinactive FROM opstage WHERE opstage_id=NEW.ophead_opstage_id) THEN
7971       NEW.ophead_active := FALSE;
7972     END IF;
7973   END IF;
7974
7975   RETURN NEW;
7976 END;
7977 $$;
7978
7979
7980 ALTER FUNCTION public._opheadbeforetrigger() OWNER TO admin;
7981
7982 --
7983 -- TOC entry 1006 (class 1255 OID 146565517)
7984 -- Dependencies: 4536 8
7985 -- Name: _packbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
7986 --
7987
7988 CREATE FUNCTION _packbeforetrigger() RETURNS trigger
7989     LANGUAGE plpgsql
7990     AS $$
7991 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
7992 -- See www.xtuple.com/CPAL for the full text of the software license.
7993 DECLARE
7994   _cmnttypeid INTEGER;
7995 BEGIN
7996   SELECT cmnttype_id INTO _cmnttypeid
7997     FROM cmnttype
7998     WHERE (cmnttype_name='ChangeLog');
7999   IF (FOUND) THEN
8000     IF ((TG_OP = 'INSERT') AND (NEW.pack_head_id) IS NOT NULL)THEN
8001       PERFORM postComment(_cmnttypeid, 'S', NEW.pack_head_id, 'Added to Packing List Batch');
8002     END IF;
8003   END IF;
8004   IF ((TG_OP = 'INSERT') OR (TG_OP = 'UPDATE')) THEN
8005     IF (NEW.pack_shiphead_id IS NOT NULL
8006          AND NEW.pack_shiphead_id NOT IN (SELECT shiphead_id
8007                                FROM shiphead
8008                                WHERE (shiphead_order_id=NEW.pack_head_id)
8009                                  AND (shiphead_order_type=NEW.pack_head_type))) THEN
8010       RAISE EXCEPTION 'Shipment does not exist for % id %',
8011                       NEW.pack_head_type, NEW.pack_head_id;
8012       RETURN OLD;
8013     END IF;
8014
8015     IF (NEW.pack_head_type = 'SO'
8016         AND NEW.pack_head_id   IN (SELECT cohead_id FROM cohead)) THEN
8017       RETURN NEW;
8018
8019     ELSEIF (NEW.pack_head_type = 'TO') THEN
8020       IF (NOT fetchMetricBool('MultiWhs')) THEN
8021         RAISE EXCEPTION 'Transfer Orders are not supported by this version of the application';
8022       ELSEIF (NEW.pack_head_id IN (SELECT tohead_id FROM tohead)) THEN
8023         RETURN NEW;
8024       END IF;
8025     END IF;
8026
8027     RAISE EXCEPTION '% with id % does not exist',
8028                     NEW.pack_head_type, NEW.pack_head_id;
8029     RETURN OLD;
8030
8031   END IF;
8032
8033   RETURN NEW;
8034 END;
8035 $$;
8036
8037
8038 ALTER FUNCTION public._packbeforetrigger() OWNER TO admin;
8039
8040 --
8041 -- TOC entry 1007 (class 1255 OID 146565518)
8042 -- Dependencies: 4536 8
8043 -- Name: _periodaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8044 --
8045
8046 CREATE FUNCTION _periodaftertrigger() RETURNS trigger
8047     LANGUAGE plpgsql
8048     AS $$
8049 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8050 -- See www.xtuple.com/CPAL for the full text of the software license.
8051 DECLARE
8052   _idoffirst INTEGER;
8053   _test      INTEGER;
8054 BEGIN
8055   -- This trigger can easily cause an infinite loop
8056   -- because of this we have to be very careful to not
8057   -- do an update on the period table if no updates
8058   -- are absolutely needed so we don't just keep
8059   -- trigger ourselves again and again
8060
8061   -- Figure out which period is the first one
8062   SELECT period_id
8063     INTO _idoffirst
8064     FROM period
8065    ORDER BY period_start
8066    LIMIT 1;
8067
8068   -- If we didn't find anything there is nothing to do
8069   IF( NOT FOUND ) THEN
8070     RETURN NEW;
8071   END IF;
8072
8073   -- do a select to see if there is at least one record that needs to be
8074   -- updated. If we do not find any then we can just leave without
8075   -- causing a retrigger of ourselves
8076   SELECT period_id
8077     INTO _test
8078     FROM period
8079    WHERE((COALESCE(period_initial, true) AND (NOT period_id=_idoffirst))
8080       OR ((NOT COALESCE(period_initial, false)) AND (period_id=_idoffirst)))
8081    LIMIT 1;
8082
8083   -- Nothing to update - get out of here
8084   IF( NOT FOUND ) THEN
8085     RETURN NEW;
8086   END IF;
8087
8088   -- Update all the period records that already have the initial flag
8089   -- set and the one that we know should be the first.
8090   -- We don't have to be as careful here since we have already ruled
8091   -- out if don't need to update already.
8092   UPDATE period
8093      SET period_initial = (_idoffirst=period_id)
8094    WHERE((COALESCE(period_initial, true))
8095       OR (period_id=_idoffirst));
8096
8097   RETURN NEW;
8098
8099 END;
8100 $$;
8101
8102
8103 ALTER FUNCTION public._periodaftertrigger() OWNER TO admin;
8104
8105 --
8106 -- TOC entry 1008 (class 1255 OID 146565519)
8107 -- Dependencies: 4536 8
8108 -- Name: _pkgcmdaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8109 --
8110
8111 CREATE FUNCTION _pkgcmdaftertrigger() RETURNS trigger
8112     LANGUAGE plpgsql
8113     AS $$
8114 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8115 -- See www.xtuple.com/CPAL for the full text of the software license.
8116 BEGIN
8117   IF (TG_OP = 'DELETE') THEN
8118     RETURN OLD;
8119   END IF;
8120
8121   RETURN NEW;
8122 END;
8123 $$;
8124
8125
8126 ALTER FUNCTION public._pkgcmdaftertrigger() OWNER TO admin;
8127
8128 --
8129 -- TOC entry 1009 (class 1255 OID 146565520)
8130 -- Dependencies: 4536 8
8131 -- Name: _pkgcmdaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8132 --
8133
8134 CREATE FUNCTION _pkgcmdaltertrigger() RETURNS trigger
8135     LANGUAGE plpgsql
8136     AS $$
8137 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8138 -- See www.xtuple.com/CPAL for the full text of the software license.
8139 BEGIN
8140   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
8141     IF (TG_OP = 'DELETE') THEN
8142       RETURN OLD;
8143     ELSE
8144       RETURN NEW;
8145     END IF;
8146   END IF;
8147
8148   IF (TG_OP = 'INSERT') THEN
8149     RAISE EXCEPTION 'You may not create custom commands in packages except using the xTuple Updater utility';
8150
8151   ELSIF (TG_OP = 'UPDATE') THEN
8152     RAISE EXCEPTION 'You may not alter custom commands in packages except using the xTuple Updater utility';
8153
8154   ELSIF (TG_OP = 'DELETE') THEN
8155     RAISE EXCEPTION 'You may not delete custom commands from packages. Try deleting or disabling the package.';
8156
8157   END IF;
8158
8159   RETURN NEW;
8160 END;
8161
8162 $$;
8163
8164
8165 ALTER FUNCTION public._pkgcmdaltertrigger() OWNER TO admin;
8166
8167 --
8168 -- TOC entry 1010 (class 1255 OID 146565521)
8169 -- Dependencies: 4536 8
8170 -- Name: _pkgcmdargaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8171 --
8172
8173 CREATE FUNCTION _pkgcmdargaftertrigger() RETURNS trigger
8174     LANGUAGE plpgsql
8175     AS $$
8176 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8177 -- See www.xtuple.com/CPAL for the full text of the software license.
8178 BEGIN
8179   IF (TG_OP = 'DELETE') THEN
8180     RETURN OLD;
8181   END IF;
8182   RETURN NEW;
8183 END;
8184 $$;
8185
8186
8187 ALTER FUNCTION public._pkgcmdargaftertrigger() OWNER TO admin;
8188
8189 --
8190 -- TOC entry 1012 (class 1255 OID 146565522)
8191 -- Dependencies: 4536 8
8192 -- Name: _pkgcmdargaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8193 --
8194
8195 CREATE FUNCTION _pkgcmdargaltertrigger() RETURNS trigger
8196     LANGUAGE plpgsql
8197     AS $$
8198 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8199 -- See www.xtuple.com/CPAL for the full text of the software license.
8200 BEGIN
8201   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
8202     IF (TG_OP = 'DELETE') THEN
8203       RETURN OLD;
8204     ELSE
8205       RETURN NEW;
8206     END IF;
8207   END IF;
8208
8209   IF (TG_OP = 'INSERT') THEN
8210     RAISE EXCEPTION 'You may not create command arguments in packages except using the xTuple Updater utility';
8211
8212   ELSIF (TG_OP = 'UPDATE') THEN
8213     RAISE EXCEPTION 'You may not alter command arguments in packages except using the xTuple Updater utility';
8214
8215   ELSIF (TG_OP = 'DELETE') THEN
8216     RAISE EXCEPTION 'You may not delete command arguments from packages. Try deleting or disabling the package.';
8217
8218   END IF;
8219
8220   RETURN NEW;
8221 END;
8222
8223 $$;
8224
8225
8226 ALTER FUNCTION public._pkgcmdargaltertrigger() OWNER TO admin;
8227
8228 --
8229 -- TOC entry 1013 (class 1255 OID 146565523)
8230 -- Dependencies: 4536 8
8231 -- Name: _pkgcmdargbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8232 --
8233
8234 CREATE FUNCTION _pkgcmdargbeforetrigger() RETURNS trigger
8235     LANGUAGE plpgsql
8236     AS $$
8237 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8238 -- See www.xtuple.com/CPAL for the full text of the software license.
8239 DECLARE
8240   _cmdargid     INTEGER;
8241   _debug        BOOL := false;
8242
8243 BEGIN
8244   IF (TG_OP = 'UPDATE') THEN
8245     RETURN NEW;
8246
8247   ELSIF (TG_OP = 'INSERT') THEN
8248     RETURN NEW;
8249
8250   ELSIF (TG_OP = 'DELETE') THEN
8251     RETURN OLD;
8252   END IF;
8253
8254   RETURN NEW;
8255 END;
8256 $$;
8257
8258
8259 ALTER FUNCTION public._pkgcmdargbeforetrigger() OWNER TO admin;
8260
8261 --
8262 -- TOC entry 1014 (class 1255 OID 146565524)
8263 -- Dependencies: 4536 8
8264 -- Name: _pkgcmdbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8265 --
8266
8267 CREATE FUNCTION _pkgcmdbeforetrigger() RETURNS trigger
8268     LANGUAGE plpgsql
8269     AS $$
8270 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8271 -- See www.xtuple.com/CPAL for the full text of the software license.
8272 DECLARE
8273   _cmdid       INTEGER;
8274   _debug        BOOL := false;
8275
8276 BEGIN
8277     IF (TG_OP = 'UPDATE') THEN
8278       IF (_debug) THEN
8279         RAISE NOTICE 'OLD.cmd_name %, NEW.cmd_name %',
8280                      OLD.cmd_name, NEW.cmd_name;
8281       END IF;
8282
8283       IF (NEW.cmd_name != OLD.cmd_name) THEN
8284         SELECT cmd_id INTO _cmdid FROM cmd WHERE cmd_name=NEW.cmd_name;
8285         IF (FOUND) THEN
8286           RAISE EXCEPTION 'Cannot change command name % because another command with that name already exists.', NEW.cmd_name;
8287         END IF;
8288       END IF;
8289
8290     ELSIF (TG_OP = 'INSERT') THEN
8291       IF (_debug) THEN
8292         RAISE NOTICE 'inserting NEW.cmd_name %', NEW.cmd_name;
8293       END IF;
8294       SELECT cmd_id INTO _cmdid FROM cmd WHERE cmd_name=NEW.cmd_name;
8295       IF (FOUND) THEN
8296         RAISE EXCEPTION 'Cannot create new command % because another command with that name already exists.', NEW.cmd_name;
8297       END IF;
8298
8299     ELSIF (TG_OP = 'DELETE') THEN
8300       DELETE FROM cmdarg WHERE cmdarg_cmd_id=OLD.cmd_id;
8301
8302       RETURN OLD;
8303     END IF;
8304
8305     RETURN NEW;
8306   END;
8307 $$;
8308
8309
8310 ALTER FUNCTION public._pkgcmdbeforetrigger() OWNER TO admin;
8311
8312 --
8313 -- TOC entry 1015 (class 1255 OID 146565525)
8314 -- Dependencies: 4536 8
8315 -- Name: _pkgheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8316 --
8317
8318 CREATE FUNCTION _pkgheadbeforetrigger() RETURNS trigger
8319     LANGUAGE plpgsql
8320     AS $$
8321 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
8322 -- See www.xtuple.com/CPAL for the full text of the software license.
8323   DECLARE
8324     _r    RECORD;
8325
8326   BEGIN
8327     IF (TG_OP = 'UPDATE') THEN
8328       NEW.pkghead_created := OLD.pkghead_created;
8329       NEW.pkghead_updated := CURRENT_TIMESTAMP;
8330       IF (NEW.pkghead_indev AND NOT userCanCreateUsers(getEffectiveXtUser())) THEN
8331         NEW.pkghead_indev = FALSE;
8332       END IF;
8333
8334     ELSIF (TG_OP = 'INSERT') THEN
8335       NEW.pkghead_created := CURRENT_TIMESTAMP;
8336       NEW.pkghead_updated := NEW.pkghead_created;
8337       IF (NEW.pkghead_indev AND NOT userCanCreateUsers(getEffectiveXtUser())) THEN
8338         NEW.pkghead_indev = FALSE;
8339       END IF;
8340
8341     ELSIF (TG_OP = 'DELETE') THEN
8342       DELETE FROM pkgdep WHERE pkgdep_pkghead_id=OLD.pkghead_id;
8343
8344       EXECUTE 'DROP SCHEMA ' || OLD.pkghead_name || ' CASCADE';
8345
8346       RETURN OLD;
8347     END IF;
8348
8349     RETURN NEW;
8350   END;
8351 $$;
8352
8353
8354 ALTER FUNCTION public._pkgheadbeforetrigger() OWNER TO admin;
8355
8356 --
8357 -- TOC entry 1016 (class 1255 OID 146565526)
8358 -- Dependencies: 4536 8
8359 -- Name: _pkgimageaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8360 --
8361
8362 CREATE FUNCTION _pkgimageaftertrigger() RETURNS trigger
8363     LANGUAGE plpgsql
8364     AS $$
8365 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8366 -- See www.xtuple.com/CPAL for the full text of the software license.
8367 BEGIN
8368   IF (TG_OP = 'DELETE') THEN
8369     RETURN OLD;
8370   END IF;
8371
8372   RETURN NEW;
8373 END;
8374 $$;
8375
8376
8377 ALTER FUNCTION public._pkgimageaftertrigger() OWNER TO admin;
8378
8379 --
8380 -- TOC entry 1017 (class 1255 OID 146565527)
8381 -- Dependencies: 4536 8
8382 -- Name: _pkgimagealtertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8383 --
8384
8385 CREATE FUNCTION _pkgimagealtertrigger() RETURNS trigger
8386     LANGUAGE plpgsql
8387     AS $$
8388 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8389 -- See www.xtuple.com/CPAL for the full text of the software license.
8390 BEGIN
8391   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
8392     IF (TG_OP = 'DELETE') THEN
8393       RETURN OLD;
8394     ELSE
8395       RETURN NEW;
8396     END IF;
8397   END IF;
8398
8399   IF (TG_OP = 'INSERT') THEN
8400     RAISE EXCEPTION 'You may not create images in packages except using the xTuple Updater utility';
8401
8402   ELSIF (TG_OP = 'UPDATE') THEN
8403     RAISE EXCEPTION 'You may not alter images in packages except using the xTuple Updater utility';
8404
8405   ELSIF (TG_OP = 'DELETE') THEN
8406     RAISE EXCEPTION 'You may not delete images from packages. Try deleting or disabling the package.';
8407
8408   END IF;
8409
8410   RETURN NEW;
8411 END;
8412 $$;
8413
8414
8415 ALTER FUNCTION public._pkgimagealtertrigger() OWNER TO admin;
8416
8417 --
8418 -- TOC entry 1018 (class 1255 OID 146565528)
8419 -- Dependencies: 4536 8
8420 -- Name: _pkgimagebeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8421 --
8422
8423 CREATE FUNCTION _pkgimagebeforetrigger() RETURNS trigger
8424     LANGUAGE plpgsql
8425     AS $$
8426 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8427 -- See www.xtuple.com/CPAL for the full text of the software license.
8428 DECLARE
8429   _imageid     INTEGER;
8430   _debug       BOOL := false;
8431
8432 BEGIN
8433   IF (TG_OP = 'UPDATE') THEN
8434     IF (_debug) THEN
8435       RAISE NOTICE 'OLD.image_name %, NEW.image_name %',
8436                    OLD.image_name, NEW.image_name;
8437     END IF;
8438
8439     IF (NEW.image_name != OLD.image_name) THEN
8440       SELECT image_id INTO _imageid FROM image WHERE image_name=NEW.image_name;
8441       IF (FOUND) THEN
8442         RAISE EXCEPTION 'Cannot change image named % because another image with that name already exists.', NEW.image_name;
8443       END IF;
8444     END IF;
8445
8446   ELSIF (TG_OP = 'INSERT') THEN
8447     IF (_debug) THEN
8448       RAISE NOTICE 'inserting NEW.image_name %', NEW.image_name;
8449     END IF;
8450     SELECT image_id INTO _imageid FROM image WHERE image_name=NEW.image_name;
8451     IF (FOUND) THEN
8452       RAISE EXCEPTION 'Cannot create new image % because another image with that name already exists.', NEW.image_name;
8453     END IF;
8454
8455   ELSIF (TG_OP = 'DELETE') THEN
8456     RETURN OLD;
8457
8458   END IF;
8459
8460   RETURN NEW;
8461 END;
8462 $$;
8463
8464
8465 ALTER FUNCTION public._pkgimagebeforetrigger() OWNER TO admin;
8466
8467 --
8468 -- TOC entry 1019 (class 1255 OID 146565529)
8469 -- Dependencies: 4536 8
8470 -- Name: _pkgitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8471 --
8472
8473 CREATE FUNCTION _pkgitembeforetrigger() RETURNS trigger
8474     LANGUAGE plpgsql
8475     AS $$
8476 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
8477 -- See www.xtuple.com/CPAL for the full text of the software license.
8478   DECLARE
8479     _functionargs TEXT;
8480     _group        TEXT;
8481     _object       TEXT;
8482     _schema       TEXT;
8483     _debug        BOOL := false;
8484   BEGIN
8485     IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
8486       _object = NEW.pkgitem_name;
8487
8488       SELECT LOWER(pkghead_name) INTO _schema
8489       FROM pkghead
8490       WHERE (pkghead_id=NEW.pkgitem_pkghead_id);
8491       IF (NOT FOUND) THEN
8492         _schema := 'public';
8493       END IF;
8494
8495       IF (NEW.pkgitem_type = 'F') THEN
8496         _object := SPLIT_PART(_object, '(', 1);
8497       ELSIF (NEW.pkgitem_type = 'M') THEN
8498         _group  := SPLIT_PART(_object, '-', 1);
8499         _object := SPLIT_PART(_object, '-', 2);
8500       END IF;
8501       IF _debug THEN
8502         RAISE NOTICE '_schema % and _object %', _schema, _object;
8503       END IF;
8504
8505       IF (NEW.pkgitem_type = 'C') THEN
8506         IF (NOT EXISTS(SELECT script_id
8507                        FROM script
8508                        WHERE ((script_id=NEW.pkgitem_item_id)
8509                           AND (script_name=NEW.pkgitem_name)))) THEN
8510           RAISE EXCEPTION 'Cannot create Script % as a Package Item without a corresponding script record.',
8511             NEW.pkgitem_name;
8512         END IF;
8513
8514       ELSIF (NEW.pkgitem_type = 'D') THEN
8515         IF (NOT EXISTS(SELECT cmd_id
8516                        FROM cmd
8517                        WHERE ((cmd_id=NEW.pkgitem_item_id)
8518                           AND (cmd_name=NEW.pkgitem_name)))) THEN
8519           RAISE EXCEPTION 'Cannot create Custom Command % as a Package Item without a corresponding cmd record.',
8520             NEW.pkgitem_name;
8521         END IF;
8522
8523       ELSIF (NEW.pkgitem_type = 'F') THEN
8524         IF (NOT EXISTS(SELECT pg_proc.oid
8525                        FROM pg_proc, pg_namespace
8526                        WHERE ((pg_proc.oid=NEW.pkgitem_item_id)
8527                           AND (proname = (_object))
8528                           AND (pronamespace=pg_namespace.oid)
8529                           AND (nspname=_schema)) )) THEN
8530           RAISE EXCEPTION 'Cannot create Function % (oid %) as a Package Item without a corresponding function in the database.',
8531                           NEW.pkgitem_name, NEW.pkgitem_item_id;
8532         END IF;
8533
8534       ELSIF (NEW.pkgitem_type = 'G') THEN
8535         IF (NOT EXISTS(SELECT pg_class.oid
8536                      FROM pg_trigger, pg_class, pg_namespace
8537                      WHERE ((tgname=_object)
8538                         AND (tgrelid=pg_class.oid)
8539                         AND (relnamespace=pg_namespace.oid)
8540                         AND (nspname=_schema)))) THEN
8541           RAISE EXCEPTION 'Cannot create Trigger % as a Package Item without a corresponding trigger in the database.',
8542             NEW.pkgitem_name;
8543         END IF;
8544
8545       ELSIF (NEW.pkgitem_type = 'I') THEN
8546         IF (NOT EXISTS(SELECT image_id
8547                        FROM image
8548                        WHERE ((image_id=NEW.pkgitem_item_id)
8549                           AND (image_name=NEW.pkgitem_name)))) THEN
8550           RAISE EXCEPTION 'Cannot create Image % as a Package Item without a corresponding image record.',
8551             NEW.pkgitem_name;
8552         END IF;
8553
8554       ELSIF (NEW.pkgitem_type = 'M') THEN
8555         IF (NOT EXISTS(SELECT metasql_id
8556                        FROM metasql
8557                        WHERE ((metasql_id=NEW.pkgitem_item_id)
8558                           AND (metasql_group=_group)
8559                           AND (metasql_name=_object)))) THEN
8560           RAISE EXCEPTION 'Cannot create MetaSQL statement % as a Package Item without a corresponding metasql record.',
8561             NEW.pkgitem_name;
8562         END IF;
8563
8564       ELSIF (NEW.pkgitem_type = 'P') THEN
8565         IF (NOT EXISTS(SELECT priv_id
8566                        FROM priv
8567                        WHERE ((priv_id=NEW.pkgitem_item_id)
8568                           AND (priv_name=NEW.pkgitem_name)))) THEN
8569           RAISE EXCEPTION 'Cannot create Privilege % as a Package Item without a corresponding priv record.',
8570             NEW.pkgitem_name;
8571         END IF;
8572
8573       ELSIF (NEW.pkgitem_type = 'R') THEN
8574         IF (NOT EXISTS(SELECT report_id
8575                        FROM report
8576                        WHERE ((report_id=NEW.pkgitem_item_id)
8577                           AND (report_name=NEW.pkgitem_name)))) THEN
8578           RAISE EXCEPTION 'Cannot create Report % as a Package Item without a corresponding report record.',
8579             NEW.pkgitem_name;
8580         END IF;
8581
8582       ELSIF (NEW.pkgitem_type = 'S') THEN
8583         IF (NOT EXISTS(SELECT oid
8584                        FROM pg_namespace
8585                        WHERE (LOWER(nspname)=LOWER(NEW.pkgitem_name)))) THEN
8586           RAISE EXCEPTION 'Cannot create Schema % as a Package Item without a corresponding schema in the database.',
8587             NEW.pkgitem_name;
8588         END IF;
8589
8590       ELSIF (NEW.pkgitem_type = 'T') THEN
8591         IF (NOT EXISTS(SELECT pg_class.oid
8592                      FROM pg_class, pg_namespace
8593                      WHERE ((relname=_object)
8594                         AND (relnamespace=pg_namespace.oid)
8595                         AND (relkind='r')
8596                         AND (nspname=_schema)))) THEN
8597           RAISE EXCEPTION 'Cannot create Table % as a Package Item without a corresponding table in the database.',
8598             NEW.pkgitem_name;
8599         END IF;
8600
8601       ELSIF (NEW.pkgitem_type = 'U') THEN
8602         IF (NOT EXISTS(SELECT uiform_id
8603                        FROM uiform
8604                        WHERE ((uiform_id=NEW.pkgitem_item_id)
8605                           AND (uiform_name=NEW.pkgitem_name)))) THEN
8606           RAISE EXCEPTION 'Cannot create User Interface Form % as a Package Item without a corresponding uiform record.',
8607             NEW.pkgitem_name;
8608         END IF;
8609
8610       ELSIF (NEW.pkgitem_type = 'V') THEN
8611         IF (NOT EXISTS(SELECT pg_class.oid
8612                      FROM pg_class, pg_namespace
8613                      WHERE ((relname=_object)
8614                         AND (relnamespace=pg_namespace.oid)
8615                         AND (relkind='v')
8616                         AND (nspname=_schema)))) THEN
8617           RAISE EXCEPTION 'Cannot create View % as a Package Item without a corresponding view in the database.',
8618             NEW.pkgitem_name;
8619         END IF;
8620
8621       ELSE
8622         RAISE EXCEPTION '"%" is not a valid type of package item.',
8623           NEW.pkgitem_type;
8624       END IF;
8625
8626     ELSIF (TG_OP = 'DELETE') THEN
8627       IF _debug THEN RAISE NOTICE 'Deleting % % %', OLD.pkgitem_item_id, OLD.pkgitem_name, OLD.pkgitem_type; END IF;
8628
8629       _object = OLD.pkgitem_name;
8630
8631       SELECT pkghead_name INTO _schema
8632       FROM pkghead
8633       WHERE (pkghead_id=OLD.pkgitem_pkghead_id);
8634       IF (NOT FOUND) THEN
8635         _schema := 'public';
8636       END IF;
8637
8638       IF (OLD.pkgitem_type = 'F') THEN
8639         _object := SPLIT_PART(_object, '(', 1);
8640       ELSIF (OLD.pkgitem_type = 'M') THEN
8641         _group  := SPLIT_PART(_object, '-', 1);
8642         _object := SPLIT_PART(_object, '-', 2);
8643       END IF;
8644       IF _debug THEN
8645         RAISE NOTICE '_schema % and _object %', _schema, _object;
8646       END IF;
8647
8648       IF (OLD.pkgitem_type = 'C') THEN
8649         DELETE FROM script WHERE ((script_id=OLD.pkgitem_item_id)
8650                               AND (script_name=OLD.pkgitem_name));
8651
8652       ELSIF (OLD.pkgitem_type = 'D') THEN
8653         DELETE FROM cmd
8654           WHERE ((cmd_id=OLD.pkgitem_item_id)
8655             AND  (cmd_name=OLD.pkgitem_name));
8656
8657       ELSIF (OLD.pkgitem_type = 'F') THEN
8658         -- SELECT dropIfExists('FUNCTION', CAST (oid::regprocedure AS TEXT), _schema)
8659         PERFORM dropIfExists('FUNCTION',
8660                             proname || '(' ||
8661                             oidvectortypes(proargtypes) || ')',
8662                             _schema)
8663         FROM pg_proc
8664         WHERE (oid=OLD.pkgitem_item_id);
8665
8666       ELSIF (OLD.pkgitem_type = 'G') THEN
8667         PERFORM dropIfExists('TRIGGER', _object, _schema);
8668
8669       ELSIF (OLD.pkgitem_type = 'I') THEN
8670         DELETE FROM image WHERE ((image_id=OLD.pkgitem_item_id)
8671                              AND (image_name=OLD.pkgitem_name));
8672
8673       ELSIF (OLD.pkgitem_type = 'M') THEN
8674         DELETE FROM metasql WHERE ((metasql_id=OLD.pkgitem_item_id)
8675                                AND (metasql_group=_group)
8676                                AND (metasql_name=_object));
8677
8678       ELSIF (OLD.pkgitem_type = 'P') THEN
8679         DELETE FROM priv
8680         WHERE ((priv_id=OLD.pkgitem_item_id) 
8681            AND (priv_name=OLD.pkgitem_name));
8682
8683       ELSIF (OLD.pkgitem_type = 'R') THEN
8684         DELETE FROM report
8685         WHERE ((report_id=OLD.pkgitem_item_id)
8686            AND (report_name=OLD.pkgitem_name));
8687
8688       ELSIF (OLD.pkgitem_type = 'S') THEN
8689         PERFORM dropIfExists('SCHEMA', OLD.pkgitem_name, OLD.pkgitem_name);
8690
8691       ELSIF (OLD.pkgitem_type = 'T') THEN
8692         PERFORM dropIfExists('TABLE', _object, _schema, true);
8693
8694       ELSIF (OLD.pkgitem_type = 'U') THEN
8695         DELETE FROM uiform
8696         WHERE ((uiform_id=OLD.pkgitem_item_id)
8697            AND (uiform_name=OLD.pkgitem_name));
8698
8699       ELSIF (OLD.pkgitem_type = 'V') THEN
8700         PERFORM dropIfExists('VIEW', _object, _schema, true);
8701
8702       ELSE
8703         RAISE EXCEPTION '"%" is not a valid type of package item.',
8704           OLD.pkgitem_type;
8705       END IF;
8706       RETURN OLD;
8707     END IF;
8708
8709     RETURN NEW;
8710   END;
8711 $$;
8712
8713
8714 ALTER FUNCTION public._pkgitembeforetrigger() OWNER TO admin;
8715
8716 --
8717 -- TOC entry 1020 (class 1255 OID 146565531)
8718 -- Dependencies: 4536 8
8719 -- Name: _pkgmetasqlaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8720 --
8721
8722 CREATE FUNCTION _pkgmetasqlaftertrigger() RETURNS trigger
8723     LANGUAGE plpgsql
8724     AS $$
8725 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8726 -- See www.xtuple.com/CPAL for the full text of the software license.
8727 BEGIN
8728   IF (TG_OP = 'DELETE') THEN
8729     RETURN OLD;
8730   END IF;
8731
8732   RETURN NEW;
8733 END;
8734 $$;
8735
8736
8737 ALTER FUNCTION public._pkgmetasqlaftertrigger() OWNER TO admin;
8738
8739 --
8740 -- TOC entry 1022 (class 1255 OID 146565532)
8741 -- Dependencies: 4536 8
8742 -- Name: _pkgmetasqlaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8743 --
8744
8745 CREATE FUNCTION _pkgmetasqlaltertrigger() RETURNS trigger
8746     LANGUAGE plpgsql
8747     AS $$
8748 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8749 -- See www.xtuple.com/CPAL for the full text of the software license.
8750 DECLARE
8751   _isdba        BOOLEAN := false;
8752
8753 BEGIN
8754   SELECT rolsuper INTO _isdba FROM pg_roles WHERE (rolname=getEffectiveXtUser());
8755
8756   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
8757     IF (TG_OP = 'DELETE') THEN
8758       RETURN OLD;
8759     ELSE
8760       RETURN NEW;
8761     END IF;
8762   END IF;
8763
8764   -- cannot combine IF's because plpgsql does not always evaluate left-to-right
8765   IF (TG_OP = 'INSERT') THEN
8766     IF (NEW.metasql_grade <= 0 AND NOT _isdba) THEN
8767       RAISE EXCEPTION 'You may not create grade 0 MetaSQL statements in packages except using the xTuple Updater utility';
8768     END IF;
8769
8770   ELSIF (TG_OP = 'UPDATE') THEN
8771     IF (NEW.metasql_grade <= 0 AND NOT _isdba) THEN
8772       RAISE EXCEPTION 'You may not alter grade 0 MetaSQL statements in packages except using the xTuple Updater utility';
8773     END IF;
8774
8775   ELSIF (TG_OP = 'DELETE') THEN
8776     IF (OLD.metasql_grade <= 0 AND NOT _isdba) THEN
8777       RAISE EXCEPTION 'You may not delete grade 0 MetaSQL statements from packages. Try deleting or disabling the package.';
8778     ELSE
8779       RETURN OLD;
8780     END IF;
8781
8782   END IF;
8783
8784   RETURN NEW;
8785 END;
8786 $$;
8787
8788
8789 ALTER FUNCTION public._pkgmetasqlaltertrigger() OWNER TO admin;
8790
8791 --
8792 -- TOC entry 1023 (class 1255 OID 146565533)
8793 -- Dependencies: 4536 8
8794 -- Name: _pkgmetasqlbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8795 --
8796
8797 CREATE FUNCTION _pkgmetasqlbeforetrigger() RETURNS trigger
8798     LANGUAGE plpgsql
8799     AS $$
8800 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8801 -- See www.xtuple.com/CPAL for the full text of the software license.
8802 DECLARE
8803   _metasqlid    INTEGER;
8804   _isdba        BOOLEAN := false;
8805
8806 BEGIN
8807   SELECT rolsuper INTO _isdba FROM pg_roles WHERE (rolname=getEffectiveXtUser());
8808
8809   IF (NOT (_isdba OR checkPrivilege('MaintainMetaSQL'))) THEN
8810     RAISE EXCEPTION '% does not have privileges to maintain MetaSQL statements in %.% (DBA=%)',
8811                 getEffectiveXtUser(), TG_TABLE_SCHEMA, TG_TABLE_NAME, _isdba;
8812   END IF;
8813
8814   IF (TG_OP = 'UPDATE') THEN
8815     RAISE DEBUG 'update OLD %-%-%, NEW %-%-%',
8816                  OLD.metasql_group, OLD.metasql_name, OLD.metasql_grade,
8817                  NEW.metasql_group, NEW.metasql_name, NEW.metasql_grade;
8818
8819     IF (NEW.metasql_name != OLD.metasql_name OR NEW.metasql_group != OLD.metasql_group OR NEW.metasql_grade != OLD.metasql_grade) THEN
8820       SELECT metasql_id INTO _metasqlid
8821       FROM metasql
8822       WHERE metasql_name=NEW.metasql_name AND metasql_group=NEW.metasql_group AND metasql_grade=NEW.metasql_grade;
8823       IF (FOUND) THEN
8824         RAISE EXCEPTION 'Cannot change the MetaSQL statement named %-%-% because another MetaSQL statement with that group, name and grade already exists.', NEW.metasql_group, NEW.metasql_name, NEW.metasql_grade;
8825       END IF;
8826     END IF;
8827
8828   ELSIF (TG_OP = 'INSERT') THEN
8829     RAISE DEBUG 'insert NEW %-% %',
8830                  NEW.metasql_group, NEW.metasql_name, NEW.metasql_grade;
8831     SELECT metasql_id INTO _metasqlid
8832     FROM metasql
8833     WHERE metasql_name=NEW.metasql_name AND metasql_group=NEW.metasql_group AND metasql_grade=NEW.metasql_grade;
8834     IF (FOUND) THEN
8835       RAISE EXCEPTION 'The new MetaSQL statement %-% % conflicts with an existing statement.',
8836                       NEW.metasql_group, NEW.metasql_name, NEW.metasql_grade;
8837     END IF;
8838
8839   ELSIF (TG_OP = 'DELETE') THEN
8840     RETURN OLD;
8841   END IF;
8842
8843   RETURN NEW;
8844 END;
8845 $$;
8846
8847
8848 ALTER FUNCTION public._pkgmetasqlbeforetrigger() OWNER TO admin;
8849
8850 --
8851 -- TOC entry 1024 (class 1255 OID 146565534)
8852 -- Dependencies: 4536 8
8853 -- Name: _pkgprivaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8854 --
8855
8856 CREATE FUNCTION _pkgprivaftertrigger() RETURNS trigger
8857     LANGUAGE plpgsql
8858     AS $$
8859 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8860 -- See www.xtuple.com/CPAL for the full text of the software license.
8861 BEGIN
8862   IF (TG_OP = 'DELETE') THEN
8863     RETURN OLD;
8864   END IF;
8865
8866   RETURN NEW;
8867 END;
8868 $$;
8869
8870
8871 ALTER FUNCTION public._pkgprivaftertrigger() OWNER TO admin;
8872
8873 --
8874 -- TOC entry 1025 (class 1255 OID 146565535)
8875 -- Dependencies: 4536 8
8876 -- Name: _pkgprivaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8877 --
8878
8879 CREATE FUNCTION _pkgprivaltertrigger() RETURNS trigger
8880     LANGUAGE plpgsql
8881     AS $$
8882 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8883 -- See www.xtuple.com/CPAL for the full text of the software license.
8884 BEGIN
8885   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
8886     IF (TG_OP = 'DELETE') THEN
8887       RETURN OLD;
8888     ELSE
8889       RETURN NEW;
8890     END IF;
8891   END IF;
8892
8893   IF (TG_OP = 'INSERT') THEN
8894     RAISE EXCEPTION 'You may not create privileges in packages except using the xTuple Updater utility';
8895
8896   ELSIF (TG_OP = 'UPDATE') THEN
8897     RAISE EXCEPTION 'You may not alter privileges in packages except using the xTuple Updater utility';
8898
8899   ELSIF (TG_OP = 'DELETE') THEN
8900     RAISE EXCEPTION 'You may not delete privileges from packages. Try deleting or disabling the package.';
8901
8902   END IF;
8903
8904   RETURN NEW;
8905 END;
8906
8907 $$;
8908
8909
8910 ALTER FUNCTION public._pkgprivaltertrigger() OWNER TO admin;
8911
8912 --
8913 -- TOC entry 1026 (class 1255 OID 146565536)
8914 -- Dependencies: 4536 8
8915 -- Name: _pkgprivbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
8916 --
8917
8918 CREATE FUNCTION _pkgprivbeforetrigger() RETURNS trigger
8919     LANGUAGE plpgsql
8920     AS $$
8921 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8922 -- See www.xtuple.com/CPAL for the full text of the software license.
8923 DECLARE
8924   _privid       INTEGER;
8925   _debug        BOOL := false;
8926
8927 BEGIN
8928   IF (TG_OP = 'UPDATE') THEN
8929     IF (_debug) THEN
8930       RAISE NOTICE 'OLD.priv_name %, NEW.priv_name %',
8931                    OLD.priv_name, NEW.priv_name;
8932     END IF;
8933
8934     IF (NEW.priv_name != OLD.priv_name) THEN
8935       SELECT priv_id INTO _privid FROM priv WHERE priv_name=NEW.priv_name;
8936       IF (FOUND) THEN
8937         RAISE EXCEPTION 'Cannot change privilege name % because another privilege with that name already exists.', NEW.priv_name;
8938       END IF;
8939     END IF;
8940
8941   ELSIF (TG_OP = 'INSERT') THEN
8942     IF (_debug) THEN
8943       RAISE NOTICE 'inserting NEW.priv_name %', NEW.priv_name;
8944     END IF;
8945     SELECT priv_id INTO _privid FROM priv WHERE priv_name=NEW.priv_name;
8946     IF (FOUND) THEN
8947       RAISE EXCEPTION 'Cannot create new privilege % because another privilege with that name already exists.', NEW.priv_name;
8948     END IF;
8949
8950   ELSIF (TG_OP = 'DELETE') THEN
8951     IF (_debug) THEN RAISE NOTICE 'deleting pkgpriv_id %', OLD.priv_id; END IF;
8952     DELETE FROM usrpriv WHERE usrpriv_priv_id=OLD.priv_id;
8953     DELETE FROM grppriv WHERE grppriv_priv_id=OLD.priv_id;
8954
8955     RETURN OLD;
8956   END IF;
8957
8958   RETURN NEW;
8959 END;
8960 $$;
8961
8962
8963 ALTER FUNCTION public._pkgprivbeforetrigger() OWNER TO admin;
8964
8965 --
8966 -- TOC entry 1027 (class 1255 OID 146565537)
8967 -- Dependencies: 4536 8
8968 -- Name: _pkgreportaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8969 --
8970
8971 CREATE FUNCTION _pkgreportaftertrigger() RETURNS trigger
8972     LANGUAGE plpgsql
8973     AS $$
8974 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8975 -- See www.xtuple.com/CPAL for the full text of the software license.
8976 BEGIN
8977   IF (TG_OP = 'DELETE') THEN
8978     RETURN OLD;
8979   END IF;
8980
8981   RETURN NEW;
8982 END;
8983 $$;
8984
8985
8986 ALTER FUNCTION public._pkgreportaftertrigger() OWNER TO admin;
8987
8988 --
8989 -- TOC entry 1028 (class 1255 OID 146565538)
8990 -- Dependencies: 4536 8
8991 -- Name: _pkgreportaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
8992 --
8993
8994 CREATE FUNCTION _pkgreportaltertrigger() RETURNS trigger
8995     LANGUAGE plpgsql
8996     AS $$
8997 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
8998 -- See www.xtuple.com/CPAL for the full text of the software license.
8999 BEGIN
9000   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
9001     IF (TG_OP = 'DELETE') THEN
9002       RETURN OLD;
9003     ELSE
9004       RETURN NEW;
9005     END IF;
9006   END IF;
9007
9008   IF (TG_OP = 'INSERT') THEN
9009     RAISE EXCEPTION 'You may not create report definitions in packages except using the xTuple Updater utility';
9010
9011   ELSIF (TG_OP = 'UPDATE') THEN
9012     RAISE EXCEPTION 'You may not alter report definitions in packages except using the xTuple Updater utility';
9013
9014   ELSIF (TG_OP = 'DELETE') THEN
9015     RAISE EXCEPTION 'You may not delete report definitions from packages. Try deleting or disabling the package.';
9016
9017   END IF;
9018
9019   RETURN NEW;
9020 END;
9021 $$;
9022
9023
9024 ALTER FUNCTION public._pkgreportaltertrigger() OWNER TO admin;
9025
9026 --
9027 -- TOC entry 1029 (class 1255 OID 146565539)
9028 -- Dependencies: 4536 8
9029 -- Name: _pkgreportbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9030 --
9031
9032 CREATE FUNCTION _pkgreportbeforetrigger() RETURNS trigger
9033     LANGUAGE plpgsql
9034     AS $$
9035 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9036 -- See www.xtuple.com/CPAL for the full text of the software license.
9037 DECLARE
9038   _reportid     INTEGER;
9039   _debug        BOOL := false;
9040
9041 BEGIN
9042   IF (TG_OP = 'UPDATE') THEN
9043     IF (_debug) THEN
9044       RAISE NOTICE 'update OLD % %, NEW % %',
9045                    OLD.report_name, OLD.report_grade, NEW.report_name, NEW.report_grade;
9046     END IF;
9047
9048     IF (NEW.report_name != OLD.report_name) THEN
9049       SELECT report_id INTO _reportid
9050       FROM report
9051       WHERE ((report_name=NEW.report_name)
9052         AND  (report_grade=NEW.report_grade));
9053       IF (FOUND) THEN
9054         RAISE EXCEPTION 'Cannot change report % % because another report with that name and grade already exists.', NEW.report_name, NEW.report_grade;
9055       END IF;
9056     END IF;
9057
9058   ELSIF (TG_OP = 'INSERT') THEN
9059     IF (_debug) THEN
9060       RAISE NOTICE 'insert NEW % %', NEW.report_name, NEW.report_grade;
9061     END IF;
9062     SELECT report_id INTO _reportid
9063     FROM report
9064     WHERE ((report_name=NEW.report_name)
9065       AND  (report_grade=NEW.report_grade));
9066     IF (FOUND) THEN
9067       RAISE EXCEPTION 'Cannot create new report % % because another report with that name and grade already exists.', NEW.report_name, NEW.report_grade;
9068     END IF;
9069
9070   ELSIF (TG_OP = 'DELETE') THEN
9071
9072     RETURN OLD;
9073   END IF;
9074
9075   RETURN NEW;
9076 END;
9077 $$;
9078
9079
9080 ALTER FUNCTION public._pkgreportbeforetrigger() OWNER TO admin;
9081
9082 --
9083 -- TOC entry 959 (class 1255 OID 146565540)
9084 -- Dependencies: 4536 8
9085 -- Name: _pkgscriptaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9086 --
9087
9088 CREATE FUNCTION _pkgscriptaftertrigger() RETURNS trigger
9089     LANGUAGE plpgsql
9090     AS $$
9091 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9092 -- See www.xtuple.com/CPAL for the full text of the software license.
9093 BEGIN
9094   IF (TG_OP = 'DELETE') THEN
9095     RETURN OLD;
9096   END IF;
9097
9098   RETURN NEW;
9099 END;
9100 $$;
9101
9102
9103 ALTER FUNCTION public._pkgscriptaftertrigger() OWNER TO admin;
9104
9105 --
9106 -- TOC entry 983 (class 1255 OID 146565541)
9107 -- Dependencies: 4536 8
9108 -- Name: _pkgscriptaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9109 --
9110
9111 CREATE FUNCTION _pkgscriptaltertrigger() RETURNS trigger
9112     LANGUAGE plpgsql
9113     AS $$
9114 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9115 -- See www.xtuple.com/CPAL for the full text of the software license.
9116 BEGIN
9117   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
9118     IF (TG_OP = 'DELETE') THEN
9119       RETURN OLD;
9120     ELSE
9121       RETURN NEW;
9122     END IF;
9123   END IF;
9124
9125   IF (TG_OP = 'INSERT') THEN
9126     RAISE EXCEPTION 'You may not create scripts in packages except using the xTuple Updater utility';
9127
9128   ELSIF (TG_OP = 'UPDATE') THEN
9129     RAISE EXCEPTION 'You may not alter scripts in packages except using the xTuple Updater utility';
9130
9131   ELSIF (TG_OP = 'DELETE') THEN
9132     RAISE EXCEPTION 'You may not delete scripts from packages. Try deleting or disabling the package.';
9133
9134   END IF;
9135
9136   RETURN NEW;
9137 END;
9138 $$;
9139
9140
9141 ALTER FUNCTION public._pkgscriptaltertrigger() OWNER TO admin;
9142
9143 --
9144 -- TOC entry 1003 (class 1255 OID 146565542)
9145 -- Dependencies: 4536 8
9146 -- Name: _pkgscriptbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9147 --
9148
9149 CREATE FUNCTION _pkgscriptbeforetrigger() RETURNS trigger
9150     LANGUAGE plpgsql
9151     AS $$
9152 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9153 -- See www.xtuple.com/CPAL for the full text of the software license.
9154 DECLARE
9155   _scriptid     INTEGER;
9156   _debug        BOOL := false;
9157
9158 BEGIN
9159   IF (TG_OP = 'UPDATE') THEN
9160     RETURN NEW;
9161
9162   ELSIF (TG_OP = 'INSERT') THEN
9163     RETURN NEW;
9164
9165   ELSIF (TG_OP = 'DELETE') THEN
9166     RETURN OLD;
9167   END IF;
9168
9169   RETURN NEW;
9170 END;
9171 $$;
9172
9173
9174 ALTER FUNCTION public._pkgscriptbeforetrigger() OWNER TO admin;
9175
9176 --
9177 -- TOC entry 1011 (class 1255 OID 146565543)
9178 -- Dependencies: 4536 8
9179 -- Name: _pkguiformaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9180 --
9181
9182 CREATE FUNCTION _pkguiformaftertrigger() RETURNS trigger
9183     LANGUAGE plpgsql
9184     AS $$
9185 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9186 -- See www.xtuple.com/CPAL for the full text of the software license.
9187 BEGIN
9188   IF (TG_OP = 'DELETE') THEN
9189     RETURN OLD;
9190   END IF;
9191
9192   RETURN NEW;
9193 END;
9194 $$;
9195
9196
9197 ALTER FUNCTION public._pkguiformaftertrigger() OWNER TO admin;
9198
9199 --
9200 -- TOC entry 1021 (class 1255 OID 146565544)
9201 -- Dependencies: 4536 8
9202 -- Name: _pkguiformaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9203 --
9204
9205 CREATE FUNCTION _pkguiformaltertrigger() RETURNS trigger
9206     LANGUAGE plpgsql
9207     AS $$
9208 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9209 -- See www.xtuple.com/CPAL for the full text of the software license.
9210 BEGIN
9211   IF (pkgMayBeModified(TG_TABLE_SCHEMA)) THEN
9212     IF (TG_OP = 'DELETE') THEN
9213       RETURN OLD;
9214     ELSE
9215       RETURN NEW;
9216     END IF;
9217   END IF;
9218
9219   IF (TG_OP = 'INSERT') THEN
9220     RAISE EXCEPTION 'You may not create forms in packages except using the xTuple Updater utility';
9221
9222   ELSIF (TG_OP = 'UPDATE') THEN
9223     RAISE EXCEPTION 'You may not alter forms in packages except using the xTuple Updater utility';
9224
9225   ELSIF (TG_OP = 'DELETE') THEN
9226     RAISE EXCEPTION 'You may not delete forms from packages. Try deleting or disabling the package.';
9227
9228   END IF;
9229
9230   RETURN NEW;
9231 END;
9232
9233 $$;
9234
9235
9236 ALTER FUNCTION public._pkguiformaltertrigger() OWNER TO admin;
9237
9238 --
9239 -- TOC entry 945 (class 1255 OID 146565545)
9240 -- Dependencies: 4536 8
9241 -- Name: _pkguiformbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9242 --
9243
9244 CREATE FUNCTION _pkguiformbeforetrigger() RETURNS trigger
9245     LANGUAGE plpgsql
9246     AS $$
9247 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9248 -- See www.xtuple.com/CPAL for the full text of the software license.
9249 DECLARE
9250   _uiformid     INTEGER;
9251   _debug        BOOL := false;
9252
9253 BEGIN
9254   IF (TG_OP = 'UPDATE') THEN
9255     RETURN NEW;
9256
9257   ELSIF (TG_OP = 'INSERT') THEN
9258     RETURN NEW;
9259
9260   ELSIF (TG_OP = 'DELETE') THEN
9261     RETURN OLD;
9262   END IF;
9263
9264   RETURN NEW;
9265 END;
9266 $$;
9267
9268
9269 ALTER FUNCTION public._pkguiformbeforetrigger() OWNER TO admin;
9270
9271 --
9272 -- TOC entry 1030 (class 1255 OID 146565546)
9273 -- Dependencies: 4536 8
9274 -- Name: _poheadtrigger(); Type: FUNCTION; Schema: public; Owner: admin
9275 --
9276
9277 CREATE FUNCTION _poheadtrigger() RETURNS trigger
9278     LANGUAGE plpgsql
9279     AS $$
9280 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9281 -- See www.xtuple.com/CPAL for the full text of the software license.
9282 DECLARE
9283   _cmnttypeid   INTEGER;
9284   _check        BOOLEAN;
9285   _maint        BOOLEAN := TRUE;
9286
9287 BEGIN
9288
9289 -- Check if we are doing maintenance
9290   IF (TG_OP = 'UPDATE') THEN
9291     IF ( (OLD.pohead_status           != NEW.pohead_status) OR
9292          (OLD.pohead_printed          != NEW.pohead_printed) ) THEN
9293       _maint := FALSE;
9294     END IF;
9295   END IF;
9296
9297   -- Check
9298   IF ( (NOT _maint) AND (NOT checkPrivilege('MaintainPurchaseOrders'))
9299                     AND (NOT checkPrivilege('PostPurchaseOrders'))
9300                     AND (NOT checkPrivilege('PrintPurchaseOrders'))
9301                     AND (NOT checkPrivilege('PostVouchers')) ) THEN
9302     RAISE EXCEPTION 'You do not have privileges to alter a Purchase Order.';
9303   END IF;
9304
9305   IF ( _maint AND (NOT checkPrivilege('MaintainPurchaseOrders')) ) THEN
9306     RAISE EXCEPTION 'You do not have privileges to alter a Purchase Order.';
9307   END IF;
9308
9309   IF (TG_OP = 'INSERT') THEN
9310     --- clear the number from the issue cache
9311     PERFORM clearNumberIssue('PoNumber', NEW.pohead_number);
9312   END IF;
9313
9314   IF ( (TG_OP = 'INSERT') OR (TG_op = 'UPDATE') ) THEN
9315     IF (NOT ISNUMERIC(NEW.pohead_number) AND NEW.pohead_saved) THEN
9316       RAISE EXCEPTION 'Purchase Order Number must be numeric.';
9317     END IF;
9318   END IF;
9319
9320   IF ( SELECT (metric_value='t')
9321        FROM metric
9322        WHERE (metric_name='POChangeLog') ) THEN
9323
9324 --  Cache the cmnttype_id for ChangeLog
9325     SELECT cmnttype_id INTO _cmnttypeid
9326     FROM cmnttype
9327     WHERE (cmnttype_name='ChangeLog');
9328     IF (FOUND) THEN
9329       IF (TG_OP = 'INSERT') THEN
9330         PERFORM postComment(_cmnttypeid, 'P', NEW.pohead_id, 'Created');
9331
9332       ELSIF (TG_OP = 'UPDATE') THEN
9333         IF (OLD.pohead_terms_id <> NEW.pohead_terms_id) THEN
9334           PERFORM postComment( _cmnttypeid, 'P', NEW.pohead_id,
9335                                ('Terms Changed from "' || oldterms.terms_code || '" to "' || newterms.terms_code || '"') )
9336           FROM terms AS oldterms, terms AS newterms
9337           WHERE ( (oldterms.terms_id=OLD.pohead_terms_id)
9338            AND (newterms.terms_id=NEW.pohead_terms_id) );
9339         END IF;
9340
9341       ELSIF (TG_OP = 'DELETE') THEN
9342         DELETE FROM docass WHERE docass_source_id = OLD.pohead_id AND docass_source_type = 'P';
9343         DELETE FROM docass WHERE docass_target_id = OLD.pohead_id AND docass_target_type = 'P';
9344         
9345         DELETE FROM comment
9346         WHERE ( (comment_source='P')
9347          AND (comment_source_id=OLD.pohead_id) );
9348       END IF;
9349     END IF;
9350   END IF;
9351
9352   IF (TG_OP = 'DELETE') THEN
9353     RETURN OLD;
9354   ELSE
9355     RETURN NEW;
9356   END IF;
9357
9358 END;
9359 $$;
9360
9361
9362 ALTER FUNCTION public._poheadtrigger() OWNER TO admin;
9363
9364 --
9365 -- TOC entry 1031 (class 1255 OID 146565547)
9366 -- Dependencies: 4536 8
9367 -- Name: _poheadtriggerafter(); Type: FUNCTION; Schema: public; Owner: admin
9368 --
9369
9370 CREATE FUNCTION _poheadtriggerafter() RETURNS trigger
9371     LANGUAGE plpgsql
9372     AS $$
9373 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9374 -- See www.xtuple.com/CPAL for the full text of the software license.
9375 BEGIN
9376   IF (COALESCE(NEW.pohead_taxzone_id,-1) <> COALESCE(OLD.pohead_taxzone_id,-1)) THEN
9377     UPDATE poitem SET poitem_taxtype_id=getItemTaxType(itemsite_item_id,NEW.pohead_taxzone_id)
9378     FROM itemsite 
9379     WHERE ((itemsite_id=poitem_itemsite_id)
9380      AND (poitem_pohead_id=NEW.pohead_id));
9381   END IF;
9382
9383   -- Do not update closed poitems
9384   IF (TG_OP = 'UPDATE') THEN
9385     IF (OLD.pohead_status != NEW.pohead_status) THEN
9386       UPDATE poitem
9387       SET poitem_status=NEW.pohead_status
9388       WHERE ( (poitem_pohead_id=NEW.pohead_id)
9389         AND   (poitem_status <> 'C') );
9390     END IF;
9391   END IF;
9392
9393   RETURN NEW;
9394 END;
9395 $$;
9396
9397
9398 ALTER FUNCTION public._poheadtriggerafter() OWNER TO admin;
9399
9400 --
9401 -- TOC entry 1032 (class 1255 OID 146565548)
9402 -- Dependencies: 4536 8
9403 -- Name: _poitemafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9404 --
9405
9406 CREATE FUNCTION _poitemafterdeletetrigger() RETURNS trigger
9407     LANGUAGE plpgsql
9408     AS $$
9409 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9410 -- See www.xtuple.com/CPAL for the full text of the software license.
9411 DECLARE
9412   _changelog BOOLEAN := FALSE;
9413 BEGIN
9414
9415   IF (OLD.poitem_status = 'O') THEN
9416     IF ( (SELECT (count(*) < 1)
9417             FROM poitem
9418            WHERE ((poitem_pohead_id=OLD.poitem_pohead_id)
9419              AND  (poitem_id != OLD.poitem_id)
9420              AND  (poitem_status <> 'C')) ) ) THEN
9421       UPDATE pohead SET pohead_status = 'C'
9422        WHERE ((pohead_id=OLD.poitem_pohead_id)
9423          AND  (pohead_status='O'));
9424     END IF;
9425   END IF;
9426
9427   IF ( SELECT fetchMetricBool('POChangeLog') ) THEN
9428     _changelog := TRUE;
9429   END IF;
9430
9431   IF ( _changelog ) THEN
9432     PERFORM postComment('ChangeLog', 'P', OLD.poitem_pohead_id, ('Deleted Line #' || OLD.poitem_linenumber::TEXT));
9433   END IF;
9434
9435   RETURN OLD;
9436 END;
9437 $$;
9438
9439
9440 ALTER FUNCTION public._poitemafterdeletetrigger() OWNER TO admin;
9441
9442 --
9443 -- TOC entry 1033 (class 1255 OID 146565549)
9444 -- Dependencies: 4536 8
9445 -- Name: _poitemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9446 --
9447
9448 CREATE FUNCTION _poitemaftertrigger() RETURNS trigger
9449     LANGUAGE plpgsql
9450     AS $$
9451 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9452 -- See www.xtuple.com/CPAL for the full text of the software license.
9453 DECLARE
9454   _changelog BOOLEAN := FALSE;
9455 BEGIN
9456
9457   IF (TG_OP = 'UPDATE') THEN
9458     IF (OLD.poitem_status <> NEW.poitem_status) THEN
9459       IF ( (SELECT (count(*) < 1)
9460               FROM poitem
9461              WHERE ((poitem_pohead_id=NEW.poitem_pohead_id)
9462                AND  (poitem_id != NEW.poitem_id)
9463                AND  (poitem_status<>'C')) ) AND (NEW.poitem_status='C') ) THEN
9464         UPDATE pohead SET pohead_status = 'C'
9465          WHERE ((pohead_id=NEW.poitem_pohead_id)
9466            AND  (pohead_status='O'));
9467       ELSE
9468         UPDATE pohead SET pohead_status = 'O'
9469          WHERE ((pohead_id=NEW.poitem_pohead_id)
9470            AND  (pohead_status='C'));
9471       END IF;
9472     END IF;
9473   END IF;
9474
9475   IF (TG_OP = 'INSERT') THEN
9476     PERFORM postEvent('POitemCreate', 'P', NEW.poitem_id,
9477                       itemsite_warehous_id,
9478                       (pohead_number || '-' || NEW.poitem_linenumber || ': ' || item_number),
9479                       NULL, NULL, NULL, NULL)
9480     FROM pohead JOIN itemsite ON (itemsite_id=NEW.poitem_itemsite_id)
9481                 JOIN item ON (item_id=itemsite_item_id)
9482     WHERE (pohead_id=NEW.poitem_pohead_id)
9483       AND (NEW.poitem_duedate <= (CURRENT_DATE + itemsite_eventfence));
9484   END IF;
9485
9486   IF ( SELECT fetchMetricBool('POChangeLog') ) THEN
9487     _changelog := TRUE;
9488   END IF;
9489
9490   IF ( _changelog ) THEN
9491     IF (TG_OP = 'INSERT') THEN
9492       PERFORM postComment('ChangeLog', 'P', NEW.poitem_pohead_id, ('Created Line #' || NEW.poitem_linenumber::TEXT));
9493       PERFORM postComment('ChangeLog', 'PI', NEW.poitem_id, 'Created');
9494
9495     ELSIF (TG_OP = 'UPDATE') THEN
9496       IF (NEW.poitem_qty_ordered <> OLD.poitem_qty_ordered) THEN
9497         PERFORM postComment( 'ChangeLog', 'PI', NEW.poitem_id,
9498                              ( 'Qty. Ordered Changed from ' || formatQty(OLD.poitem_qty_ordered) ||
9499                                ' to ' || formatQty(NEW.poitem_qty_ordered ) ) );
9500       END IF;
9501       IF (NEW.poitem_unitprice <> OLD.poitem_unitprice) THEN
9502         PERFORM postComment( 'ChangeLog', 'PI', NEW.poitem_id,
9503                              ( 'Unit Price Changed from ' || formatPurchPrice(OLD.poitem_unitprice) ||
9504                                ' to ' || formatPurchPrice(NEW.poitem_unitprice ) ) );
9505       END IF;
9506       IF (NEW.poitem_duedate <> OLD.poitem_duedate) THEN
9507         PERFORM postComment( 'ChangeLog', 'PI', NEW.poitem_id,
9508                              ( 'Due Date Changed from ' || formatDate(OLD.poitem_duedate) ||
9509                                ' to ' || formatDate(NEW.poitem_duedate ) ) );
9510       END IF;
9511       IF (COALESCE(OLD.poitem_taxtype_id, -1) <> COALESCE(NEW.poitem_taxtype_id, -1)) THEN
9512         PERFORM postComment( 'ChangeLog', 'PI', NEW.poitem_id,
9513                              ( 'Tax Type Changed from "' ||
9514                                COALESCE((SELECT taxtype_name FROM taxtype WHERE taxtype_id=OLD.poitem_taxtype_id), 'None') ||
9515                                '" (' || COALESCE(OLD.poitem_taxtype_id, 0) ||
9516                                ') to "' ||
9517                                COALESCE((SELECT taxtype_name FROM taxtype WHERE taxtype_id=NEW.poitem_taxtype_id), 'None') ||
9518                                '" (' || COALESCE(NEW.poitem_taxtype_id, 0) || ')' ) );
9519       END IF;
9520       IF (NEW.poitem_status <> OLD.poitem_status) THEN
9521         IF (NEW.poitem_status = 'C') THEN
9522           PERFORM postComment('ChangeLog', 'PI', NEW.poitem_id, 'Closed');
9523         ELSIF (NEW.poitem_status = 'O') THEN
9524           PERFORM postComment('ChangeLog', 'PI', NEW.poitem_id, 'Opened');
9525         END IF;
9526       END IF;
9527
9528     END IF;
9529   END IF;
9530
9531   RETURN NEW;
9532
9533 END;
9534 $$;
9535
9536
9537 ALTER FUNCTION public._poitemaftertrigger() OWNER TO admin;
9538
9539 --
9540 -- TOC entry 1034 (class 1255 OID 146565550)
9541 -- Dependencies: 4536 8
9542 -- Name: _poitemdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9543 --
9544
9545 CREATE FUNCTION _poitemdeletetrigger() RETURNS trigger
9546     LANGUAGE plpgsql
9547     AS $$
9548 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9549 -- See www.xtuple.com/CPAL for the full text of the software license.
9550 DECLARE
9551 BEGIN
9552
9553   IF (NOT checkPrivilege('MaintainPurchaseOrders')) THEN
9554     RAISE EXCEPTION 'You do not have privileges to alter a Purchase Order.';
9555   END IF;
9556
9557   IF (EXISTS(SELECT recv_id
9558              FROM recv
9559              WHERE ((recv_order_type='PO')
9560                 AND (recv_orderitem_id=OLD.poitem_id)
9561                 AND (recv_qty>0)))) THEN
9562     RAISE EXCEPTION 'Cannot delete an P/O Item which has been received';
9563   END IF;
9564
9565   DELETE FROM comment
9566    WHERE ( (comment_source='PI')
9567      AND   (comment_source_id=OLD.poitem_id) );
9568
9569   DELETE FROM charass
9570    WHERE ((charass_target_type='PI')
9571      AND  (charass_target_id=OLD.poitem_id));
9572
9573   RETURN OLD;
9574
9575 END;
9576 $$;
9577
9578
9579 ALTER FUNCTION public._poitemdeletetrigger() OWNER TO admin;
9580
9581 --
9582 -- TOC entry 1035 (class 1255 OID 146565551)
9583 -- Dependencies: 4536 8
9584 -- Name: _poitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
9585 --
9586
9587 CREATE FUNCTION _poitemtrigger() RETURNS trigger
9588     LANGUAGE plpgsql
9589     AS $$
9590 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9591 -- See www.xtuple.com/CPAL for the full text of the software license.
9592 DECLARE
9593   _cmnttypeid   INTEGER;
9594   _status       CHAR(1);
9595   _check        BOOLEAN;
9596   _cnt          INTEGER;
9597   _s            RECORD;
9598 BEGIN
9599
9600   -- Check
9601   IF ( (TG_OP = 'UPDATE') AND
9602        (NOT checkPrivilege('MaintainPurchaseOrders')) AND
9603        (NOT checkPrivilege('ChangePurchaseOrderQty')) AND
9604        (NOT checkPrivilege('EnterReceipts')) AND
9605        (NOT checkPrivilege('PostVouchers')) ) THEN
9606     RAISE EXCEPTION 'You do not have privileges to alter a Purchase Order.';
9607   END IF;
9608   IF ( (TG_OP = 'INSERT') AND (NOT checkPrivilege('MaintainPurchaseOrders')) ) THEN
9609     RAISE EXCEPTION 'You do not have privileges to alter a Purchase Order.';
9610   END IF;
9611
9612   IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
9613     SELECT pohead_status INTO _status
9614     FROM pohead
9615     WHERE (pohead_id=NEW.poitem_pohead_id);
9616
9617     IF (NEW.poitem_itemsite_id=-1) THEN
9618       NEW.poitem_itemsite_id := NULL;
9619     END IF;
9620     IF (NEW.poitem_expcat_id=-1) THEN
9621       NEW.poitem_expcat_id := NULL;
9622     END IF;
9623
9624     IF (NEW.poitem_itemsite_id IS NOT NULL AND NEW.poitem_expcat_id IS NOT NULL) THEN
9625       RAISE EXCEPTION 'A purchase order line may not include both an inventory and non-inventory item';
9626     ELSIF (NEW.poitem_itemsite_id IS NULL AND NEW.poitem_expcat_id IS NULL) THEN
9627       RAISE EXCEPTION 'A purchase order line must specify either an inventory item or a non-inventory expense category';
9628     ELSIF (NEW.poitem_qty_ordered IS NULL) THEN
9629       RAISE EXCEPTION 'A purchase order line must specify a quantity';
9630     ELSIF (COALESCE(NEW.poitem_itemsite_id,-1) != -1) THEN
9631       SELECT (COUNT(item_id)=1) INTO _check
9632       FROM itemsite, item
9633       WHERE ((itemsite_id=NEW.poitem_itemsite_id)
9634       AND (itemsite_item_id=item_id)
9635       AND (item_type IN ('P','O','M','T')));
9636       IF NOT (_check) THEN
9637         RAISE EXCEPTION 'The item is not a purchasable item type';
9638       END IF;
9639     END IF;
9640   END IF;
9641
9642   IF (TG_OP = 'INSERT') THEN
9643     IF (_status='C') THEN
9644       RAISE EXCEPTION 'New lines may not be inserted into a closed purchase order';
9645     END IF;
9646     
9647     --Fetch and apply default item source data if applicable    
9648     IF ((NEW.poitem_itemsrc_id IS NULL) AND (NEW.poitem_itemsite_id IS NOT NULL)) THEN
9649       IF (NEW.poitem_itemsrc_id IS NULL) THEN
9650         SELECT COUNT(itemsrc_id)  INTO _cnt
9651         FROM pohead,itemsrc,itemsite
9652         WHERE ((pohead_id=NEW.poitem_pohead_id)
9653         AND (pohead_vend_id=itemsrc_vend_id)
9654         AND (itemsite_id=NEW.poitem_itemsite_id)
9655         AND (itemsite_item_id=itemsrc_item_id));
9656
9657         IF (_cnt = 1) THEN
9658           -- We found the one and only item source, so populate data for it
9659           SELECT itemsrc.* INTO _s
9660           FROM pohead,itemsrc,itemsite
9661           WHERE ((pohead_id=NEW.poitem_pohead_id)
9662           AND (pohead_vend_id=itemsrc_vend_id)
9663           AND (itemsite_id=NEW.poitem_itemsite_id)
9664           AND (itemsite_item_id=itemsrc_item_id));
9665           IF (FOUND) THEN
9666             NEW.poitem_itemsrc_id               := _s.itemsrc_id;
9667             NEW.poitem_vend_uom                 := _s.itemsrc_vend_uom;
9668             NEW.poitem_invvenduomratio          := _s.itemsrc_invvendoruomratio;
9669             NEW.poitem_duedate                  := COALESCE(NEW.poitem_duedate, CURRENT_DATE + _s.itemsrc_leadtime);
9670             NEW.poitem_vend_item_number         := COALESCE(NEW.poitem_vend_item_number,_s.itemsrc_vend_item_number);
9671             NEW.poitem_vend_item_descrip        := COALESCE(NEW.poitem_vend_item_descrip,_s.itemsrc_vend_item_descrip);
9672             NEW.poitem_manuf_name               := COALESCE(NEW.poitem_manuf_name,_s.itemsrc_manuf_name);
9673             NEW.poitem_manuf_item_number        := COALESCE(NEW.poitem_manuf_item_number, _s.itemsrc_manuf_item_number);
9674             NEW.poitem_manuf_item_descrip       := COALESCE(NEW.poitem_manuf_item_descrip, _s.itemsrc_manuf_item_descrip);
9675           END IF;
9676         ELSIF (_cnt > 1) THEN
9677           -- There are multiple sources, see if there is an exact match with provided vendor info.
9678           SELECT itemsrc.* INTO _s
9679           FROM pohead,itemsrc,itemsite
9680           WHERE ((pohead_id=NEW.poitem_pohead_id)
9681           AND (pohead_vend_id=itemsrc_vend_id)
9682           AND (itemsite_id=NEW.poitem_itemsite_id)
9683           AND (itemsite_item_id=itemsrc_item_id)
9684           AND (NEW.poitem_vend_item_number=itemsrc_vend_item_number)
9685           AND (COALESCE(NEW.poitem_manuf_name,'')=COALESCE(itemsrc_manuf_name,''))
9686           AND (COALESCE(NEW.poitem_manuf_item_number,'')=COALESCE(itemsrc_manuf_item_number,'')));
9687           IF (FOUND) THEN
9688             NEW.poitem_itemsrc_id               := _s.itemsrc_id;
9689             NEW.poitem_vend_uom                 := _s.itemsrc_vend_uom;
9690             NEW.poitem_invvenduomratio          := _s.itemsrc_invvendoruomratio;
9691             NEW.poitem_duedate                  := COALESCE(NEW.poitem_duedate, CURRENT_DATE + _s.itemsrc_leadtime);
9692             NEW.poitem_vend_item_descrip        := COALESCE(NEW.poitem_vend_item_descrip,_s.itemsrc_vend_item_descrip);
9693             NEW.poitem_manuf_item_descrip       := COALESCE(NEW.poitem_manuf_item_descrip, _s.itemsrc_manuf_item_descrip);
9694           END IF;
9695         END IF;
9696       END IF;
9697     END IF;
9698
9699     IF (NEW.poitem_duedate IS NULL) THEN
9700       RAISE EXCEPTION  'A due date is required';
9701     END IF;
9702     
9703     --Set defaults
9704     NEW.poitem_linenumber               := COALESCE(NEW.poitem_linenumber,(
9705                                                 SELECT COALESCE(MAX(poitem_linenumber),0) + 1
9706                                                 FROM poitem
9707                                                 WHERE (poitem_pohead_id=NEW.poitem_pohead_id)));
9708     NEW.poitem_status                  := _status;
9709     NEW.poitem_invvenduomratio  := COALESCE(NEW.poitem_invvenduomratio,1);
9710     IF (NEW.poitem_invvenduomratio = 0.0) THEN
9711       NEW.poitem_invvenduomratio = 1.0;
9712     END IF;
9713     NEW.poitem_vend_item_number         := COALESCE(NEW.poitem_vend_item_number,'');
9714     NEW.poitem_vend_item_descrip        := COALESCE(NEW.poitem_vend_item_descrip,'');
9715     NEW.poitem_unitprice        := COALESCE(NEW.poitem_unitprice,(
9716                                                 SELECT itemsrcPrice(NEW.poitem_itemsrc_id, COALESCE(itemsite_warehous_id, -1), pohead_dropship,
9717                                                        NEW.poitem_qty_ordered, pohead_curr_id, CURRENT_DATE)
9718                                                 FROM itemsite, pohead
9719                                                 WHERE ( (itemsite_id=NEW.poitem_itemsite_id)
9720                                                 AND (pohead_id=NEW.poitem_pohead_id) )), 0.0);
9721     NEW.poitem_stdcost                  := COALESCE(NEW.poitem_stdcost,(
9722                                                 SELECT stdcost(itemsite_item_id)
9723                                                 FROM itemsite
9724                                                 WHERE (itemsite_id=NEW.poitem_itemsite_id)));
9725     NEW.poitem_bom_rev_id               := COALESCE(NEW.poitem_bom_rev_id,(
9726                                                 SELECT getActiveRevId('BOM',itemsite_item_id)
9727                                                 FROM itemsite
9728                                                 WHERE (itemsite_id=NEW.poitem_itemsite_id)));
9729     NEW.poitem_boo_rev_id               := COALESCE(NEW.poitem_boo_rev_id,(
9730                                                 SELECT getActiveRevId('BOO',itemsite_item_id)
9731                                                 FROM itemsite
9732                                                 WHERE (itemsite_id=NEW.poitem_itemsite_id)));
9733     NEW.poitem_comments         := COALESCE(NEW.poitem_comments,'');
9734     NEW.poitem_freight                  := COALESCE(NEW.poitem_freight,0);
9735     NEW.poitem_qty_received             := 0;
9736     NEW.poitem_qty_returned             := 0;
9737     NEW.poitem_qty_vouchered            := 0;
9738       
9739   END IF;
9740
9741   IF (TG_OP = 'UPDATE') THEN
9742     IF (NEW.poitem_itemsite_id != OLD.poitem_itemsite_id) THEN
9743       RAISE EXCEPTION 'You may not change the item site for a line item.';
9744     ELSIF (NEW.poitem_expcat_id != OLD.poitem_expcat_id) THEN
9745       RAISE EXCEPTION 'You may not change the expense category for a line item.';
9746     END IF;
9747   END IF;
9748
9749   RETURN NEW;
9750
9751 END;
9752 $$;
9753
9754
9755 ALTER FUNCTION public._poitemtrigger() OWNER TO admin;
9756
9757 --
9758 -- TOC entry 1036 (class 1255 OID 146565553)
9759 -- Dependencies: 4536 8
9760 -- Name: _prjaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9761 --
9762
9763 CREATE FUNCTION _prjaftertrigger() RETURNS trigger
9764     LANGUAGE plpgsql
9765     AS $$
9766 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9767 -- See www.xtuple.com/CPAL for the full text of the software license.
9768 DECLARE
9769   _cmnttypeid INTEGER;
9770 BEGIN
9771
9772 --  Cache the cmnttype_id for ChangeLog
9773   SELECT cmnttype_id INTO _cmnttypeid
9774   FROM cmnttype
9775   WHERE (cmnttype_name='ChangeLog');
9776   IF (NOT FOUND) THEN
9777     RAISE EXCEPTION 'Comment type ChangeLog not found';
9778   END IF;
9779
9780   IF (TG_OP = 'INSERT') THEN
9781     PERFORM postComment(_cmnttypeid, 'J', NEW.prj_id, 'Created');
9782   ELSIF (TG_OP = 'UPDATE') THEN
9783     IF (OLD.prj_start_date <> NEW.prj_start_date) THEN
9784       PERFORM postComment( _cmnttypeid, 'J', NEW.prj_id,
9785                            ('Start Date Changed from ' || formatDate(OLD.prj_start_date) || ' to ' || formatDate(NEW.prj_start_date)) );
9786     END IF;
9787     IF (OLD.prj_due_date <> NEW.prj_due_date) THEN
9788       PERFORM postComment( _cmnttypeid, 'J', NEW.prj_id,
9789                            ('Due Date Changed from ' || formatDate(OLD.prj_due_date) || ' to ' || formatDate(NEW.prj_due_date)) );
9790     END IF;
9791     IF (OLD.prj_assigned_date <> NEW.prj_assigned_date) THEN
9792       PERFORM postComment( _cmnttypeid, 'J', NEW.prj_id,
9793                            ('Assigned Date Changed from ' || formatDate(OLD.prj_assigned_date) || ' to ' || formatDate(NEW.prj_assigned_date)) );
9794     END IF;
9795     IF (OLD.prj_completed_date <> NEW.prj_completed_date) THEN
9796       PERFORM postComment( _cmnttypeid, 'J', NEW.prj_id,
9797                            ('Completed Date Changed from ' || formatDate(OLD.prj_completed_date) || ' to ' || formatDate(NEW.prj_completed_date)) );
9798     END IF;
9799
9800   END IF;
9801
9802   RETURN NEW;
9803 END;
9804 $$;
9805
9806
9807 ALTER FUNCTION public._prjaftertrigger() OWNER TO admin;
9808
9809 --
9810 -- TOC entry 1038 (class 1255 OID 146565554)
9811 -- Dependencies: 4536 8
9812 -- Name: _prjbeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9813 --
9814
9815 CREATE FUNCTION _prjbeforedeletetrigger() RETURNS trigger
9816     LANGUAGE plpgsql
9817     AS $$
9818 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9819 -- See www.xtuple.com/CPAL for the full text of the software license.
9820 DECLARE
9821   _recurid     INTEGER;
9822   _newparentid INTEGER;
9823 BEGIN
9824
9825   IF (TG_OP = 'DELETE') THEN
9826     DELETE FROM docass WHERE docass_source_id = OLD.prj_id AND docass_source_type = 'J';
9827     DELETE FROM docass WHERE docass_target_id = OLD.prj_id AND docass_target_type = 'J';
9828     
9829     SELECT recur_id INTO _recurid
9830       FROM recur
9831      WHERE ((recur_parent_id=OLD.prj_id)
9832         AND (recur_parent_type='J'));
9833
9834     IF (_recurid IS NOT NULL) THEN
9835       SELECT MIN(prj_id) INTO _newparentid
9836         FROM prj
9837        WHERE ((prj_recurring_prj_id=OLD.prj_id)
9838           AND (prj_id!=OLD.prj_id));
9839
9840       -- client is responsible for warning about deleting a recurring prj
9841       IF (_newparentid IS NULL) THEN
9842         DELETE FROM recur WHERE recur_id=_recurid;
9843       ELSE
9844         UPDATE recur SET recur_parent_id=_newparentid
9845          WHERE recur_id=_recurid;
9846       END IF;
9847
9848     END IF;
9849
9850     RETURN OLD;
9851   END IF;
9852
9853   RETURN NEW;
9854 END;
9855 $$;
9856
9857
9858 ALTER FUNCTION public._prjbeforedeletetrigger() OWNER TO admin;
9859
9860 --
9861 -- TOC entry 1039 (class 1255 OID 146565555)
9862 -- Dependencies: 4536 8
9863 -- Name: _prjtaskaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9864 --
9865
9866 CREATE FUNCTION _prjtaskaftertrigger() RETURNS trigger
9867     LANGUAGE plpgsql
9868     AS $$
9869 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9870 -- See www.xtuple.com/CPAL for the full text of the software license.
9871 DECLARE
9872   _cmnttypeid INTEGER;
9873 BEGIN
9874
9875   SELECT cmnttype_id INTO _cmnttypeid
9876   FROM cmnttype
9877   WHERE (cmnttype_name='ChangeLog');
9878   IF (NOT FOUND) THEN
9879     RAISE EXCEPTION 'Comment type ChangeLog not found';
9880   END IF;
9881
9882   IF (TG_OP = 'INSERT') THEN
9883     PERFORM postComment(_cmnttypeid, 'TA', NEW.prjtask_id, 'Created');
9884
9885   ELSIF (TG_OP = 'UPDATE') THEN
9886     IF (OLD.prjtask_start_date <> NEW.prjtask_start_date) THEN
9887       PERFORM postComment( _cmnttypeid, 'TA', NEW.prjtask_id,
9888                            ('Start Date Changed from ' || formatDate(OLD.prjtask_start_date) || ' to ' || formatDate(NEW.prjtask_start_date)) );
9889     END IF;
9890     IF (OLD.prjtask_due_date <> NEW.prjtask_due_date) THEN
9891       PERFORM postComment( _cmnttypeid, 'TA', NEW.prjtask_id,
9892                            ('Due Date Changed from ' || formatDate(OLD.prjtask_due_date) || ' to ' || formatDate(NEW.prjtask_due_date)) );
9893     END IF;
9894     IF (OLD.prjtask_assigned_date <> NEW.prjtask_assigned_date) THEN
9895       PERFORM postComment( _cmnttypeid, 'TA', NEW.prjtask_id,
9896                            ('Assigned Date Changed from ' || formatDate(OLD.prjtask_assigned_date) || ' to ' || formatDate(NEW.prjtask_assigned_date)) );
9897     END IF;
9898     IF (OLD.prjtask_completed_date <> NEW.prjtask_completed_date) THEN
9899       PERFORM postComment( _cmnttypeid, 'TA', NEW.prjtask_id,
9900                            ('Completed Date Changed from ' || formatDate(OLD.prjtask_completed_date) || ' to ' || formatDate(NEW.prjtask_completed_date)) );
9901     END IF;
9902     IF (OLD.prjtask_hours_actual != NEW.prjtask_hours_actual) THEN
9903       PERFORM postComment(_cmnttypeid, 'TA', NEW.prjtask_id, 
9904           'Actual Hours changed from ' || formatQty(OLD.prjtask_hours_actual) || ' to ' || formatQty(NEW.prjtask_hours_actual));
9905     END IF;
9906     IF (OLD.prjtask_exp_actual != NEW.prjtask_exp_actual) THEN
9907       PERFORM postComment(_cmnttypeid, 'TA', NEW.prjtask_id, 
9908           'Actual Expense changed from ' || formatQty(OLD.prjtask_exp_actual) || ' to ' || formatQty(NEW.prjtask_exp_actual));
9909     END IF;
9910
9911   END IF;
9912   
9913   RETURN NEW;
9914 END;
9915 $$;
9916
9917
9918 ALTER FUNCTION public._prjtaskaftertrigger() OWNER TO admin;
9919
9920 --
9921 -- TOC entry 1040 (class 1255 OID 146565556)
9922 -- Dependencies: 4536 8
9923 -- Name: _prjtasktrigger(); Type: FUNCTION; Schema: public; Owner: admin
9924 --
9925
9926 CREATE FUNCTION _prjtasktrigger() RETURNS trigger
9927     LANGUAGE plpgsql
9928     AS $$
9929 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
9930 -- See www.xtuple.com/CPAL for the full text of the software license.
9931 BEGIN
9932
9933   --  Checks
9934   IF (NEW.prjtask_owner_username=getEffectiveXtUser()) THEN
9935     IF (NOT checkPrivilege('MaintainAllProjects') AND NOT checkPrivilege('MaintainPersonalProjects')) THEN
9936       RAISE EXCEPTION 'You do not have privileges to maintain Projects.';
9937     END IF;
9938   ELSIF (NOT checkPrivilege('MaintainAllProjects')) THEN
9939     RAISE EXCEPTION 'You do not have privileges to maintain Projects.';
9940   ELSIF (LENGTH(COALESCE(NEW.prjtask_number,'')) = 0) THEN
9941     RAISE EXCEPTION 'You must ender a valid number.';
9942   ELSIF (LENGTH(COALESCE(NEW.prjtask_name,'')) = 0) THEN
9943     RAISE EXCEPTION 'You must ender a valid name.';     
9944   END IF;
9945
9946   RETURN NEW;
9947 END;
9948 $$;
9949
9950
9951 ALTER FUNCTION public._prjtasktrigger() OWNER TO admin;
9952
9953 --
9954 -- TOC entry 1041 (class 1255 OID 146565557)
9955 -- Dependencies: 4536 8
9956 -- Name: _prospectafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
9957 --
9958
9959 CREATE FUNCTION _prospectafterdeletetrigger() RETURNS trigger
9960     LANGUAGE plpgsql
9961     AS $$
9962 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
9963 -- See www.xtuple.com/CPAL for the full text of the software license.
9964 BEGIN
9965   IF EXISTS(SELECT 1 FROM quhead WHERE quhead_cust_id = OLD.prospect_id) AND
9966      NOT EXISTS (SELECT 1 FROM custinfo WHERE cust_id = OLD.prospect_id) THEN
9967     RAISE EXCEPTION '[xtuple: deleteProspect, -1]';
9968   END IF;
9969
9970   IF (fetchMetricBool('ProspectChangeLog')) THEN
9971     PERFORM postComment(cmnttype_id, 'PSPCT', OLD.prospect_id,
9972                         'Deleted "' || OLD.prospect_number || '"')
9973       FROM cmnttype
9974      WHERE (cmnttype_name='ChangeLog');
9975   END IF;
9976
9977   RETURN OLD;
9978 END;
9979 $$;
9980
9981
9982 ALTER FUNCTION public._prospectafterdeletetrigger() OWNER TO admin;
9983
9984 --
9985 -- TOC entry 1042 (class 1255 OID 146565558)
9986 -- Dependencies: 4536 8
9987 -- Name: _prospectaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
9988 --
9989
9990 CREATE FUNCTION _prospectaftertrigger() RETURNS trigger
9991     LANGUAGE plpgsql
9992     AS $$
9993 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
9994 -- See www.xtuple.com/CPAL for the full text of the software license.
9995 DECLARE
9996   _cmnttypeid   INTEGER;
9997   _custid       INTEGER;
9998   _prospectid   INTEGER;
9999
10000 BEGIN
10001
10002   IF (TG_OP = 'INSERT') THEN
10003     SELECT crmacct_cust_id, crmacct_prospect_id INTO _custid, _prospectid
10004       FROM crmacct
10005      WHERE crmacct_number=NEW.prospect_number;
10006
10007     IF (_custid > 0 AND _custid != _prospectid) THEN
10008       RAISE EXCEPTION '[xtuple: createProspect, -2]';
10009     END IF;
10010
10011     IF (_prospectid > 0) THEN
10012       RAISE EXCEPTION '[xtuple: createProspect, -3]';
10013     END IF;
10014
10015     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
10016     LOOP
10017       UPDATE crmacct SET crmacct_prospect_id=NEW.prospect_id,
10018                          crmacct_cust_id=NULL,
10019                          crmacct_name=NEW.prospect_name
10020        WHERE crmacct_number=NEW.prospect_number;
10021       IF (FOUND) THEN
10022         EXIT;
10023       END IF;
10024       BEGIN
10025         INSERT INTO crmacct(crmacct_number,      crmacct_name,
10026                             crmacct_active,      crmacct_type,
10027                             crmacct_prospect_id, crmacct_cntct_id_1
10028                   ) VALUES (NEW.prospect_number, NEW.prospect_name,
10029                             NEW.prospect_active, 'O',
10030                             NEW.prospect_id,     NEW.prospect_cntct_id);
10031         EXIT;
10032       EXCEPTION WHEN unique_violation THEN
10033             -- do nothing, and loop to try the UPDATE again
10034       END;
10035     END LOOP;
10036
10037     /* TODO: default characteristic assignments based on what? */
10038
10039   ELSIF (TG_OP = 'UPDATE') THEN
10040     UPDATE crmacct SET crmacct_number = NEW.prospect_number
10041     WHERE ((crmacct_prospect_id=NEW.prospect_id)
10042       AND  (crmacct_number!=NEW.prospect_number));
10043
10044     UPDATE crmacct SET crmacct_name = NEW.prospect_name
10045     WHERE ((crmacct_prospect_id=NEW.prospect_id)
10046       AND  (crmacct_name!=NEW.prospect_name));
10047
10048   END IF;
10049
10050   IF (fetchMetricBool('ProspectChangeLog')) THEN
10051     SELECT cmnttype_id INTO _cmnttypeid
10052       FROM cmnttype
10053      WHERE (cmnttype_name='ChangeLog');
10054
10055     IF (_cmnttypeid IS NOT NULL) THEN
10056       IF (TG_OP = 'INSERT') THEN
10057         PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id, 'Created');
10058
10059       ELSIF (TG_OP = 'UPDATE') THEN
10060         IF (OLD.prospect_active <> NEW.prospect_active) THEN
10061           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10062                               CASE WHEN NEW.prospect_active THEN 'Activated'
10063                                    ELSE 'Deactivated' END);
10064         END IF;
10065
10066         IF (OLD.prospect_number <> NEW.prospect_number) THEN
10067           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10068                               'Number changed from "' || OLD.prospect_number ||
10069                               '" to "' || NEW.prospect_number || '"');
10070         END IF;
10071
10072         IF (OLD.prospect_name <> NEW.prospect_name) THEN
10073           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10074                               'Name changed from "' || OLD.prospect_name ||
10075                               '" to "' || NEW.prospect_name || '"');
10076         END IF;
10077
10078         IF (OLD.prospect_cntct_id <> NEW.prospect_cntct_id) THEN
10079           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10080                               'Contact changed from "' ||
10081                               formatCntctName(OLD.prospect_cntct_id) || '" to "' ||
10082                               formatCntctName(NEW.prospect_cntct_id) || '"');
10083         END IF;
10084
10085         IF (OLD.prospect_taxauth_id <> NEW.prospect_taxauth_id) THEN
10086           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10087                               'Tax Authority changed from "' ||
10088                               (SELECT taxauth_code FROM taxauth
10089                                 WHERE taxauth_id=OLD.prospect_taxauth_id) ||
10090                               '" to "' ||
10091                               (SELECT taxauth_code FROM taxauth
10092                                 WHERE taxauth_id=NEW.prospect_taxauth_id) || '"');
10093         END IF;
10094
10095         IF (OLD.prospect_salesrep_id <> NEW.prospect_salesrep_id) THEN
10096           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10097                               'Sales Rep changed from "' ||
10098                               (SELECT salesrep_number FROM salesrep
10099                                WHERE salesrep_id=OLD.prospect_salesrep_id) ||
10100                               '" to "' ||
10101                               (SELECT salesrep_number FROM salesrep
10102                                WHERE salesrep_id=NEW.prospect_salesrep_id) || '"');
10103         END IF;
10104
10105         IF (OLD.prospect_warehous_id <> NEW.prospect_warehous_id) THEN
10106           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10107                               'Warehouse changed from "' ||
10108                               (SELECT warehous_code FROM whsinfo
10109                                 WHERE warehous_id=OLD.prospect_warehous_id) ||
10110                               '" to "' ||
10111                               (SELECT warehous_code FROM whsinfo
10112                                 WHERE warehous_id=NEW.prospect_warehous_id) || '"');
10113         END IF;
10114
10115         IF (OLD.prospect_taxzone_id <> NEW.prospect_taxzone_id) THEN
10116           PERFORM postComment(_cmnttypeid, 'PSPCT', NEW.prospect_id,
10117                               'Tax Zone changed from "' ||
10118                               (SELECT taxzone_code FROM taxzone
10119                                 WHERE taxzone_id=OLD.prospect_taxzone_id) || '" to "' ||
10120                               (SELECT taxzone_code FROM taxzone
10121                                 WHERE taxzone_id=NEW.prospect_taxzone_id) || '"');
10122         END IF;
10123
10124       END IF;
10125     END IF;
10126   END IF;
10127
10128   RETURN NEW;
10129 END;
10130 $$;
10131
10132
10133 ALTER FUNCTION public._prospectaftertrigger() OWNER TO admin;
10134
10135 --
10136 -- TOC entry 1043 (class 1255 OID 146565559)
10137 -- Dependencies: 4536 8
10138 -- Name: _prospectbeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
10139 --
10140
10141 CREATE FUNCTION _prospectbeforedeletetrigger() RETURNS trigger
10142     LANGUAGE plpgsql
10143     AS $$
10144 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
10145 -- See www.xtuple.com/CPAL for the full text of the software license.
10146 BEGIN
10147   IF (NOT checkPrivilege('MaintainProspectMasters')) THEN
10148     RAISE EXCEPTION 'You do not have privileges to maintain Prospects.';
10149   END IF;
10150
10151   UPDATE crmacct SET crmacct_prospect_id = NULL
10152    WHERE crmacct_prospect_id = OLD.prospect_id;
10153
10154   RETURN OLD;
10155 END;
10156 $$;
10157
10158
10159 ALTER FUNCTION public._prospectbeforedeletetrigger() OWNER TO admin;
10160
10161 --
10162 -- TOC entry 1044 (class 1255 OID 146565560)
10163 -- Dependencies: 4536 8
10164 -- Name: _prospecttrigger(); Type: FUNCTION; Schema: public; Owner: admin
10165 --
10166
10167 CREATE FUNCTION _prospecttrigger() RETURNS trigger
10168     LANGUAGE plpgsql
10169     AS $$
10170 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
10171 -- See www.xtuple.com/CPAL for the full text of the software license.
10172 BEGIN
10173   IF (NOT checkPrivilege('MaintainProspectMasters')) THEN
10174     RAISE EXCEPTION 'You do not have privileges to maintain Prospects.';
10175   END IF;
10176
10177   IF (NEW.prospect_number IS NULL) THEN
10178     RAISE EXCEPTION 'You must supply a valid Prospect Number.';
10179   END IF;
10180
10181   NEW.prospect_number := UPPER(NEW.prospect_number);
10182
10183   RETURN NEW;
10184 END;
10185 $$;
10186
10187
10188 ALTER FUNCTION public._prospecttrigger() OWNER TO admin;
10189
10190 --
10191 -- TOC entry 1045 (class 1255 OID 146565561)
10192 -- Dependencies: 4536 8
10193 -- Name: _prtrigger(); Type: FUNCTION; Schema: public; Owner: admin
10194 --
10195
10196 CREATE FUNCTION _prtrigger() RETURNS trigger
10197     LANGUAGE plpgsql
10198     AS $$
10199 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10200 -- See www.xtuple.com/EULA for the full text of the software license.
10201 BEGIN
10202   --- clear the number from the issue cache
10203   PERFORM clearNumberIssue('PrNumber', NEW.pr_number);
10204
10205   RETURN NEW;
10206 END;
10207 $$;
10208
10209
10210 ALTER FUNCTION public._prtrigger() OWNER TO admin;
10211
10212 --
10213 -- TOC entry 1046 (class 1255 OID 146565562)
10214 -- Dependencies: 4536 8
10215 -- Name: _quheadtrigger(); Type: FUNCTION; Schema: public; Owner: admin
10216 --
10217
10218 CREATE FUNCTION _quheadtrigger() RETURNS trigger
10219     LANGUAGE plpgsql
10220     AS $$
10221 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10222 -- See www.xtuple.com/CPAL for the full text of the software license.
10223 DECLARE
10224   _cmnttypeid INTEGER;
10225   _oldHoldType TEXT;
10226   _newHoldType TEXT;
10227   _p RECORD;
10228   _a RECORD;
10229   _w RECORD;
10230   _shiptoId INTEGER;
10231   _addrId INTEGER;
10232   _prjId INTEGER;
10233   _check BOOLEAN;
10234   _numGen CHAR(1);
10235
10236 BEGIN
10237
10238   --  Checks
10239   SELECT checkPrivilege('MaintainQuotes') INTO _check;
10240   IF NOT (_check) THEN
10241     RAISE EXCEPTION 'You do not have privileges to maintain Quotes.';
10242   END IF;
10243
10244   -- If this is imported, check the quote number
10245   IF (TG_OP = 'INSERT') THEN
10246     IF (NEW.quhead_imported) THEN
10247       SELECT fetchMetricText('QUNumberGeneration') INTO _numGen;
10248       IF ((NEW.quhead_number IS NULL) AND (_numGen='M')) THEN
10249         RAISE EXCEPTION 'You must supply a Quote Number.';
10250       ELSE
10251         IF ((NEW.quhead_number IS NOT NULL) AND (_numGen='A')) THEN
10252           RAISE EXCEPTION 'You may not supply a new Quote Number xTuple will generate the number.';
10253         ELSE
10254           IF ((NEW.quhead_number IS NULL) AND (_numGen='O')) THEN
10255             SELECT fetchqunumber() INTO NEW.quhead_number;
10256           ELSE
10257             IF (NEW.quhead_number IS NULL) THEN
10258               SELECT fetchsonumber() INTO NEW.quhead_number;
10259             END IF;
10260           END IF;
10261         END IF;
10262       END IF;
10263     END IF;
10264     
10265     IF (fetchMetricText('QUNumberGeneration') IN ('A','O')) THEN
10266       --- clear the number from the issue cache
10267       PERFORM clearNumberIssue('QuNumber', NEW.quhead_number);
10268     ELSIF (fetchMetricText('QUNumberGeneration') = 'S') THEN
10269       --- clear the number from the issue cache
10270       PERFORM clearNumberIssue('SoNumber', NEW.quhead_number);
10271     END IF;
10272     
10273   ELSE
10274     IF (TG_OP = 'UPDATE') THEN
10275        IF (NEW.quhead_number <> OLD.quhead_number) THEN
10276          RAISE EXCEPTION 'The order number may not be changed.';
10277        END IF;
10278     END IF;
10279   END IF;
10280
10281   IF (TG_OP IN ('INSERT','UPDATE')) THEN
10282     -- Get Customer data
10283     IF (NEW.quhead_shipto_id IS NULL) THEN
10284       SELECT * INTO _p FROM (
10285       SELECT cust_number,cust_usespos,cust_blanketpos,cust_ffbillto,
10286              cust_ffshipto,cust_name,cust_salesrep_id,cust_terms_id,cust_shipvia,
10287              cust_commprcnt,cust_curr_id,cust_taxzone_id,
10288              addr_line1,addr_line2,addr_line3,addr_city,addr_state,addr_postalcode,addr_country,
10289              shipto_id,shipto_addr_id,shipto_name,shipto_salesrep_id,shipto_shipvia,
10290              shipto_shipchrg_id,shipto_shipform_id,shipto_commission,shipto_taxzone_id
10291       FROM custinfo
10292         LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
10293         LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
10294         LEFT OUTER JOIN shiptoinfo ON ((cust_id=shipto_cust_id) AND shipto_default)
10295       WHERE (cust_id=NEW.quhead_cust_id)
10296       UNION
10297       SELECT prospect_number,false,false,true,
10298              true,prospect_name,prospect_salesrep_id,null,null,
10299              null,null,prospect_taxzone_id,
10300              addr_line1,addr_line2,addr_line3,addr_city,addr_state,addr_postalcode,addr_country,
10301              null,null,null,null,null,
10302              null,null,null,null
10303       FROM prospect
10304         LEFT OUTER JOIN cntct ON (prospect_cntct_id=cntct_id)
10305         LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
10306       WHERE (prospect_id=NEW.quhead_cust_id)) AS data;
10307     ELSE
10308       SELECT cust_creditstatus,cust_number,cust_usespos,cust_blanketpos,cust_ffbillto,
10309              cust_ffshipto,cust_name,cust_salesrep_id,cust_terms_id,cust_shipvia,
10310              cust_shipchrg_id,cust_shipform_id,cust_commprcnt,cust_curr_id,cust_taxzone_id,
10311              addr_line1,addr_line2,addr_line3,addr_city,addr_state,addr_postalcode,addr_country,
10312              shipto_id,shipto_addr_id,shipto_name,shipto_salesrep_id,shipto_shipvia,
10313              shipto_shipchrg_id,shipto_shipform_id,shipto_commission,shipto_taxzone_id INTO _p
10314       FROM shiptoinfo,custinfo
10315         LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
10316         LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
10317       WHERE ((cust_id=NEW.quhead_cust_id)
10318       AND (shipto_id=shipto_id));
10319     END IF;
10320
10321     -- If there is customer data, then we can get to work
10322     IF (FOUND) THEN
10323       -- Only check PO number for imports because UI checks when whole quote is saved
10324       IF (TG_OP = 'INSERT') THEN
10325           -- Set to defaults if values not provided
10326           NEW.quhead_shipto_id          := COALESCE(NEW.quhead_shipto_id,_p.shipto_id);
10327           NEW.quhead_salesrep_id        := COALESCE(NEW.quhead_salesrep_id,_p.shipto_salesrep_id,_p.cust_salesrep_id);
10328           NEW.quhead_terms_id           := COALESCE(NEW.quhead_terms_id,_p.cust_terms_id);
10329           NEW.quhead_shipvia            := COALESCE(NEW.quhead_shipvia,_p.shipto_shipvia,_p.cust_shipvia);
10330           NEW.quhead_commission         := COALESCE(NEW.quhead_commission,_p.shipto_commission,_p.cust_commprcnt);
10331           NEW.quhead_quotedate          := COALESCE(NEW.quhead_quotedate,current_date);
10332           NEW.quhead_packdate           := COALESCE(NEW.quhead_packdate,NEW.quhead_quotedate);
10333           NEW.quhead_curr_id            := COALESCE(NEW.quhead_curr_id,_p.cust_curr_id,basecurrid());
10334           NEW.quhead_taxzone_id         := COALESCE(NEW.quhead_taxzone_id,_p.shipto_taxzone_id,_p.cust_taxzone_id);
10335           NEW.quhead_freight            := COALESCE(NEW.quhead_freight,0);
10336           NEW.quhead_custponumber       := COALESCE(NEW.quhead_custponumber,'');
10337           NEW.quhead_ordercomments      := COALESCE(NEW.quhead_ordercomments,'');
10338           NEW.quhead_shipcomments       := COALESCE(NEW.quhead_shipcomments,'');
10339           NEW.quhead_shiptophone        := COALESCE(NEW.quhead_shiptophone,'');
10340           NEW.quhead_misc               := COALESCE(NEW.quhead_misc,0);
10341           NEW.quhead_misc_descrip       := COALESCE(NEW.quhead_misc_descrip,'');
10342
10343           IF ((NEW.quhead_warehous_id IS NULL) OR (NEW.quhead_fob IS NULL)) THEN
10344             IF (NEW.quhead_warehous_id IS NULL) THEN
10345               SELECT warehous_id,warehous_fob INTO _w
10346               FROM usrpref, whsinfo
10347               WHERE ((warehous_id=CAST(usrpref_value AS INTEGER))
10348                 AND (warehous_shipping)
10349                 AND (warehous_active)
10350                 AND (usrpref_username=getEffectiveXtUser())
10351                 AND (usrpref_name='PreferredWarehouse'));
10352             ELSE
10353               SELECT warehous_id,warehous_fob INTO _w
10354               FROM whsinfo
10355               WHERE (warehous_id=NEW.quhead_warehous_id);
10356             END IF;
10357             
10358             IF (FOUND) THEN
10359               NEW.quhead_warehous_id    := COALESCE(NEW.quhead_warehous_id,_w.warehous_id);
10360               NEW.quhead_fob            := COALESCE(NEW.quhead_fob,_w.warehous_fob);
10361             END IF;
10362           END IF;
10363       END IF;
10364       
10365       --Auto create project if applicable
10366       IF ((TG_OP = 'INSERT') AND (COALESCE(NEW.quhead_prj_id,-1)=-1)) THEN
10367         SELECT fetchMetricBool('AutoCreateProjectsForOrders') INTO _check;
10368         IF (_check) THEN
10369           SELECT NEXTVAL('prj_prj_id_seq') INTO _prjId;
10370           NEW.quhead_prj_id := _prjId;
10371           INSERT INTO prj (prj_id, prj_number, prj_name, prj_descrip,
10372                            prj_status, prj_so, prj_wo, prj_po,
10373                            prj_owner_username, prj_start_date, prj_due_date,
10374                            prj_assigned_date, prj_completed_date, prj_username,
10375                            prj_recurring_prj_id, prj_crmacct_id,
10376                            prj_cntct_id, prj_prjtype_id)
10377           SELECT _prjId, NEW.quhead_number, NEW.quhead_number, 'Auto Generated Project from Quote.',
10378                  'O', TRUE, TRUE, TRUE,
10379                  getEffectiveXTUser(), NEW.quhead_quotedate, NEW.quhead_packdate,
10380                  NEW.quhead_quotedate, NULL, getEffectiveXTUser(),
10381                  NULL, crmacct_id,
10382                  NEW.quhead_billto_cntct_id, NULL
10383           FROM crmacct
10384           WHERE (crmacct_cust_id=NEW.quhead_cust_id)
10385              OR (crmacct_prospect_id=NEW.quhead_cust_id)
10386           LIMIT 1;
10387         END IF;
10388       END IF;
10389
10390       -- Deal with Billing Address
10391       IF (TG_OP = 'INSERT') THEN
10392         IF (_p.cust_ffbillto) THEN
10393           -- If they didn't supply data, we'll put in the bill to address
10394           NEW.quhead_billtoname=COALESCE(NEW.quhead_billtoname,_p.cust_name,'');
10395           NEW.quhead_billtoaddress1=COALESCE(NEW.quhead_billtoaddress1,_p.addr_line1,'');
10396           NEW.quhead_billtoaddress2=COALESCE(NEW.quhead_billtoaddress2,_p.addr_line2,'');
10397           NEW.quhead_billtoaddress3=COALESCE(NEW.quhead_billtoaddress3,_p.addr_line3,'');    
10398           NEW.quhead_billtocity=COALESCE(NEW.quhead_billtocity,_p.addr_city,''); 
10399           NEW.quhead_billtostate=COALESCE(NEW.quhead_billtostate,_p.addr_state,'');
10400           NEW.quhead_billtozip=COALESCE(NEW.quhead_billtozip,_p.addr_postalcode,'');
10401           NEW.quhead_billtocountry=COALESCE(NEW.quhead_billtocountry,_p.addr_country,'');   
10402         ELSE
10403           -- Free form not allowed, we're going to put in the address regardless
10404           NEW.quhead_billtoname=COALESCE(_p.cust_name,'');
10405           NEW.quhead_billtoaddress1=COALESCE(_p.addr_line1,'');
10406           NEW.quhead_billtoaddress2=COALESCE(_p.addr_line2,'');
10407           NEW.quhead_billtoaddress3=COALESCE(_p.addr_line3,'');    
10408           NEW.quhead_billtocity=COALESCE(_p.addr_city,''); 
10409           NEW.quhead_billtostate=COALESCE(_p.addr_state,'');
10410           NEW.quhead_billtozip=COALESCE(_p.addr_postalcode,'');
10411           NEW.quhead_billtocountry=COALESCE(_p.addr_country,'');
10412         END IF;
10413       END IF;
10414
10415       -- Now let's look at Shipto Address
10416       -- If there's nothing in the address fields and there is a shipto id 
10417       -- or there is a default address available, let's put in some shipto address data
10418       IF ((TG_OP = 'INSERT') 
10419        AND NOT ((NEW.quhead_shipto_id IS NULL) AND NOT _p.cust_ffshipto)
10420        AND (NEW.quhead_shiptoname IS NULL)
10421        AND (NEW.quhead_shiptoaddress1 IS NULL)
10422        AND (NEW.quhead_shiptoaddress2 IS NULL)
10423        AND (NEW.quhead_shiptoaddress3 IS NULL)
10424        AND (NEW.quhead_shiptocity IS NULL)
10425        AND (NEW.quhead_shiptostate IS NULL)
10426        AND (NEW.quhead_shiptocountry IS NULL)) THEN
10427         IF ((NEW.quhead_shipto_id IS NULL) AND (_p.shipto_id IS NOT NULL)) THEN
10428           _shiptoId := _p.shipto_addr_id;
10429         ELSE
10430           _shiptoId := NEW.quhead_shipto_id;
10431         END IF;
10432
10433         SELECT * INTO _a 
10434         FROM shiptoinfo, addr 
10435         WHERE ((shipto_id=_shiptoId)
10436         AND (addr_id=shipto_addr_id));
10437
10438         NEW.quhead_shiptoname := COALESCE(_p.shipto_name,'');
10439         NEW.quhead_shiptoaddress1 := COALESCE(_a.addr_line1,'');
10440         NEW.quhead_shiptoaddress2 := COALESCE(_a.addr_line2,'');
10441         NEW.quhead_shiptoaddress3 := COALESCE(_a.addr_line3,'');    
10442         NEW.quhead_shiptocity := COALESCE(_a.addr_city,''); 
10443         NEW.quhead_shiptostate := COALESCE(_a.addr_state,'');
10444         NEW.quhead_shiptozipcode := COALESCE(_a.addr_postalcode,'');
10445         NEW.quhead_shiptocountry := COALESCE(_a.addr_country,'');
10446       ELSE
10447         IF (_p.cust_ffshipto) THEN
10448           -- Use Address Save function to see if the new address entered matches
10449           -- data for the shipto number.  If not that will insert new address for CRM
10450           SELECT SaveAddr(
10451             NULL,
10452             NULL,
10453             NEW.quhead_shiptoaddress1,
10454             NEW.quhead_shiptoaddress2,
10455             NEW.quhead_shiptoaddress3,
10456             NEW.quhead_shiptocity,
10457             NEW.quhead_shiptostate,
10458             NEW.quhead_shiptozipcode,
10459             NEW.quhead_shiptocountry,
10460             'CHANGEONE') INTO _addrId;
10461           SELECT shipto_addr_id INTO _shiptoid FROM shiptoinfo WHERE (shipto_id=NEW.quhead_shipto_id);
10462            -- If the address passed doesn't match shipto address, then it's something else
10463            IF (_shiptoid <> _addrId) THEN
10464              NEW.quhead_shipto_id := NULL;
10465            END IF;
10466         ELSE
10467           SELECT quhead_shipto_id INTO _shiptoid FROM quhead WHERE (quhead_id=NEW.quhead_id);
10468           -- Get the shipto address
10469             IF (COALESCE(NEW.quhead_shipto_id,-1) <> COALESCE(_shiptoid,-1)) THEN
10470             SELECT * INTO _a 
10471             FROM shiptoinfo
10472             LEFT OUTER JOIN cntct ON (shipto_cntct_id=cntct_id)
10473             LEFT OUTER JOIN addr ON (shipto_addr_id=addr_id)
10474             WHERE (shipto_id=NEW.quhead_shipto_id);
10475             IF (FOUND) THEN
10476               -- Free form not allowed so we're going to make sure address matches Shipto data
10477               NEW.quhead_shiptoname := COALESCE(_a.shipto_name,'');
10478               NEW.quhead_shiptophone := COALESCE(_a.cntct_phone,'');
10479               NEW.quhead_shiptoaddress1 := COALESCE(_a.addr_line1,'');
10480               NEW.quhead_shiptoaddress2 := COALESCE(_a.addr_line2,'');
10481               NEW.quhead_shiptoaddress3 := COALESCE(_a.addr_line3,'');    
10482               NEW.quhead_shiptocity := COALESCE(_a.addr_city,''); 
10483               NEW.quhead_shiptostate := COALESCE(_a.addr_state,'');
10484               NEW.quhead_shiptozipcode := COALESCE(_a.addr_postalcode,'');
10485               NEW.quhead_shiptocountry := COALESCE(_a.addr_country,''); 
10486             ELSE
10487               -- If no shipto data and free form not allowed, this won't work
10488               RAISE EXCEPTION 'Free form Shipto is not allowed on this Customer. You must supply a valid Shipto ID.';
10489             END IF;
10490           END IF;
10491         END IF;
10492       END IF;
10493     END IF;
10494   END IF;
10495
10496   IF ( SELECT (metric_value='t')
10497        FROM metric
10498        WHERE (metric_name='SalesOrderChangeLog') ) THEN
10499
10500 --  Cache the cmnttype_id for ChangeLog
10501     SELECT cmnttype_id INTO _cmnttypeid
10502     FROM cmnttype
10503     WHERE (cmnttype_name='ChangeLog');
10504     IF (FOUND) THEN
10505       IF (TG_OP = 'INSERT') THEN
10506         PERFORM postComment(_cmnttypeid, 'Q', NEW.quhead_id, 'Created');
10507
10508       ELSIF (TG_OP = 'UPDATE') THEN
10509
10510         IF (OLD.quhead_terms_id <> NEW.quhead_terms_id) THEN
10511           PERFORM postComment( _cmnttypeid, 'Q', NEW.quhead_id,
10512                                ('Terms Changed from "' || oldterms.terms_code || '" to "' || newterms.terms_code || '"') )
10513           FROM terms AS oldterms, terms AS newterms
10514           WHERE ( (oldterms.terms_id=OLD.quhead_terms_id)
10515            AND (newterms.terms_id=NEW.quhead_terms_id) );
10516         END IF;
10517
10518       ELSIF (TG_OP = 'DELETE') THEN
10519         DELETE FROM comment
10520         WHERE ( (comment_source='Q')
10521          AND (comment_source_id=OLD.quhead_id) );
10522       END IF;
10523     END IF;
10524   END IF;
10525
10526   IF (TG_OP = 'DELETE') THEN
10527     RETURN OLD;
10528   ELSE
10529     RETURN NEW;
10530   END IF;
10531
10532 END;
10533 $$;
10534
10535
10536 ALTER FUNCTION public._quheadtrigger() OWNER TO admin;
10537
10538 --
10539 -- TOC entry 1048 (class 1255 OID 146565564)
10540 -- Dependencies: 4536 8
10541 -- Name: _quitemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
10542 --
10543
10544 CREATE FUNCTION _quitemaftertrigger() RETURNS trigger
10545     LANGUAGE plpgsql
10546     AS $$
10547 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10548 -- See www.xtuple.com/CPAL for the full text of the software license.
10549 DECLARE
10550   _check NUMERIC;
10551 BEGIN
10552
10553   --If auto calculate freight, recalculate quhead_freight
10554   IF (SELECT quhead_calcfreight FROM quhead WHERE (quhead_id=NEW.quitem_quhead_id)) THEN
10555     UPDATE quhead SET quhead_freight =
10556       (SELECT SUM(freightdata_total) FROM freightDetail('QU',
10557                                                         quhead_id,
10558                                                         quhead_cust_id,
10559                                                         quhead_shipto_id,
10560                                                         quhead_quotedate,
10561                                                         quhead_shipvia,
10562                                                         quhead_curr_id))
10563     WHERE quhead_id=NEW.quitem_quhead_id;
10564   END IF;
10565
10566   RETURN NEW;
10567 END;
10568 $$;
10569
10570
10571 ALTER FUNCTION public._quitemaftertrigger() OWNER TO admin;
10572
10573 --
10574 -- TOC entry 1049 (class 1255 OID 146565565)
10575 -- Dependencies: 4536 8
10576 -- Name: _quitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
10577 --
10578
10579 CREATE FUNCTION _quitembeforetrigger() RETURNS trigger
10580     LANGUAGE plpgsql
10581     AS $$
10582 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10583 -- See www.xtuple.com/CPAL for the full text of the software license.
10584 DECLARE
10585   _check NUMERIC;
10586   _itemNumber TEXT;
10587 BEGIN
10588   -- Check
10589   IF (NEW.quitem_scheddate IS NULL) THEN
10590         RAISE EXCEPTION 'A schedule date is required.';
10591   END IF;
10592
10593   -- If this is imported, go ahead and insert default characteristics
10594    IF ((TG_OP = 'INSERT') AND NEW.quitem_imported) THEN
10595      PERFORM updateCharAssignment('SI', NEW.quitem_id, char_id, charass_value) 
10596      FROM (
10597        SELECT DISTINCT char_id, char_name, charass_value
10598        FROM charass, char, itemsite, item
10599        WHERE ((itemsite_id=NEW.quitem_itemsite_id)
10600        AND (itemsite_item_id=item_id)
10601        AND (charass_target_type='I') 
10602        AND (charass_target_id=item_id)
10603        AND (charass_default)
10604        AND (char_id=charass_char_id))
10605        ORDER BY char_name) AS data;
10606    END IF;
10607
10608   RETURN NEW;
10609 END;
10610 $$;
10611
10612
10613 ALTER FUNCTION public._quitembeforetrigger() OWNER TO admin;
10614
10615 --
10616 -- TOC entry 1050 (class 1255 OID 146565566)
10617 -- Dependencies: 4536 8
10618 -- Name: _quitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
10619 --
10620
10621 CREATE FUNCTION _quitemtrigger() RETURNS trigger
10622     LANGUAGE plpgsql
10623     AS $$
10624 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10625 -- See www.xtuple.com/CPAL for the full text of the software license.
10626 DECLARE
10627   _changelog BOOLEAN := FALSE;
10628   _check BOOLEAN;
10629
10630 BEGIN
10631   --  Checks
10632   SELECT checkPrivilege('MaintainQuotes') INTO _check;
10633   IF NOT (_check) THEN
10634     RAISE EXCEPTION 'You do not have privileges to maintain Quotes.';
10635   END IF;
10636
10637   IF ( SELECT fetchMetricBool('SalesOrderChangeLog') ) THEN
10638     _changelog := TRUE;
10639   END IF;
10640
10641   IF (TG_OP = 'INSERT') THEN
10642     IF (_changelog) THEN
10643       PERFORM postComment('ChangeLog', 'QI', NEW.quitem_id, 'Created');
10644     END IF;
10645
10646     RETURN NEW;
10647   END IF;
10648
10649   IF (TG_OP = 'DELETE') THEN
10650     DELETE FROM comment
10651     WHERE ( (comment_source='QI')
10652      AND (comment_source_id=OLD.quitem_id) );
10653
10654     DELETE FROM charass
10655      WHERE ((charass_target_type='QI')
10656        AND  (charass_target_id=OLD.quitem_id));
10657  
10658     RETURN OLD;
10659   END IF;
10660
10661   IF (TG_OP = 'UPDATE') THEN
10662     IF (_changelog) THEN
10663       IF (NEW.quitem_qtyord <> OLD.quitem_qtyord) THEN
10664         PERFORM postComment( 'ChangeLog', 'QI', NEW.quitem_id,
10665                              ( 'Changed Qty. Ordered from ' || formatQty(OLD.quitem_qtyord) ||
10666                                ' to ' || formatQty(NEW.quitem_qtyord) ) );
10667       END IF;
10668
10669       IF (NEW.quitem_price <> OLD.quitem_price) THEN
10670         PERFORM postComment( 'ChangeLog', 'QI', NEW.quitem_id,
10671                              ( 'Changed Unit Price from ' || formatPrice(OLD.quitem_price) ||
10672                                ' to ' || formatPrice(NEW.quitem_price) ) );
10673       END IF;
10674
10675       IF (NEW.quitem_scheddate <> OLD.quitem_scheddate) THEN
10676         PERFORM postComment( 'ChangeLog', 'QI', NEW.quitem_id,
10677                              ( 'Changed Sched. Date from ' || formatDate(OLD.quitem_scheddate) ||
10678                                ' to ' || formatDate(NEW.quitem_scheddate)) );
10679       END IF;
10680     END IF;
10681   END IF;
10682
10683 --  NEW.quitem_lastupdated = CURRENT_TIMESTAMP;
10684
10685   RETURN NEW;
10686
10687 END;
10688 $$;
10689
10690
10691 ALTER FUNCTION public._quitemtrigger() OWNER TO admin;
10692
10693 --
10694 -- TOC entry 1051 (class 1255 OID 146565567)
10695 -- Dependencies: 4536 8
10696 -- Name: _recuraftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
10697 --
10698
10699 CREATE FUNCTION _recuraftertrigger() RETURNS trigger
10700     LANGUAGE plpgsql
10701     AS $$
10702 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10703 -- See www.xtuple.com/CPAL for the full text of the software license.
10704 DECLARE
10705   _parentid   INTEGER;
10706   _parenttype TEXT;
10707 BEGIN
10708   IF (TG_OP = 'DELETE') THEN
10709     IF (UPPER(OLD.recur_parent_type) = 'TODO') THEN
10710       UPDATE todoitem SET todoitem_recurring_todoitem_id=NULL
10711        WHERE (todoitem_recurring_todoitem_id=OLD.recur_parent_id);
10712     END IF;
10713
10714     RETURN OLD;
10715   END IF;
10716
10717   RETURN NEW;
10718 END;
10719 $$;
10720
10721
10722 ALTER FUNCTION public._recuraftertrigger() OWNER TO admin;
10723
10724 --
10725 -- TOC entry 1052 (class 1255 OID 146565568)
10726 -- Dependencies: 4536 8
10727 -- Name: _reporttrigger(); Type: FUNCTION; Schema: public; Owner: admin
10728 --
10729
10730 CREATE FUNCTION _reporttrigger() RETURNS trigger
10731     LANGUAGE plpgsql
10732     AS $$
10733 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10734 -- See www.xtuple.com/CPAL for the full text of the software license.
10735 BEGIN
10736
10737   NEW.report_loaddate = CURRENT_TIMESTAMP;
10738   RETURN NEW;
10739
10740 END;
10741 $$;
10742
10743
10744 ALTER FUNCTION public._reporttrigger() OWNER TO admin;
10745
10746 --
10747 -- TOC entry 1053 (class 1255 OID 146565569)
10748 -- Dependencies: 4536 8
10749 -- Name: _salesrepafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
10750 --
10751
10752 CREATE FUNCTION _salesrepafterdeletetrigger() RETURNS trigger
10753     LANGUAGE plpgsql
10754     AS $$
10755 BEGIN
10756   IF (SELECT fetchMetricValue('DefaultSalesRep') = OLD.salesrep_id) THEN
10757     RAISE EXCEPTION 'Cannot delete the default Sales Rep [xtuple: salesrep, -1, %]',
10758                     OLD.salesrep_number;
10759   END IF;
10760
10761   PERFORM postComment('ChangeLog', 'SR', OLD.salesrep_id,
10762                       'Deleted "' || OLD.salesrep_number || '"');
10763
10764   RETURN OLD;
10765 END;
10766 $$;
10767
10768
10769 ALTER FUNCTION public._salesrepafterdeletetrigger() OWNER TO admin;
10770
10771 --
10772 -- TOC entry 1054 (class 1255 OID 146565570)
10773 -- Dependencies: 4536 8
10774 -- Name: _salesrepaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
10775 --
10776
10777 CREATE FUNCTION _salesrepaftertrigger() RETURNS trigger
10778     LANGUAGE plpgsql
10779     AS $$
10780 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10781 -- See www.xtuple.com/CPAL for the full text of the software license.
10782 DECLARE
10783
10784 BEGIN
10785
10786   IF (TG_OP = 'INSERT') THEN
10787     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
10788     LOOP
10789       UPDATE crmacct SET crmacct_salesrep_id=NEW.salesrep_id,
10790                          crmacct_name=NEW.salesrep_name
10791       WHERE crmacct_number=NEW.salesrep_number;
10792       IF (FOUND) THEN
10793         EXIT;
10794       END IF;
10795       BEGIN
10796         INSERT INTO crmacct(crmacct_number,      crmacct_name,      crmacct_active,
10797                             crmacct_type,        crmacct_salesrep_id
10798                   ) VALUES (NEW.salesrep_number, NEW.salesrep_name, NEW.salesrep_active,
10799                             'I',                 NEW.salesrep_id);
10800         EXIT;
10801       EXCEPTION WHEN unique_violation THEN
10802             -- do nothing, and loop to try the UPDATE again
10803       END;
10804     END LOOP;
10805
10806     -- TODO: default characteristic assignments?
10807
10808   ELSIF (TG_OP = 'UPDATE') THEN
10809     UPDATE crmacct SET crmacct_number = NEW.salesrep_number
10810     WHERE ((crmacct_salesrep_id=NEW.salesrep_id)
10811       AND  (crmacct_number!=NEW.salesrep_number));
10812
10813     UPDATE crmacct SET crmacct_name = NEW.salesrep_name
10814     WHERE ((crmacct_salesrep_id=NEW.salesrep_id)
10815       AND  (crmacct_name!=NEW.salesrep_name));
10816   END IF;
10817
10818   IF (fetchMetricBool('SalesRepChangeLog')) THEN
10819       IF (TG_OP = 'INSERT') THEN
10820         PERFORM postComment('ChangeLog', 'SR', NEW.salesrep_id, 'Created');
10821
10822       ELSIF (TG_OP = 'UPDATE') THEN
10823         IF (OLD.salesrep_active <> NEW.salesrep_active) THEN
10824           PERFORM postComment('ChangeLog', 'SR', NEW.salesrep_id,
10825                               CASE WHEN NEW.salesrep_active THEN 'Activated'
10826                                    ELSE 'Deactivated' END);
10827         END IF;
10828
10829         IF (OLD.salesrep_number <> NEW.salesrep_number) THEN
10830           PERFORM postComment('ChangeLog', 'SR', NEW.salesrep_id,
10831                               'Number changed from "' || OLD.salesrep_number ||
10832                               '" to "' || NEW.salesrep_number || '"');
10833         END IF;
10834
10835         IF (OLD.salesrep_name <> NEW.salesrep_name) THEN
10836           PERFORM postComment('ChangeLog', 'SR', NEW.salesrep_id,
10837                               'Name changed from "' || OLD.salesrep_name ||
10838                               '" to "' || NEW.salesrep_name || '"');
10839         END IF;
10840
10841         IF (OLD.salesrep_commission <> NEW.salesrep_commission) THEN
10842           PERFORM postComment('ChangeLog', 'SR', NEW.salesrep_id,
10843                               'Commission changed from "' || OLD.salesrep_commission ||
10844                               '" to "' || NEW.salesrep_commission || '"');
10845         END IF;
10846
10847         IF (OLD.salesrep_method <> NEW.salesrep_method) THEN
10848           PERFORM postComment('ChangeLog', 'SR', NEW.salesrep_id,
10849                               'Method changed from "' || OLD.salesrep_method ||
10850                               '" to "' || NEW.salesrep_method || '"');
10851         END IF;
10852
10853     END IF;
10854   END IF;
10855
10856   RETURN NEW;
10857 END;
10858 $$;
10859
10860
10861 ALTER FUNCTION public._salesrepaftertrigger() OWNER TO admin;
10862
10863 --
10864 -- TOC entry 1055 (class 1255 OID 146565571)
10865 -- Dependencies: 4536 8
10866 -- Name: _salesrepbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
10867 --
10868
10869 CREATE FUNCTION _salesrepbeforetrigger() RETURNS trigger
10870     LANGUAGE plpgsql
10871     AS $$
10872 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10873 -- See www.xtuple.com/CPAL for the full text of the software license.
10874 BEGIN
10875
10876   IF NOT (checkPrivilege('MaintainSalesReps')) THEN
10877     RAISE EXCEPTION 'You do not have privileges to maintain Sales Reps.';
10878   END IF;
10879
10880   IF (TG_OP IN ('INSERT', 'UPDATE')) THEN
10881     IF (NEW.salesrep_number IS NULL) THEN
10882       RAISE EXCEPTION 'You must supply a valid Sales Rep Number.';
10883     END IF;
10884
10885     IF (NEW.salesrep_commission IS NULL) THEN
10886       RAISE EXCEPTION 'You must supply a Commission Rate for this Sales Rep.';
10887     END IF;
10888
10889     IF (TG_OP = 'INSERT' AND fetchMetricText('CRMAccountNumberGeneration') IN ('A','O') AND isNumeric(NEW.salesrep_number)) THEN
10890       --- clear the number from the issue cache
10891       PERFORM clearNumberIssue('CRMAccountNumber', NEW.salesrep_number);
10892     END IF;
10893
10894     NEW.salesrep_number = UPPER(NEW.salesrep_number);
10895
10896     -- deprecated column salesrep_emp_id
10897     -- TODO: will this prevent breaking the crmacct-emp relationship?
10898     IF (TG_OP = 'UPDATE') THEN
10899       SELECT crmacct_emp_id INTO NEW.salesrep_emp_id
10900         FROM crmacct
10901        WHERE crmacct_salesrep_id = NEW.salesrep_id;
10902     END IF;
10903
10904   ELSIF (TG_OP = 'DELETE') THEN
10905     UPDATE crmacct SET crmacct_salesrep_id = NULL
10906      WHERE crmacct_salesrep_id = OLD.salesrep_id;
10907     RETURN OLD;
10908   END IF;
10909
10910   RETURN NEW;
10911 END;
10912 $$;
10913
10914
10915 ALTER FUNCTION public._salesrepbeforetrigger() OWNER TO admin;
10916
10917 --
10918 -- TOC entry 1058 (class 1255 OID 146565572)
10919 -- Dependencies: 4536 8
10920 -- Name: _saletypebeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
10921 --
10922
10923 CREATE FUNCTION _saletypebeforedeletetrigger() RETURNS trigger
10924     LANGUAGE plpgsql
10925     AS $$
10926 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10927 -- See www.xtuple.com/CPAL for the full text of the software license.
10928 DECLARE
10929   _check TEXT;
10930
10931 BEGIN
10932 --  Check to see if any sales orders are assigned to the passed saletype
10933   SELECT cohead_number INTO _check
10934   FROM cohead
10935   WHERE (cohead_saletype_id=OLD.saletype_id)
10936   LIMIT 1;
10937   IF (FOUND) THEN
10938     RAISE EXCEPTION 'Assigned to Sales Order % and possibly more. [xtuple: deletesaletype, -1]', _check;
10939   END IF;
10940
10941 --  Check to see if any quotes are assigned to the passed saletype
10942   SELECT quhead_number INTO _check
10943   FROM quhead
10944   WHERE (quhead_saletype_id=OLD.saletype_id)
10945   LIMIT 1;
10946   IF (FOUND) THEN
10947     RAISE EXCEPTION 'Assigned to Quote % and possibly more. [xtuple: deletesaletype, -2]', _check;
10948   END IF;
10949
10950 --  Check to see if any invoice are assigned to the passed saletype
10951   SELECT invchead_invcnumber INTO _check
10952   FROM invchead
10953   WHERE (invchead_saletype_id=OLD.saletype_id)
10954   LIMIT 1;
10955   IF (FOUND) THEN
10956     RAISE EXCEPTION 'Assigned to Invoice % and possibly more. [xtuple: deletesaletype, -3]', _check;
10957   END IF;
10958
10959 --  Check to see if any credit memos are assigned to the passed saletype
10960   SELECT cmhead_number INTO _check
10961   FROM cmhead
10962   WHERE (cmhead_saletype_id=OLD.saletype_id)
10963   LIMIT 1;
10964   IF (FOUND) THEN
10965     RAISE EXCEPTION 'Assigned to Credit Memo % and possibly more. [xtuple: deletesaletype, -4]', _check;
10966   END IF;
10967
10968 --  Check to see if any return ruthorizations are assigned to the passed saletype
10969   IF (fetchMetricBool('EnableReturnAuth')) THEN
10970     SELECT rahead_number INTO _check
10971     FROM rahead
10972     WHERE (rahead_saletype_id=OLD.saletype_id)
10973     LIMIT 1;
10974     IF (FOUND) THEN
10975       RAISE EXCEPTION 'Assigned to Return Authorization % and possibly more returns. [xtuple: deleteSaleType, -5]', _check;
10976     END IF;
10977   END IF;
10978
10979   RETURN OLD;
10980 END;
10981 $$;
10982
10983
10984 ALTER FUNCTION public._saletypebeforedeletetrigger() OWNER TO admin;
10985
10986 --
10987 -- TOC entry 1059 (class 1255 OID 146565573)
10988 -- Dependencies: 4536 8
10989 -- Name: _shipdatasumtrigger(); Type: FUNCTION; Schema: public; Owner: admin
10990 --
10991
10992 CREATE FUNCTION _shipdatasumtrigger() RETURNS trigger
10993     LANGUAGE plpgsql
10994     AS $$
10995 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
10996 -- See www.xtuple.com/CPAL for the full text of the software license.
10997 BEGIN
10998
10999   IF (LENGTH(TRIM(NEW.shipdatasum_shiphead_number)) = 0) THEN
11000     NEW.shipdatasum_shiphead_number = NULL;
11001   END IF;
11002
11003   RETURN NEW;
11004
11005 END;
11006 $$;
11007
11008
11009 ALTER FUNCTION public._shipdatasumtrigger() OWNER TO admin;
11010
11011 --
11012 -- TOC entry 1060 (class 1255 OID 146565574)
11013 -- Dependencies: 4536 8
11014 -- Name: _shipdatatrigger(); Type: FUNCTION; Schema: public; Owner: admin
11015 --
11016
11017 CREATE FUNCTION _shipdatatrigger() RETURNS trigger
11018     LANGUAGE plpgsql
11019     AS $$
11020 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11021 -- See www.xtuple.com/CPAL for the full text of the software license.
11022 DECLARE
11023   _newShipdata_cohead_number    INTEGER;
11024   _shipdatasum_shipper          TEXT;
11025   _rows                         INTEGER;
11026   _cohead_id                    INTEGER;
11027   _shiphead_number              TEXT;
11028   _headcount                    INTEGER;
11029
11030 BEGIN
11031   --  This is where the shipper is identified and may need to be changed
11032   NEW.shipdata_cohead_number := TRIM(NEW.shipdata_cohead_number);
11033
11034   IF (substring(NEW.shipdata_cosmisc_tracknum from 1 for 2) = '1Z') THEN
11035     _shipdatasum_shipper := 'UPS';
11036   ELSE
11037     _shipdatasum_shipper := 'UNKNOWN';
11038   END IF;
11039
11040   IF (LENGTH(TRIM(NEW.shipdata_shiphead_number)) = 0) THEN
11041     NEW.shipdata_shiphead_number := NULL;
11042   END IF;
11043
11044   IF (NEW.shipdata_cosmisc_tracknum = NEW.shipdata_cosmisc_packnum_tracknum) THEN
11045     IF (NEW.shipdata_void_ind = 'Y') THEN
11046       --  Delete the current shipdatasum
11047       DELETE FROM shipdatasum
11048       WHERE ((shipdatasum_cohead_number = NEW.shipdata_cohead_number)
11049         AND  (shipdatasum_cosmisc_tracknum = NEW.shipdata_cosmisc_tracknum));
11050
11051     ELSIF (TG_OP = 'INSERT') THEN
11052
11053 --      RAISE NOTICE 'Getting cohead_id (%)', NEW.shipdata_cohead_number;
11054       IF (NEW.shipdata_shiphead_number IS NULL) THEN
11055         SELECT cohead_id INTO _cohead_id FROM cohead WHERE cohead_number = NEW.shipdata_cohead_number;
11056
11057         IF (FOUND) THEN
11058
11059 --          RAISE NOTICE 'Getting shiphead number (%)', _cohead_id;
11060           SELECT count(shiphead_order_id), MAX(shiphead_number) INTO _headcount, _shiphead_number 
11061           FROM shiphead 
11062           WHERE ((shiphead_tracknum IS NULL OR shiphead_tracknum = '') 
11063           AND ( shiphead_order_type = 'SO' and shiphead_order_id = _cohead_id) );
11064           
11065           IF (_headcount = 1) THEN
11066 --            RAISE NOTICE 'Updating Shiphead Number (%)', _shiphead_number;
11067             NEW.shipdata_shiphead_number = _shiphead_number;
11068             
11069           ELSIF (_headcount > 1) THEN
11070             -- Trap for potential workflow problem.  Can only infer shiphead from sales order number 
11071             -- if shipping one at a time
11072             RAISE EXCEPTION 'Multiple shipments exist for this order.  Please provide a specific a shipment number.';
11073           END IF;
11074         END IF;
11075       END IF;
11076
11077       INSERT INTO shipdatasum
11078               (shipdatasum_cohead_number, shipdatasum_cosmisc_tracknum,
11079                shipdatasum_cosmisc_packnum_tracknum, shipdatasum_weight,
11080                shipdatasum_base_freight, shipdatasum_total_freight,
11081                shipdatasum_base_freight_curr_id, shipdatasum_total_freight_curr_id,
11082                shipdatasum_shipper, shipdatasum_billing_option,
11083                shipdatasum_package_type, shipdatasum_shiphead_number)
11084        VALUES (NEW.shipdata_cohead_number, NEW.shipdata_cosmisc_tracknum,
11085                NEW.shipdata_cosmisc_packnum_tracknum, NEW.shipdata_weight,
11086                NEW.shipdata_base_freight, NEW.shipdata_total_freight,
11087                NEW.shipdata_base_freight_curr_id, NEW.shipdata_total_freight_curr_id,
11088                _shipdatasum_shipper, NEW.shipdata_billing_option,
11089                NEW.shipdata_package_type, NEW.shipdata_shiphead_number);
11090
11091     ELSIF (TG_OP = 'UPDATE') THEN
11092        UPDATE shipdatasum SET
11093               shipdatasum_cohead_number=NEW.shipdata_cohead_number,
11094               shipdatasum_cosmisc_tracknum=NEW.shipdata_cosmisc_tracknum,
11095               shipdatasum_cosmisc_packnum_tracknum=NEW.shipdata_cosmisc_packnum_tracknum,
11096               shipdatasum_weight=NEW.shipdata_weight,
11097               shipdatasum_base_freight=NEW.shipdata_base_freight,
11098               shipdatasum_total_freight=NEW.shipdata_total_freight,
11099               shipdatasum_base_freight_curr_id=NEW.shipdata_base_freight_curr_id,
11100               shipdatasum_total_freight_curr_id=NEW.shipdata_total_freight_curr_id,
11101               shipdatasum_shipper=_shipdatasum_shipper,
11102               shipdatasum_billing_option=NEW.shipdata_billing_option,
11103               shipdatasum_package_type=NEW.shipdata_package_type,
11104               shipdatasum_shiphead_number=NEW.shipdata_shiphead_number
11105        WHERE ((TRIM(shipdatasum_cohead_number)=TRIM(OLD.shipdata_cohead_number))
11106           AND (TRIM(shipdatasum_cosmisc_tracknum)=TRIM(OLD.shipdata_cosmisc_tracknum))
11107           AND (TRIM(shipdatasum_cosmisc_packnum_tracknum)=TRIM(OLD.shipdata_cosmisc_packnum_tracknum)));
11108
11109        GET DIAGNOSTICS _rows = ROW_COUNT;
11110        IF (_rows <= 0) THEN
11111          INSERT INTO shipdatasum
11112                 (shipdatasum_cohead_number, shipdatasum_cosmisc_tracknum,
11113                  shipdatasum_cosmisc_packnum_tracknum, shipdatasum_weight,
11114                  shipdatasum_base_freight, shipdatasum_total_freight,
11115                  shipdatasum_base_freight_curr_id, shipdatasum_total_freight_curr_id,
11116                  shipdatasum_shipper, shipdatasum_billing_option,
11117                  shipdatasum_package_type, shipdatasum_shiphead_number)
11118          VALUES (NEW.shipdata_cohead_number, NEW.shipdata_cosmisc_tracknum,
11119                  NEW.shipdata_cosmisc_packnum_tracknum, NEW.shipdata_weight,
11120                  NEW.shipdata_base_freight, NEW.shipdata_total_freight,
11121                  NEW.shipdata_base_freight_curr_id, NEW.shipdata_total_freight_curr_id,
11122                  _shipdatasum_shipper, NEW.shipdata_billing_option,
11123                  NEW.shipdata_package_type, NEW.shipdata_shiphead_number);
11124        END IF;
11125     END IF;
11126   END IF;
11127
11128   RETURN NEW;
11129
11130 END;
11131 $$;
11132
11133
11134 ALTER FUNCTION public._shipdatatrigger() OWNER TO admin;
11135
11136 --
11137 -- TOC entry 1061 (class 1255 OID 146565575)
11138 -- Dependencies: 4536 8
11139 -- Name: _shipformafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
11140 --
11141
11142 CREATE FUNCTION _shipformafterdeletetrigger() RETURNS trigger
11143     LANGUAGE plpgsql
11144     AS $$
11145 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11146 -- See www.xtuple.com/CPAL for the full text of the software license.
11147 BEGIN
11148   IF (fetchMetricValue('DefaultShipFormId') = OLD.shipform_id) THEN
11149     RAISE EXCEPTION 'Cannot delete the default Shipping Form [xtuple: shipform, -1, %, %]',
11150                     OLD.shipform_name, OLD.shipform_report_name;
11151   END IF;
11152
11153   RETURN OLD;
11154 END;
11155 $$;
11156
11157
11158 ALTER FUNCTION public._shipformafterdeletetrigger() OWNER TO admin;
11159
11160 --
11161 -- TOC entry 1062 (class 1255 OID 146565576)
11162 -- Dependencies: 4536 8
11163 -- Name: _shipheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
11164 --
11165
11166 CREATE FUNCTION _shipheadbeforetrigger() RETURNS trigger
11167     LANGUAGE plpgsql
11168     AS $$
11169 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11170 -- See www.xtuple.com/CPAL for the full text of the software license.
11171 BEGIN
11172   IF ((TG_OP = 'INSERT') OR (TG_OP = 'UPDATE')) THEN
11173
11174     IF (NEW.shiphead_order_type = 'SO'
11175         AND NEW.shiphead_order_id   IN (SELECT cohead_id FROM cohead)) THEN
11176       RETURN NEW;
11177
11178     ELSEIF (NEW.shiphead_order_type = 'TO'
11179         AND NEW.shiphead_order_id   IN (SELECT tohead_id FROM tohead)) THEN
11180       RETURN NEW;
11181
11182     END IF;
11183
11184     RAISE EXCEPTION '% with id % does not exist',
11185                     NEW.shiphead_order_type, NEW.shiphead_order_id;
11186     RETURN OLD;
11187
11188   END IF;
11189
11190   RETURN NEW;
11191 END;
11192 $$;
11193
11194
11195 ALTER FUNCTION public._shipheadbeforetrigger() OWNER TO admin;
11196
11197 --
11198 -- TOC entry 1063 (class 1255 OID 146565577)
11199 -- Dependencies: 4536 8
11200 -- Name: _shiptoinfoaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
11201 --
11202
11203 CREATE FUNCTION _shiptoinfoaftertrigger() RETURNS trigger
11204     LANGUAGE plpgsql
11205     AS $$
11206 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11207 -- See www.xtuple.com/CPAL for the full text of the software license.
11208 DECLARE
11209   _cmnttypeid INTEGER;
11210
11211 BEGIN
11212   IF (NEW.shipto_default) THEN
11213     UPDATE shiptoinfo
11214     SET shipto_default = false
11215     WHERE ((shipto_cust_id=NEW.shipto_cust_id)
11216     AND (shipto_id <> NEW.shipto_id));
11217   END IF;
11218
11219   IF (SELECT fetchMetricBool('CustomerChangeLog')) THEN
11220 --  Cache the cmnttype_id for ChangeLog
11221     SELECT cmnttype_id INTO _cmnttypeid
11222     FROM cmnttype
11223     WHERE (cmnttype_name='ChangeLog');
11224     IF (FOUND) THEN
11225       IF (TG_OP = 'INSERT') THEN
11226         PERFORM postComment(_cmnttypeid, 'C', NEW.shipto_cust_id, 'Created');
11227
11228       ELSIF (TG_OP = 'UPDATE') THEN
11229         IF (OLD.shipto_name <> NEW.shipto_name) THEN
11230           PERFORM postComment( _cmnttypeid, 'C', NEW.shipto_cust_id,
11231                                ( NEW.shipto_name || ': Ship To Name Changed from "' || COALESCE(OLD.shipto_name, '') ||
11232                                  '" to "' || COALESCE(NEW.shipto_name, '') || '"' ) );
11233         END IF;
11234         IF (OLD.shipto_shipvia <> NEW.shipto_shipvia) THEN
11235           PERFORM postComment( _cmnttypeid, 'C', NEW.shipto_cust_id,
11236                                ( NEW.shipto_name || ': Ship To ShipVia Changed from "' || COALESCE(OLD.shipto_shipvia, '') ||
11237                                  '" to "' || COALESCE(NEW.shipto_shipvia, '') || '"' ) );
11238         END IF;
11239         IF (COALESCE(OLD.shipto_taxzone_id, -1) <> COALESCE(NEW.shipto_taxzone_id, -1)) THEN
11240           PERFORM postComment( _cmnttypeid, 'C', NEW.shipto_cust_id,
11241                                ( NEW.shipto_name || ': Ship To Tax Zone Changed from "' || COALESCE((SELECT taxzone_code
11242                                                                                             FROM taxzone
11243                                                                                             WHERE taxzone_id=OLD.shipto_taxzone_id), 'None') ||
11244                                  '" to "' || COALESCE((SELECT taxzone_code
11245                                               FROM taxzone
11246                                               WHERE taxzone_id=NEW.shipto_taxzone_id), 'None') || '"' ) );
11247         END IF;
11248         IF (OLD.shipto_shipzone_id <> NEW.shipto_shipzone_id) THEN
11249           PERFORM postComment( _cmnttypeid, 'C', NEW.shipto_cust_id,
11250                                ( NEW.shipto_name || ': Ship To Shipping Zone Changed from "' || (SELECT shipzone_name
11251                                                                                                  FROM shipzone
11252                                                                                                  WHERE shipzone_id=OLD.shipto_shipzone_id) ||
11253                                  '" to "' || (SELECT shipzone_name
11254                                               FROM shipzone
11255                                               WHERE shipzone_id=NEW.shipto_shipzone_id) || '"' ) );
11256         END IF;
11257         IF (OLD.shipto_salesrep_id <> NEW.shipto_salesrep_id) THEN
11258           PERFORM postComment( _cmnttypeid, 'C', NEW.shipto_cust_id,
11259                                ( NEW.shipto_name || ': Ship To Sales Rep Changed from "' || (SELECT salesrep_name
11260                                                                                              FROM salesrep
11261                                                                                              WHERE salesrep_id=OLD.shipto_salesrep_id) ||
11262                                  '" to "' || (SELECT salesrep_name
11263                                               FROM salesrep
11264                                               WHERE salesrep_id=NEW.shipto_salesrep_id) || '"' ) );
11265         END IF;
11266         IF (OLD.shipto_active <> NEW.shipto_active) THEN
11267           IF (NEW.shipto_active) THEN
11268             PERFORM postComment(_cmnttypeid, 'C', NEW.shipto_cust_id, (NEW.shipto_name || ': Ship To Activated'));
11269           ELSE
11270             PERFORM postComment(_cmnttypeid, 'C', NEW.shipto_cust_id, (NEW.shipto_name || ': Ship To Deactivated'));
11271           END IF;
11272         END IF;
11273       END IF;
11274     END IF;
11275   END IF;
11276
11277   RETURN NEW;
11278 END;
11279 $$;
11280
11281
11282 ALTER FUNCTION public._shiptoinfoaftertrigger() OWNER TO admin;
11283
11284 --
11285 -- TOC entry 1064 (class 1255 OID 146565578)
11286 -- Dependencies: 4536 8
11287 -- Name: _shipviaafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
11288 --
11289
11290 CREATE FUNCTION _shipviaafterdeletetrigger() RETURNS trigger
11291     LANGUAGE plpgsql
11292     AS $$
11293 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11294 -- See www.xtuple.com/CPAL for the full text of the software license.
11295 BEGIN
11296   IF (SELECT fetchMetricValue('DefaultShipViaId') = OLD.shipvia_id) THEN
11297     RAISE EXCEPTION 'Cannot delete the default Ship-Via [xtuple: shipvia, -1, %]',
11298                     OLD.shipvia_code;
11299   END IF;
11300
11301   RETURN OLD;
11302 END;
11303 $$;
11304
11305
11306 ALTER FUNCTION public._shipviaafterdeletetrigger() OWNER TO admin;
11307
11308 --
11309 -- TOC entry 1065 (class 1255 OID 146565579)
11310 -- Dependencies: 4536 8
11311 -- Name: _sltransaltertrigger(); Type: FUNCTION; Schema: public; Owner: admin
11312 --
11313
11314 CREATE FUNCTION _sltransaltertrigger() RETURNS trigger
11315     LANGUAGE plpgsql
11316     AS $$
11317 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11318 -- See www.xtuple.com/CPAL for the full text of the software license.
11319 DECLARE
11320   _externalCompany      BOOLEAN := false;
11321   _updated BOOLEAN := false;
11322 BEGIN
11323   IF(TG_OP='DELETE') THEN
11324     RAISE EXCEPTION 'You may not delete Journal Transactions once they have been created.';
11325   ELSIF (TG_OP = 'UPDATE') THEN 
11326     IF(OLD.sltrans_id != NEW.sltrans_id) THEN
11327       _updated := true;
11328     ELSIF(OLD.sltrans_date != NEW.sltrans_date) THEN
11329       _updated := true;
11330     ELSIF(OLD.sltrans_accnt_id != NEW.sltrans_accnt_id) THEN
11331       _updated := true;
11332     ELSIF(OLD.sltrans_amount != NEW.sltrans_amount) THEN
11333       _updated := true;
11334     ELSIF(OLD.sltrans_username != NEW.sltrans_username) THEN
11335       _updated := true;
11336     ELSIF( (OLD.sltrans_sequence IS NULL     AND NEW.sltrans_sequence IS NOT NULL)
11337         OR (OLD.sltrans_sequence IS NOT NULL AND NEW.sltrans_sequence IS NULL)
11338         OR (COALESCE(OLD.sltrans_sequence,0) != COALESCE(NEW.sltrans_sequence,0)) ) THEN
11339       _updated := true;
11340     ELSIF( (OLD.sltrans_created IS NULL     AND NEW.sltrans_created IS NOT NULL)
11341         OR (OLD.sltrans_created IS NOT NULL AND NEW.sltrans_created IS NULL)
11342         OR (COALESCE(OLD.sltrans_created,now()) != COALESCE(NEW.sltrans_created,now())) ) THEN
11343       _updated := true;
11344     ELSIF( (OLD.sltrans_source IS NULL     AND NEW.sltrans_source IS NOT NULL)
11345         OR (OLD.sltrans_source IS NOT NULL AND NEW.sltrans_source IS NULL)
11346         OR (COALESCE(OLD.sltrans_source,'') != COALESCE(NEW.sltrans_source,'')) ) THEN
11347       _updated := true;
11348     ELSIF( (OLD.sltrans_docnumber IS NULL     AND NEW.sltrans_docnumber IS NOT NULL)
11349         OR (OLD.sltrans_docnumber IS NOT NULL AND NEW.sltrans_docnumber IS NULL)
11350         OR (COALESCE(OLD.sltrans_docnumber,'') != COALESCE(NEW.sltrans_docnumber,'')) ) THEN
11351       _updated := true;
11352     ELSIF( (OLD.sltrans_doctype IS NULL     AND NEW.sltrans_doctype IS NOT NULL)
11353         OR (OLD.sltrans_doctype IS NOT NULL AND NEW.sltrans_doctype IS NULL)
11354         OR (COALESCE(OLD.sltrans_doctype,'') != COALESCE(NEW.sltrans_doctype,'')) ) THEN
11355       _updated := true;
11356     END IF;
11357
11358     IF(_updated) THEN
11359       RAISE EXCEPTION 'You may not alter some Journal Transaction fields once they have been created.';
11360     END IF;
11361   ELSE
11362     RAISE EXCEPTION 'trigger for sltrans table called in unexpected state.';
11363   END IF;
11364   RETURN NEW;
11365 END;
11366 $$;
11367
11368
11369 ALTER FUNCTION public._sltransaltertrigger() OWNER TO admin;
11370
11371 --
11372 -- TOC entry 1047 (class 1255 OID 146565580)
11373 -- Dependencies: 4536 8
11374 -- Name: _sltransinserttrigger(); Type: FUNCTION; Schema: public; Owner: admin
11375 --
11376
11377 CREATE FUNCTION _sltransinserttrigger() RETURNS trigger
11378     LANGUAGE plpgsql
11379     AS $$
11380 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11381 -- See www.xtuple.com/CPAL for the full text of the software license.
11382 DECLARE
11383   _reqNotes BOOLEAN;
11384   _externalCompany      BOOLEAN := false;
11385 BEGIN
11386   -- Checks
11387   SELECT company_external INTO _externalCompany
11388   FROM company JOIN accnt ON (company_number=accnt_company)
11389   WHERE (accnt_id=NEW.sltrans_accnt_id);
11390   IF (_externalCompany) THEN
11391     RAISE EXCEPTION 'Transactions are not allowed for G/L Accounts with External Company segments.';
11392   END IF;
11393   
11394   RETURN NEW;
11395 END;
11396 $$;
11397
11398
11399 ALTER FUNCTION public._sltransinserttrigger() OWNER TO admin;
11400
11401 --
11402 -- TOC entry 1056 (class 1255 OID 146565581)
11403 -- Dependencies: 4536 8
11404 -- Name: _soheadtrigger(); Type: FUNCTION; Schema: public; Owner: admin
11405 --
11406
11407 CREATE FUNCTION _soheadtrigger() RETURNS trigger
11408     LANGUAGE plpgsql
11409     AS $$
11410 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11411 -- See www.xtuple.com/CPAL for the full text of the software license.
11412 DECLARE
11413   _p RECORD;
11414   _a RECORD;
11415   _w RECORD;
11416   _shiptoId INTEGER;
11417   _addrId INTEGER;
11418   _prjId INTEGER;
11419   _check BOOLEAN;
11420   _numGen CHAR(1);
11421
11422 BEGIN
11423
11424   -- Checks
11425   -- Start with privileges
11426   IF (TG_OP = 'INSERT') THEN
11427     IF ( (NOT checkPrivilege('MaintainSalesOrders')) AND
11428        (NOT checkPrivilege('EnterReceipts')) ) THEN
11429       RAISE EXCEPTION 'You do not have privileges to create a Sales Order.';
11430     END IF;
11431   ELSIF (TG_OP = 'UPDATE') THEN
11432     IF ( (NOT checkPrivilege('MaintainSalesOrders')) AND
11433          (NOT checkPrivilege('IssueStockToShipping')) AND
11434          (NEW.cohead_holdtype = OLD.cohead_holdtype) ) THEN
11435       RAISE EXCEPTION 'You do not have privileges to alter a Sales Order.';
11436     END IF;
11437   ELSE
11438     IF ( (NOT checkPrivilege('MaintainSalesOrders')) AND
11439          (NOT checkPrivilege('IssueStockToShipping')) ) THEN
11440       RAISE EXCEPTION 'You do not have privileges to alter a Sales Order.';
11441     END IF;
11442   END IF;
11443
11444   -- If this is imported, check the order number
11445   IF (TG_OP = 'INSERT') THEN
11446     IF (NEW.cohead_imported) THEN
11447       SELECT fetchMetricText('CONumberGeneration') INTO _numGen;
11448       IF ((NEW.cohead_number IS NULL) AND (_numGen='M')) THEN
11449         RAISE EXCEPTION 'You must supply an Order Number.';
11450       ELSE
11451         IF (NEW.cohead_number IS NULL) THEN
11452           SELECT fetchsonumber() INTO NEW.cohead_number;
11453         END IF;
11454       END IF;
11455     END IF;
11456
11457     IF (fetchMetricText('CONumberGeneration') IN ('A','O')) THEN
11458       --- clear the number from the issue cache
11459       PERFORM clearNumberIssue('SoNumber', NEW.cohead_number);
11460     END IF;
11461   ELSE
11462     IF (TG_OP = 'UPDATE') THEN
11463       IF (NEW.cohead_number <> OLD.cohead_number) THEN
11464         RAISE EXCEPTION 'The order number may not be changed.';
11465       END IF;
11466     END IF;
11467   END IF;
11468
11469   IF (TG_OP IN ('INSERT','UPDATE')) THEN
11470
11471     -- Get Customer data
11472     IF (NEW.cohead_shipto_id IS NULL) THEN
11473       SELECT cust_creditstatus,cust_number,cust_usespos,cust_blanketpos,cust_ffbillto,
11474              cust_ffshipto,cust_name,cust_salesrep_id,cust_terms_id,cust_shipvia,
11475              cust_shipchrg_id,cust_shipform_id,cust_commprcnt,cust_curr_id,cust_taxzone_id,
11476              cntct.*,addr.*,
11477              shipto_id,shipto_addr_id,shipto_name,shipto_salesrep_id,shipto_shipvia,
11478              shipto_shipchrg_id,shipto_shipform_id,shipto_commission,shipto_taxzone_id INTO _p
11479       FROM custinfo
11480         LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
11481         LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
11482         LEFT OUTER JOIN shiptoinfo ON ((cust_id=shipto_cust_id) AND shipto_default)
11483       WHERE (cust_id=NEW.cohead_cust_id);
11484     ELSE
11485       SELECT cust_creditstatus,cust_number,cust_usespos,cust_blanketpos,cust_ffbillto,
11486              cust_ffshipto,cust_name,cust_salesrep_id,cust_terms_id,cust_shipvia,
11487              cust_shipchrg_id,cust_shipform_id,cust_commprcnt,cust_curr_id,cust_taxzone_id,
11488              cntct.*,addr.*,
11489              shipto_id,shipto_addr_id,shipto_name,shipto_salesrep_id,shipto_shipvia,
11490              shipto_shipchrg_id,shipto_shipform_id,shipto_commission,shipto_taxzone_id INTO _p
11491       FROM shiptoinfo,custinfo
11492         LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
11493         LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
11494       WHERE ((cust_id=NEW.cohead_cust_id)
11495         AND  (shipto_id=NEW.cohead_shipto_id));
11496     END IF;
11497
11498     -- If there is customer data, then we can get to work
11499     IF (FOUND) THEN
11500
11501       -- Check Credit
11502       IF (TG_OP = 'INSERT') THEN
11503           IF (_p.cust_creditstatus = 'H') THEN
11504             SELECT checkPrivilege('CreateSOForHoldCustomer') INTO _check;
11505             IF NOT (_check) THEN
11506               RAISE EXCEPTION 'Customer % has been placed 
11507                                on a Credit Hold and you do not have 
11508                                privilege to create Sales Orders for 
11509                                Customers on Credit Hold.  The selected 
11510                                Customer must be taken off of Credit Hold 
11511                                before you may create a new Sales Order 
11512                                for the Customer.',_p.cust_number;
11513             ELSE
11514               NEW.cohead_holdtype='C';
11515             END IF;
11516           END IF;
11517           IF (_p.cust_creditstatus = 'W') THEN
11518             SELECT checkPrivilege('CreateSOForWarnCustomer') INTO _check;
11519             IF NOT (_check) THEN
11520               RAISE EXCEPTION 'Customer % has been placed on 
11521                               a Credit Warning and you do not have 
11522                               privilege to create Sales Orders for 
11523                               Customers on Credit Warning.  The 
11524                               selected Customer must be taken off of 
11525                               Credit Warning before you may create a 
11526                               new Sales Order for the Customer.',_p.cust_number;
11527             ELSE
11528               NEW.cohead_holdtype='C';
11529             END IF;
11530           END IF;
11531
11532           -- Set to defaults if values not provided
11533           NEW.cohead_shipto_id  := COALESCE(NEW.cohead_shipto_id,_p.shipto_id);
11534           NEW.cohead_terms_id           := COALESCE(NEW.cohead_terms_id,_p.cust_terms_id);
11535           NEW.cohead_orderdate          := COALESCE(NEW.cohead_orderdate,current_date);
11536           NEW.cohead_packdate           := COALESCE(NEW.cohead_packdate,NEW.cohead_orderdate);
11537           NEW.cohead_curr_id            := COALESCE(NEW.cohead_curr_id,_p.cust_curr_id,basecurrid());
11538           NEW.cohead_freight            := COALESCE(NEW.cohead_freight,0);
11539           NEW.cohead_custponumber       := COALESCE(NEW.cohead_custponumber,'');
11540           NEW.cohead_ordercomments      := COALESCE(NEW.cohead_ordercomments,'');
11541           NEW.cohead_shipcomments       := COALESCE(NEW.cohead_shipcomments,'');
11542           NEW.cohead_shiptophone        := COALESCE(NEW.cohead_shiptophone,'');
11543           NEW.cohead_misc               := COALESCE(NEW.cohead_misc,0);
11544           NEW.cohead_misc_descrip       := COALESCE(NEW.cohead_misc_descrip,'');
11545           NEW.cohead_shipcomplete       := COALESCE(NEW.cohead_shipcomplete,false);
11546
11547           IF (_p.shipto_id IS NOT NULL) THEN -- Pull in over ride values
11548             NEW.cohead_salesrep_id      := COALESCE(NEW.cohead_salesrep_id,_p.shipto_salesrep_id);
11549             NEW.cohead_shipvia          := COALESCE(NEW.cohead_shipvia,_p.shipto_shipvia);
11550             NEW.cohead_shipchrg_id      := COALESCE(NEW.cohead_shipchrg_id,_p.shipto_shipchrg_id);
11551             NEW.cohead_shipform_id      := COALESCE(NEW.cohead_shipform_id,_p.shipto_shipform_id);
11552             NEW.cohead_commission       := COALESCE(NEW.cohead_commission,_p.shipto_commission);
11553             IF (NEW.cohead_taxzone_id=-1) THEN
11554               NEW.cohead_taxzone_id     := NULL;
11555             ELSE
11556               NEW.cohead_taxzone_id     := COALESCE(NEW.cohead_taxzone_id,_p.shipto_taxzone_id);
11557             END IF;
11558           ELSE
11559             NEW.cohead_salesrep_id      := COALESCE(NEW.cohead_salesrep_id,_p.cust_salesrep_id);
11560             NEW.cohead_shipvia          := COALESCE(NEW.cohead_shipvia,_p.cust_shipvia);
11561             NEW.cohead_shipchrg_id      := COALESCE(NEW.cohead_shipchrg_id,_p.cust_shipchrg_id);
11562             NEW.cohead_shipform_id      := COALESCE(NEW.cohead_shipform_id,_p.cust_shipform_id);
11563             NEW.cohead_commission       := COALESCE(NEW.cohead_commission,_p.cust_commprcnt);
11564             IF (NEW.cohead_taxzone_id=-1) THEN
11565               NEW.cohead_taxzone_id     := NULL;
11566             ELSE
11567               NEW.cohead_taxzone_id     := COALESCE(NEW.cohead_taxzone_id,_p.cust_taxzone_id);
11568             END IF;
11569           END IF;
11570
11571           IF ((NEW.cohead_warehous_id IS NULL) OR (NEW.cohead_fob IS NULL)) THEN
11572             IF (NEW.cohead_warehous_id IS NULL) THEN
11573               SELECT warehous_id,warehous_fob INTO _w
11574               FROM usrpref, whsinfo
11575               WHERE ((warehous_id=CAST(usrpref_value AS INTEGER))
11576                 AND (warehous_shipping)
11577                 AND (warehous_active)
11578                 AND (usrpref_username=getEffectiveXtUser())
11579                 AND (usrpref_name='PreferredWarehouse'));
11580             ELSE
11581               SELECT warehous_id,warehous_fob INTO _w
11582               FROM whsinfo
11583               WHERE (warehous_id=NEW.cohead_warehous_id);
11584             END IF;
11585             
11586             IF (FOUND) THEN
11587               NEW.cohead_warehous_id    := COALESCE(NEW.cohead_warehous_id,_w.warehous_id);
11588               NEW.cohead_fob            := COALESCE(NEW.cohead_fob,_w.warehous_fob);
11589             END IF;
11590           END IF;
11591           
11592       END IF;
11593
11594       -- Only Check P/O logic for imports, because UI checks when entire order is saved
11595       IF (NEW.cohead_imported) THEN
11596
11597         -- Check for required Purchase Order
11598         IF (_p.cust_usespos AND ((NEW.cohead_custponumber IS NULL) OR (TRIM(BOTH FROM NEW.cohead_custponumber)=''))) THEN
11599             RAISE EXCEPTION 'You must enter a Customer P/O for this Sales Order.';
11600         END IF;
11601  
11602         -- Check for duplicate Purchase Orders if not allowed
11603         IF (_p.cust_usespos AND NOT (_p.cust_blanketpos)) THEN
11604           SELECT cohead_id INTO _a
11605           FROM cohead
11606           WHERE ((cohead_cust_id=NEW.cohead_cust_id)
11607           AND  (cohead_id<>NEW.cohead_id)
11608           AND  (UPPER(cohead_custponumber) = UPPER(NEW.cohead_custponumber)) )
11609           UNION
11610           SELECT quhead_id
11611           FROM quhead
11612           WHERE ((quhead_cust_id=NEW.cohead_cust_id)
11613           AND  (quhead_id<>NEW.cohead_id)
11614           AND  (UPPER(quhead_custponumber) = UPPER(NEW.cohead_custponumber)) );
11615           IF (FOUND) THEN
11616             RAISE EXCEPTION 'This Customer does not use Blanket P/O
11617                             Numbers and the P/O Number you entered has 
11618                             already been used for another Sales Order.
11619                             Please verify the P/O Number and either
11620                             enter a new P/O Number or add to the
11621                             existing Sales Order.';
11622          END IF;
11623         END IF;
11624       END IF;
11625
11626       --Auto create project if applicable
11627       IF ((TG_OP = 'INSERT') AND (COALESCE(NEW.cohead_prj_id,-1)=-1)) THEN
11628         SELECT fetchMetricBool('AutoCreateProjectsForOrders') INTO _check;
11629         IF (_check) THEN
11630           SELECT NEXTVAL('prj_prj_id_seq') INTO _prjId;
11631           NEW.cohead_prj_id := _prjId;
11632           INSERT INTO prj (prj_id, prj_number, prj_name, prj_descrip,
11633                            prj_status, prj_so, prj_wo, prj_po,
11634                            prj_owner_username, prj_start_date, prj_due_date,
11635                            prj_assigned_date, prj_completed_date, prj_username,
11636                            prj_recurring_prj_id, prj_crmacct_id,
11637                            prj_cntct_id, prj_prjtype_id)
11638           SELECT _prjId, NEW.cohead_number, NEW.cohead_number, 'Auto Generated Project from Sales Order.',
11639                  'O', TRUE, TRUE, TRUE,
11640                  getEffectiveXTUser(), NEW.cohead_orderdate, NEW.cohead_packdate,
11641                  NEW.cohead_orderdate, NULL, getEffectiveXTUser(),
11642                  NULL, crmacct_id,
11643                  NEW.cohead_billto_cntct_id, NULL
11644           FROM crmacct
11645           WHERE (crmacct_cust_id=NEW.cohead_cust_id);
11646         END IF;
11647       END IF;
11648
11649       IF (TG_OP = 'UPDATE') THEN
11650         SELECT true INTO _check
11651         FROM coitem
11652         WHERE ( (coitem_status='C')
11653         AND (coitem_cohead_id=NEW.cohead_id) ) 
11654         LIMIT 1;
11655
11656         IF (NOT FOUND) THEN
11657
11658         --Update project references on supply
11659         UPDATE pr SET pr_prj_id=NEW.cohead_prj_id
11660                    FROM coitem
11661                    WHERE ((coitem_cohead_id=NEW.cohead_id) 
11662                    AND  (coitem_order_type='R') 
11663                    AND  (coitem_order_id=pr_id));
11664
11665         PERFORM changeWoProject(coitem_order_id, NEW.cohead_prj_id, TRUE)
11666                     FROM coitem
11667                     WHERE ((coitem_cohead_id=NEW.cohead_id)
11668                     AND  (coitem_order_type='W'));
11669         ELSE
11670           IF NEW.cohead_prj_id <> COALESCE(OLD.cohead_prj_id,-1) THEN
11671             RAISE EXCEPTION 'You can not change the project ID on orders with closed lines.';
11672           END IF;
11673         END IF;
11674       END IF;
11675
11676       -- Deal with Billing Address
11677       IF (TG_OP = 'INSERT') THEN
11678         IF (_p.cust_ffbillto) THEN
11679           -- If they didn't supply data, we'll put in the bill to contact and address
11680           NEW.cohead_billto_cntct_id=COALESCE(NEW.cohead_billto_cntct_id,_p.cntct_id);
11681           NEW.cohead_billto_cntct_honorific=COALESCE(NEW.cohead_billto_cntct_honorific,_p.cntct_honorific,'');
11682           NEW.cohead_billto_cntct_first_name=COALESCE(NEW.cohead_billto_cntct_first_name,_p.cntct_first_name,'');
11683           NEW.cohead_billto_cntct_middle=COALESCE(NEW.cohead_billto_cntct_middle,_p.cntct_middle,'');    
11684           NEW.cohead_billto_cntct_last_name=COALESCE(NEW.cohead_billto_cntct_last_name,_p.cntct_last_name,''); 
11685           NEW.cohead_billto_cntct_phone=COALESCE(NEW.cohead_billto_cntct_phone,_p.cntct_phone,'');
11686           NEW.cohead_billto_cntct_title=COALESCE(NEW.cohead_billto_cntct_title,_p.cntct_title,'');
11687           NEW.cohead_billto_cntct_fax=COALESCE(NEW.cohead_billto_cntct_fax,_p.cntct_fax,''); 
11688           NEW.cohead_billto_cntct_email=COALESCE(NEW.cohead_billto_cntct_email,_p.cntct_email,''); 
11689           NEW.cohead_billtoname=COALESCE(NEW.cohead_billtoname,_p.cust_name,'');
11690           NEW.cohead_billtoaddress1=COALESCE(NEW.cohead_billtoaddress1,_p.addr_line1,'');
11691           NEW.cohead_billtoaddress2=COALESCE(NEW.cohead_billtoaddress2,_p.addr_line2,'');
11692           NEW.cohead_billtoaddress3=COALESCE(NEW.cohead_billtoaddress3,_p.addr_line3,'');    
11693           NEW.cohead_billtocity=COALESCE(NEW.cohead_billtocity,_p.addr_city,''); 
11694           NEW.cohead_billtostate=COALESCE(NEW.cohead_billtostate,_p.addr_state,'');
11695           NEW.cohead_billtozipcode=COALESCE(NEW.cohead_billtozipcode,_p.addr_postalcode,'');
11696           NEW.cohead_billtocountry=COALESCE(NEW.cohead_billtocountry,_p.addr_country,'');   
11697         ELSE
11698           -- Free form not allowed, we're going to put in the address regardless
11699           NEW.cohead_billto_cntct_id=_p.cntct_id;
11700           NEW.cohead_billto_cntct_honorific=COALESCE(_p.cntct_honorific,'');
11701           NEW.cohead_billto_cntct_first_name=COALESCE(_p.cntct_first_name,'');
11702           NEW.cohead_billto_cntct_middle=COALESCE(_p.cntct_middle,'');    
11703           NEW.cohead_billto_cntct_last_name=COALESCE(_p.cntct_last_name,''); 
11704           NEW.cohead_billto_cntct_phone=COALESCE(_p.cntct_phone,'');
11705           NEW.cohead_billto_cntct_title=COALESCE(_p.cntct_title,'');
11706           NEW.cohead_billto_cntct_fax=COALESCE(_p.cntct_fax,''); 
11707           NEW.cohead_billto_cntct_email=COALESCE(_p.cntct_email,''); 
11708           NEW.cohead_billtoname=COALESCE(_p.cust_name,'');
11709           NEW.cohead_billtoaddress1=COALESCE(_p.addr_line1,'');
11710           NEW.cohead_billtoaddress2=COALESCE(_p.addr_line2,'');
11711           NEW.cohead_billtoaddress3=COALESCE(_p.addr_line3,'');    
11712           NEW.cohead_billtocity=COALESCE(_p.addr_city,''); 
11713           NEW.cohead_billtostate=COALESCE(_p.addr_state,'');
11714           NEW.cohead_billtozipcode=COALESCE(_p.addr_postalcode,'');
11715           NEW.cohead_billtocountry=COALESCE(_p.addr_country,'');
11716         END IF;
11717       END IF;
11718
11719       -- Now let's look at Shipto Address
11720       -- If there's nothing in the address fields and there is a shipto id 
11721       -- or there is a default address available, let's put in some shipto address data
11722       IF ((TG_OP = 'INSERT') 
11723         AND NOT ((NEW.cohead_shipto_id IS NULL) AND NOT _p.cust_ffshipto)
11724         AND (NEW.cohead_shipto_cntct_id IS NULL)
11725         AND (NEW.cohead_shipto_cntct_honorific IS NULL)
11726         AND (NEW.cohead_shipto_cntct_first_name IS NULL)
11727         AND (NEW.cohead_shipto_cntct_middle IS NULL)
11728         AND (NEW.cohead_shipto_cntct_last_name IS NULL)
11729         AND (NEW.cohead_shipto_cntct_suffix IS NULL)
11730         AND (NEW.cohead_shipto_cntct_phone IS NULL)
11731         AND (NEW.cohead_shipto_cntct_title IS NULL)
11732         AND (NEW.cohead_shipto_cntct_fax IS NULL)
11733         AND (NEW.cohead_shipto_cntct_email IS NULL)
11734         AND (NEW.cohead_shiptoname IS NULL)
11735         AND (NEW.cohead_shiptoaddress1 IS NULL)
11736         AND (NEW.cohead_shiptoaddress2 IS NULL)
11737         AND (NEW.cohead_shiptoaddress3 IS NULL)
11738         AND (NEW.cohead_shiptocity IS NULL)
11739         AND (NEW.cohead_shiptostate IS NULL)
11740         AND (NEW.cohead_shiptocountry IS NULL)) THEN
11741         IF ((NEW.cohead_shipto_id IS NULL) AND (_p.shipto_id IS NOT NULL)) THEN
11742           _shiptoId := _p.shipto_addr_id;
11743         ELSE
11744           _shiptoId := NEW.cohead_shipto_id;
11745         END IF;
11746
11747         SELECT * INTO _a 
11748         FROM shiptoinfo
11749           LEFT OUTER JOIN addr ON (addr_id=shipto_addr_id)
11750           LEFT OUTER JOIN cntct ON (cntct_id=shipto_cntct_id)
11751         WHERE (shipto_id=_shiptoId);
11752
11753         NEW.cohead_shipto_cntct_id := _a.cntct_id;
11754         NEW.cohead_shipto_cntct_honorific := COALESCE(_a.cntct_honorific,'');
11755         NEW.cohead_shipto_cntct_first_name := COALESCE(_a.cntct_first_name,'');
11756         NEW.cohead_shipto_cntct_middle := COALESCE(_a.cntct_middle,'');
11757         NEW.cohead_shipto_cntct_last_name := COALESCE(_a.cntct_last_name,'');
11758         NEW.cohead_shipto_cntct_suffix := COALESCE(_a.cntct_suffix,'');
11759         NEW.cohead_shipto_cntct_phone := COALESCE(_a.cntct_phone,'');
11760         NEW.cohead_shipto_cntct_title := COALESCE(_a.cntct_title,'');
11761         NEW.cohead_shipto_cntct_fax := COALESCE(_a.cntct_fax,'');
11762         NEW.cohead_shipto_cntct_email := COALESCE(_a.cntct_email,'');
11763         NEW.cohead_shiptoname := COALESCE(_p.shipto_name,'');
11764         NEW.cohead_shiptoaddress1 := COALESCE(_a.addr_line1,'');
11765         NEW.cohead_shiptoaddress2 := COALESCE(_a.addr_line2,'');
11766         NEW.cohead_shiptoaddress3 := COALESCE(_a.addr_line3,'');    
11767         NEW.cohead_shiptocity := COALESCE(_a.addr_city,''); 
11768         NEW.cohead_shiptostate := COALESCE(_a.addr_state,'');
11769         NEW.cohead_shiptozipcode := COALESCE(_a.addr_postalcode,'');
11770         NEW.cohead_shiptocountry := COALESCE(_a.addr_country,'');
11771       ELSE
11772         IF (_p.cust_ffshipto) THEN
11773           -- Use Address Save function to see if the new address entered matches
11774           -- data for the shipto number.  If not that will insert new address for CRM
11775           SELECT SaveAddr(
11776             NULL,
11777             NULL,
11778             NEW.cohead_shiptoaddress1,
11779             NEW.cohead_shiptoaddress2,
11780             NEW.cohead_shiptoaddress3,
11781             NEW.cohead_shiptocity,
11782             NEW.cohead_shiptostate,
11783             NEW.cohead_shiptozipcode,
11784             NEW.cohead_shiptocountry,
11785             'CHANGEONE') INTO _addrId;
11786           SELECT shipto_addr_id INTO _shiptoid FROM shiptoinfo WHERE (shipto_id=NEW.cohead_shipto_id);
11787           -- If the address passed doesn't match shipto address, then it's something else
11788           IF (_shiptoid <> _addrId) THEN
11789             NEW.cohead_shipto_id := NULL;
11790           END IF;
11791         ELSE
11792           SELECT cohead_shipto_id INTO _shiptoid FROM cohead WHERE (cohead_id=NEW.cohead_id);
11793           -- Get the shipto address
11794           IF (COALESCE(NEW.cohead_shipto_id,-1) <> COALESCE(_shiptoid,-1)) THEN
11795             SELECT * INTO _a 
11796             FROM shiptoinfo
11797               LEFT OUTER JOIN cntct ON (shipto_cntct_id=cntct_id)
11798               LEFT OUTER JOIN addr ON (shipto_addr_id=addr_id)
11799             WHERE (shipto_id=NEW.cohead_shipto_id);
11800             IF (FOUND) THEN
11801               -- Free form not allowed so we're going to make sure address matches Shipto data
11802               NEW.cohead_shipto_cntct_id=_a.cntct_id;
11803               NEW.cohead_shipto_cntct_honorific=COALESCE(_a.cntct_honorific,'');
11804               NEW.cohead_shipto_cntct_first_name=COALESCE(_a.cntct_first_name,'');
11805               NEW.cohead_shipto_cntct_middle=COALESCE(_a.cntct_middle,'');    
11806               NEW.cohead_shipto_cntct_last_name=COALESCE(_a.cntct_last_name,''); 
11807               NEW.cohead_shipto_cntct_phone=COALESCE(_a.cntct_phone,'');
11808               NEW.cohead_shipto_cntct_title=COALESCE(_a.cntct_title,'');
11809               NEW.cohead_shipto_cntct_fax=COALESCE(_a.cntct_fax,''); 
11810               NEW.cohead_shipto_cntct_email=COALESCE(_a.cntct_email,''); 
11811               NEW.cohead_shiptoname := COALESCE(_a.shipto_name,'');
11812               NEW.cohead_shiptophone := COALESCE(_a.cntct_phone,'');
11813               NEW.cohead_shiptoaddress1 := COALESCE(_a.addr_line1,'');
11814               NEW.cohead_shiptoaddress2 := COALESCE(_a.addr_line2,'');
11815               NEW.cohead_shiptoaddress3 := COALESCE(_a.addr_line3,'');    
11816               NEW.cohead_shiptocity := COALESCE(_a.addr_city,''); 
11817               NEW.cohead_shiptostate := COALESCE(_a.addr_state,'');
11818               NEW.cohead_shiptozipcode := COALESCE(_a.addr_postalcode,'');
11819               NEW.cohead_shiptocountry := COALESCE(_a.addr_country,''); 
11820             ELSE
11821               -- If no shipto data and free form not allowed, this won't work
11822               RAISE EXCEPTION 'Free form Shipto is not allowed on this Customer. You must supply a valid Shipto ID.';
11823             END IF;
11824           END IF;
11825         END IF;
11826       END IF;
11827     END IF;
11828   END IF;
11829
11830   IF ( SELECT (metric_value='t')
11831        FROM metric
11832        WHERE (metric_name='SalesOrderChangeLog') ) THEN
11833
11834     IF (TG_OP = 'INSERT') THEN
11835       PERFORM postComment('ChangeLog', 'S', NEW.cohead_id, 'Created');
11836
11837     ELSIF (TG_OP = 'UPDATE') THEN
11838
11839       IF ( (OLD.cohead_terms_id <> NEW.cohead_terms_id) AND
11840            (OLD.cohead_cust_id = NEW.cohead_cust_id) ) THEN
11841         PERFORM postComment( 'ChangeLog', 'S', NEW.cohead_id,
11842                              ('Terms Changed from "' || oldterms.terms_code || '" to "' || newterms.terms_code || '"') )
11843         FROM terms AS oldterms, terms AS newterms
11844         WHERE ( (oldterms.terms_id=OLD.cohead_terms_id)
11845          AND (newterms.terms_id=NEW.cohead_terms_id) );
11846       END IF;
11847
11848       IF ( (OLD.cohead_shipvia <> NEW.cohead_shipvia) AND
11849            (OLD.cohead_cust_id = NEW.cohead_cust_id) ) THEN
11850         PERFORM postComment ('ChangeLog', 'S', New.cohead_id, ('Shipvia Changed from "' || OLD.cohead_shipvia || '" to "' || NEW.cohead_shipvia || '"'));
11851       END IF;
11852
11853       IF (OLD.cohead_holdtype <> NEW.cohead_holdtype) THEN
11854         PERFORM postComment( 'ChangeLog', 'S', NEW.cohead_id,
11855                              ( 'Hold Type Changed from ' || (CASE OLD.cohead_holdtype WHEN('N') THEN 'No Hold'
11856                                                                                       WHEN('C') THEN 'Credit Hold'
11857                                                                                       WHEN('P') THEN 'Packing Hold'
11858                                                                                       WHEN('S') THEN 'Shipping Hold'
11859                                                                                       ELSE 'Unknown/Error' END) ||
11860                                ' to ' || (CASE NEW.cohead_holdtype WHEN('N') THEN 'No Hold'
11861                                                                    WHEN('C') THEN 'Credit Hold'
11862                                                                    WHEN('P') THEN 'Packing Hold'
11863                                                                    WHEN('S') THEN 'Shipping Hold'
11864                                                                    ELSE 'Unknown/Error' END) ) );
11865       END IF;
11866
11867     ELSIF (TG_OP = 'DELETE') THEN
11868       DELETE FROM docass WHERE docass_source_id = OLD.cohead_id AND docass_source_type = 'S';
11869       DELETE FROM docass WHERE docass_target_id = OLD.cohead_id AND docass_target_type = 'S';
11870       
11871       DELETE FROM comment
11872       WHERE ( (comment_source='S')
11873        AND (comment_source_id=OLD.cohead_id) );
11874     END IF;
11875   END IF;
11876
11877   IF (TG_OP = 'UPDATE') THEN
11878     IF ( (NOT (OLD.cohead_holdtype = 'N')) AND
11879          (NEW.cohead_holdtype='N') ) THEN
11880       PERFORM postEvent('SoReleased', 'S', NEW.cohead_id,
11881                         NEW.cohead_warehous_id, NEW.cohead_number,
11882                         NULL, NULL, NULL, NULL);
11883     END IF;
11884
11885     IF (OLD.cohead_ordercomments <> NEW.cohead_ordercomments) THEN
11886       PERFORM postEvent('SoNotesChanged', 'S', NEW.cohead_id,
11887                         NEW.cohead_warehous_id, NEW.cohead_number,
11888                         NULL, NULL, NULL, NULL);
11889     END IF;
11890
11891     IF ((OLD.cohead_shipchrg_id != NEW.cohead_shipchrg_id)
11892         OR (OLD.cohead_freight != NEW.cohead_freight)
11893         OR (OLD.cohead_shipvia != NEW.cohead_shipvia)) THEN
11894       UPDATE shiphead SET 
11895         shiphead_shipchrg_id=
11896              CASE WHEN (NEW.cohead_shipchrg_id <= 0) THEN NULL
11897                   ELSE NEW.cohead_shipchrg_id
11898              END,
11899         shiphead_freight=NEW.cohead_freight,
11900         shiphead_shipvia=NEW.cohead_shipvia
11901       WHERE ((shiphead_order_type='SO')
11902       AND  (shiphead_order_id=NEW.cohead_id)
11903       AND  (NOT shiphead_shipped));
11904     END IF;
11905   END IF;
11906
11907   IF (TG_OP = 'DELETE') THEN
11908     RETURN OLD;
11909   ELSE
11910     NEW.cohead_lastupdated = CURRENT_TIMESTAMP;
11911
11912     RETURN NEW;
11913   END IF;
11914
11915 END;
11916 $$;
11917
11918
11919 ALTER FUNCTION public._soheadtrigger() OWNER TO admin;
11920
11921 --
11922 -- TOC entry 1066 (class 1255 OID 146565583)
11923 -- Dependencies: 4536 8
11924 -- Name: _soheadtriggerafter(); Type: FUNCTION; Schema: public; Owner: admin
11925 --
11926
11927 CREATE FUNCTION _soheadtriggerafter() RETURNS trigger
11928     LANGUAGE plpgsql
11929     AS $$
11930 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11931 -- See www.xtuple.com/CPAL for the full text of the software license.
11932 BEGIN
11933   IF (COALESCE(NEW.cohead_taxzone_id,-1) <> COALESCE(OLD.cohead_taxzone_id,-1)) THEN
11934     UPDATE coitem SET coitem_taxtype_id=getItemTaxType(itemsite_item_id,NEW.cohead_taxzone_id)
11935     FROM itemsite 
11936     WHERE ((itemsite_id=coitem_itemsite_id)
11937      AND (coitem_cohead_id=NEW.cohead_id));
11938   END IF;
11939
11940   -- update comments on any associated drop ship POs
11941   IF (COALESCE(NEW.cohead_shipcomments, TEXT('')) <> COALESCE(OLD.cohead_shipcomments, TEXT(''))) THEN
11942     UPDATE pohead SET pohead_comments=NEW.cohead_shipcomments
11943     FROM poitem JOIN coitem ON (coitem_cohead_id=NEW.cohead_id AND coitem_order_type='P' AND coitem_order_id=poitem_id)
11944     WHERE (pohead_id=poitem_pohead_id);
11945   END IF;
11946
11947   RETURN NEW;
11948 END;
11949 $$;
11950
11951
11952 ALTER FUNCTION public._soheadtriggerafter() OWNER TO admin;
11953
11954 --
11955 -- TOC entry 1067 (class 1255 OID 146565584)
11956 -- Dependencies: 4536 8
11957 -- Name: _soitemafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
11958 --
11959
11960 CREATE FUNCTION _soitemafterdeletetrigger() RETURNS trigger
11961     LANGUAGE plpgsql
11962     AS $$
11963 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11964 -- See www.xtuple.com/CPAL for the full text of the software license.
11965 DECLARE
11966
11967 BEGIN
11968
11969   IF (OLD.coitem_status = 'O') THEN
11970     IF ( (SELECT (count(*) < 1)
11971             FROM coitem
11972            WHERE ((coitem_cohead_id=OLD.coitem_cohead_id)
11973              AND  (coitem_id != OLD.coitem_id)
11974              AND  (coitem_status = 'O')) ) ) THEN
11975       UPDATE cohead SET cohead_status = 'C'
11976        WHERE ((cohead_id=OLD.coitem_cohead_id)
11977          AND  (cohead_status='O'));
11978     END IF;
11979   END IF;
11980
11981   RETURN OLD;
11982 END;
11983 $$;
11984
11985
11986 ALTER FUNCTION public._soitemafterdeletetrigger() OWNER TO admin;
11987
11988 --
11989 -- TOC entry 1068 (class 1255 OID 146565585)
11990 -- Dependencies: 4536 8
11991 -- Name: _soitemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
11992 --
11993
11994 CREATE FUNCTION _soitemaftertrigger() RETURNS trigger
11995     LANGUAGE plpgsql
11996     AS $$
11997 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
11998 -- See www.xtuple.com/CPAL for the full text of the software license.
11999 DECLARE
12000   _check NUMERIC;
12001   _r RECORD;
12002   _kit BOOLEAN;
12003   _fractional BOOLEAN;
12004   _rec RECORD;
12005   _kstat TEXT;
12006   _pstat TEXT;
12007   _result INTEGER;
12008   _coitemid INTEGER;
12009   _itemsrcid INTEGER;
12010   _orderid INTEGER;
12011
12012 BEGIN
12013
12014   _rec := NEW;
12015
12016   --Cache some information
12017   SELECT * INTO _r
12018   FROM cohead
12019   WHERE (cohead_id=_rec.coitem_cohead_id);
12020
12021   --Determine if this is a kit for later processing
12022   SELECT COALESCE(item_type,'')='K', item_fractional
12023     INTO _kit, _fractional
12024     FROM itemsite, item
12025    WHERE((itemsite_item_id=item_id)
12026      AND (itemsite_id=_rec.coitem_itemsite_id));
12027   _kit := COALESCE(_kit, false);
12028   _fractional := COALESCE(_fractional, false);
12029
12030   IF (_kit) THEN
12031   -- Kit Processing
12032     IF (TG_OP = 'INSERT') THEN
12033   -- Create Sub Lines for Kit Components
12034       PERFORM explodeKit(NEW.coitem_cohead_id, NEW.coitem_linenumber, 0, NEW.coitem_itemsite_id,
12035                          NEW.coitem_qtyord, NEW.coitem_scheddate, NEW.coitem_promdate, NEW.coitem_memo);
12036       IF (fetchMetricBool('KitComponentInheritCOS')) THEN
12037   -- Update kit line item COS
12038         UPDATE coitem
12039         SET coitem_cos_accnt_id = CASE WHEN (COALESCE(NEW.coitem_cos_accnt_id, -1) != -1)
12040                                          THEN NEW.coitem_cos_accnt_id
12041                                        WHEN (NEW.coitem_warranty)
12042                                          THEN resolveCOWAccount(NEW.coitem_itemsite_id, _r.cohead_cust_id, _r.cohead_saletype_id, _r.cohead_shipzone_id)
12043                                        ELSE resolveCOSAccount(NEW.coitem_itemsite_id, _r.cohead_cust_id, _r.cohead_saletype_id, _r.cohead_shipzone_id)
12044                                   END
12045         WHERE((coitem_cohead_id=NEW.coitem_cohead_id)
12046           AND (coitem_linenumber = NEW.coitem_linenumber)
12047           AND (coitem_subnumber > 0));
12048       END IF;
12049     END IF;
12050     IF (TG_OP = 'UPDATE') THEN
12051       IF (NEW.coitem_qtyord <> OLD.coitem_qtyord) THEN
12052   -- Recreate Sub Lines for Kit Components
12053       FOR _coitemid IN
12054         SELECT coitem_id
12055         FROM coitem
12056         WHERE ( (coitem_cohead_id=OLD.coitem_cohead_id)
12057           AND   (coitem_linenumber=OLD.coitem_linenumber)
12058           AND   (coitem_subnumber > 0) )
12059         LOOP
12060           SELECT deleteSoItem(_coitemid) INTO _result;
12061           IF (_result < 0) THEN
12062              RAISE EXCEPTION 'Error deleting kit components: deleteSoItem(integer) Error:%', _result;
12063           END IF;
12064         END LOOP;
12065
12066         PERFORM explodeKit(NEW.coitem_cohead_id, NEW.coitem_linenumber, 0, NEW.coitem_itemsite_id,
12067                            NEW.coitem_qtyord, NEW.coitem_scheddate, NEW.coitem_promdate);
12068       END IF;
12069       IF ( (NEW.coitem_qtyord <> OLD.coitem_qtyord) OR
12070            (NEW.coitem_cos_accnt_id <> OLD.coitem_cos_accnt_id) ) THEN
12071         IF (fetchMetricBool('KitComponentInheritCOS')) THEN
12072   -- Update kit line item COS
12073           UPDATE coitem
12074           SET coitem_cos_accnt_id = CASE WHEN (COALESCE(NEW.coitem_cos_accnt_id, -1) != -1)
12075                                            THEN NEW.coitem_cos_accnt_id
12076                                          WHEN (NEW.coitem_warranty)
12077                                            THEN resolveCOWAccount(NEW.coitem_itemsite_id, _r.cohead_cust_id, _r.cohead_saletype_id, _r.cohead_shipzone_id)
12078                                          ELSE resolveCOSAccount(NEW.coitem_itemsite_id, _r.cohead_cust_id, _r.cohead_saletype_id, _r.cohead_shipzone_id)
12079                                     END
12080           WHERE((coitem_cohead_id=NEW.coitem_cohead_id)
12081             AND (coitem_linenumber = NEW.coitem_linenumber)
12082             AND (coitem_subnumber > 0));
12083         END IF;
12084       END IF;
12085       IF (NEW.coitem_scheddate <> OLD.coitem_scheddate) THEN
12086   -- Update kit line item Schedule Date
12087         UPDATE coitem
12088         SET coitem_scheddate = NEW.coitem_scheddate
12089         WHERE((coitem_cohead_id=NEW.coitem_cohead_id)
12090           AND (coitem_linenumber = NEW.coitem_linenumber)
12091           AND (coitem_subnumber > 0));
12092       END IF;
12093     END IF;
12094   END IF;
12095
12096   IF (TG_OP = 'INSERT') THEN
12097     -- Create Purchase Request if flagged to do so
12098     IF ((NEW.coitem_order_type='R') AND (NEW.coitem_order_id=-1)) THEN
12099       SELECT createpr(CAST(cohead_number AS INTEGER), 'S', NEW.coitem_id) INTO _orderid
12100       FROM cohead
12101       WHERE (cohead_id=NEW.coitem_cohead_id);
12102       IF (_orderid > 0) THEN
12103         UPDATE coitem SET coitem_order_id=_orderid
12104         WHERE (coitem_id=NEW.coitem_id);
12105       END IF;
12106     END IF;
12107
12108     -- Create Purchase Order if flagged to do so
12109     IF ((NEW.coitem_order_type='P') AND (NEW.coitem_order_id=-1)) THEN
12110       SELECT itemsrc_id INTO _itemsrcid
12111       FROM itemsite JOIN itemsrc ON (itemsrc_item_id=itemsite_item_id AND itemsrc_default)
12112       WHERE (itemsite_id=NEW.coitem_itemsite_id);
12113       IF (FOUND) THEN
12114         SELECT createPurchaseToSale(NEW.coitem_id,
12115                                     _itemsrcid,
12116                                     itemsite_dropship,
12117                                     CASE WHEN (NEW.coitem_prcost=0.0) THEN NULL
12118                                          ELSE NEW.coitem_prcost
12119                                     END) INTO _orderid
12120         FROM itemsite
12121         WHERE (itemsite_id=NEW.coitem_itemsite_id);
12122         IF (_orderid > 0) THEN
12123           UPDATE coitem SET coitem_order_id=_orderid
12124           WHERE (coitem_id=NEW.coitem_id);
12125         END IF;
12126       END IF;
12127     END IF;
12128
12129     -- Update Purchase Order comments
12130     IF (NEW.coitem_order_type='P') THEN
12131       UPDATE poitem SET poitem_comments=NEW.coitem_memo
12132       WHERE ((poitem_order_id=NEW.coitem_id) AND (poitem_order_type='S'));
12133     END IF;
12134   END IF;
12135
12136   IF (TG_OP = 'UPDATE') THEN
12137     IF (NEW.coitem_order_type = 'P') THEN
12138       --If soitem is cancelled
12139       IF ((NEW.coitem_status = 'X') AND (OLD.coitem_status <> 'X')) THEN
12140         PERFORM postEvent('PoItemSoCancelled', 'P', poitem_id,
12141                           itemsite_warehous_id,
12142                           (pohead_number || '-' || poitem_linenumber || ':' || item_number),
12143                           NULL, NULL, NULL, NULL)
12144         FROM poitem JOIN itemsite ON (itemsite_id=poitem_itemsite_id)
12145                     JOIN item ON (item_id=itemsite_item_id)
12146                     JOIN pohead ON (pohead_id=poitem_pohead_id)
12147         WHERE ( (poitem_id=OLD.coitem_order_id)
12148           AND   (poitem_duedate <= (CURRENT_DATE + itemsite_eventfence)) );
12149       --If soitem notes changed
12150       ELSIF (NEW.coitem_memo <> OLD.coitem_memo) THEN 
12151         UPDATE poitem SET poitem_comments=NEW.coitem_memo
12152         WHERE ((poitem_order_id=NEW.coitem_id) AND (poitem_order_type='S'));
12153       END IF;
12154     END IF;
12155   END IF;
12156
12157   IF (_rec.coitem_subnumber > 0) THEN
12158     SELECT coitem_status
12159       INTO _kstat
12160       FROM coitem
12161      WHERE((coitem_cohead_id=_rec.coitem_cohead_id)
12162        AND (coitem_linenumber=_rec.coitem_linenumber)
12163        AND (coitem_subnumber = 0));
12164     IF ((SELECT count(*)
12165            FROM coitem
12166           WHERE((coitem_cohead_id=_rec.coitem_cohead_id)
12167             AND (coitem_linenumber=_rec.coitem_linenumber)
12168             AND (coitem_subnumber <> _rec.coitem_subnumber)
12169             AND (coitem_subnumber > 0)
12170             AND (coitem_status = 'O'))) > 0) THEN
12171       _pstat := 'O';
12172     ELSE
12173       _pstat := _rec.coitem_status;
12174     END IF;
12175   END IF;
12176
12177   IF(TG_OP = 'INSERT') THEN
12178     IF (_rec.coitem_subnumber > 0 AND _rec.coitem_status = 'O') THEN
12179       _pstat := 'O';
12180     END IF;
12181   ELSIF (TG_OP = 'UPDATE') THEN
12182     IF (_rec.coitem_subnumber > 0 AND _rec.coitem_status = 'O') THEN
12183       _pstat := 'O';
12184     END IF;
12185
12186     IF ((NEW.coitem_status = 'C') AND (OLD.coitem_status <> 'C')) THEN
12187       IF(_kit) THEN
12188         UPDATE coitem
12189            SET coitem_status='C'
12190          WHERE((coitem_cohead_id=OLD.coitem_cohead_id)
12191            AND (coitem_linenumber=OLD.coitem_linenumber)
12192            AND (coitem_status='O')
12193            AND (coitem_subnumber > 0));
12194       END IF;
12195     END IF;
12196
12197     IF ((NEW.coitem_status = 'X') AND (OLD.coitem_status <> 'X')) THEN
12198       IF(_kit) THEN
12199         UPDATE coitem
12200            SET coitem_status='X'
12201          WHERE((coitem_cohead_id=OLD.coitem_cohead_id)
12202            AND (coitem_linenumber=OLD.coitem_linenumber)
12203            AND (coitem_status='O')
12204            AND (coitem_subnumber > 0));
12205       END IF;
12206     END IF;
12207
12208     IF(NEW.coitem_status = 'O' AND OLD.coitem_status <> 'O') THEN
12209       IF(_kit) THEN
12210         UPDATE coitem
12211            SET coitem_status='O'
12212          WHERE((coitem_cohead_id=OLD.coitem_cohead_id)
12213            AND (coitem_linenumber=OLD.coitem_linenumber)
12214            AND ((coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) > 0)
12215            AND (coitem_subnumber > 0));
12216       END IF;
12217     END IF;
12218
12219   END IF;
12220
12221   IF ((_kstat IS NOT NULL) AND (_pstat IS NOT NULL) AND (_rec.coitem_subnumber > 0) AND (_kstat <> _pstat)) THEN
12222     UPDATE coitem
12223        SET coitem_status = _pstat
12224      WHERE((coitem_cohead_id=_rec.coitem_cohead_id)
12225        AND (coitem_linenumber=_rec.coitem_linenumber)
12226        AND (coitem_subnumber = 0));
12227   END IF;
12228
12229   --If auto calculate freight, recalculate cohead_freight
12230   IF (SELECT cohead_calcfreight FROM cohead WHERE (cohead_id=NEW.coitem_cohead_id)) THEN
12231     UPDATE cohead SET cohead_freight = COALESCE(
12232       (SELECT SUM(freightdata_total) FROM freightDetail('SO',
12233                                                         cohead_id,
12234                                                         cohead_cust_id,
12235                                                         cohead_shipto_id,
12236                                                         cohead_orderdate,
12237                                                         cohead_shipvia,
12238                                                         cohead_curr_id)), 0)
12239     WHERE cohead_id=NEW.coitem_cohead_id;
12240   END IF;
12241
12242   RETURN NEW;
12243 END;
12244 $$;
12245
12246
12247 ALTER FUNCTION public._soitemaftertrigger() OWNER TO admin;
12248
12249 --
12250 -- TOC entry 1069 (class 1255 OID 146565587)
12251 -- Dependencies: 4536 8
12252 -- Name: _soitembeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
12253 --
12254
12255 CREATE FUNCTION _soitembeforedeletetrigger() RETURNS trigger
12256     LANGUAGE plpgsql
12257     AS $$
12258 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12259 -- See www.xtuple.com/CPAL for the full text of the software license.
12260 DECLARE
12261
12262   _r              RECORD;
12263   _kit            BOOLEAN := FALSE;
12264   _shipped        BOOLEAN := FALSE;
12265   _coitemid       INTEGER := 0;
12266   _result         INTEGER := 0;
12267
12268 BEGIN
12269
12270   -- Check Priv
12271   IF NOT (checkPrivilege('MaintainSalesOrders')) THEN
12272     RAISE EXCEPTION 'You do not have privileges to alter a Sales Order.';
12273   END IF;
12274
12275   -- Cache some information
12276   SELECT * INTO _r
12277     FROM cohead, itemsite, item
12278    WHERE ( (cohead_id=OLD.coitem_cohead_id)
12279      AND   (itemsite_id=OLD.coitem_itemsite_id)
12280      AND   (item_id=itemsite_item_id) );
12281
12282   _kit := (COALESCE(_r.item_type,'')='K');
12283
12284   -- Check for shipped kit components
12285   IF(_kit AND OLD.coitem_status <> 'C' AND OLD.coitem_status <> 'X') THEN
12286     IF (EXISTS (SELECT coitem_id
12287                   FROM coitem JOIN shipitem ON (shipitem_orderitem_id=coitem_id)
12288                               JOIN shiphead ON (shiphead_id=shipitem_shiphead_id AND shiphead_order_type='SO')
12289                  WHERE ((coitem_cohead_id=OLD.coitem_cohead_id)
12290                    AND  (coitem_linenumber=OLD.coitem_linenumber)
12291                    AND (coitem_subnumber > 0))
12292               GROUP BY coitem_id
12293                 HAVING (SUM(shipitem_qty) > 0)
12294                  LIMIT 1) ) THEN
12295       _shipped := TRUE;
12296     END IF;
12297   END IF;
12298
12299   IF(_kit AND _shipped) THEN
12300     RAISE EXCEPTION 'You can not delete this Sales Order Line as it has several sub components that have already been shipped.';
12301   END IF;
12302
12303   DELETE FROM comment
12304    WHERE ( (comment_source='SI')
12305      AND   (comment_source_id=OLD.coitem_id) );
12306
12307   DELETE FROM charass
12308    WHERE ((charass_target_type='SI')
12309      AND  (charass_target_id=OLD.coitem_id));
12310
12311   -- Delete Sub Lines for Kit Components
12312   IF (OLD.coitem_subnumber = 0) THEN
12313     FOR _coitemid IN
12314       SELECT coitem_id
12315         FROM coitem
12316        WHERE ( (coitem_cohead_id=OLD.coitem_cohead_id)
12317          AND   (coitem_linenumber=OLD.coitem_linenumber)
12318          AND   (coitem_subnumber > 0) )
12319       LOOP
12320       SELECT deleteSoItem(_coitemid) INTO _result;
12321       IF (_result < 0) THEN
12322         IF NOT (_r.itemsite_createsopo AND (_result = -10 OR _result = -20)) THEN
12323           RAISE EXCEPTION 'Error deleting kit components: deleteSoItem(integer) Error:%', _result;
12324         END IF;
12325       END IF;
12326     END LOOP;
12327   END IF;
12328
12329   IF (OLD.coitem_scheddate <= (CURRENT_DATE + _r.itemsite_eventfence)) THEN
12330     PERFORM postEvent('SoitemCancelled', 'S', OLD.coitem_id,
12331                       _r.itemsite_warehous_id, (_r.cohead_number || '-' || OLD.coitem_linenumber),
12332                       NULL, NULL, NULL, NULL);
12333   END IF;
12334
12335   RETURN OLD;
12336 END;
12337 $$;
12338
12339
12340 ALTER FUNCTION public._soitembeforedeletetrigger() OWNER TO admin;
12341
12342 --
12343 -- TOC entry 1070 (class 1255 OID 146565588)
12344 -- Dependencies: 4536 8
12345 -- Name: _soitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
12346 --
12347
12348 CREATE FUNCTION _soitembeforetrigger() RETURNS trigger
12349     LANGUAGE plpgsql
12350     AS $$
12351 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12352 -- See www.xtuple.com/CPAL for the full text of the software license.
12353 DECLARE
12354   _check NUMERIC;
12355   _itemNumber TEXT;
12356   _r RECORD;
12357   _kit BOOLEAN;
12358
12359 BEGIN
12360
12361   --Determine if this is a kit for later processing
12362   SELECT COALESCE(item_type,'')='K'
12363   INTO _kit
12364   FROM itemsite, item
12365   WHERE((itemsite_item_id=item_id)
12366   AND (itemsite_id=NEW.coitem_itemsite_id));
12367   _kit := COALESCE(_kit, false);
12368   
12369   IF (TG_OP = 'INSERT') THEN
12370
12371     -- If this is imported, go ahead and insert default characteristics
12372     IF (NEW.coitem_imported) THEN
12373       INSERT INTO charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_price)
12374       SELECT 'SI', NEW.coitem_id, char_id, charass_value,
12375              itemcharprice(item_id,char_id,charass_value,cohead_cust_id,cohead_shipto_id,NEW.coitem_qtyord,cohead_curr_id,cohead_orderdate) 
12376         FROM (
12377            SELECT DISTINCT char_id, char_name, charass_value, item_id, cohead_cust_id, cohead_shipto_id, cohead_curr_id, cohead_orderdate
12378              FROM cohead, charass, char, itemsite, item
12379             WHERE((itemsite_id=NEW.coitem_itemsite_id)
12380               AND (itemsite_item_id=item_id)
12381               AND (charass_target_type='I') 
12382               AND (charass_target_id=item_id)
12383               AND (charass_default)
12384               AND (char_id=charass_char_id)
12385               AND (cohead_id=NEW.coitem_cohead_id))
12386            ORDER BY char_name) AS data;
12387     END IF;
12388   END IF;
12389
12390   -- Create work order and process if flagged to do so
12391   IF ((NEW.coitem_order_type='W') AND (NEW.coitem_order_id=-1)) THEN
12392     SELECT createwo(CAST(cohead_number AS INTEGER),
12393                     NEW.coitem_itemsite_id,
12394                     1, -- priority
12395                     validateOrderQty(NEW.coitem_itemsite_id, NEW.coitem_qtyord, TRUE),
12396                     itemsite_leadtime,
12397                     NEW.coitem_scheddate,
12398                     NEW.coitem_memo,
12399                     'S',
12400                     NEW.coitem_id,
12401                     cohead_prj_id) INTO NEW.coitem_order_id
12402     FROM cohead, itemsite 
12403     WHERE ((cohead_id=NEW.coitem_cohead_id)
12404     AND (itemsite_id=NEW.coitem_itemsite_id));
12405
12406     INSERT INTO charass
12407       (charass_target_type, charass_target_id,
12408        charass_char_id, charass_value) 
12409        SELECT 'W', NEW.coitem_order_id, charass_char_id, charass_value
12410        FROM charass
12411        WHERE ((charass_target_type='SI')
12412        AND  (charass_target_id=NEW.coitem_id));
12413   END IF;
12414    
12415   IF (TG_OP = 'UPDATE') THEN
12416 --  Update P/R date if applicable
12417
12418     IF (NEW.coitem_scheddate <> OLD.coitem_scheddate AND NEW.coitem_order_type='R' AND NEW.coitem_order_id > 1) THEN
12419       UPDATE pr SET pr_duedate = NEW.coitem_scheddate WHERE (pr_order_id=NEW.coitem_id AND pr_order_type='S');
12420     END IF;
12421     
12422 --  If closing or cancelling and there is a job item work order, then close job and distribute remaining costs
12423     IF ((NEW.coitem_status = 'C' AND OLD.coitem_status <> 'C')
12424      OR (NEW.coitem_status = 'X' AND OLD.coitem_status <> 'X'))
12425      AND (OLD.coitem_order_id > -1) THEN
12426
12427       SELECT wo_id, wo_wipvalue INTO _r
12428        FROM wo,itemsite,item
12429       WHERE ((wo_ordtype='S')
12430       AND (wo_ordid=OLD.coitem_id)
12431       AND (itemsite_id=wo_itemsite_id)
12432       AND (item_id=itemsite_item_id)
12433       AND (itemsite_costmethod = 'J'));
12434
12435       IF (FOUND) THEN
12436         IF (_r.wo_wipvalue > 0) THEN
12437         --  Distribute to G/L, debit Cost of Sales, credit WIP
12438           PERFORM MIN(insertGLTransaction( 'W/O', 'WO', formatWoNumber(NEW.coitem_order_id), 'Job Closed Incomplete',
12439                                            costcat_wip_accnt_id,
12440                                            CASE WHEN (COALESCE(NEW.coitem_cos_accnt_id, -1) != -1)
12441                                                   THEN NEW.coitem_cos_accnt_id
12442                                                 WHEN (NEW.coitem_warranty=TRUE)
12443                                                   THEN resolveCOWAccount(itemsite_id, cohead_cust_id, cohead_saletype_id, cohead_shipzone_id)
12444                                                 ELSE resolveCOSAccount(itemsite_id, cohead_cust_id, cohead_saletype_id, cohead_shipzone_id)
12445                                            END,
12446                                            -1,  _r.wo_wipvalue, current_date ))
12447           FROM itemsite, costcat, cohead
12448           WHERE ((itemsite_id=NEW.coitem_itemsite_id)
12449            AND (itemsite_costcat_id=costcat_id)
12450            AND (cohead_id=NEW.coitem_cohead_id));
12451         END IF;
12452
12453         UPDATE wo SET
12454           wo_status = 'C',
12455           wo_wipvalue = 0
12456         WHERE (wo_id = _r.wo_id);
12457
12458       END IF;
12459     END IF;
12460
12461 --  Likewise, reopen the job if line reopened
12462     IF ((NEW.coitem_status != 'C' AND OLD.coitem_status = 'C')
12463      OR (NEW.coitem_status != 'X' AND OLD.coitem_status = 'X'))
12464      AND (OLD.coitem_order_id > -1) THEN
12465         UPDATE wo SET
12466           wo_status = 'I'
12467         FROM itemsite, item
12468         WHERE ((wo_ordtype = 'S')
12469          AND (wo_ordid=NEW.coitem_id)
12470          AND (wo_itemsite_id=itemsite_id)
12471          AND (itemsite_item_id=item_id)
12472          AND (itemsite_costmethod='J'));
12473     END IF;
12474
12475 --  Handle links to Return Authorization
12476     IF (fetchMetricBool('EnableReturnAuth')) THEN 
12477       SELECT * INTO _r 
12478       FROM raitem,rahead 
12479       WHERE ((raitem_new_coitem_id=NEW.coitem_id)
12480       AND (rahead_id=raitem_rahead_id));
12481       IF (FOUND) THEN
12482         IF ((_r.raitem_qtyauthorized <> NEW.coitem_qtyord OR
12483             _r.raitem_qty_uom_id <> NEW.coitem_qty_uom_id OR
12484             _r.raitem_qty_invuomratio <> NEW.coitem_qty_invuomratio OR
12485             _r.raitem_price_uom_id <> NEW.coitem_price_uom_id OR
12486             _r.raitem_price_invuomratio <> NEW.coitem_price_invuomratio)
12487             AND NOT (NEW.coitem_status = 'X' AND _r.raitem_qtyauthorized = 0)) THEN
12488           RAISE EXCEPTION 'Quantities for line item % may only be changed on the Return Authorization that created it.',NEW.coitem_linenumber;
12489         END IF;
12490         IF (OLD.coitem_warranty <> NEW.coitem_warranty) THEN
12491           UPDATE raitem SET raitem_warranty = NEW.coitem_warranty
12492            WHERE((raitem_new_coitem_id=NEW.coitem_id)
12493              AND (raitem_warranty != NEW.coitem_warranty));
12494         END IF;
12495         IF (OLD.coitem_cos_accnt_id <> NEW.coitem_cos_accnt_id) THEN
12496           UPDATE raitem SET raitem_cos_accnt_id = NEW.coitem_cos_accnt_id
12497            WHERE((raitem_new_coitem_id=NEW.coitem_id)
12498              AND (COALESCE(raitem_cos_accnt_id,-1) != COALESCE(NEW.coitem_cos_accnt_id,-1)));
12499         END IF;
12500         IF (OLD.coitem_taxtype_id <> NEW.coitem_taxtype_id) THEN
12501           UPDATE raitem SET raitem_taxtype_id = NEW.coitem_taxtype_id
12502            WHERE((raitem_new_coitem_id=NEW.coitem_id)
12503              AND (COALESCE(raitem_taxtype_id,-1) != COALESCE(NEW.coitem_taxtype_id,-1)));
12504         END IF;
12505         IF (OLD.coitem_scheddate <> NEW.coitem_scheddate) THEN
12506           UPDATE raitem SET raitem_scheddate = NEW.coitem_scheddate
12507            WHERE((raitem_new_coitem_id=NEW.coitem_id)
12508              AND (raitem_scheddate != NEW.coitem_scheddate));
12509         END IF;
12510         IF (OLD.coitem_memo <> NEW.coitem_memo) THEN
12511           UPDATE raitem SET raitem_notes = NEW.coitem_memo
12512            WHERE((raitem_new_coitem_id=NEW.coitem_id)
12513              AND (raitem_notes != NEW.coitem_memo));
12514         END IF;
12515         IF ((OLD.coitem_qtyshipped <> NEW.coitem_qtyshipped) AND 
12516            (NEW.coitem_qtyshipped >= _r.raitem_qtyauthorized) AND
12517            ((_r.raitem_disposition = 'S') OR
12518            (_r.raitem_status = 'O') AND
12519            (_r.raitem_disposition IN ('P','V')) AND
12520            (_r.raitem_qtyreceived >= _r.raitem_qtyauthorized))) THEN
12521           UPDATE raitem SET raitem_status = 'C' 
12522           WHERE (raitem_new_coitem_id=NEW.coitem_id);
12523         END IF;
12524       END IF;
12525     END IF; 
12526   END IF; 
12527
12528   RETURN NEW;
12529 END;
12530 $$;
12531
12532
12533 ALTER FUNCTION public._soitembeforetrigger() OWNER TO admin;
12534
12535 --
12536 -- TOC entry 1071 (class 1255 OID 146565590)
12537 -- Dependencies: 4536 8
12538 -- Name: _soitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
12539 --
12540
12541 CREATE FUNCTION _soitemtrigger() RETURNS trigger
12542     LANGUAGE plpgsql
12543     AS $$
12544 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12545 -- See www.xtuple.com/CPAL for the full text of the software license.
12546 DECLARE
12547   _changelog BOOLEAN := FALSE;
12548   _check BOOLEAN;
12549   _kit BOOLEAN;
12550   _shipped BOOLEAN;
12551   _atShipping NUMERIC;
12552   _tmp INTEGER;
12553   _rec RECORD;
12554 BEGIN
12555   -- Check
12556   SELECT checkPrivilege('MaintainSalesOrders') OR checkPrivilege('ShipOrders') OR checkPrivilege('IssueStockToShipping') INTO _check;
12557   IF NOT (_check) THEN
12558     RAISE EXCEPTION 'You do not have privileges to alter a Sales Order.';
12559   END IF;
12560
12561   IF ( SELECT fetchMetricBool('SalesOrderChangeLog') ) THEN
12562     _changelog := TRUE;
12563   END IF;
12564
12565   IF (TG_OP IN ('INSERT','UPDATE')) THEN
12566     IF (NEW.coitem_scheddate IS NULL) THEN
12567       IF (fetchmetricbool('AllowASAPShipSchedules')) THEN
12568         NEW.coitem_scheddate := current_date;
12569       ELSE
12570         RAISE EXCEPTION 'A schedule date is required.';
12571       END IF;
12572     END IF;
12573   END IF;
12574
12575   _rec := NEW;
12576
12577   SELECT COALESCE(item_type,'')='K'
12578     INTO _kit
12579     FROM itemsite, item
12580    WHERE((itemsite_item_id=item_id)
12581      AND (itemsite_id=_rec.coitem_itemsite_id));
12582   _kit := COALESCE(_kit, false);
12583   _shipped := false;
12584   IF(_kit AND _rec.coitem_status <> 'C' AND _rec.coitem_status <> 'X') THEN
12585     SELECT coitem_id
12586       INTO _tmp
12587       FROM coitem JOIN shipitem ON (shipitem_orderitem_id=coitem_id)
12588                   JOIN shiphead ON (shiphead_id=shipitem_shiphead_id AND shiphead_order_type='SO')
12589      WHERE((coitem_cohead_id=_rec.coitem_cohead_id)
12590        AND (coitem_linenumber=_rec.coitem_linenumber)
12591        AND (coitem_subnumber > 0))
12592      GROUP BY coitem_id
12593     HAVING (SUM(shipitem_qty) > 0)
12594      LIMIT 1;
12595     IF (FOUND) THEN
12596       _shipped := true;
12597     END IF;
12598   END IF;
12599   
12600   IF (TG_OP ='UPDATE') THEN
12601     IF ((OLD.coitem_status <> 'C') AND (NEW.coitem_status = 'C')) THEN
12602       SELECT qtyAtShipping(NEW.coitem_id) INTO _atShipping;
12603       IF (_atShipping > 0) THEN
12604         RAISE EXCEPTION 'Line % cannot be Closed at this time as there is inventory at shipping.',NEW.coitem_linenumber;
12605       END IF;
12606     END IF;
12607   END IF;
12608
12609   IF (TG_OP = 'INSERT') THEN
12610     PERFORM postEvent('SoitemCreated', 'S', NEW.coitem_id,
12611                       itemsite_warehous_id, (cohead_number || '-' || NEW.coitem_linenumber),
12612                       NULL, NULL, NULL, NULL)
12613     FROM cohead, itemsite
12614     WHERE ( (cohead_id=NEW.coitem_cohead_id)
12615       AND   (itemsite_id=NEW.coitem_itemsite_id)
12616       AND   (NEW.coitem_scheddate <= (CURRENT_DATE + itemsite_eventfence)) );
12617
12618     IF (_changelog) THEN
12619       PERFORM postComment('ChangeLog', 'SI', NEW.coitem_id, 'Created');
12620     END IF;
12621
12622     --Set defaults if no values passed
12623     NEW.coitem_linenumber       := COALESCE(NEW.coitem_linenumber,
12624                                           (SELECT (COALESCE(MAX(coitem_linenumber), 0) + 1)
12625                                            FROM coitem
12626                                            WHERE (coitem_cohead_id=NEW.coitem_cohead_id)));
12627     NEW.coitem_status           := COALESCE(NEW.coitem_status,'O');
12628     NEW.coitem_scheddate        := COALESCE(NEW.coitem_scheddate,
12629                                            (SELECT MIN(coitem_scheddate)
12630                                             FROM coitem
12631                                             WHERE (coitem_cohead_id=NEW.coitem_cohead_id)));
12632     NEW.coitem_memo             := COALESCE(NEW.coitem_memo,'');
12633     NEW.coitem_prcost           := COALESCE(NEW.coitem_prcost,0);
12634     NEW.coitem_warranty := COALESCE(NEW.coitem_warranty,false);
12635
12636     IF (NEW.coitem_status='O') THEN
12637       UPDATE cohead SET cohead_status = 'O'
12638        WHERE ((cohead_id=NEW.coitem_cohead_id)
12639          AND  (cohead_status='C'));
12640     END IF;
12641
12642     RETURN NEW;
12643
12644   ELSIF (TG_OP = 'UPDATE') THEN
12645     IF (NEW.coitem_qtyord <> OLD.coitem_qtyord) THEN
12646       IF(_kit) THEN
12647         IF(_shipped) THEN
12648           RAISE EXCEPTION 'You can not change the qty ordered for a Kit item when one or more of its components have shipped inventory.';
12649         END IF;
12650       END IF;
12651       PERFORM postEvent('SoitemQtyChanged', 'S', NEW.coitem_id,
12652                         itemsite_warehous_id, (cohead_number || '-' || NEW.coitem_linenumber),
12653                         NEW.coitem_qtyord, OLD.coitem_qtyord, NULL, NULL)
12654       FROM cohead, itemsite
12655       WHERE ( (cohead_id=NEW.coitem_cohead_id)
12656         AND   (itemsite_id=NEW.coitem_itemsite_id)
12657         AND   ( (NEW.coitem_scheddate <= (CURRENT_DATE + itemsite_eventfence))
12658          OR     (OLD.coitem_scheddate <= (CURRENT_DATE + itemsite_eventfence)) ) );
12659
12660       IF (_changelog) THEN
12661         PERFORM postComment( 'ChangeLog', 'SI', NEW.coitem_id,
12662                              ( 'Changed Qty. Ordered from ' || formatQty(OLD.coitem_qtyord) ||
12663                                ' to ' || formatQty(NEW.coitem_qtyord) ) );
12664       END IF;
12665
12666     END IF;
12667
12668     IF (NEW.coitem_price <> OLD.coitem_price) THEN
12669       IF (_changelog) THEN
12670         PERFORM postComment( 'ChangeLog', 'SI', NEW.coitem_id,
12671                              ( 'Changed Unit Price from ' || formatPrice(OLD.coitem_price) ||
12672                                ' to ' || formatPrice(NEW.coitem_price) ) );
12673       END IF;
12674
12675     END IF;
12676
12677     IF (NEW.coitem_scheddate <> OLD.coitem_scheddate) THEN
12678       PERFORM postEvent('SoitemSchedDateChanged', 'S', NEW.coitem_id,
12679                         itemsite_warehous_id, (cohead_number || '-' || NEW.coitem_linenumber),
12680                         NULL, NULL, NEW.coitem_scheddate, OLD.coitem_scheddate)
12681       FROM cohead, itemsite
12682       WHERE ( (cohead_id=NEW.coitem_cohead_id)
12683         AND   (itemsite_id=NEW.coitem_itemsite_id)
12684         AND   ( (NEW.coitem_scheddate <= (CURRENT_DATE + itemsite_eventfence))
12685          OR     (OLD.coitem_scheddate <= (CURRENT_DATE + itemsite_eventfence)) ) );
12686
12687       IF (_changelog) THEN
12688         PERFORM postComment( 'ChangeLog', 'SI', NEW.coitem_id,
12689                              ( 'Changed Sched. Date from ' || formatDate(OLD.coitem_scheddate) ||
12690                                ' to ' || formatDate(NEW.coitem_scheddate)) );
12691       END IF;
12692
12693     END IF;
12694
12695     IF ((NEW.coitem_status = 'C') AND (OLD.coitem_status <> 'C')) THEN
12696       NEW.coitem_closedate = CURRENT_TIMESTAMP;
12697       NEW.coitem_close_username = getEffectiveXtUser();
12698       NEW.coitem_qtyreserved := 0;
12699
12700       IF (_changelog) THEN
12701         PERFORM postComment('ChangeLog', 'SI', NEW.coitem_id, 'Closed');
12702       END IF;
12703     END IF;
12704
12705     IF ((NEW.coitem_status <> 'C') AND (OLD.coitem_status = 'C')) THEN
12706       NEW.coitem_closedate = NULL;
12707       NEW.coitem_close_username = NULL;
12708
12709       IF (_changelog) THEN
12710         PERFORM postComment('ChangeLog', 'SI', NEW.coitem_id, 'Reopened');
12711       END IF;
12712     END IF;
12713
12714     IF ((NEW.coitem_status = 'X') AND (OLD.coitem_status <> 'X')) THEN
12715       IF ((OLD.coitem_order_type = 'W') AND
12716           (SELECT wo_status IN ('O', 'E', 'R')
12717             FROM wo
12718             WHERE (wo_id=OLD.coitem_order_id))) THEN
12719       -- Close any associated W/O
12720         PERFORM closeWo(OLD.coitem_order_id, FALSE, CURRENT_DATE);
12721       ELSIF (OLD.coitem_order_type = 'R') THEN 
12722       -- Delete any associated P/R
12723         PERFORM deletePr(OLD.coitem_order_id);
12724       END IF;
12725
12726       NEW.coitem_qtyreserved := 0;
12727
12728       IF (_changelog) THEN
12729         PERFORM postComment('ChangeLog', 'SI', NEW.coitem_id, 'Canceled');
12730         PERFORM postComment('ChangeLog', 'S', NEW.coitem_cohead_id, 'Line # '|| NEW.coitem_linenumber ||' Canceled');
12731       END IF;
12732
12733       PERFORM postEvent('SoitemCancelled', 'S', OLD.coitem_id,
12734                         itemsite_warehous_id, (cohead_number || '-' || OLD.coitem_linenumber),
12735                         NULL, NULL, NULL, NULL)
12736       FROM cohead, itemsite
12737       WHERE ( (cohead_id=OLD.coitem_cohead_id)
12738         AND   (itemsite_id=OLD.coitem_itemsite_id)
12739         AND   (OLD.coitem_scheddate <= (CURRENT_DATE + itemsite_eventfence)) );
12740
12741     END IF;
12742
12743     IF ((NEW.coitem_qtyreserved <> OLD.coitem_qtyreserved) AND (_changelog)) THEN
12744       PERFORM postComment('ChangeLog', 'SI', NEW.coitem_id, 'Changed Qty Reserved to '|| NEW.coitem_qtyreserved);
12745     END IF;
12746
12747   END IF;
12748
12749   NEW.coitem_lastupdated = CURRENT_TIMESTAMP;
12750
12751   -- Handle status for header
12752   IF (TG_OP = 'UPDATE') THEN
12753     IF (OLD.coitem_status <> NEW.coitem_status) THEN
12754       IF ( (SELECT (count(*) < 1)
12755               FROM coitem
12756              WHERE ((coitem_cohead_id=NEW.coitem_cohead_id)
12757                AND  (coitem_id != NEW.coitem_id)
12758                AND  (coitem_status='O')) ) AND (NEW.coitem_status<>'O') ) THEN
12759         UPDATE cohead SET cohead_status = 'C'
12760          WHERE ((cohead_id=NEW.coitem_cohead_id)
12761            AND  (cohead_status='O'));
12762       ELSE
12763         UPDATE cohead SET cohead_status = 'O'
12764          WHERE ((cohead_id=NEW.coitem_cohead_id)
12765            AND  (cohead_status='C'));
12766       END IF;
12767     END IF;
12768   END IF;
12769
12770   RETURN NEW;
12771
12772 END;
12773 $$;
12774
12775
12776 ALTER FUNCTION public._soitemtrigger() OWNER TO admin;
12777
12778 --
12779 -- TOC entry 1072 (class 1255 OID 146565592)
12780 -- Dependencies: 4536 8
12781 -- Name: _taxauthafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
12782 --
12783
12784 CREATE FUNCTION _taxauthafterdeletetrigger() RETURNS trigger
12785     LANGUAGE plpgsql
12786     AS $$
12787 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12788 -- See www.xtuple.com/CPAL for the full text of the software license.
12789 BEGIN
12790   IF (EXISTS(SELECT 1
12791                FROM checkhead
12792               WHERE checkhead_recip_id = OLD.taxauth_id
12793                 AND checkhead_recip_type='T')) THEN
12794     RAISE EXCEPTION 'Cannot delete the tax authority % because checks have been written to it [xtuple: deleteTaxAuthority, -7, %]',
12795                     OLD.taxauth_number, OLD.taxauth_number;
12796   END IF;
12797
12798   IF (fetchMetricValue('DefaultTaxAuthority') = OLD.taxauth_id) THEN
12799     RAISE EXCEPTION 'Cannot delete the default Tax Authority [xtuple: deleteTaxAuthority, -8, %]',
12800                     OLD.taxauth_code;
12801   END IF;
12802
12803   IF (fetchMetricBool('TaxAuthChangeLog')) THEN
12804     PERFORM postComment(cmnttype_id, 'TAXAUTH', OLD.taxauth_id,
12805                         'Deleted "' || OLD.taxauth_number || '"')
12806       FROM cmnttype
12807      WHERE (cmnttype_name='ChangeLog');
12808   END IF;
12809
12810   RETURN OLD;
12811 END;
12812 $$;
12813
12814
12815 ALTER FUNCTION public._taxauthafterdeletetrigger() OWNER TO admin;
12816
12817 --
12818 -- TOC entry 1073 (class 1255 OID 146565593)
12819 -- Dependencies: 4536 8
12820 -- Name: _taxauthaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
12821 --
12822
12823 CREATE FUNCTION _taxauthaftertrigger() RETURNS trigger
12824     LANGUAGE plpgsql
12825     AS $$
12826 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12827 -- See www.xtuple.com/CPAL for the full text of the software license.
12828 DECLARE
12829   _cmnttypeid INTEGER;
12830
12831 BEGIN
12832   IF (TG_OP = 'INSERT') THEN
12833     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
12834     LOOP
12835       UPDATE crmacct SET crmacct_taxauth_id=NEW.taxauth_id,
12836                          crmacct_name=NEW.taxauth_name
12837        WHERE crmacct_number=NEW.taxauth_code;
12838       IF (FOUND) THEN
12839         EXIT;
12840       END IF;
12841       BEGIN
12842         INSERT INTO crmacct(crmacct_number,   crmacct_name,     crmacct_active,
12843                             crmacct_type,     crmacct_taxauth_id
12844                   ) VALUES (NEW.taxauth_code, NEW.taxauth_name, TRUE, 
12845                             'O',              NEW.taxauth_id);
12846         EXIT;
12847       EXCEPTION WHEN unique_violation THEN
12848             -- do nothing, and loop to try the UPDATE again
12849       END;
12850     END LOOP;
12851
12852     /* TODO: default characteristic assignments based on what? */
12853
12854   ELSIF (TG_OP = 'UPDATE') THEN
12855     UPDATE crmacct SET crmacct_number = NEW.taxauth_code
12856     WHERE ((crmacct_taxauth_id=NEW.taxauth_id)
12857       AND  (crmacct_number!=NEW.taxauth_code));
12858
12859     UPDATE crmacct SET crmacct_name = NEW.taxauth_name
12860     WHERE ((crmacct_taxauth_id=NEW.taxauth_id)
12861       AND  (crmacct_name!=NEW.taxauth_name));
12862
12863   END IF;
12864
12865   IF (fetchMetricBool('TaxAuthChangeLog')) THEN
12866     SELECT cmnttype_id INTO _cmnttypeid
12867       FROM cmnttype
12868      WHERE (cmnttype_name='ChangeLog');
12869
12870     IF (_cmnttypeid IS NOT NULL) THEN
12871       IF (TG_OP = 'INSERT') THEN
12872         PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id, 'Created');
12873
12874       ELSIF (TG_OP = 'UPDATE') THEN
12875         IF (OLD.taxauth_code <> NEW.taxauth_code) THEN
12876           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12877                               'Code changed from "' || OLD.taxauth_code ||
12878                               '" to "' || NEW.taxauth_code || '"');
12879         END IF;
12880
12881         IF (OLD.taxauth_name <> NEW.taxauth_name) THEN
12882           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12883                               'Name changed from "' || OLD.taxauth_name ||
12884                               '" to "' || NEW.taxauth_name || '"');
12885         END IF;
12886
12887         IF (OLD.taxauth_extref <> NEW.taxauth_extref) THEN
12888           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12889                               'External Ref. changed from "' || OLD.taxauth_extref ||
12890                               '" to "' || NEW.taxauth_extref || '"');
12891         END IF;
12892
12893         IF (OLD.taxauth_addr_id <> NEW.taxauth_addr_id) THEN
12894           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12895                               'Address changed from ' || formatAddr(OLD.taxauth_addr_id)
12896                               || ' to ' || formatAddr(NEW.taxauth_addr_id));
12897         END IF;
12898
12899         IF (OLD.taxauth_curr_id <> NEW.taxauth_curr_id) THEN
12900           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12901                               'Currency changed from "' ||
12902                               currConcat(OLD.taxauth_curr_id) || '" to "' ||
12903                               currConcat(NEW.taxauth_curr_id) || '"');
12904         END IF;
12905
12906         IF (OLD.taxauth_county <> NEW.taxauth_county) THEN
12907           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12908                               'County changed from "' || OLD.taxauth_county ||
12909                               '" to "' || NEW.taxauth_county || '"');
12910         END IF;
12911
12912         IF (OLD.taxauth_accnt_id <> NEW.taxauth_accnt_id) THEN
12913           PERFORM postComment(_cmnttypeid, 'TAXAUTH', NEW.taxauth_id,
12914                               'Account changed from "' ||
12915                               formatGLAccount(OLD.taxauth_accnt_id) || '" to "' ||
12916                               formatGLAccount(NEW.taxauth_accnt_id) || '"');
12917         END IF;
12918
12919       END IF;
12920     END IF;
12921   END IF;
12922
12923   RETURN NEW;
12924 END;
12925 $$;
12926
12927
12928 ALTER FUNCTION public._taxauthaftertrigger() OWNER TO admin;
12929
12930 --
12931 -- TOC entry 1074 (class 1255 OID 146565594)
12932 -- Dependencies: 4536 8
12933 -- Name: _taxauthbeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
12934 --
12935
12936 CREATE FUNCTION _taxauthbeforedeletetrigger() RETURNS trigger
12937     LANGUAGE plpgsql
12938     AS $$
12939 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12940 -- See www.xtuple.com/CPAL for the full text of the software license.
12941 BEGIN
12942   IF (NOT checkPrivilege('MaintainTaxAuthorities')) THEN
12943     RAISE EXCEPTION 'You do not have privileges to maintain Tax Authorities.';
12944   END IF;
12945
12946   UPDATE crmacct SET crmacct_taxauth_id = NULL
12947    WHERE crmacct_taxauth_id = OLD.taxauth_id;
12948
12949   RETURN OLD;
12950 END;
12951 $$;
12952
12953
12954 ALTER FUNCTION public._taxauthbeforedeletetrigger() OWNER TO admin;
12955
12956 --
12957 -- TOC entry 1075 (class 1255 OID 146565595)
12958 -- Dependencies: 4536 8
12959 -- Name: _taxauthbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
12960 --
12961
12962 CREATE FUNCTION _taxauthbeforetrigger() RETURNS trigger
12963     LANGUAGE plpgsql
12964     AS $$
12965 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
12966 -- See www.xtuple.com/CPAL for the full text of the software license.
12967 BEGIN
12968   IF (NOT checkPrivilege('MaintainTaxAuthorities')) THEN
12969     RAISE EXCEPTION 'You do not have privileges to maintain Tax Authorities.';
12970   END IF;
12971
12972   IF (NEW.taxauth_code IS NULL) THEN
12973     RAISE EXCEPTION 'You must supply a Tax Authority Code.';
12974   END IF;
12975
12976   IF (TG_OP = 'INSERT' AND
12977       fetchMetricText('CRMAccountNumberGeneration') IN ('A','O')) THEN
12978     PERFORM clearNumberIssue('CRMAccountNumber', NEW.taxauth_code);
12979   END IF;
12980
12981   NEW.taxauth_code := UPPER(NEW.taxauth_code);
12982
12983   RETURN NEW;
12984 END;
12985 $$;
12986
12987
12988 ALTER FUNCTION public._taxauthbeforetrigger() OWNER TO admin;
12989
12990 --
12991 -- TOC entry 1037 (class 1255 OID 146565596)
12992 -- Dependencies: 4536 8
12993 -- Name: _termsafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
12994 --
12995
12996 CREATE FUNCTION _termsafterdeletetrigger() RETURNS trigger
12997     LANGUAGE plpgsql
12998     AS $$
12999 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13000 -- See www.xtuple.com/CPAL for the full text of the software license.
13001 BEGIN
13002   IF (fetchMetricValue('DefaultTerms') = OLD.terms_id) THEN
13003     RAISE EXCEPTION 'Cannot delete the default Terms [xtuple: terms, -1, %]',
13004                     OLD.terms_code;
13005   END IF;
13006
13007   RETURN OLD;
13008 END;
13009 $$;
13010
13011
13012 ALTER FUNCTION public._termsafterdeletetrigger() OWNER TO admin;
13013
13014 --
13015 -- TOC entry 1076 (class 1255 OID 146565597)
13016 -- Dependencies: 4536 8
13017 -- Name: _todoitemtrigger(); Type: FUNCTION; Schema: public; Owner: admin
13018 --
13019
13020 CREATE FUNCTION _todoitemtrigger() RETURNS trigger
13021     LANGUAGE plpgsql
13022     AS $$
13023 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13024 -- See www.xtuple.com/CPAL for the full text of the software license.
13025 DECLARE
13026   _recurid     INTEGER;
13027   _newparentid INTEGER;
13028
13029 BEGIN
13030   IF (TG_OP = 'DELETE') THEN
13031     SELECT recur_id INTO _recurid
13032       FROM recur
13033      WHERE ((recur_parent_id=OLD.todoitem_id)
13034        AND  (recur_parent_type='TODO'));
13035
13036     IF (_recurid IS NOT NULL) THEN
13037       RAISE DEBUG 'recur_id for deleted todoitem = %', _recurid;
13038
13039       SELECT todoitem_id INTO _newparentid
13040         FROM todoitem
13041        WHERE ((todoitem_recurring_todoitem_id=OLD.todoitem_id)
13042           AND (todoitem_id!=OLD.todoitem_id))
13043        ORDER BY todoitem_due_date
13044        LIMIT 1;
13045
13046       RAISE DEBUG '_newparentid for deleted todoitem = %', COALESCE(_newparentid, NULL);
13047
13048       -- client is responsible for warning about deleting a recurring todoitem
13049       IF (_newparentid IS NULL) THEN
13050         DELETE FROM recur WHERE recur_id=_recurid;
13051       ELSE
13052         UPDATE recur SET recur_parent_id=_newparentid
13053          WHERE recur_id=_recurid;
13054
13055         UPDATE todoitem SET todoitem_recurring_todoitem_id=_newparentid
13056          WHERE todoitem_recurring_todoitem_id=OLD.todoitem_id
13057            AND todoitem_id != OLD.todoitem_id;
13058
13059         RAISE DEBUG 'reparented recurrence';
13060       END IF;
13061     END IF;
13062
13063     DELETE FROM alarm
13064      WHERE ((alarm_source='TODO')
13065         AND (alarm_source_id=OLD.todoitem_id));
13066
13067     DELETE FROM docass WHERE docass_source_id = OLD.todoitem_id AND docass_source_type = 'TODO';
13068     DELETE FROM docass WHERE docass_target_id = OLD.todoitem_id AND docass_target_type = 'TODO';
13069
13070     RETURN OLD;
13071   END IF;
13072
13073   RETURN NEW;
13074 END;
13075 $$;
13076
13077
13078 ALTER FUNCTION public._todoitemtrigger() OWNER TO admin;
13079
13080 --
13081 -- TOC entry 1077 (class 1255 OID 146565598)
13082 -- Dependencies: 4536 8
13083 -- Name: _uomconvupdate(); Type: FUNCTION; Schema: public; Owner: admin
13084 --
13085
13086 CREATE FUNCTION _uomconvupdate() RETURNS trigger
13087     LANGUAGE plpgsql
13088     AS $$
13089 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13090 -- See www.xtuple.com/CPAL for the full text of the software license.
13091 BEGIN
13092  
13093   UPDATE itemuomconv
13094   SET itemuomconv_to_value = NEW.uomconv_to_value,
13095   itemuomconv_from_value = NEW.uomconv_from_value,
13096   itemuomconv_fractional = NEW.uomconv_fractional
13097   WHERE((itemuomconv_from_uom_id = NEW.uomconv_from_uom_id)
13098   AND (itemuomconv_to_uom_id = NEW.uomconv_to_uom_id));
13099
13100 RETURN NEW;
13101
13102 END; 
13103 $$;
13104
13105
13106 ALTER FUNCTION public._uomconvupdate() OWNER TO admin;
13107
13108 --
13109 -- TOC entry 1078 (class 1255 OID 146565599)
13110 -- Dependencies: 4536 8
13111 -- Name: _usrprefaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
13112 --
13113
13114 CREATE FUNCTION _usrprefaftertrigger() RETURNS trigger
13115     LANGUAGE plpgsql
13116     AS $$
13117 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13118 -- See www.xtuple.com/CPAL for the full text of the software license.
13119 BEGIN
13120
13121   IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
13122     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
13123     IF (NEW.usrpref_name='active') THEN
13124       LOOP
13125         UPDATE crmacct SET crmacct_usr_username=NEW.usrpref_username
13126          WHERE crmacct_number=UPPER(NEW.usrpref_username);
13127         IF (FOUND) THEN
13128           EXIT;
13129         END IF;
13130         BEGIN
13131           INSERT INTO crmacct(crmacct_number,        crmacct_active,
13132                               crmacct_type,          crmacct_usr_username
13133                     ) VALUES (NEW.usrpref_username,  NEW.usrpref_value::BOOL,
13134                               'I',                   NEW.usrpref_username);
13135           EXIT;
13136         EXCEPTION WHEN unique_violation THEN
13137             -- do nothing, and loop to try the UPDATE again
13138         END;
13139       END LOOP;
13140
13141     ELSIF (NEW.usrpref_name='propername') THEN
13142       LOOP
13143         UPDATE crmacct SET crmacct_name=NEW.usrpref_value
13144          WHERE crmacct_number=UPPER(NEW.usrpref_username);
13145         IF (FOUND) THEN
13146           EXIT;
13147         END IF;
13148         BEGIN
13149           INSERT INTO crmacct(crmacct_number,        crmacct_active,
13150                               crmacct_name,
13151                               crmacct_type,          crmacct_usr_username
13152                     ) VALUES (UPPER(NEW.usrpref_username), TRUE,
13153                               NEW.usrpref_value,
13154                               'I',                   NEW.usrpref_username);
13155           EXIT;
13156         EXCEPTION WHEN unique_violation THEN
13157             -- do nothing, and loop to try the UPDATE again
13158         END;
13159       END LOOP;
13160
13161     END IF;
13162
13163   ELSIF (TG_OP = 'DELETE') THEN
13164     RETURN OLD;
13165   END IF;
13166
13167   RETURN NEW;
13168 END;
13169 $$;
13170
13171
13172 ALTER FUNCTION public._usrprefaftertrigger() OWNER TO admin;
13173
13174 --
13175 -- TOC entry 1079 (class 1255 OID 146565600)
13176 -- Dependencies: 4536 8
13177 -- Name: _usrprefbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13178 --
13179
13180 CREATE FUNCTION _usrprefbeforetrigger() RETURNS trigger
13181     LANGUAGE plpgsql
13182     AS $$
13183 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13184 -- See www.xtuple.com/CPAL for the full text of the software license.
13185 BEGIN
13186   IF NOT (checkPrivilege('MaintainUsers') OR
13187           checkPrivilege('MaintainPreferencesOthers') OR
13188           (checkPrivilege('MaintainPreferencesSelf'))) THEN
13189     -- 2 IFs because plpgsql doesn't always evaluate boolean exprs left-to-right
13190     IF (TG_OP = 'DELETE') THEN
13191       IF NOT (OLD.usrpref_name LIKE '%/checked' OR OLD.usrpref_name LIKE '%/columnsShown') THEN
13192         RAISE EXCEPTION 'You do not have privileges to change this User Preference.';
13193       END IF;
13194     ELSIF (NEW.usrpref_username = getEffectiveXtUser()) THEN
13195       IF NOT (NEW.usrpref_name LIKE '%/checked' OR NEW.usrpref_name LIKE '%/columnsShown') THEN
13196         RAISE EXCEPTION 'You do not have privileges to change this User Preference.';
13197       END IF;
13198     END IF;
13199   END IF;
13200
13201   IF (TG_OP IN ('INSERT', 'UPDATE')) THEN
13202     IF (NEW.usrpref_name = 'locale') THEN
13203       IF NOT EXISTS(SELECT locale_id
13204                       FROM locale
13205                      WHERE locale_id = NEW.usrpref_value::INTEGER) THEN
13206         RAISE EXCEPTION 'You must supply a valid Locale.';
13207       END IF;
13208
13209     ELSIF (NEW.usrpref_name IN ('agent', 'active')) THEN
13210       IF (NEW.usrpref_value NOT IN ('t', 'f')) THEN
13211         RAISE EXCEPTION '% must be either "t" or "f"', NEW.usrpref_name;
13212       END IF;
13213     END IF;
13214
13215   ELSIF (TG_OP = 'DELETE') THEN
13216     RETURN OLD;
13217   END IF;
13218
13219   RETURN NEW;
13220 END;
13221 $$;
13222
13223
13224 ALTER FUNCTION public._usrprefbeforetrigger() OWNER TO admin;
13225
13226 --
13227 -- TOC entry 1080 (class 1255 OID 146565601)
13228 -- Dependencies: 4536 8
13229 -- Name: _usrprivtrigger(); Type: FUNCTION; Schema: public; Owner: admin
13230 --
13231
13232 CREATE FUNCTION _usrprivtrigger() RETURNS trigger
13233     LANGUAGE plpgsql
13234     AS $$
13235 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13236 -- See www.xtuple.com/CPAL for the full text of the software license.
13237 DECLARE
13238   _check BOOLEAN;
13239   _returnVal INTEGER;
13240 BEGIN
13241   -- This looks like a candidate for a foreign key but isn't.
13242   -- fkeys don't work if the foreign key value resides in a child of the 
13243   -- table and not the table itself.
13244   IF ((TG_OP = 'UPDATE' OR TG_OP = 'INSERT') AND
13245       (NOT EXISTS(SELECT priv_id
13246                   FROM priv
13247                   WHERE (priv_id=NEW.usrpriv_priv_id)))) THEN
13248     RAISE EXCEPTION 'Privilege id % does not exist or is part of a disabled package.',
13249                 NEW.usrpriv_priv_id;
13250     RETURN OLD;
13251
13252   ELSIF (TG_OP = 'DELETE') THEN
13253     RETURN OLD;
13254   END IF;
13255
13256   RETURN NEW;
13257 END;
13258 $$;
13259
13260
13261 ALTER FUNCTION public._usrprivtrigger() OWNER TO admin;
13262
13263 --
13264 -- TOC entry 1082 (class 1255 OID 146565602)
13265 -- Dependencies: 4536 8
13266 -- Name: _vendaddrtrigger(); Type: FUNCTION; Schema: public; Owner: admin
13267 --
13268
13269 CREATE FUNCTION _vendaddrtrigger() RETURNS trigger
13270     LANGUAGE plpgsql
13271     AS $$
13272 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13273 -- See www.xtuple.com/CPAL for the full text of the software license.
13274 DECLARE
13275   _check      BOOLEAN;
13276   _vendname   TEXT;
13277
13278 BEGIN
13279
13280 --  Checks
13281   SELECT checkPrivilege('MaintainVendors') INTO _check;
13282   IF NOT (_check) THEN
13283     RAISE EXCEPTION 'You do not have privileges to maintain Vendors.';
13284   END IF;
13285
13286   IF (TG_OP IN ('INSERT','UPDATE')) THEN
13287
13288     IF (LENGTH(COALESCE(NEW.vendaddr_code, ''))=0) THEN
13289       RAISE EXCEPTION 'You must supply a valid Vendor Address Number.';
13290     END IF;
13291
13292     IF (LENGTH(COALESCE(NEW.vendaddr_name, ''))=0) THEN
13293       RAISE EXCEPTION 'You must supply a valid Vendor Address Name.';
13294     END IF;
13295
13296     IF (NEW.vendaddr_vend_id IS NULL) THEN
13297       RAISE EXCEPTION 'You must supply a valid Vendor ID.';
13298     END IF;
13299
13300     SELECT vendaddr_code INTO _vendname
13301     FROM vendaddrinfo
13302     WHERE ( (vendaddr_vend_id=NEW.vendaddr_vend_id)
13303       AND (UPPER(vendaddr_code)=UPPER(NEW.vendaddr_code))
13304       AND (vendaddr_id<>NEW.vendaddr_id) );
13305     IF (FOUND) THEN
13306       RAISE EXCEPTION 'The Vendor Address Number entered cannot be used as it is in use.';
13307     END IF;
13308
13309   END IF;
13310   
13311   IF (TG_OP = 'DELETE') THEN
13312     RETURN OLD;
13313   END IF;
13314
13315   RETURN NEW;
13316 END;
13317 $$;
13318
13319
13320 ALTER FUNCTION public._vendaddrtrigger() OWNER TO admin;
13321
13322 --
13323 -- TOC entry 1083 (class 1255 OID 146565603)
13324 -- Dependencies: 4536 8
13325 -- Name: _vendaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
13326 --
13327
13328 CREATE FUNCTION _vendaftertrigger() RETURNS trigger
13329     LANGUAGE plpgsql
13330     AS $$
13331 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
13332 -- See www.xtuple.com/CPAL for the full text of the software license.
13333 DECLARE
13334   _cmnttypeid   INTEGER;
13335
13336 BEGIN
13337
13338   IF (TG_OP = 'INSERT') THEN
13339     -- http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
13340     LOOP
13341       UPDATE crmacct SET crmacct_vend_id=NEW.vend_id,
13342                          crmacct_name=NEW.vend_name
13343        WHERE crmacct_number=NEW.vend_number;
13344       IF (FOUND) THEN
13345         EXIT;
13346       END IF;
13347       BEGIN
13348         INSERT INTO crmacct(crmacct_number,     crmacct_name,    crmacct_active,
13349                             crmacct_type,       crmacct_vend_id,
13350                             crmacct_cntct_id_1, crmacct_cntct_id_2
13351                   ) VALUES (NEW.vend_number,    NEW.vend_name,   NEW.vend_active,
13352                             'O',                NEW.vend_id,
13353                             NEW.vend_cntct1_id, NEW.vend_cntct2_id);
13354         EXIT;
13355       EXCEPTION WHEN unique_violation THEN
13356             -- do nothing, and loop to try the UPDATE again
13357       END;
13358     END LOOP;
13359
13360     /* TODO: default characteristic assignments based on vendgrp? */
13361
13362   ELSIF (TG_OP = 'UPDATE') THEN
13363     UPDATE crmacct SET crmacct_number = NEW.vend_number
13364     WHERE ((crmacct_vend_id=NEW.vend_id)
13365       AND  (crmacct_number!=NEW.vend_number));
13366
13367     UPDATE crmacct SET crmacct_name = NEW.vend_name
13368     WHERE ((crmacct_vend_id=NEW.vend_id)
13369       AND  (crmacct_name!=NEW.vend_name));
13370
13371   END IF;
13372
13373   IF (fetchMetricBool('VendorChangeLog')) THEN
13374     SELECT cmnttype_id INTO _cmnttypeid
13375       FROM cmnttype
13376      WHERE (cmnttype_name='ChangeLog');
13377
13378     IF (_cmnttypeid IS NOT NULL) THEN
13379       IF (TG_OP = 'INSERT') THEN
13380         PERFORM postComment(_cmnttypeid, 'V', NEW.vend_id, 'Created');
13381
13382       ELSIF (TG_OP = 'UPDATE') THEN
13383
13384         IF (OLD.vend_number <> NEW.vend_number) THEN
13385           PERFORM postComment(_cmnttypeid, 'V', NEW.vend_id,
13386                               ('Number Changed from "' || OLD.vend_number ||
13387                                '" to "' || NEW.vend_number || '"') );
13388         END IF;
13389
13390         IF (OLD.vend_name <> NEW.vend_name) THEN
13391           PERFORM postComment( _cmnttypeid, 'V', NEW.vend_id,
13392                               ('Name Changed from "' || OLD.vend_name ||
13393                                '" to "' || NEW.vend_name || '"') );
13394         END IF;
13395
13396         IF (OLD.vend_active <> NEW.vend_active) THEN
13397           PERFORM postComment(_cmnttypeid, 'V', NEW.vend_id,
13398                               CASE WHEN NEW.vend_active THEN 'Activated'
13399                                    ELSE 'Deactivated' END);
13400         END IF;
13401
13402       END IF;
13403     END IF;
13404   END IF;
13405
13406   RETURN NEW;
13407 END;
13408 $$;
13409
13410
13411 ALTER FUNCTION public._vendaftertrigger() OWNER TO admin;
13412
13413 --
13414 -- TOC entry 1084 (class 1255 OID 146565604)
13415 -- Dependencies: 4536 8
13416 -- Name: _vendinfoafterdeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13417 --
13418
13419 CREATE FUNCTION _vendinfoafterdeletetrigger() RETURNS trigger
13420     LANGUAGE plpgsql
13421     AS $$
13422 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
13423 -- See www.xtuple.com/CPAL for the full text of the software license.
13424 BEGIN
13425   IF EXISTS(SELECT 1
13426               FROM checkhead
13427              WHERE ((checkhead_recip_id=OLD.vend_id)
13428                 AND (checkhead_recip_type='V'))) THEN
13429     RAISE EXCEPTION '[xtuple: deleteVendor, -7]';
13430   END IF;
13431
13432   DELETE FROM taxreg
13433    WHERE ((taxreg_rel_type='V')
13434       AND (taxreg_rel_id=OLD.vend_id));
13435
13436   IF (fetchMetricBool('VendorChangeLog')) THEN
13437     PERFORM postComment(cmnttype_id, 'V', OLD.vend_id,
13438                         ('Deleted "' || OLD.vend_number || '"'))
13439       FROM cmnttype
13440      WHERE (cmnttype_name='ChangeLog');
13441   END IF;
13442
13443   RETURN OLD;
13444 END;
13445 $$;
13446
13447
13448 ALTER FUNCTION public._vendinfoafterdeletetrigger() OWNER TO admin;
13449
13450 --
13451 -- TOC entry 1085 (class 1255 OID 146565605)
13452 -- Dependencies: 4536 8
13453 -- Name: _vendinfobeforedeletetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13454 --
13455
13456 CREATE FUNCTION _vendinfobeforedeletetrigger() RETURNS trigger
13457     LANGUAGE plpgsql
13458     AS $$
13459 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
13460 -- See www.xtuple.com/CPAL for the full text of the software license.
13461 BEGIN
13462   IF NOT (checkPrivilege('MaintainVendors')) THEN
13463     RAISE EXCEPTION 'You do not have privileges to maintain Vendors.';
13464   END IF;
13465
13466   DELETE FROM itemsrcp
13467    WHERE itemsrcp_itemsrc_id IN (SELECT itemsrc_id
13468                                    FROM itemsrc
13469                                   WHERE itemsrc_vend_id=OLD.vend_id);
13470
13471   DELETE FROM itemsrc WHERE (itemsrc_vend_id=OLD.vend_id);
13472
13473   DELETE FROM vendaddrinfo WHERE (vendaddr_vend_id=OLD.vend_id);
13474
13475   DELETE FROM docass WHERE docass_source_id = OLD.vend_id AND docass_source_type = 'V';
13476   DELETE FROM docass WHERE docass_target_id = OLD.vend_id AND docass_target_type = 'V';
13477
13478   UPDATE crmacct SET crmacct_vend_id = NULL
13479    WHERE crmacct_vend_id = OLD.vend_id;
13480   RETURN OLD;
13481 END;
13482 $$;
13483
13484
13485 ALTER FUNCTION public._vendinfobeforedeletetrigger() OWNER TO admin;
13486
13487 --
13488 -- TOC entry 1086 (class 1255 OID 146565606)
13489 -- Dependencies: 4536 8
13490 -- Name: _vendtrigger(); Type: FUNCTION; Schema: public; Owner: admin
13491 --
13492
13493 CREATE FUNCTION _vendtrigger() RETURNS trigger
13494     LANGUAGE plpgsql
13495     AS $$
13496 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
13497 -- See www.xtuple.com/CPAL for the full text of the software license.
13498 BEGIN
13499
13500   IF NOT (checkPrivilege('MaintainVendors')) THEN
13501     RAISE EXCEPTION 'You do not have privileges to maintain Vendors.';
13502   END IF;
13503
13504   IF (LENGTH(COALESCE(NEW.vend_number, ''))=0) THEN
13505     RAISE EXCEPTION 'You must supply a valid Vendor Number.';
13506   END IF;
13507
13508   IF (LENGTH(COALESCE(NEW.vend_name, ''))=0) THEN
13509     RAISE EXCEPTION 'You must supply a valid Vendor Name.';
13510   END IF;
13511
13512   IF (NEW.vend_vendtype_id IS NULL) THEN
13513     RAISE EXCEPTION 'You must supply a valid Vendor Type ID.';
13514   END IF;
13515
13516   IF (NEW.vend_terms_id IS NULL) THEN
13517     RAISE EXCEPTION 'You must supply a valid Terms Code ID.';
13518   END IF;
13519
13520   IF (TG_OP = 'INSERT' AND fetchMetricText('CRMAccountNumberGeneration') IN ('A','O')) THEN
13521     PERFORM clearNumberIssue('CRMAccountNumber', NEW.vend_number);
13522   END IF;
13523
13524   NEW.vend_number := UPPER(NEW.vend_number);
13525
13526   RETURN NEW;
13527 END;
13528 $$;
13529
13530
13531 ALTER FUNCTION public._vendtrigger() OWNER TO admin;
13532
13533 --
13534 -- TOC entry 1087 (class 1255 OID 146565607)
13535 -- Dependencies: 4536 8
13536 -- Name: _vodistaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
13537 --
13538
13539 CREATE FUNCTION _vodistaftertrigger() RETURNS trigger
13540     LANGUAGE plpgsql
13541     AS $$
13542 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13543 -- See www.xtuple.com/CPAL for the full text of the software license.
13544 DECLARE
13545   _r RECORD;
13546
13547 BEGIN
13548   IF ( (TG_OP = 'UPDATE') OR (TG_OP = 'DELETE') ) THEN
13549     IF (OLD.vodist_tax_id <> -1) THEN
13550     -- Delete any existing voheadtax adjustment records
13551       DELETE FROM voheadtax
13552       WHERE ( (taxhist_parent_id=OLD.vodist_vohead_id)
13553         AND   (taxhist_tax_id=OLD.vodist_tax_id)
13554         AND   (taxhist_taxtype_id=getAdjustmentTaxTypeId()) );
13555     END IF;
13556   END IF;
13557
13558   IF (TG_OP = 'DELETE') THEN
13559     RETURN OLD;
13560   END IF;
13561
13562 -- Cache Voucher Head
13563   SELECT * INTO _r
13564   FROM vohead
13565   WHERE (vohead_id=NEW.vodist_vohead_id);
13566   IF (NOT FOUND) THEN
13567     RAISE EXCEPTION 'Voucher head not found';
13568   END IF;
13569
13570   IF (NEW.vodist_tax_id <> -1) THEN
13571   -- Insert adjustment voheadtax
13572     INSERT INTO voheadtax
13573       ( taxhist_parent_id,
13574         taxhist_taxtype_id,
13575         taxhist_tax_id,
13576         taxhist_basis,
13577         taxhist_basis_tax_id,
13578         taxhist_sequence,
13579         taxhist_percent,
13580         taxhist_amount,
13581         taxhist_tax,
13582         taxhist_docdate )
13583     VALUES
13584       ( NEW.vodist_vohead_id,
13585         getAdjustmentTaxTypeId(),
13586         NEW.vodist_tax_id,
13587         0,
13588         NULL,
13589         1,
13590         0,
13591         0,
13592         (NEW.vodist_amount * -1),
13593         _r.vohead_docdate );
13594   END IF;
13595
13596   RETURN NEW;
13597 END;
13598 $$;
13599
13600
13601 ALTER FUNCTION public._vodistaftertrigger() OWNER TO admin;
13602
13603 --
13604 -- TOC entry 1088 (class 1255 OID 146565608)
13605 -- Dependencies: 4536 8
13606 -- Name: _vodistbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13607 --
13608
13609 CREATE FUNCTION _vodistbeforetrigger() RETURNS trigger
13610     LANGUAGE plpgsql
13611     AS $$
13612 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13613 -- See www.xtuple.com/CPAL for the full text of the software license.
13614 DECLARE
13615
13616 BEGIN
13617   IF (TG_OP = 'DELETE') THEN
13618     IF (OLD.vodist_tax_id <> -1) THEN
13619     -- Delete any existing voheadtax adjustment records
13620       DELETE FROM voheadtax
13621       WHERE ( (taxhist_parent_id=OLD.vodist_vohead_id)
13622         AND   (taxhist_tax_id=OLD.vodist_tax_id)
13623         AND   (taxhist_taxtype_id=getAdjustmentTaxTypeId()) );
13624     END IF;
13625
13626     RETURN OLD;
13627   END IF;
13628
13629   RETURN NEW;
13630 END;
13631 $$;
13632
13633
13634 ALTER FUNCTION public._vodistbeforetrigger() OWNER TO admin;
13635
13636 --
13637 -- TOC entry 1089 (class 1255 OID 146565609)
13638 -- Dependencies: 4536 8
13639 -- Name: _voheadaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
13640 --
13641
13642 CREATE FUNCTION _voheadaftertrigger() RETURNS trigger
13643     LANGUAGE plpgsql
13644     AS $$
13645 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13646 -- See www.xtuple.com/CPAL for the full text of the software license.
13647 BEGIN
13648   IF (TG_OP = 'DELETE') THEN
13649     PERFORM releaseVoNumber(CAST(OLD.vohead_number AS INTEGER));
13650     RETURN OLD;
13651   END IF;
13652
13653   IF (TG_OP = 'INSERT') THEN
13654     PERFORM clearNumberIssue('VcNumber', NEW.vohead_number);
13655     RETURN NEW;
13656   END IF;
13657
13658   IF (TG_OP = 'UPDATE') THEN
13659     IF ( (COALESCE(NEW.vohead_taxzone_id,-1) <> COALESCE(OLD.vohead_taxzone_id,-1)) OR
13660          (NEW.vohead_docdate <> OLD.vohead_docdate) OR
13661          (NEW.vohead_curr_id <> OLD.vohead_curr_id) ) THEN
13662       PERFORM calculateTaxHist( 'voitemtax',
13663                                 voitem_id,
13664                                 NEW.vohead_taxzone_id,
13665                                 voitem_taxtype_id,
13666                                 NEW.vohead_docdate,
13667                                 NEW.vohead_curr_id,
13668                                 (vodist_amount * -1) )
13669       FROM voitem JOIN vodist ON ( (vodist_vohead_id=voitem_vohead_id) AND
13670                                    (vodist_poitem_id=voitem_poitem_id) )
13671       WHERE (voitem_vohead_id = NEW.vohead_id);
13672     END IF;
13673
13674     -- Touch any Misc Tax Distributions so voheadtax is recalculated
13675     IF (NEW.vohead_docdate <> OLD.vohead_docdate) THEN
13676       UPDATE vodist SET vodist_vohead_id=NEW.vohead_id
13677       WHERE ( (vodist_vohead_id=OLD.vohead_id)
13678         AND   (vodist_tax_id <> -1) );
13679     END IF;
13680   END IF;
13681
13682   RETURN NEW;
13683 END;
13684 $$;
13685
13686
13687 ALTER FUNCTION public._voheadaftertrigger() OWNER TO admin;
13688
13689 --
13690 -- TOC entry 1090 (class 1255 OID 146565610)
13691 -- Dependencies: 4536 8
13692 -- Name: _voheadbeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13693 --
13694
13695 CREATE FUNCTION _voheadbeforetrigger() RETURNS trigger
13696     LANGUAGE plpgsql
13697     AS $$
13698 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13699 -- See www.xtuple.com/CPAL for the full text of the software license.
13700 DECLARE
13701   _recurid     INTEGER;
13702   _newparentid INTEGER;
13703
13704 BEGIN
13705   IF (TG_OP = 'DELETE') THEN
13706     IF (OLD.vohead_posted) THEN
13707       -- Cannot delete a posted voucher
13708       RAISE EXCEPTION 'Cannot delete a posted voucher';
13709     END IF;
13710
13711     /* TODO: is setting recv_invoiced and poreject_invoiced to FALSE correct?
13712              this behavior is inherited from the now-defunct deleteVoucher.
13713      */
13714     UPDATE recv SET recv_vohead_id = NULL,
13715                     recv_voitem_id = NULL,
13716                     recv_invoiced  = FALSE
13717      WHERE recv_vohead_id = OLD.vohead_id;
13718
13719     UPDATE poreject SET poreject_vohead_id = NULL,
13720                         poreject_voitem_id = NULL,
13721                         poreject_invoiced  = FALSE
13722      WHERE poreject_vohead_id = OLD.vohead_id;
13723
13724     DELETE FROM vodist    WHERE vodist_vohead_id  = OLD.vohead_id;
13725     DELETE FROM voheadtax WHERE taxhist_parent_id = OLD.vohead_id;
13726     DELETE FROM voitem    WHERE voitem_vohead_id  = OLD.vohead_id;
13727
13728     SELECT recur_id INTO _recurid
13729       FROM recur
13730      WHERE ((recur_parent_id=OLD.vohead_id)
13731         AND (recur_parent_type='V'));
13732     IF (_recurid IS NOT NULL) THEN
13733       SELECT vohead_id INTO _newparentid
13734         FROM vohead
13735        WHERE ((vohead_recurring_vohead_id=OLD.vohead_id)
13736           AND (vohead_id!=OLD.vohead_id))
13737        ORDER BY vohead_docdate
13738        LIMIT 1;
13739
13740       IF (_newparentid IS NULL) THEN
13741         DELETE FROM recur WHERE recur_id=_recurid;
13742       ELSE
13743         UPDATE recur SET recur_parent_id=_newparentid
13744          WHERE recur_id=_recurid;
13745         UPDATE vohead SET vohead_recurring_vohead_id=_newparentid
13746          WHERE vohead_recurring_vohead_id=OLD.vohead_id
13747            AND vohead_id!=OLD.vohead_id;
13748       END IF;
13749     END IF;
13750
13751     RETURN OLD;
13752   END IF;
13753
13754   RETURN NEW;
13755 END;
13756 $$;
13757
13758
13759 ALTER FUNCTION public._voheadbeforetrigger() OWNER TO admin;
13760
13761 --
13762 -- TOC entry 1091 (class 1255 OID 146565611)
13763 -- Dependencies: 4536 8
13764 -- Name: _voitemaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
13765 --
13766
13767 CREATE FUNCTION _voitemaftertrigger() RETURNS trigger
13768     LANGUAGE plpgsql
13769     AS $$
13770 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13771 -- See www.xtuple.com/CPAL for the full text of the software license.
13772 DECLARE
13773   _r RECORD;
13774
13775 BEGIN
13776   IF (TG_OP = 'DELETE') THEN
13777     RETURN OLD;
13778   END IF;
13779
13780 -- Cache Voucher Head
13781   SELECT * INTO _r
13782   FROM vohead
13783   WHERE (vohead_id=NEW.voitem_vohead_id);
13784   IF (NOT FOUND) THEN
13785     RAISE EXCEPTION 'Voucher head not found';
13786   END IF;
13787
13788 -- Calculate Tax
13789   PERFORM calculateTaxHist( 'voitemtax',
13790                             NEW.voitem_id,
13791                             COALESCE(_r.vohead_taxzone_id, -1),
13792                             NEW.voitem_taxtype_id,
13793                             COALESCE(_r.vohead_docdate, CURRENT_DATE),
13794                             COALESCE(_r.vohead_curr_id, -1),
13795                             COALESCE(SUM(vodist_amount * -1), 0) )
13796   FROM vodist
13797   WHERE ( (vodist_vohead_id=_r.vohead_id)
13798     AND   (vodist_poitem_id=NEW.voitem_poitem_id) );
13799
13800   RETURN NEW;
13801 END;
13802 $$;
13803
13804
13805 ALTER FUNCTION public._voitemaftertrigger() OWNER TO admin;
13806
13807 --
13808 -- TOC entry 1092 (class 1255 OID 146565612)
13809 -- Dependencies: 4536 8
13810 -- Name: _voitembeforetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13811 --
13812
13813 CREATE FUNCTION _voitembeforetrigger() RETURNS trigger
13814     LANGUAGE plpgsql
13815     AS $$
13816 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13817 -- See www.xtuple.com/CPAL for the full text of the software license.
13818 DECLARE
13819
13820 BEGIN
13821   IF (TG_OP = 'DELETE') THEN
13822     DELETE FROM voitemtax
13823     WHERE (taxhist_parent_id=OLD.voitem_id);
13824
13825     RETURN OLD;
13826   END IF;
13827
13828   RETURN NEW;
13829 END;
13830 $$;
13831
13832
13833 ALTER FUNCTION public._voitembeforetrigger() OWNER TO admin;
13834
13835 --
13836 -- TOC entry 1093 (class 1255 OID 146565613)
13837 -- Dependencies: 4536 8
13838 -- Name: _warehoustrigger(); Type: FUNCTION; Schema: public; Owner: admin
13839 --
13840
13841 CREATE FUNCTION _warehoustrigger() RETURNS trigger
13842     LANGUAGE plpgsql
13843     AS $$
13844 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13845 -- See www.xtuple.com/CPAL for the full text of the software license.
13846 DECLARE
13847   _cmnttypeid INTEGER;
13848   _check      BOOLEAN;
13849   _checkId    INTEGER;
13850
13851 BEGIN
13852
13853   -- Checks
13854   -- Start with privileges
13855   IF (TG_OP = 'INSERT') THEN
13856     SELECT checkPrivilege('MaintainWarehouses') INTO _check;
13857     IF NOT (_check) THEN
13858       RAISE EXCEPTION 'You do not have privileges to add new Sites.';
13859     END IF;
13860   ELSE
13861     SELECT checkPrivilege('MaintainWarehouses') OR checkPrivilege('IssueCountTags') INTO _check;
13862     IF NOT (_check) THEN
13863       RAISE EXCEPTION 'You do not have privileges to alter a Site.';
13864     END IF;
13865   END IF;
13866
13867   -- Code is required
13868   IF (LENGTH(COALESCE(NEW.warehous_code,''))=0) THEN
13869     RAISE EXCEPTION 'You must supply a valid Site Code.';
13870   END IF;
13871   
13872   -- Sitetype is required
13873   IF (NEW.warehous_sitetype_id IS NULL) THEN
13874     RAISE EXCEPTION 'You must supply a valid Site Type.';
13875   END IF;
13876
13877   -- Cost Category is required for Transit types
13878   IF ((NEW.warehous_transit) AND (NEW.warehous_costcat_id IS NULL)) THEN
13879     RAISE EXCEPTION 'You must supply a valid Cost Category for Transit Sites.';
13880   END IF;
13881
13882   -- Code must be unique
13883   SELECT warehous_id INTO _checkId
13884   FROM whsinfo
13885   WHERE ( (UPPER(warehous_code)=UPPER(NEW.warehous_code))
13886     AND   (warehous_id<>NEW.warehous_id) );
13887   IF (FOUND) THEN
13888     RAISE EXCEPTION 'You must supply a unique Site Code.';
13889   END IF;
13890   
13891   -- Count Tag Prefix must be unique
13892   IF (TG_OP = 'INSERT') THEN
13893     SELECT warehous_id INTO _checkId
13894     FROM whsinfo
13895     WHERE (warehous_counttag_prefix=NEW.warehous_counttag_prefix);
13896   ELSE
13897     SELECT warehous_id INTO _checkId
13898     FROM whsinfo
13899     WHERE ( (warehous_counttag_prefix=NEW.warehous_counttag_prefix)
13900       AND   (warehous_id<>NEW.warehous_id) );
13901   END IF;
13902   IF (FOUND) THEN
13903     RAISE EXCEPTION 'You must supply a unique Count Tag Prefix.';
13904   END IF;
13905   
13906   -- Check Complete
13907   -- Change Log
13908   IF ( SELECT (metric_value='t')
13909        FROM metric
13910        WHERE (metric_name='WarehouseChangeLog') ) THEN
13911
13912 --  Cache the cmnttype_id for ChangeLog
13913     SELECT cmnttype_id INTO _cmnttypeid
13914     FROM cmnttype
13915     WHERE (cmnttype_name='ChangeLog');
13916     IF (FOUND) THEN
13917       IF (TG_OP = 'INSERT') THEN
13918         PERFORM postComment(_cmnttypeid, 'WH', NEW.warehous_id, 'Created');
13919
13920       ELSIF (TG_OP = 'UPDATE') THEN
13921         IF (OLD.warehous_code <> NEW.warehous_code) THEN
13922           PERFORM postComment( _cmnttypeid, 'WH', NEW.warehous_id,
13923                                ('Code Changed from "' || OLD.warehous_code || '" to "' || NEW.warehous_code || '"') );
13924         END IF;
13925
13926         IF (OLD.warehous_descrip <> NEW.warehous_descrip) THEN
13927           PERFORM postComment( _cmnttypeid, 'WH', NEW.warehous_id,
13928                                ( 'Description Changed from "' || OLD.warehous_descrip ||
13929                                  '" to "' || NEW.warehous_descrip || '"' ) );
13930         END IF;
13931
13932         IF (OLD.warehous_active <> NEW.warehous_active) THEN
13933           IF (NEW.warehous_active) THEN
13934             PERFORM postComment(_cmnttypeid, 'WH', NEW.warehous_id, 'Activated');
13935           ELSE
13936             PERFORM postComment(_cmnttypeid, 'WH', NEW.warehous_id, 'Deactivated');
13937           END IF;
13938         END IF;
13939
13940       END IF;
13941     END IF;
13942   END IF;
13943   
13944   RETURN NEW;
13945
13946 END;
13947 $$;
13948
13949
13950 ALTER FUNCTION public._warehoustrigger() OWNER TO admin;
13951
13952 --
13953 -- TOC entry 1094 (class 1255 OID 146565614)
13954 -- Dependencies: 4536 8
13955 -- Name: _whsezonetrigger(); Type: FUNCTION; Schema: public; Owner: admin
13956 --
13957
13958 CREATE FUNCTION _whsezonetrigger() RETURNS trigger
13959     LANGUAGE plpgsql
13960     AS $$
13961 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
13962 -- See www.xtuple.com/CPAL for the full text of the software license.
13963 DECLARE
13964   _check      BOOLEAN;
13965   _checkId    INTEGER;
13966
13967 BEGIN
13968
13969   -- Checks
13970   -- Start with privileges
13971   IF (TG_OP = 'INSERT') THEN
13972     SELECT checkPrivilege('MaintainWarehouses') INTO _check;
13973     IF NOT (_check) THEN
13974       RAISE EXCEPTION 'You do not have privileges to add new Site Zones.';
13975     END IF;
13976   ELSE
13977     SELECT checkPrivilege('MaintainWarehouses') INTO _check;
13978     IF NOT (_check) THEN
13979       RAISE EXCEPTION 'You do not have privileges to alter a Site Zone.';
13980     END IF;
13981   END IF;
13982
13983   -- Name is required
13984   IF (LENGTH(COALESCE(NEW.whsezone_name,''))=0) THEN
13985     RAISE EXCEPTION 'You must supply a valid Site Zone Name.';
13986   END IF;
13987   
13988   -- Site is required
13989   IF (NEW.whsezone_warehous_id IS NULL) THEN
13990     RAISE EXCEPTION 'You must supply a valid Site.';
13991   END IF;
13992
13993   RETURN NEW;
13994
13995 END;
13996 $$;
13997
13998
13999 ALTER FUNCTION public._whsezonetrigger() OWNER TO admin;
14000
14001 --
14002 -- TOC entry 1095 (class 1255 OID 146565615)
14003 -- Dependencies: 4536 8
14004 -- Name: _womatlaftertrigger(); Type: FUNCTION; Schema: public; Owner: admin
14005 --
14006
14007 CREATE FUNCTION _womatlaftertrigger() RETURNS trigger
14008     LANGUAGE plpgsql
14009     AS $$
14010 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14011 -- See www.xtuple.com/CPAL for the full text of the software license.
14012 DECLARE
14013
14014 BEGIN
14015
14016   IF (TG_OP = 'INSERT') THEN
14017
14018   --  Create any required P/R's
14019     PERFORM createPr('W', NEW.womatl_id)
14020        FROM itemsite 
14021       WHERE ((itemsite_id=NEW.womatl_itemsite_id)
14022         AND  (itemsite_createpr));
14023
14024   END IF;
14025
14026   RETURN NEW;
14027
14028 END;
14029 $$;
14030
14031
14032 ALTER FUNCTION public._womatlaftertrigger() OWNER TO admin;
14033
14034 --
14035 -- TOC entry 1097 (class 1255 OID 146565616)
14036 -- Dependencies: 4536 8
14037 -- Name: _wotrigger(); Type: FUNCTION; Schema: public; Owner: admin
14038 --
14039
14040 CREATE FUNCTION _wotrigger() RETURNS trigger
14041     LANGUAGE plpgsql
14042     AS $$
14043 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14044 -- See www.xtuple.com/CPAL for the full text of the software license.
14045 DECLARE
14046
14047 BEGIN
14048
14049   IF (TG_OP = 'INSERT') THEN
14050     PERFORM postEvent('WoCreated', 'W', NEW.wo_id,
14051                       itemsite_warehous_id,
14052                       (NEW.wo_number || '-' || NEW.wo_subnumber), 
14053                       NULL, NULL, NULL, NULL)
14054     FROM itemsite
14055     WHERE (itemsite_id=NEW.wo_itemsite_id)
14056       AND (NEW.wo_duedate <= (CURRENT_DATE + itemsite_eventfence));
14057
14058     PERFORM postComment('ChangeLog', 'W', NEW.wo_id, 'Created');
14059
14060     IF (fetchMetricText('WONumberGeneration') IN ('A','O')) THEN
14061       --- clear the number from the issue cache
14062       PERFORM clearNumberIssue('WoNumber', NEW.wo_number);
14063     END IF;
14064
14065     RETURN NEW;
14066
14067   ELSE
14068       IF (TG_OP = 'DELETE') THEN
14069       PERFORM postEvent('WoCancelled', 'W', OLD.wo_id,
14070                         itemsite_warehous_id,
14071                         (OLD.wo_number || '-' || OLD.wo_subnumber), 
14072                         NULL, NULL, NULL, NULL)
14073       FROM itemsite
14074       WHERE (itemsite_id=OLD.wo_itemsite_id)
14075         AND (OLD.wo_duedate <= (CURRENT_DATE + itemsite_eventfence));
14076
14077       DELETE FROM docass WHERE docass_source_id = OLD.wo_id AND docass_source_type = 'W';
14078       DELETE FROM docass WHERE docass_target_id = OLD.wo_id AND docass_target_type = 'W';
14079
14080       DELETE FROM comment
14081       WHERE ( (comment_source='W')
14082        AND (comment_source_id=OLD.wo_id) );
14083
14084       DELETE FROM charass
14085        WHERE ((charass_target_type='W')
14086          AND  (charass_target_id=OLD.wo_id));
14087
14088        RETURN OLD;
14089
14090     ELSE
14091       IF (TG_OP = 'UPDATE') THEN
14092
14093         IF (NEW.wo_qtyord <> OLD.wo_qtyord) THEN
14094           PERFORM postEvent('WoQtyChanged', 'W', NEW.wo_id,
14095                             itemsite_warehous_id,
14096                             (NEW.wo_number || '-' || NEW.wo_subnumber), 
14097                             NEW.wo_qtyord, OLD.wo_qtyord, NULL, NULL)
14098           FROM itemsite
14099           WHERE (itemsite_id=NEW.wo_itemsite_id)
14100             AND ( (NEW.wo_duedate <= (CURRENT_DATE + itemsite_eventfence))
14101              OR   (OLD.wo_duedate <= (CURRENT_DATE + itemsite_eventfence)) );
14102
14103           PERFORM postComment( 'ChangeLog', 'W', NEW.wo_id,
14104                                ( 'Qty. Ordered Changed from ' || formatQty(OLD.wo_qtyord) ||
14105                                  ' to ' || formatQty(NEW.wo_qtyord ) ) );
14106         END IF;
14107
14108         IF (NEW.wo_duedate <> OLD.wo_duedate) THEN
14109           PERFORM postEvent('WoDueDateChanged', 'W', NEW.wo_id,
14110                             itemsite_warehous_id,
14111                             (NEW.wo_number || '-' || NEW.wo_subnumber), 
14112                             NULL, NULL, NEW.wo_duedate, OLD.wo_duedate)
14113           FROM itemsite
14114           WHERE (itemsite_id=NEW.wo_itemsite_id)
14115             AND ( (NEW.wo_duedate <= (CURRENT_DATE + itemsite_eventfence))
14116              OR   (OLD.wo_duedate <= (CURRENT_DATE + itemsite_eventfence)) );
14117
14118           PERFORM postComment( 'ChangeLog', 'W', NEW.wo_id,
14119                                ( 'Due Date Changed from ' || formatDate(OLD.wo_duedate) ||
14120                                  ' to ' || formatDate(NEW.wo_duedate ) ) );
14121         END IF;
14122
14123         IF (NEW.wo_status <> OLD.wo_status) THEN
14124           PERFORM postComment( 'ChangeLog', 'W', NEW.wo_id,
14125                                ('Status Changed from ' || OLD.wo_status || ' to ' || NEW.wo_status) );
14126         END IF;
14127
14128       END IF; 
14129     END IF;
14130   END IF;
14131
14132   IF (TG_OP = 'UPDATE') THEN
14133     IF (NEW.wo_prj_id <> OLD.wo_prj_id) THEN
14134       UPDATE wo SET wo_prj_id=NEW.wo_prj_id
14135       WHERE (wo_ordtype='W')
14136         AND (wo_ordid=NEW.wo_id);
14137     END IF;
14138   END IF;
14139
14140   RETURN NEW;
14141
14142 END;
14143 $$;
14144
14145
14146 ALTER FUNCTION public._wotrigger() OWNER TO admin;
14147
14148 --
14149 -- TOC entry 1098 (class 1255 OID 146565617)
14150 -- Dependencies: 4536 8
14151 -- Name: acknowledgemessage(integer); Type: FUNCTION; Schema: public; Owner: admin
14152 --
14153
14154 CREATE FUNCTION acknowledgemessage(integer) RETURNS boolean
14155     LANGUAGE plpgsql
14156     AS $_$
14157 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14158 -- See www.xtuple.com/CPAL for the full text of the software license.
14159 DECLARE
14160   pMsgid ALIAS FOR $1;
14161
14162 BEGIN
14163
14164   UPDATE msguser
14165   SET msguser_viewed=CURRENT_TIMESTAMP
14166   WHERE ( (msguser_msg_id=pMsgid)
14167    AND (msguser_username=getEffectiveXtUser()) );
14168
14169   RETURN TRUE;
14170
14171 END;
14172 $_$;
14173
14174
14175 ALTER FUNCTION public.acknowledgemessage(integer) OWNER TO admin;
14176
14177 --
14178 -- TOC entry 1099 (class 1255 OID 146565618)
14179 -- Dependencies: 4536 8
14180 -- Name: actcost(integer); Type: FUNCTION; Schema: public; Owner: admin
14181 --
14182
14183 CREATE FUNCTION actcost(integer) RETURNS numeric
14184     LANGUAGE plpgsql
14185     AS $_$
14186 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14187 -- See www.xtuple.com/CPAL for the full text of the software license.
14188 BEGIN
14189   RETURN actCost($1, NULL, baseCurrId());
14190 END;
14191 $_$;
14192
14193
14194 ALTER FUNCTION public.actcost(integer) OWNER TO admin;
14195
14196 --
14197 -- TOC entry 1100 (class 1255 OID 146565619)
14198 -- Dependencies: 4536 8
14199 -- Name: actcost(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
14200 --
14201
14202 CREATE FUNCTION actcost(integer, integer) RETURNS numeric
14203     LANGUAGE plpgsql
14204     AS $_$
14205 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14206 -- See www.xtuple.com/CPAL for the full text of the software license.
14207 BEGIN
14208   RETURN actCost($1, $2, baseCurrId());
14209 END;
14210 $_$;
14211
14212
14213 ALTER FUNCTION public.actcost(integer, integer) OWNER TO admin;
14214
14215 --
14216 -- TOC entry 1101 (class 1255 OID 146565620)
14217 -- Dependencies: 4536 8
14218 -- Name: actcost(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
14219 --
14220
14221 CREATE FUNCTION actcost(integer, integer, integer) RETURNS numeric
14222     LANGUAGE plpgsql
14223     AS $_$
14224 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14225 -- See www.xtuple.com/CPAL for the full text of the software license.
14226 DECLARE
14227   pItemid ALIAS FOR $1;
14228   pBomitemid ALIAS FOR $2;
14229   pCurrid ALIAS FOR $3;
14230   _cost NUMERIC;
14231
14232 BEGIN
14233
14234   -- Return actual cost in the given currency at the current conversion rate
14235   SELECT SUM(CASE WHEN (bomitemcost_id IS NOT NULL) THEN
14236                   ROUND(currToCurr(bomitemcost_curr_id, pCurrid, bomitemcost_actcost, CURRENT_DATE), 6)
14237                   ELSE
14238                   ROUND(currToCurr(itemcost_curr_id, pCurrid, itemcost_actcost, CURRENT_DATE), 6)
14239              END) INTO _cost
14240   FROM itemcost
14241     LEFT OUTER JOIN bomitemcost ON (bomitemcost_bomitem_id=pBomitemid AND bomitemcost_costelem_id=itemcost_costelem_id)
14242   WHERE (itemcost_item_id=pItemid);
14243
14244   IF (_cost IS NULL) THEN
14245     RETURN 0;
14246   ELSE
14247     RETURN _cost;
14248   END IF;
14249
14250 END;
14251 $_$;
14252
14253
14254 ALTER FUNCTION public.actcost(integer, integer, integer) OWNER TO admin;
14255
14256 --
14257 -- TOC entry 1102 (class 1255 OID 146565621)
14258 -- Dependencies: 4536 8
14259 -- Name: addrusecount(integer); Type: FUNCTION; Schema: public; Owner: admin
14260 --
14261
14262 CREATE FUNCTION addrusecount(integer) RETURNS integer
14263     LANGUAGE plpgsql STABLE
14264     AS $_$
14265 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14266 -- See www.xtuple.com/CPAL for the full text of the software license.
14267 DECLARE
14268   pAddrId ALIAS FOR $1;
14269   _fk RECORD;
14270   _r RECORD;
14271   _seq INTEGER;
14272   _col TEXT;
14273   _qry TEXT;
14274   _count INTEGER = 0;
14275
14276 BEGIN
14277   -- Determine where this address is used by analyzing foreign key linkages
14278   -- TO DO: Can this be rationalized with cntctused(int)?
14279   FOR _fk IN
14280     SELECT pg_namespace.nspname AS schemaname, con.relname AS tablename, conkey AS seq, conrelid AS class_id 
14281     FROM pg_constraint, pg_class f, pg_class con, pg_namespace
14282     WHERE confrelid=f.oid
14283     AND conrelid=con.oid
14284     AND f.relname = 'addr'
14285     AND con.relnamespace=pg_namespace.oid
14286     AND con.relname NOT IN ('pohead') -- exception(s) where address key doesn't actually drive document information
14287   LOOP
14288     -- Validate
14289     IF (ARRAY_UPPER(_fk.seq,1) > 1) THEN
14290       RAISE EXCEPTION 'Checks to tables where the address is one of multiple foreign key columns is not supported. Error on Table: %',
14291         pg_namespace.nspname || '.' || con.relname;
14292     END IF;
14293     
14294     _seq := _fk.seq[1];
14295
14296     -- Get the specific column name
14297     SELECT attname INTO _col
14298     FROM pg_attribute, pg_class
14299     WHERE ((attrelid=pg_class.oid)
14300     AND (pg_class.oid=_fk.class_id)
14301     AND (attnum=_seq));
14302
14303     -- See if there are dependencies
14304     _qry := 'SELECT * 
14305             FROM ' || _fk.schemaname || '.' || _fk.tablename || '
14306             WHERE ('|| _col || '=' || pAddrId || ');';
14307
14308     FOR _r IN 
14309       EXECUTE _qry
14310     LOOP
14311       _count := _count + 1;
14312     END LOOP;
14313          
14314   END LOOP;
14315
14316   RETURN _count;
14317
14318 END;
14319 $_$;
14320
14321
14322 ALTER FUNCTION public.addrusecount(integer) OWNER TO admin;
14323
14324 --
14325 -- TOC entry 1103 (class 1255 OID 146565622)
14326 -- Dependencies: 4536 8
14327 -- Name: addtaxtoglseries(integer, text, text, text, integer, date, date, text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
14328 --
14329
14330 CREATE FUNCTION addtaxtoglseries(integer, text, text, text, integer, date, date, text, integer, text) RETURNS numeric
14331     LANGUAGE plpgsql
14332     AS $_$
14333 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14334 -- See www.xtuple.com/CPAL for the full text of the software license.
14335 DECLARE
14336   pSequence     ALIAS FOR $1;
14337   pSource       ALIAS FOR $2;
14338   pDocType      ALIAS FOR $3;
14339   pDocNumber    ALIAS FOR $4;
14340   pCurrId     ALIAS FOR $5;
14341   pExchDate     ALIAS FOR $6;
14342   pDistDate     ALIAS FOR $7;
14343   pTableName    ALIAS FOR $8;
14344   pParentId     ALIAS FOR $9;
14345   pNotes        ALIAS FOR $10;
14346
14347   _count        INTEGER := 0;
14348   _baseTax      NUMERIC := 0;
14349   _returnVal    NUMERIC := 0;
14350   _t            RECORD;
14351   _test INTEGER := 0;
14352
14353 BEGIN
14354
14355 -- This is just a fancy select statement on taxhist.
14356 -- Because all tax records tables inherit from taxhist,
14357 -- we can use the same select statement for all.
14358 -- https://www.postgresql.org/docs/8.1/static/ddl-inherit.html
14359 -- pTableName in the where clause narrows down the selection
14360 -- to the correct sub table.
14361
14362   FOR _t IN SELECT *
14363             FROM taxhist JOIN tax ON (tax_id = taxhist_tax_id)
14364                          JOIN pg_class ON (pg_class.oid = taxhist.tableoid)
14365             WHERE ( (taxhist_parent_id = pParentId)
14366               AND   (relname = pTableName) ) LOOP
14367
14368     _count := _count + 1;
14369     _baseTax := currToBase(pCurrId, _t.taxhist_tax, pExchDate);
14370     _returnVal := _returnVal + _baseTax;
14371     PERFORM insertIntoGLSeries( pSequence, pSource, pDocType, pDocNumber,
14372                                 _t.tax_sales_accnt_id, _baseTax,
14373                                 pDistDate, pNotes );
14374                                 
14375     UPDATE taxhist SET 
14376       taxhist_docdate=pExchDate,
14377       taxhist_distdate=pDistDate,
14378       taxhist_curr_id=pCurrId,
14379       taxhist_curr_rate=curr_rate
14380     FROM curr_rate
14381     WHERE ((taxhist_id=_t.taxhist_id)
14382       AND (pCurrId=curr_id)
14383       AND ( pExchDate BETWEEN curr_effective 
14384                           AND curr_expires) );
14385
14386   END LOOP;
14387
14388   RETURN _returnVal;
14389 END;
14390 $_$;
14391
14392
14393 ALTER FUNCTION public.addtaxtoglseries(integer, text, text, text, integer, date, date, text, integer, text) OWNER TO admin;
14394
14395 --
14396 -- TOC entry 1104 (class 1255 OID 146565623)
14397 -- Dependencies: 4536 8
14398 -- Name: addtopackinglistbatch(integer); Type: FUNCTION; Schema: public; Owner: admin
14399 --
14400
14401 CREATE FUNCTION addtopackinglistbatch(integer) RETURNS integer
14402     LANGUAGE plpgsql
14403     AS $_$
14404 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14405 -- See www.xtuple.com/CPAL for the full text of the software license.
14406 DECLARE
14407   pSoheadid     ALIAS FOR $1;
14408   returnVal     INTEGER;
14409 BEGIN
14410
14411   -- MIN because error codes are negative
14412   SELECT MIN(addToPackingListBatch('SO', pSoheadid, shiphead_id)) INTO returnVal
14413   FROM shiphead
14414   WHERE ((shiphead_order_id=pSoheadid)
14415     AND  (NOT shiphead_shipped)
14416     AND  (shiphead_order_type='SO'));
14417   IF (NOT FOUND OR returnVal IS NULL) THEN
14418     returnVal := addToPackingListBatch('SO', pSoheadid, NULL);
14419   END IF;
14420
14421   RETURN returnVal;
14422 END;
14423 $_$;
14424
14425
14426 ALTER FUNCTION public.addtopackinglistbatch(integer) OWNER TO admin;
14427
14428 --
14429 -- TOC entry 1057 (class 1255 OID 146565624)
14430 -- Dependencies: 4536 8
14431 -- Name: addtopackinglistbatch(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
14432 --
14433
14434 CREATE FUNCTION addtopackinglistbatch(integer, integer) RETURNS integer
14435     LANGUAGE plpgsql
14436     AS $_$
14437 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14438 -- See www.xtuple.com/CPAL for the full text of the software license.
14439 BEGIN
14440   RETURN addToPackingListBatch('SO', $1, $2);
14441 END;
14442 $_$;
14443
14444
14445 ALTER FUNCTION public.addtopackinglistbatch(integer, integer) OWNER TO admin;
14446
14447 --
14448 -- TOC entry 1081 (class 1255 OID 146565625)
14449 -- Dependencies: 4536 8
14450 -- Name: addtopackinglistbatch(text, integer); Type: FUNCTION; Schema: public; Owner: admin
14451 --
14452
14453 CREATE FUNCTION addtopackinglistbatch(text, integer) RETURNS integer
14454     LANGUAGE plpgsql
14455     AS $_$
14456 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14457 -- See www.xtuple.com/CPAL for the full text of the software license.
14458 DECLARE
14459   pheadtype     ALIAS FOR $1;
14460   pheadid       ALIAS FOR $2;
14461   returnVal     INTEGER;
14462 BEGIN
14463   -- MIN because error codes are negative
14464   SELECT MIN(addToPackingListBatch(pheadtype, pheadid, shiphead_id)) INTO returnVal
14465   FROM shiphead
14466   WHERE ((shiphead_order_id=pheadid)
14467     AND  (NOT shiphead_shipped)
14468     AND  (shiphead_order_type=pheadtype));
14469
14470   IF (NOT FOUND OR returnVal IS NULL) THEN
14471     returnVal := addToPackingListBatch(pheadtype, pheadid, NULL);
14472   END IF;
14473
14474   RETURN returnVal;
14475 END;
14476 $_$;
14477
14478
14479 ALTER FUNCTION public.addtopackinglistbatch(text, integer) OWNER TO admin;
14480
14481 --
14482 -- TOC entry 1105 (class 1255 OID 146565626)
14483 -- Dependencies: 4536 8
14484 -- Name: addtopackinglistbatch(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
14485 --
14486
14487 CREATE FUNCTION addtopackinglistbatch(text, integer, integer) RETURNS integer
14488     LANGUAGE plpgsql
14489     AS $_$
14490 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14491 -- See www.xtuple.com/CPAL for the full text of the software license.
14492 DECLARE
14493   pheadtype     ALIAS FOR $1;
14494   pheadid       ALIAS FOR $2;
14495   pshipheadid   ALIAS FOR $3;
14496   _check INTEGER;
14497
14498 BEGIN
14499   SELECT pack_id INTO _check
14500   FROM pack
14501   WHERE ((pack_head_id=pheadid)
14502     AND  ((pack_shiphead_id=pshipheadid) OR 
14503           (pshipheadid IS NULL AND pack_shiphead_id IS NULL))
14504     AND  (pack_head_type=pheadtype)
14505         );
14506
14507   IF (NOT FOUND) THEN
14508     INSERT INTO pack
14509     ( pack_head_type, pack_head_id, pack_shiphead_id, pack_printed )
14510     VALUES
14511     ( pheadtype, pheadid, pshipheadid, FALSE );
14512     -- Auto Firm Sales Orders conditionally based on metric
14513     IF ( (pheadtype = 'SO') AND (fetchMetricBool('FirmSalesOrderPackingList')) ) THEN
14514       UPDATE coitem SET coitem_firm=TRUE
14515       WHERE (coitem_cohead_id=pheadid);
14516     END IF; 
14517   END IF;
14518
14519   RETURN pheadid;
14520
14521 END;
14522 $_$;
14523
14524
14525 ALTER FUNCTION public.addtopackinglistbatch(text, integer, integer) OWNER TO admin;
14526
14527 --
14528 -- TOC entry 1106 (class 1255 OID 146565627)
14529 -- Dependencies: 4536 8
14530 -- Name: addtopackinglistbatch(integer, text, integer); Type: FUNCTION; Schema: public; Owner: admin
14531 --
14532
14533 CREATE FUNCTION addtopackinglistbatch(integer, text, integer) RETURNS integer
14534     LANGUAGE plpgsql
14535     AS $_$
14536 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14537 -- See www.xtuple.com/CPAL for the full text of the software license.
14538 DECLARE
14539   pwarehousid   ALIAS FOR $1;
14540   pheadtype     ALIAS FOR $2;
14541   pheadid       ALIAS FOR $3;
14542   returnVal     INTEGER;
14543 BEGIN
14544   -- MIN because error codes are negative
14545   SELECT MIN(addToPackingListBatch(pheadtype, pheadid,
14546                                    getOpenShipmentId(pheadtype, pheadid, pwarehousid))) INTO returnVal;
14547
14548   IF (NOT FOUND OR returnVal IS NULL) THEN
14549     returnVal := addToPackingListBatch(pheadtype, pheadid, NULL);
14550   END IF;
14551
14552   RETURN returnVal;
14553 END;
14554 $_$;
14555
14556
14557 ALTER FUNCTION public.addtopackinglistbatch(integer, text, integer) OWNER TO admin;
14558
14559 --
14560 -- TOC entry 1107 (class 1255 OID 146565628)
14561 -- Dependencies: 4536 8
14562 -- Name: adjustinvvalue(integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
14563 --
14564
14565 CREATE FUNCTION adjustinvvalue(integer, numeric, integer) RETURNS integer
14566     LANGUAGE plpgsql
14567     AS $_$
14568 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14569 -- See www.xtuple.com/CPAL for the full text of the software license.
14570 DECLARE
14571   pItemsiteid     ALIAS FOR $1;
14572   pNewValue       ALIAS FOR $2;
14573   pAccountid      ALIAS FOR $3;
14574   _delta          NUMERIC;
14575   _glreturn       INTEGER;
14576   _invhistid      INTEGER;
14577   _itemlocSeries  INTEGER;
14578
14579 BEGIN
14580
14581   SELECT pNewValue - itemsite_value INTO _delta
14582   FROM itemsite
14583   WHERE (itemsite_id=pItemsiteid)
14584   FOR UPDATE;
14585
14586   IF (NOT FOUND) THEN
14587     RETURN -1;
14588   END IF;
14589
14590   SELECT insertGLTransaction('I/M', '', 'Post Value',
14591          'Inventory Value Adjustment for ' || item_number,
14592          COALESCE (pAccountid, costcat_adjustment_accnt_id),
14593          costcat_asset_accnt_id, -1,
14594          _delta, CURRENT_DATE) INTO _glreturn
14595   FROM itemsite
14596    JOIN costcat ON (itemsite_costcat_id=costcat_id)
14597    JOIN item ON (itemsite_item_id=item_id)
14598   WHERE (itemsite_id=pItemsiteid);
14599
14600 --  Create the AD transaction
14601   INSERT INTO invhist
14602    ( invhist_itemsite_id,
14603      invhist_transdate, invhist_transtype, invhist_invqty,
14604      invhist_qoh_before, invhist_qoh_after,
14605      invhist_docnumber, invhist_comments,
14606      invhist_invuom, invhist_unitcost, invhist_hasdetail,
14607      invhist_costmethod, invhist_value_before, invhist_value_after,
14608      invhist_series )
14609   SELECT itemsite_id,
14610          CURRENT_TIMESTAMP, 'AD', 0.0,
14611          itemsite_qtyonhand, itemsite_qtyonhand,
14612          '', 'Inventory Value Adjustment',
14613          uom_name, _delta, FALSE,
14614          itemsite_costmethod, itemsite_value, pNewValue,
14615          0
14616   FROM itemsite, item, uom
14617   WHERE ( (itemsite_item_id=item_id)
14618    AND (item_inv_uom_id=uom_id)
14619    AND (itemsite_id=pItemsiteid) );
14620
14621   UPDATE itemsite SET itemsite_value=pNewValue
14622   WHERE (itemsite_id=pItemsiteid);
14623
14624   RETURN 0;
14625
14626 END;
14627 $_$;
14628
14629
14630 ALTER FUNCTION public.adjustinvvalue(integer, numeric, integer) OWNER TO admin;
14631
14632 --
14633 -- TOC entry 1108 (class 1255 OID 146565629)
14634 -- Dependencies: 4536 8
14635 -- Name: adjustments(text); Type: FUNCTION; Schema: public; Owner: admin
14636 --
14637
14638 CREATE FUNCTION adjustments(text) RETURNS boolean
14639     LANGUAGE plpgsql
14640     AS $_$
14641 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14642 -- See www.xtuple.com/CPAL for the full text of the software license.
14643 DECLARE
14644   pTransType ALIAS FOR $1;
14645
14646 BEGIN
14647   IF (pTransType IN ('CC', 'AD')) THEN
14648     RETURN TRUE;
14649   ELSE
14650     RETURN FALSE;
14651   END IF;
14652
14653 END;
14654 $_$;
14655
14656
14657 ALTER FUNCTION public.adjustments(text) OWNER TO admin;
14658
14659 --
14660 -- TOC entry 1109 (class 1255 OID 146565630)
14661 -- Dependencies: 4536 8
14662 -- Name: allocatedforso(integer, date); Type: FUNCTION; Schema: public; Owner: admin
14663 --
14664
14665 CREATE FUNCTION allocatedforso(integer, date) RETURNS numeric
14666     LANGUAGE plpgsql STABLE
14667     AS $_$
14668 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14669 -- See www.xtuple.com/CPAL for the full text of the software license.
14670 DECLARE
14671   pItemsiteid ALIAS FOR $1;
14672   pDate ALIAS FOR $2;
14673
14674 BEGIN
14675
14676   RETURN allocatedForSo(pItemsiteid, startOfTime(), pDate);
14677
14678 END;
14679 $_$;
14680
14681
14682 ALTER FUNCTION public.allocatedforso(integer, date) OWNER TO admin;
14683
14684 --
14685 -- TOC entry 1110 (class 1255 OID 146565631)
14686 -- Dependencies: 4536 8
14687 -- Name: allocatedforso(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
14688 --
14689
14690 CREATE FUNCTION allocatedforso(integer, integer) RETURNS numeric
14691     LANGUAGE plpgsql STABLE
14692     AS $_$
14693 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14694 -- See www.xtuple.com/CPAL for the full text of the software license.
14695 DECLARE
14696   pItemsiteid ALIAS FOR $1;
14697   pDate ALIAS FOR $2;
14698
14699 BEGIN
14700
14701   RETURN allocatedForSo(pItemsiteid, startOfTime(), (CURRENT_DATE + pDate));
14702
14703 END;
14704 $_$;
14705
14706
14707 ALTER FUNCTION public.allocatedforso(integer, integer) OWNER TO admin;
14708
14709 --
14710 -- TOC entry 1111 (class 1255 OID 146565632)
14711 -- Dependencies: 4536 8
14712 -- Name: allocatedforso(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
14713 --
14714
14715 CREATE FUNCTION allocatedforso(integer, date, date) RETURNS numeric
14716     LANGUAGE plpgsql STABLE
14717     AS $_$
14718 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14719 -- See www.xtuple.com/CPAL for the full text of the software license.
14720 DECLARE
14721   pItemsiteid ALIAS FOR $1;
14722   pStartDate ALIAS FOR $2;
14723   pEndDate ALIAS FOR $3;
14724   _qty NUMERIC;
14725
14726 BEGIN
14727
14728   SELECT COALESCE(SUM(noNeg(itemuomtouom(itemsite_item_id, coitem_qty_uom_id, NULL, coitem_qtyord - (coitem_qtyshipped + qtyAtShipping(coitem_id)) + coitem_qtyreturned))), 0.0) INTO _qty
14729   FROM coitem, itemsite, item
14730   WHERE ( (coitem_itemsite_id=itemsite_id)
14731     AND (itemsite_item_id=item_id)
14732     AND (coitem_status='O')
14733     AND (coitem_itemsite_id=pItemsiteid)
14734     AND (coitem_scheddate BETWEEN pStartDate AND pEndDate) );
14735
14736   RETURN _qty;
14737
14738 END;
14739 $_$;
14740
14741
14742 ALTER FUNCTION public.allocatedforso(integer, date, date) OWNER TO admin;
14743
14744 --
14745 -- TOC entry 1112 (class 1255 OID 146565633)
14746 -- Dependencies: 4536 8
14747 -- Name: allocatedforwo(integer, date); Type: FUNCTION; Schema: public; Owner: admin
14748 --
14749
14750 CREATE FUNCTION allocatedforwo(integer, date) RETURNS numeric
14751     LANGUAGE plpgsql STABLE
14752     AS $_$
14753 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14754 -- See www.xtuple.com/CPAL for the full text of the software license.
14755 DECLARE
14756   pItemsiteid ALIAS FOR $1;
14757   pDate ALIAS FOR $2;
14758
14759 BEGIN
14760
14761   RETURN allocatedForWo(pItemsiteid, startOfTime(), pDate);
14762
14763 END;
14764 $_$;
14765
14766
14767 ALTER FUNCTION public.allocatedforwo(integer, date) OWNER TO admin;
14768
14769 --
14770 -- TOC entry 1113 (class 1255 OID 146565634)
14771 -- Dependencies: 4536 8
14772 -- Name: allocatedforwo(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
14773 --
14774
14775 CREATE FUNCTION allocatedforwo(integer, integer) RETURNS numeric
14776     LANGUAGE plpgsql STABLE
14777     AS $_$
14778 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14779 -- See www.xtuple.com/CPAL for the full text of the software license.
14780 DECLARE
14781   pItemsiteid ALIAS FOR $1;
14782   pLookAheadDays ALIAS FOR $2;
14783
14784 BEGIN
14785
14786   RETURN allocatedForWo(pItemsiteid, startOfTime(), (CURRENT_DATE + pLookaheadDays));
14787
14788 END;
14789 $_$;
14790
14791
14792 ALTER FUNCTION public.allocatedforwo(integer, integer) OWNER TO admin;
14793
14794 --
14795 -- TOC entry 1116 (class 1255 OID 146565635)
14796 -- Dependencies: 4536 8
14797 -- Name: allocatedforwo(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
14798 --
14799
14800 CREATE FUNCTION allocatedforwo(integer, date, date) RETURNS numeric
14801     LANGUAGE plpgsql STABLE
14802     AS $_$
14803 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14804 -- See www.xtuple.com/CPAL for the full text of the software license.
14805 DECLARE
14806   pItemsiteid ALIAS FOR $1;
14807   pStartDate ALIAS FOR $2;
14808   pEndDate ALIAS FOR $3;
14809   _itemtype TEXT;
14810   _qty NUMERIC;
14811
14812 BEGIN
14813
14814   SELECT item_type INTO _itemtype
14815   FROM itemsite JOIN item ON (item_id=itemsite_item_id)
14816   WHERE (itemsite_id=pItemsiteid);
14817
14818   IF (_itemtype != 'T') THEN
14819     SELECT
14820       COALESCE(SUM(noNeg(itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq - womatl_qtyiss))), 0.0) INTO _qty
14821     FROM womatl JOIN wo ON (wo_id=womatl_wo_id AND wo_status IN ('E','I','R'))
14822                 JOIN itemsite ON (itemsite_id=womatl_itemsite_id)
14823     WHERE (womatl_itemsite_id=pItemsiteid)
14824       AND (womatl_duedate BETWEEN pStartDate AND pEndDate);
14825   ELSE
14826     SELECT
14827       COALESCE(SUM(noNeg(itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq))), 0.0)  -
14828         (
14829                 SELECT COALESCE(SUM(invhist_invqty),0) 
14830                 FROM itemsite, item, wo, womatl
14831                         LEFT OUTER JOIN womatlpost ON (womatl_id=womatlpost_womatl_id)
14832                         LEFT OUTER JOIN invhist ON ((womatlpost_invhist_id=invhist_id)
14833                             AND (invhist_invqty > 0))
14834                 WHERE ( (womatl_itemsite_id=pItemsiteid)
14835                 AND (womatl_itemsite_id=itemsite_id)
14836                 AND (itemsite_item_id=item_id)
14837                 AND (womatl_duedate BETWEEN pStartDate AND pEndDate) 
14838                 AND (wo_id=womatl_wo_id)
14839                 AND (wo_status IN ('E','I','R')) )
14840         ) INTO _qty
14841     FROM womatl JOIN wo ON (wo_id=womatl_wo_id AND wo_status IN ('E','I','R'))
14842                 JOIN itemsite ON (itemsite_id=womatl_itemsite_id)
14843     WHERE (womatl_itemsite_id=pItemsiteid)
14844       AND (womatl_duedate BETWEEN pStartDate AND pEndDate);
14845   END IF;
14846
14847   RETURN COALESCE(_qty,0);
14848
14849 END;
14850 $_$;
14851
14852
14853 ALTER FUNCTION public.allocatedforwo(integer, date, date) OWNER TO admin;
14854
14855 --
14856 -- TOC entry 1117 (class 1255 OID 146565636)
14857 -- Dependencies: 4536 8
14858 -- Name: alterencrypt(text, text); Type: FUNCTION; Schema: public; Owner: admin
14859 --
14860
14861 CREATE FUNCTION alterencrypt(text, text) RETURNS integer
14862     LANGUAGE plpgsql
14863     AS $_$
14864 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14865 -- See www.xtuple.com/CPAL for the full text of the software license.
14866 DECLARE
14867   pOldKey ALIAS FOR $1;
14868   pNewKey ALIAS FOR $2;
14869   _cc RECORD;
14870   _ccaud RECORD;
14871   _metricenc RECORD;
14872   num_updated INTEGER;
14873
14874 BEGIN
14875
14876   num_updated := 0;
14877
14878 -- Update ccard
14879
14880   FOR _cc IN SELECT ccard_id, 
14881              decrypt(setbytea(ccard_name), setbytea(pOldKey), 'bf') AS ccard_name,
14882              decrypt(setbytea(ccard_address1), setbytea(pOldKey), 'bf') AS ccard_address1,
14883              decrypt(setbytea(ccard_address2), setbytea(pOldKey), 'bf') AS ccard_address2,
14884              decrypt(setbytea(ccard_city), setbytea(pOldKey), 'bf') AS ccard_city,
14885              decrypt(setbytea(ccard_state), setbytea(pOldKey), 'bf') AS ccard_state,
14886              decrypt(setbytea(ccard_zip), setbytea(pOldKey), 'bf') AS ccard_zip,
14887              decrypt(setbytea(ccard_country), setbytea(pOldKey), 'bf') AS ccard_country,
14888              decrypt(setbytea(ccard_number), setbytea(pOldKey), 'bf') AS ccard_number,
14889              decrypt(setbytea(ccard_month_expired), setbytea(pOldKey), 'bf') AS ccard_month_expired,
14890              decrypt(setbytea(ccard_year_expired), setbytea(pOldKey), 'bf') AS ccard_year_expired
14891       FROM ccard LOOP
14892
14893       UPDATE ccard
14894              set ccard_name = encrypt(setbytea(_cc.ccard_name), setbytea(pNewKey), 'bf'),
14895                  ccard_address1 = encrypt(setbytea(_cc.ccard_address1), setbytea(pNewKey), 'bf'),
14896                  ccard_address2 = encrypt(setbytea(_cc.ccard_address2), setbytea(pNewKey), 'bf'),
14897                  ccard_city = encrypt(setbytea(_cc.ccard_city), setbytea(pNewKey), 'bf'),
14898                  ccard_state = encrypt(setbytea(_cc.ccard_state), setbytea(pNewKey), 'bf'),
14899                  ccard_zip = encrypt(setbytea(_cc.ccard_zip), setbytea(pNewKey), 'bf'),
14900                  ccard_country = encrypt(setbytea(_cc.ccard_country), setbytea(pNewKey), 'bf'),
14901                  ccard_number = encrypt(setbytea(_cc.ccard_number), setbytea(pNewKey), 'bf'),
14902                  ccard_month_expired = encrypt(setbytea(_cc.ccard_month_expired), setbytea(pNewKey), 'bf'),
14903                  ccard_year_expired = encrypt(setbytea(_cc.ccard_year_expired), setbytea(pNewKey), 'bf')
14904       WHERE ccard_id = _cc.ccard_id;
14905
14906       num_updated := num_updated + 1;
14907
14908   END LOOP;
14909
14910 -- Update ccardaud
14911
14912   FOR _ccaud IN SELECT ccardaud_id, 
14913              decrypt(setbytea(ccardaud_ccard_name_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_name_old,
14914              decrypt(setbytea(ccardaud_ccard_name_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_name_new,
14915              decrypt(setbytea(ccardaud_ccard_address1_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_address1_old,
14916              decrypt(setbytea(ccardaud_ccard_address1_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_address1_new,
14917              decrypt(setbytea(ccardaud_ccard_address2_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_address2_old,
14918              decrypt(setbytea(ccardaud_ccard_address2_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_address2_new,
14919              decrypt(setbytea(ccardaud_ccard_city_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_city_old,
14920              decrypt(setbytea(ccardaud_ccard_city_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_city_new,
14921              decrypt(setbytea(ccardaud_ccard_state_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_state_old,
14922              decrypt(setbytea(ccardaud_ccard_state_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_state_new,
14923              decrypt(setbytea(ccardaud_ccard_zip_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_zip_old,
14924              decrypt(setbytea(ccardaud_ccard_zip_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_zip_new,
14925              decrypt(setbytea(ccardaud_ccard_country_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_country_old,
14926              decrypt(setbytea(ccardaud_ccard_country_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_country_new,
14927              decrypt(setbytea(ccardaud_ccard_number_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_number_old,
14928              decrypt(setbytea(ccardaud_ccard_number_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_number_new,
14929              decrypt(setbytea(ccardaud_ccard_month_expired_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_month_expired_old,
14930              decrypt(setbytea(ccardaud_ccard_month_expired_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_month_expired_new,
14931              decrypt(setbytea(ccardaud_ccard_year_expired_old), setbytea(pOldKey), 'bf') AS ccardaud_ccard_year_expired_old,
14932              decrypt(setbytea(ccardaud_ccard_year_expired_new), setbytea(pOldKey), 'bf') AS ccardaud_ccard_year_expired_new
14933       FROM ccardaud LOOP
14934
14935       UPDATE ccardaud
14936              set ccardaud_ccard_name_old = encrypt(setbytea(_ccaud.ccardaud_ccard_name_old), setbytea(pNewKey), 'bf'),
14937                  ccardaud_ccard_name_new = encrypt(setbytea(_ccaud.ccardaud_ccard_name_new), setbytea(pNewKey), 'bf'),
14938                  ccardaud_ccard_address1_old = encrypt(setbytea(_ccaud.ccardaud_ccard_address1_old), setbytea(pNewKey), 'bf'),
14939                  ccardaud_ccard_address1_new = encrypt(setbytea(_ccaud.ccardaud_ccard_address1_new), setbytea(pNewKey), 'bf'),
14940                  ccardaud_ccard_address2_old = encrypt(setbytea(_ccaud.ccardaud_ccard_address2_old), setbytea(pNewKey), 'bf'),
14941                  ccardaud_ccard_address2_new = encrypt(setbytea(_ccaud.ccardaud_ccard_address2_new), setbytea(pNewKey), 'bf'),
14942                  ccardaud_ccard_city_old = encrypt(setbytea(_ccaud.ccardaud_ccard_city_old), setbytea(pNewKey), 'bf'),
14943                  ccardaud_ccard_city_new = encrypt(setbytea(_ccaud.ccardaud_ccard_city_new), setbytea(pNewKey), 'bf'),
14944                  ccardaud_ccard_state_old = encrypt(setbytea(_ccaud.ccardaud_ccard_state_old), setbytea(pNewKey), 'bf'),
14945                  ccardaud_ccard_state_new = encrypt(setbytea(_ccaud.ccardaud_ccard_state_new), setbytea(pNewKey), 'bf'),
14946                  ccardaud_ccard_zip_old = encrypt(setbytea(_ccaud.ccardaud_ccard_zip_old), setbytea(pNewKey), 'bf'),
14947                  ccardaud_ccard_zip_new = encrypt(setbytea(_ccaud.ccardaud_ccard_zip_new), setbytea(pNewKey), 'bf'),
14948                  ccardaud_ccard_country_old = encrypt(setbytea(_ccaud.ccardaud_ccard_country_old), setbytea(pNewKey), 'bf'),
14949                  ccardaud_ccard_country_new = encrypt(setbytea(_ccaud.ccardaud_ccard_country_new), setbytea(pNewKey), 'bf'),
14950                  ccardaud_ccard_number_old = encrypt(setbytea(_ccaud.ccardaud_ccard_number_old), setbytea(pNewKey), 'bf'),
14951                  ccardaud_ccard_number_new = encrypt(setbytea(_ccaud.ccardaud_ccard_number_new), setbytea(pNewKey), 'bf'),
14952                  ccardaud_ccard_month_expired_old = encrypt(setbytea(_ccaud.ccardaud_ccard_month_expired_old), setbytea(pNewKey), 'bf'),
14953                  ccardaud_ccard_month_expired_new = encrypt(setbytea(_ccaud.ccardaud_ccard_month_expired_new), setbytea(pNewKey), 'bf'),
14954                  ccardaud_ccard_year_expired_old = encrypt(setbytea(_ccaud.ccardaud_ccard_year_expired_old), setbytea(pNewKey), 'bf'),
14955                  ccardaud_ccard_year_expired_new = encrypt(setbytea(_ccaud.ccardaud_ccard_year_expired_new), setbytea(pNewKey), 'bf')
14956       WHERE ccardaud_id = _ccaud.ccardaud_id;
14957
14958       num_updated := num_updated + 1;
14959
14960   END LOOP;
14961
14962 -- Update metricenc
14963
14964   FOR _metricenc IN SELECT metricenc_id, 
14965              decrypt(setbytea(metricenc_value), setbytea(pOldKey), 'bf') AS metricenc_value
14966       FROM metricenc LOOP
14967
14968       UPDATE metricenc
14969              set metricenc_value = encrypt(setbytea(_metricenc.metricenc_value), setbytea(pNewKey), 'bf')
14970       WHERE metricenc_id = _metricenc.metricenc_id;
14971
14972       num_updated := num_updated + 1;
14973
14974   END LOOP;
14975
14976
14977   RETURN num_updated;
14978
14979 END;
14980 $_$;
14981
14982
14983 ALTER FUNCTION public.alterencrypt(text, text) OWNER TO admin;
14984
14985 --
14986 -- TOC entry 1118 (class 1255 OID 146565637)
14987 -- Dependencies: 2651 4536 8
14988 -- Name: apaging(date, boolean); Type: FUNCTION; Schema: public; Owner: admin
14989 --
14990
14991 CREATE FUNCTION apaging(date, boolean) RETURNS SETOF apaging
14992     LANGUAGE plpgsql
14993     AS $_$
14994 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
14995 -- See www.xtuple.com/CPAL for the full text of the software license.
14996 DECLARE
14997   pAsOfDate ALIAS FOR $1;
14998   pUseDocDate ALIAS FOR $2;
14999   _row apaging%ROWTYPE;
15000   _x RECORD;
15001   _returnVal INTEGER;
15002   _asOfDate DATE;
15003 BEGIN
15004
15005   _asOfDate := COALESCE(pAsOfDate,current_date);
15006
15007   FOR _x IN
15008         SELECT
15009         --report uses currency rate snapshot to convert all amounts to base based on apopen_docdate to ensure the same exchange rate
15010
15011         --today and greater base:
15012         CASE WHEN((apopen.apopen_duedate >= DATE(_asOfDate)))
15013         THEN (((apopen.apopen_amount - apopen.apopen_paid +
15014                 COALESCE(SUM(apapply_target_paid * apopen.apopen_curr_rate / target.apopen_curr_rate),0))) / apopen.apopen_curr_rate *
15015                 CASE WHEN (apopen.apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END) ELSE 0 END AS cur_val,
15016
15017         --0 to 30 base
15018         CASE WHEN((apopen.apopen_duedate >= DATE(_asOfDate)-30) AND (apopen.apopen_duedate < DATE(_asOfDate)))
15019         THEN (((apopen.apopen_amount - apopen.apopen_paid +
15020                 COALESCE(SUM(apapply_target_paid * apopen.apopen_curr_rate / target.apopen_curr_rate),0))) / apopen.apopen_curr_rate *
15021                 CASE WHEN (apopen.apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END) ELSE 0 END AS thirty_val,
15022
15023         --30-60 base
15024         CASE WHEN((apopen.apopen_duedate >= DATE(_asOfDate)-60) AND (apopen.apopen_duedate < DATE(_asOfDate) - 30 ))
15025         THEN (((apopen.apopen_amount - apopen.apopen_paid +
15026                 COALESCE(SUM(apapply_target_paid * apopen.apopen_curr_rate / target.apopen_curr_rate),0))) / apopen.apopen_curr_rate *
15027                 CASE WHEN (apopen.apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END) ELSE 0 END AS sixty_val,
15028
15029         --60-90 base
15030         CASE WHEN((apopen.apopen_duedate >= DATE(_asOfDate)-90) AND (apopen.apopen_duedate < DATE(_asOfDate) - 60))
15031         THEN (((apopen.apopen_amount - apopen.apopen_paid +
15032                 COALESCE(SUM(apapply_target_paid * apopen.apopen_curr_rate / target.apopen_curr_rate),0))) / apopen.apopen_curr_rate *
15033                 CASE WHEN (apopen.apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END) ELSE 0 END AS ninety_val,
15034
15035         --greater than 90 base:
15036         CASE WHEN((apopen.apopen_duedate > DATE(_asOfDate)-10000) AND (apopen.apopen_duedate < DATE(_asOfDate) - 90))
15037         THEN (((apopen.apopen_amount - apopen.apopen_paid +
15038                 COALESCE(SUM(apapply_target_paid * apopen.apopen_curr_rate / target.apopen_curr_rate),0))) / apopen.apopen_curr_rate *
15039                 CASE WHEN (apopen.apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END) ELSE 0 END AS plus_val,
15040
15041         --total amount base:
15042         CASE WHEN((apopen.apopen_duedate > DATE(_asOfDate)-10000))
15043         THEN (((apopen.apopen_amount - apopen.apopen_paid +
15044                 COALESCE(SUM(apapply_target_paid * apopen.apopen_curr_rate / target.apopen_curr_rate),0))) / apopen.apopen_curr_rate *
15045                 CASE WHEN (apopen.apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END) ELSE 0 END AS total_val,
15046
15047         --AP Open Amount base
15048         CASE WHEN apopen.apopen_doctype IN ('C', 'R') 
15049         THEN (apopen.apopen_amount / apopen.apopen_curr_rate * -1.0)
15050         ELSE (apopen.apopen_amount / apopen.apopen_curr_rate) END AS apopen_amount,
15051         
15052         apopen.apopen_docdate,
15053         apopen.apopen_duedate,
15054         apopen.apopen_ponumber,
15055         apopen.apopen_invcnumber,
15056         apopen.apopen_docnumber,
15057         apopen.apopen_doctype,
15058         vend_id,
15059         vend_name,
15060         vend_number,
15061         vend_vendtype_id,
15062         vendtype_code,
15063         terms_descrip,
15064         determineDiscountDate(terms_id, apopen.apopen_docdate) AS discdate,
15065         noNeg(apopen.apopen_discountable_amount *
15066                      CASE WHEN (CURRENT_DATE <= determineDiscountDate(terms_id, apopen.apopen_docdate)) THEN terms_discprcnt
15067                      ELSE 0.0 END) AS disc_val,
15068         terms_discdays AS discdays,
15069         (terms_discprcnt * 100.0) AS discprcnt
15070
15071         FROM vendinfo, vendtype, apopen
15072           LEFT OUTER JOIN terms ON (apopen_terms_id=terms_id)
15073           LEFT OUTER JOIN apapply ON (((apopen_id=apapply_target_apopen_id)
15074                                     OR (apopen_id=apapply_source_apopen_id))
15075                                    AND (apapply_postdate >_asOfDate))
15076           LEFT OUTER JOIN apopen target ON (target.apopen_id=apapply_target_apopen_id)
15077         WHERE ( (apopen.apopen_vend_id = vend_id)
15078         AND (vend_vendtype_id=vendtype_id)
15079         AND (CASE WHEN (pUseDocDate) THEN apopen.apopen_docdate ELSE apopen.apopen_distdate END <= _asOfDate)
15080         AND (COALESCE(apopen.apopen_closedate,_asOfDate+1)>_asOfDate) )
15081         GROUP BY apopen.apopen_id,apopen.apopen_docdate,apopen.apopen_duedate,apopen.apopen_ponumber,
15082                  apopen.apopen_invcnumber,apopen.apopen_docnumber,apopen.apopen_doctype,apopen.apopen_paid,
15083                  apopen.apopen_curr_id,apopen.apopen_amount,vend_id,vend_name,vend_number,vend_vendtype_id,vendtype_code,terms_descrip,
15084                  apopen.apopen_curr_rate, terms_id, terms_discdays, terms_discprcnt, apopen.apopen_discountable_amount
15085         ORDER BY vend_number, apopen.apopen_duedate
15086   LOOP
15087         _row.apaging_docdate := _x.apopen_docdate;
15088         _row.apaging_duedate := _x.apopen_duedate;
15089         _row.apaging_ponumber := _x.apopen_ponumber;
15090         _row.apaging_invcnumber := _x.apopen_invcnumber;
15091         _row.apaging_docnumber := _x.apopen_docnumber;
15092         _row.apaging_doctype := _x.apopen_doctype;
15093         _row.apaging_vend_id := _x.vend_id;
15094         _row.apaging_vend_number := _x.vend_number;
15095         _row.apaging_vend_name := _x.vend_name;
15096         _row.apaging_vend_vendtype_id := _x.vend_vendtype_id;
15097         _row.apaging_vendtype_code := _x.vendtype_code;
15098         _row.apaging_terms_descrip := _x.terms_descrip;
15099         _row.apaging_apopen_amount := _x.apopen_amount;
15100         _row.apaging_cur_val := _x.cur_val;
15101         _row.apaging_thirty_val := _x.thirty_val;
15102         _row.apaging_sixty_val := _x.sixty_val;
15103         _row.apaging_ninety_val := _x.ninety_val;
15104         _row.apaging_plus_val := _x.plus_val;
15105         _row.apaging_total_val := _x.total_val;
15106         _row.apaging_discdate := _x.discdate;
15107         _row.apaging_disc_val := _x.disc_val;
15108         _row.apaging_discdays := _x.discdays;
15109         _row.apaging_discprcnt := _x.discprcnt;
15110         RETURN NEXT _row;
15111   END LOOP;
15112   RETURN;
15113 END;
15114 $_$;
15115
15116
15117 ALTER FUNCTION public.apaging(date, boolean) OWNER TO admin;
15118
15119 --
15120 -- TOC entry 1119 (class 1255 OID 146565638)
15121 -- Dependencies: 4536 8
15122 -- Name: apapplied(integer, date); Type: FUNCTION; Schema: public; Owner: admin
15123 --
15124
15125 CREATE FUNCTION apapplied(integer, date) RETURNS numeric
15126     LANGUAGE plpgsql
15127     AS $_$
15128 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15129 -- See www.xtuple.com/CPAL for the full text of the software license.
15130 DECLARE
15131   pApopenid ALIAS FOR $1;
15132   pDate ALIAS FOR $2;
15133   _amount NUMERIC;
15134
15135 BEGIN
15136
15137   -- Return amount applied to an apopen in base currency as of apapply_postdate
15138   SELECT SUM(currtobase(apapply_curr_id,apapply_amount,apapply_postdate)) INTO _amount
15139   FROM apapply
15140   WHERE (((apapply_target_apopen_id = pApopenid) OR (apapply_source_apopen_id = pApopenid))
15141   AND (((apapply_journalnumber=0) AND (apapply_postdate <= pDate))
15142   OR EXISTS(SELECT * 
15143              FROM gltrans 
15144              WHERE ((gltrans_journalnumber=apapply_journalnumber)
15145              AND (gltrans_date <= pDate)))));
15146
15147   IF (_amount IS NULL) THEN
15148     RETURN 0;
15149   ELSE
15150     RETURN _amount;
15151   END IF;
15152
15153 END;
15154 $_$;
15155
15156
15157 ALTER FUNCTION public.apapplied(integer, date) OWNER TO admin;
15158
15159 --
15160 -- TOC entry 1120 (class 1255 OID 146565639)
15161 -- Dependencies: 4536 8
15162 -- Name: apcheckpending(integer); Type: FUNCTION; Schema: public; Owner: admin
15163 --
15164
15165 CREATE FUNCTION apcheckpending(integer) RETURNS numeric
15166     LANGUAGE plpgsql STABLE
15167     AS $_$
15168 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15169 -- See www.xtuple.com/CPAL for the full text of the software license.
15170 DECLARE
15171   pApopenid     ALIAS FOR $1;
15172   _qty NUMERIC  := 0.0;
15173
15174 BEGIN
15175
15176   SELECT SUM(checkitem_amount + checkitem_discount) INTO _qty
15177     FROM checkitem JOIN checkhead ON (checkitem_checkhead_id=checkhead_id)
15178    WHERE ((checkitem_apopen_id=pApopenid)
15179      AND (NOT checkhead_deleted)
15180      AND (NOT checkhead_replaced)
15181      AND (NOT checkhead_void)
15182      AND (NOT checkhead_posted));
15183
15184   RETURN COALESCE(_qty, 0.0);
15185
15186 END;
15187 $_$;
15188
15189
15190 ALTER FUNCTION public.apcheckpending(integer) OWNER TO admin;
15191
15192 --
15193 -- TOC entry 1121 (class 1255 OID 146565640)
15194 -- Dependencies: 4536 8
15195 -- Name: apcurrgain(integer, integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
15196 --
15197
15198 CREATE FUNCTION apcurrgain(integer, integer, numeric, date) RETURNS numeric
15199     LANGUAGE plpgsql
15200     AS $_$
15201 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15202 -- See www.xtuple.com/CPAL for the full text of the software license.
15203 DECLARE
15204   pApopenId ALIAS FOR $1;
15205   pCurrId ALIAS FOR $2;
15206   pValue ALIAS FOR $3;
15207   pDate ALIAS FOR $4;
15208   _start DATE;
15209   _end DATE;
15210   _gain NUMERIC;
15211   _r RECORD;
15212
15213 BEGIN
15214   IF (pApopenId IS NULL OR pValue = 0) THEN
15215     RETURN 0;
15216   END IF;
15217
15218   SELECT apopen_docdate, apopen_curr_rate
15219     INTO _r
15220   FROM apopen
15221   WHERE (apopen_id=pApopenId);
15222
15223   IF (_r.apopen_docdate > pDate) THEN
15224     _gain := (currToBase(pCurrId, pValue, pDate) - (pValue / _r.apopen_curr_rate)) * -1;
15225   ELSE
15226     _gain := (pValue / _r.apopen_curr_rate) - currToBase(pCurrId, pValue, pDate);
15227   END IF;
15228   
15229   IF (_gain IS NULL) THEN
15230     RAISE EXCEPTION 'Error processing currency gain/loss.';
15231   END IF;
15232
15233   RETURN _gain;
15234 END;
15235 $_$;
15236
15237
15238 ALTER FUNCTION public.apcurrgain(integer, integer, numeric, date) OWNER TO admin;
15239
15240 --
15241 -- TOC entry 1122 (class 1255 OID 146565641)
15242 -- Dependencies: 4536 8
15243 -- Name: applyapcreditmemotobalance(integer); Type: FUNCTION; Schema: public; Owner: admin
15244 --
15245
15246 CREATE FUNCTION applyapcreditmemotobalance(integer) RETURNS integer
15247     LANGUAGE plpgsql
15248     AS $_$
15249 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15250 -- See www.xtuple.com/CPAL for the full text of the software license.
15251 DECLARE
15252   pApopenid ALIAS FOR $1;
15253   _amount NUMERIC;
15254   _curr_id INTEGER;
15255   _curr_rate NUMERIC;
15256   _docdate DATE;
15257   _applyAmount NUMERIC;
15258   _r RECORD;
15259   _p RECORD;
15260
15261 BEGIN
15262
15263 --  Find the balance to apply
15264   SELECT (apopen_amount - apopen_paid - COALESCE(prepared,0.0) - COALESCE(selected,0.0) - COALESCE(SUM(currToCurr(apcreditapply_curr_id,
15265                                                   apopen_curr_id,
15266                                                   apcreditapply_amount,
15267                                                   apopen_docdate)), 0)),
15268           apopen_curr_id, apopen_curr_rate, apopen_docdate INTO _amount, _curr_id, _curr_rate, _docdate
15269   FROM apopen 
15270     LEFT OUTER JOIN apcreditapply ON (apcreditapply_source_apopen_id=apopen_id)
15271     LEFT OUTER JOIN (SELECT apopen_id AS selected_apopen_id,
15272                        SUM(currToCurr(apselect_curr_id, apopen_curr_id, apselect_amount + apselect_discount, apselect_date)) AS selected
15273                      FROM apselect JOIN apopen ON (apselect_apopen_id=apopen_id)
15274                      GROUP BY apopen_id) AS sub1 ON (apopen_id=selected_apopen_id)
15275     LEFT OUTER JOIN (SELECT apopen_id AS prepared_apopen_id,
15276                        SUM(checkitem_amount + checkitem_discount) AS prepared
15277                      FROM checkhead 
15278                        JOIN checkitem ON (checkitem_checkhead_id=checkhead_id)
15279                        JOIN apopen ON (checkitem_apopen_id=apopen_id)
15280                      WHERE ((NOT checkhead_posted)
15281                        AND  (NOT checkhead_void))
15282                      GROUP BY apopen_id) AS sub2 ON (prepared_apopen_id=apopen_id)
15283   WHERE (apopen_id=pApopenid)
15284   GROUP BY apopen_amount, apopen_paid, apopen_curr_id, apopen_curr_rate, apopen_docdate, prepared, selected;
15285
15286   IF (_amount < 0) THEN
15287     RETURN -1;
15288   END IF;
15289
15290 --  Loop through the apopen items in order of due date
15291   FOR _r IN SELECT target.apopen_id AS apopenid,
15292                    currToCurr(target.apopen_curr_id,source.apopen_curr_id, 
15293                      target.apopen_amount - target.apopen_paid - COALESCE(prepared,0.0) - COALESCE(selected,0.0) - COALESCE(applied,0.0),
15294                      current_date) AS balance
15295            FROM apopen AS source, apopen AS target
15296              LEFT OUTER JOIN (SELECT apcreditapply_target_apopen_id AS applied_apopen_id,
15297                                      SUM(currToCurr(apcreditapply_curr_id, apopen_curr_id, apcreditapply_amount, apopen_docdate)) AS applied
15298                               FROM apcreditapply JOIN apopen ON (apopen_id=apcreditapply_source_apopen_id)
15299                               GROUP BY apcreditapply_target_apopen_id) AS sub3
15300                               ON (target.apopen_id=applied_apopen_id)
15301              LEFT OUTER JOIN (SELECT apopen_id AS selected_apopen_id,
15302                                 SUM(currToCurr(apselect_curr_id, apopen_curr_id, apselect_amount + apselect_discount, apselect_date)) AS selected
15303                                     FROM apselect JOIN apopen ON (apselect_apopen_id=apopen_id)
15304                                 GROUP BY apopen_id) AS sub1
15305                                 ON (target.apopen_id=selected_apopen_id)
15306              LEFT OUTER JOIN (SELECT apopen_id AS prepared_apopen_id,
15307                                 SUM(checkitem_amount + checkitem_discount) AS prepared
15308                               FROM checkhead 
15309                                 JOIN checkitem ON (checkitem_checkhead_id=checkhead_id)
15310                                 JOIN apopen ON (checkitem_apopen_id=apopen_id)
15311                               WHERE ((NOT checkhead_posted)
15312                                AND  (NOT checkhead_void))
15313                               GROUP BY apopen_id) AS sub2 ON (prepared_apopen_id=target.apopen_id)
15314             WHERE ( (source.apopen_vend_id=target.apopen_vend_id)
15315              AND (target.apopen_doctype IN ('V', 'D'))
15316              AND (target.apopen_open)
15317              AND (source.apopen_id=pApopenid) )
15318             ORDER BY target.apopen_duedate, (target.apopen_amount - target.apopen_paid) LOOP
15319
15320 --  Determine the amount to apply
15321     IF (_r.balance <= 0.0) THEN
15322       CONTINUE;
15323     ELSEIF (_r.balance > _amount) THEN
15324       _applyAmount := _amount;
15325     ELSE
15326       _applyAmount := _r.balance;
15327     END IF;
15328
15329 --  Does an apcreditapply record already exist?
15330     SELECT apcreditapply_id, 
15331               apcreditapply_amount * _curr_rate / 
15332                  currRate(apcreditapply_curr_id,_docdate) AS apcreditapply_amount
15333       INTO _p
15334     FROM apcreditapply
15335     WHERE ( (apcreditapply_target_apopen_id=_r.apopenid)
15336      AND (apcreditapply_source_apopen_id=pApopenid) );
15337
15338     IF (FOUND) THEN
15339 --  The following is depreciated, just skip the record
15340 --  Recalculate the amount to apply
15341 --      IF ((_r.balance - _p.apcreditapply_amount) > _amount) THEN
15342 --        _applyAmount := _amount;
15343 --      ELSE
15344 --        _applyAmount := (_r.balance - _p.apcreditapply_amount);
15345 --      END IF;
15346
15347 --  Update the apcreditapply with the new amount to apply
15348 --      UPDATE apcreditapply
15349 --      SET apcreditapply_amount = (apcreditapply_amount + 
15350 --          _applyAmount *  currRate(apcreditapply_curr_id,_docdate) / _curr_rate)
15351 --      WHERE (apcreditapply_id=_p.apcreditapply_id);
15352
15353       CONTINUE;
15354     ELSE
15355 --  Create a new apcreditapply record
15356       INSERT INTO apcreditapply
15357       ( apcreditapply_source_apopen_id, apcreditapply_target_apopen_id,
15358         apcreditapply_amount, apcreditapply_curr_id )
15359       VALUES
15360       ( pApopenid, _r.apopenid, _applyAmount, _curr_id );
15361     END IF;
15362
15363     _amount := (_amount - _applyAmount);
15364     IF (_amount = 0) THEN
15365       EXIT;
15366     END IF;
15367
15368   END LOOP;
15369
15370   RETURN 1;
15371
15372 END;
15373 $_$;
15374
15375
15376 ALTER FUNCTION public.applyapcreditmemotobalance(integer) OWNER TO admin;
15377
15378 --
15379 -- TOC entry 1123 (class 1255 OID 146565642)
15380 -- Dependencies: 4536 8
15381 -- Name: applyapcredits(integer); Type: FUNCTION; Schema: public; Owner: admin
15382 --
15383
15384 CREATE FUNCTION applyapcredits(integer) RETURNS integer
15385     LANGUAGE plpgsql
15386     AS $_$
15387 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15388 -- See www.xtuple.com/CPAL for the full text of the software license.
15389 DECLARE
15390   pVendId   ALIAS FOR $1;
15391   _result   INTEGER;
15392   _apopenid INTEGER;
15393   _r        RECORD;
15394
15395 BEGIN
15396
15397   -- Fetch credit memo(s) for the vendor
15398   FOR _r IN SELECT apopen_id, apopen_duedate
15399             FROM apopen JOIN vendinfo ON (apopen_vend_id = vend_id)
15400             WHERE ((apopen_doctype = 'C')
15401                AND (apopen_status = 'O')
15402                AND (vend_id = pVendId))
15403             ORDER BY apopen_duedate
15404   LOOP
15405     -- Apply credit memo(s) according to due date
15406     SELECT applyapcreditmemotobalance(_r.apopen_id) INTO _result;
15407
15408     -- Post the credit memo if applied
15409     IF (_result = 1) THEN
15410       SELECT postapcreditmemoapplication(_r.apopen_id) INTO _apopenid;
15411       IF (_apopenid < 0) THEN
15412         RETURN -1;
15413       END IF;
15414     ELSE
15415       RETURN -1;
15416     END IF;
15417
15418   END LOOP;
15419
15420 RETURN 1;
15421
15422 END;
15423 $_$;
15424
15425
15426 ALTER FUNCTION public.applyapcredits(integer) OWNER TO admin;
15427
15428 --
15429 -- TOC entry 1124 (class 1255 OID 146565643)
15430 -- Dependencies: 4536 8
15431 -- Name: applyarcreditmemotobalance(integer); Type: FUNCTION; Schema: public; Owner: admin
15432 --
15433
15434 CREATE FUNCTION applyarcreditmemotobalance(integer) RETURNS integer
15435     LANGUAGE plpgsql
15436     AS $_$
15437 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15438 -- See www.xtuple.com/CPAL for the full text of the software license.
15439 DECLARE
15440   pAropenid ALIAS FOR $1;
15441
15442 BEGIN
15443
15444   RETURN applyARCreditMemoToBalance(pAropenid, NULL);
15445
15446 END;
15447 $_$;
15448
15449
15450 ALTER FUNCTION public.applyarcreditmemotobalance(integer) OWNER TO admin;
15451
15452 --
15453 -- TOC entry 1125 (class 1255 OID 146565644)
15454 -- Dependencies: 4536 8
15455 -- Name: applyarcreditmemotobalance(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
15456 --
15457
15458 CREATE FUNCTION applyarcreditmemotobalance(integer, integer) RETURNS integer
15459     LANGUAGE plpgsql
15460     AS $_$
15461 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15462 -- See www.xtuple.com/CPAL for the full text of the software license.
15463 DECLARE
15464   pSourceAropenid ALIAS FOR $1;
15465   pTargetAropenid ALIAS FOR $2;
15466   _amount NUMERIC;
15467   _amountcurrid INTEGER;
15468   _applyAmount NUMERIC;
15469   _applycurrid  INTEGER;
15470   _curr_rate NUMERIC;
15471   _r RECORD;
15472   _p RECORD;
15473
15474 BEGIN
15475
15476 --  Find the balance to apply
15477   SELECT (aropen_amount - COALESCE(SUM(currToCurr(arcreditapply_curr_id,
15478                                                   aropen_curr_id,
15479                                                   arcreditapply_amount,
15480                                                   aropen_docdate)), 0) - aropen_paid - COALESCE(prepared,0.0) - COALESCE(cashapplied,0.0)),
15481          aropen_curr_id, aropen_curr_rate INTO _amount, _amountcurrid, _curr_rate
15482   FROM aropen LEFT OUTER JOIN arcreditapply ON (arcreditapply_source_aropen_id=aropen_id)
15483               LEFT OUTER JOIN (SELECT aropen_id AS prepared_aropen_id,
15484                                 SUM(checkitem_amount + checkitem_discount) AS prepared
15485                                FROM checkhead JOIN checkitem ON (checkitem_checkhead_id=checkhead_id)
15486                                               JOIN aropen ON (checkitem_aropen_id=aropen_id)
15487                                WHERE ((NOT checkhead_posted)
15488                                 AND  (NOT checkhead_void))
15489                                GROUP BY aropen_id) AS sub1
15490                       ON (prepared_aropen_id=aropen_id)
15491              LEFT OUTER JOIN (SELECT aropen_id AS cash_aropen_id,
15492                                      SUM(cashrcptitem_amount + cashrcptitem_discount) * -1.0 AS cashapplied
15493                                 FROM cashrcpt JOIN cashrcptitem ON (cashrcptitem_cashrcpt_id=cashrcpt_id)
15494                                               JOIN aropen ON (cashrcptitem_aropen_id=aropen_id)
15495                                WHERE (NOT cashrcpt_posted) AND (NOT cashrcpt_void)
15496                                GROUP BY aropen_id ) AS sub2
15497                       ON (cash_aropen_id=aropen_id)
15498   WHERE (aropen_id=pSourceAropenid)
15499   GROUP BY aropen_amount, aropen_paid, aropen_curr_id, aropen_curr_rate, prepared, cashapplied;
15500
15501   IF (_amount < 0) THEN
15502     RETURN -1;
15503   END IF;
15504
15505 --  Loop through the aropen items in order of due date
15506   FOR _r IN SELECT target.aropen_id AS aropenid,
15507                    currToCurr(target.aropen_curr_id,source.aropen_curr_id,
15508                               (target.aropen_amount - target.aropen_paid - calcpendingarapplications(target.aropen_id)),
15509                               current_date) AS balance,
15510                    target.aropen_curr_id AS curr_id,
15511                    target.aropen_docdate AS docdate
15512             FROM aropen AS target, aropen AS source
15513             WHERE ( (source.aropen_cust_id=target.aropen_cust_id)
15514              AND (target.aropen_doctype IN ('D', 'I'))
15515              AND (target.aropen_open)
15516              AND (source.aropen_id=pSourceAropenid)
15517              AND ((pTargetAropenid IS NULL) OR (target.aropen_id=pTargetAropenid)) )
15518             ORDER BY target.aropen_duedate, target.aropen_docnumber LOOP
15519
15520 --  Determine the amount to apply
15521     IF (_r.balance > _amount) THEN
15522       _applyAmount := _amount;
15523     ELSE
15524       _applyAmount := _r.balance;
15525     END IF;
15526     _applycurrid := _amountcurrid;
15527
15528 --  Does an arcreditapply record already exist?
15529     SELECT arcreditapply_id,
15530            arcreditapply_amount,
15531            arcreditapply_amount * _curr_rate / 
15532                  currRate(arcreditapply_curr_id,_r.docdate) AS
15533                       arcreditapply_amount_applycurr INTO _p
15534     FROM arcreditapply
15535     WHERE ( (arcreditapply_target_aropen_id=_r.aropenid)
15536      AND (arcreditapply_source_aropen_id=pSourceAropenid) );
15537
15538     IF (FOUND) THEN
15539 --  Offset the amount to apply by the amount already applied
15540       _applyAmount := (_applyAmount - _p.arcreditapply_amount_applycurr);
15541       IF (_applyAmount < 0) THEN
15542         _applyAmount := 0;
15543       END IF;
15544
15545 --  Update the arcreditapply with the new amount to apply
15546       UPDATE arcreditapply
15547       SET arcreditapply_amount = (arcreditapply_amount + 
15548           _applyAmount *  currRate(arcreditapply_curr_id,_r.docdate) / _curr_rate)
15549       WHERE (arcreditapply_id=_p.arcreditapply_id);
15550
15551     ELSE
15552 --  Create a new arcreditapply record
15553       INSERT INTO arcreditapply
15554       ( arcreditapply_source_aropen_id, arcreditapply_target_aropen_id,
15555         arcreditapply_amount, arcreditapply_curr_id )
15556       VALUES
15557       ( pSourceAropenid, _r.aropenid, _applyAmount, _applycurrid );
15558     END IF;
15559
15560     _amount := _amount - currToCurr(_applycurrid, _amountcurrid, _applyAmount, _r.docdate);
15561     IF (_amount = 0) THEN
15562       EXIT;
15563     END IF;
15564
15565   END LOOP;
15566
15567   RETURN 1;
15568
15569 END;
15570 $_$;
15571
15572
15573 ALTER FUNCTION public.applyarcreditmemotobalance(integer, integer) OWNER TO admin;
15574
15575 --
15576 -- TOC entry 1126 (class 1255 OID 146565645)
15577 -- Dependencies: 4536 8
15578 -- Name: applycashreceiptlinebalance(integer, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
15579 --
15580
15581 CREATE FUNCTION applycashreceiptlinebalance(integer, integer, numeric, integer) RETURNS numeric
15582     LANGUAGE plpgsql
15583     AS $_$
15584 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15585 -- See www.xtuple.com/CPAL for the full text of the software license.
15586 DECLARE
15587   pCashrcptId ALIAS FOR $1;
15588   pAropenid ALIAS FOR $2;
15589   pAmount ALIAS FOR $3;
15590   pCurrId ALIAS FOR $4;
15591   _balance NUMERIC;
15592   _amount NUMERIC;
15593   _applyAmount NUMERIC := 0;
15594   _discount NUMERIC := 0;
15595   _discprct NUMERIC;
15596   _docDate DATE;
15597   _r RECORD;
15598   _doctype CHAR(1);
15599
15600 BEGIN
15601
15602 --  All calculations performed in currency of Cash Receipt
15603
15604 --  Clear previously applied
15605   DELETE FROM cashrcptitem WHERE ((cashrcptitem_cashrcpt_id=pCashrcptId) AND (cashrcptitem_aropen_id=pAropenId));
15606
15607 --  Find the balance to apply
15608   SELECT (pAmount - (COALESCE(SUM(cashrcptitem_amount), 0) ) ),
15609     COALESCE(cashrcpt_docdate, current_date)
15610     INTO _amount, _docDate
15611   FROM cashrcpt LEFT OUTER JOIN cashrcptitem ON (cashrcptitem_cashrcpt_id = cashrcpt_id)
15612   WHERE (cashrcpt_id=pCashrcptid)
15613   GROUP BY cashrcpt_curr_id, cashrcpt_distdate, cashrcpt_docdate;
15614
15615   SELECT (_amount - COALESCE(SUM(cashrcptmisc_amount), 0)) INTO _amount
15616   FROM cashrcptmisc
15617   WHERE (cashrcptmisc_cashrcpt_id=pCashrcptid);
15618
15619   SELECT aropen_doctype INTO _doctype
15620   FROM aropen
15621   WHERE (aropen_id=pAropenId);
15622   
15623   RAISE DEBUG 'Amount (%) DocType (%)', _amount, _doctype;
15624
15625   IF (_amount <= 0 AND _doctype IN ('I','D')) THEN
15626     RETURN 0;
15627   END IF;
15628
15629 --  Determine Line balance
15630   SELECT currToCurr(aropen_curr_id, cashrcpt_curr_id,
15631          aropen_amount - aropen_paid, cashrcpt_distdate) -
15632          COALESCE((SELECT (SUM(cashrcptitem_amount) + SUM(cashrcptitem_discount))
15633                    FROM cashrcptitem, cashrcpt
15634                    WHERE ((cashrcpt_id=cashrcptitem_cashrcpt_id)
15635                      AND  (NOT cashrcpt_void)
15636                      AND  (NOT cashrcpt_posted)
15637                      AND  (cashrcpt_id != pCashrcptId)
15638                      AND  (cashrcptitem_aropen_id=pAropenId))), 0)
15639          INTO _balance
15640          FROM aropen, cashrcpt
15641            WHERE ((aropen_id=pAropenId)
15642            AND (cashrcpt_id=pCashrcptId));
15643
15644   RAISE DEBUG 'Balance (%)', _balance;
15645             
15646 --  If Invoice or Debit Memo, determine Max Discount as per Terms
15647   IF (_doctype IN ('I','D')) THEN
15648     SELECT  round(noNeg(_balance * 
15649             CASE WHEN (_docDate <= determineDiscountDate(terms_id, aropen_docdate)) THEN COALESCE(terms_discprcnt, 0.0) 
15650             ELSE 0.00 END - applied),2),
15651             CASE WHEN (_docDate <= determineDiscountDate(terms_id, aropen_docdate)) THEN COALESCE(terms_discprcnt, 0.0) 
15652             ELSE 0.00 END INTO _discount, _discprct
15653     FROM aropen LEFT OUTER JOIN terms ON (terms_id=aropen_terms_id), 
15654          (SELECT COALESCE(SUM(arapply_applied), 0.00) AS applied  
15655           FROM arapply, aropen 
15656           WHERE ((arapply_target_aropen_id=pAropenId) 
15657            AND (arapply_source_aropen_id=pAropenId) 
15658            AND  (aropen_discount) )
15659              ) AS data 
15660     WHERE (aropen_id=pAropenId);
15661
15662 --  Determine the amount to apply
15663     IF (_balance <= _amount + _discount) THEN
15664       _applyAmount := _balance - _discount;
15665     ELSE
15666       _discount := round((_amount / (1 - _discprct)) - _amount, 2);
15667       _applyAmount := _amount;
15668     END IF;
15669   ELSIF (_doctype IN ('C', 'R')) THEN
15670   -- Handle Credits, discounts don't apply here
15671     _applyAmount := _balance * -1;
15672   ELSE
15673     _applyAmount := _amount;
15674   END IF;
15675
15676   IF (_applyAmount != 0) THEN
15677 --  Create a new cashrcptitem
15678       INSERT INTO cashrcptitem
15679       ( cashrcptitem_aropen_id, cashrcptitem_cashrcpt_id,
15680         cashrcptitem_amount,cashrcptitem_discount )
15681       VALUES
15682       ( pAropenid, pCashrcptid, round(_applyAmount, 2), round(_discount, 2) );
15683   END IF;
15684
15685   RETURN abs(_applyAmount);
15686
15687 END;
15688 $_$;
15689
15690
15691 ALTER FUNCTION public.applycashreceiptlinebalance(integer, integer, numeric, integer) OWNER TO admin;
15692
15693 --
15694 -- TOC entry 1127 (class 1255 OID 146565646)
15695 -- Dependencies: 4536 8
15696 -- Name: applycashreceipttobalance(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
15697 --
15698
15699 CREATE FUNCTION applycashreceipttobalance(integer, numeric) RETURNS integer
15700     LANGUAGE plpgsql
15701     AS $_$
15702 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15703 -- See www.xtuple.com/CPAL for the full text of the software license.
15704 DECLARE
15705   pCashrcptid ALIAS FOR $1;
15706   pAmount ALIAS FOR $2;
15707
15708 BEGIN
15709   RETURN applyCashReceiptToBalance(pCashrcptid, pAmount, baseCurrId() );
15710 END;
15711 $_$;
15712
15713
15714 ALTER FUNCTION public.applycashreceipttobalance(integer, numeric) OWNER TO admin;
15715
15716 --
15717 -- TOC entry 1128 (class 1255 OID 146565647)
15718 -- Dependencies: 4536 8
15719 -- Name: applycashreceipttobalance(integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
15720 --
15721
15722 CREATE FUNCTION applycashreceipttobalance(integer, numeric, integer) RETURNS integer
15723     LANGUAGE plpgsql
15724     AS $_$
15725 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15726 -- See www.xtuple.com/CPAL for the full text of the software license.
15727 DECLARE
15728   pCashrcptid ALIAS FOR $1;
15729   pAmount ALIAS FOR $2;
15730   pCurrId ALIAS FOR $3;
15731
15732 BEGIN
15733
15734   RETURN applyCashReceiptToBalance(pCashrcptid, pAmount, pCurrId, false);
15735
15736 END;
15737 $_$;
15738
15739
15740 ALTER FUNCTION public.applycashreceipttobalance(integer, numeric, integer) OWNER TO admin;
15741
15742 --
15743 -- TOC entry 1129 (class 1255 OID 146565648)
15744 -- Dependencies: 4536 8
15745 -- Name: applycashreceipttobalance(integer, numeric, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
15746 --
15747
15748 CREATE FUNCTION applycashreceipttobalance(integer, numeric, integer, boolean) RETURNS integer
15749     LANGUAGE plpgsql
15750     AS $_$
15751 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15752 -- See www.xtuple.com/CPAL for the full text of the software license.
15753 DECLARE
15754   pCashrcptid ALIAS FOR $1;
15755   pAmount ALIAS FOR $2;
15756   pCurrId ALIAS FOR $3;
15757   pInclCredits ALIAS FOR $4;
15758   _amount NUMERIC;
15759   _applied NUMERIC := 0;
15760   _applyAmount NUMERIC;
15761   _discount NUMERIC;
15762   _discprct NUMERIC;
15763   _docDate DATE;
15764   _r RECORD;
15765   _toApply NUMERIC;
15766
15767 BEGIN
15768
15769 --  Apply open credits first if applicable
15770   IF (pInclCredits) THEN
15771     -- First find total debits unaccounted for by this receipt so we can apply as much credit 
15772     -- as possible to clear, but no more
15773     SELECT coalesce(noNeg(sum(currToCurr(aropen_curr_id, cashrcpt_curr_id,
15774          aropen_amount - aropen_paid, cashrcpt_distdate) -
15775          COALESCE((SELECT (SUM(cashrcptitem_amount) + SUM(cashrcptitem_discount))
15776                    FROM cashrcptitem, cashrcpt
15777                    WHERE ((cashrcpt_id=cashrcptitem_cashrcpt_id)
15778                      AND  (NOT cashrcpt_void)
15779                      AND  (NOT cashrcpt_posted)
15780                      AND  (cashrcpt_id != pCashrcptid)
15781                      AND  (cashrcptitem_aropen_id=aropen_id))), 0)) - pAmount),0)
15782     INTO _toApply
15783     FROM cashrcpt
15784       JOIN custinfo ON (cashrcpt_cust_id=cust_id)
15785       JOIN aropen ON (cust_id=aropen_cust_id)
15786     WHERE ((cashrcpt_id=pCashrcptid)
15787       AND (aropen_open)
15788       AND (aropen_doctype IN ('I','D')));
15789            
15790     -- Loop through and apply credits until we account for all remaining debits we can
15791     FOR _r IN 
15792       SELECT aropen_id
15793       FROM cashrcpt
15794         JOIN custinfo ON (cashrcpt_cust_id=cust_id)
15795         JOIN aropen ON (cust_id=aropen_cust_id)
15796       WHERE ((cashrcpt_id=pCashrcptid)
15797         AND (aropen_open)
15798         AND (aropen_doctype IN ('C','R')))
15799       ORDER BY aropen_duedate, aropen_docnumber
15800     LOOP
15801      EXIT WHEN _toApply <= 0;
15802       _toApply := _toApply - applyCashReceiptLineBalance(pCashrcptid, _r.aropen_id, _toApply, pCurrId);
15803     END LOOP;
15804   END IF;
15805
15806 --  Find the balance to apply
15807   SELECT (currToCurr(pCurrId, cashrcpt_curr_id, pAmount, cashrcpt_distdate) -
15808               (COALESCE(SUM(cashrcptitem_amount), 0) ) ),
15809               COALESCE(cashrcpt_docdate, current_date) 
15810               INTO _amount, _docDate
15811   FROM cashrcpt LEFT OUTER JOIN cashrcptitem ON (cashrcptitem_cashrcpt_id = cashrcpt_id)
15812   WHERE (cashrcpt_id=pCashrcptid)
15813   GROUP BY cashrcpt_curr_id, cashrcpt_distdate, cashrcpt_docdate;
15814
15815   SELECT (_amount - COALESCE(SUM(cashrcptmisc_amount), 0)) INTO _amount
15816   FROM cashrcptmisc
15817   WHERE (cashrcptmisc_cashrcpt_id=pCashrcptid);
15818
15819   IF (_amount = 0) THEN
15820     RETURN 1;
15821   END IF;
15822
15823 --  Loop through the aropen item in order of due date, searching only for
15824 --  aropen items that are open, for the current customer and have an outstanding balance
15825   FOR _r IN SELECT aropen_id,
15826                currToCurr(aropen_curr_id, cashrcpt_curr_id,
15827                aropen_amount - aropen_paid, cashrcpt_distdate) -
15828                COALESCE((SELECT SUM(cashrcptitem_amount) + SUM(cashrcptitem_discount)
15829                            FROM cashrcptitem, cashrcpt
15830                            WHERE ((cashrcpt_id=cashrcptitem_cashrcpt_id)
15831                              AND  (NOT cashrcpt_void)
15832                              AND  (NOT cashrcpt_posted)
15833                              AND  (cashrcpt_id != pCashrcptId)
15834                              AND  (cashrcptitem_aropen_id=aropen_id))), 0) AS balance,
15835                    s.cashrcptitem_id AS cashrcptitem_id
15836             FROM cashrcpt, aropen LEFT OUTER JOIN
15837                  cashrcptitem s ON (s.cashrcptitem_aropen_id=aropen_id AND s.cashrcptitem_cashrcpt_id=pCashrcptId)
15838                  LEFT OUTER JOIN terms ON (aropen_terms_id=terms_id),
15839                  (SELECT COALESCE(SUM(arapply_applied), 0.00) AS applied  
15840                   FROM arapply, aropen 
15841                   WHERE ((arapply_target_aropen_id=aropen_id) 
15842                     AND (arapply_source_aropen_id=aropen_id) 
15843                     AND  (aropen_discount) )
15844                  ) AS data
15845
15846             WHERE ( (aropen_cust_id=cashrcpt_cust_id)
15847              AND (aropen_doctype IN ('I', 'D'))
15848              AND (aropen_open)
15849              AND (cashrcpt_id=pCashrcptid) )
15850             ORDER BY aropen_duedate, aropen_amount, balance LOOP
15851
15852 --  Determine Max Discount as per Terms
15853     SELECT  round(noNeg(_r.balance * 
15854             CASE WHEN (_docDate <= determineDiscountDate(terms_id, aropen_docdate)) THEN terms_discprcnt 
15855             ELSE 0.00 END - applied),2),
15856             CASE WHEN (_docDate <= determineDiscountDate(terms_id, aropen_docdate)) THEN terms_discprcnt 
15857             ELSE 0.00 END INTO _discount, _discprct
15858             FROM aropen LEFT OUTER JOIN terms ON (terms_id=aropen_terms_id), 
15859                  (SELECT COALESCE(SUM(arapply_applied), 0.00) AS applied  
15860                           FROM arapply, aropen 
15861                   WHERE ((arapply_target_aropen_id=_r.aropen_id) 
15862                   AND (arapply_source_aropen_id=_r.aropen_id) 
15863                   AND  (aropen_discount) )
15864                  ) AS data 
15865             WHERE (aropen_id=_r.aropen_id);
15866
15867 --  Determine the amount to apply
15868     IF (_r.balance <= _amount + _discount) THEN
15869       _applyAmount := _r.balance - _discount;
15870     ELSE
15871       _discount := round((_amount / (1 - _discprct)) - _amount, 2);
15872       _applyAmount := _amount;
15873     END IF;
15874
15875     IF (_applyAmount > 0) THEN
15876 --  Does an cashrcptitem already exist?
15877       IF (_r.cashrcptitem_id IS NOT NULL) THEN
15878 --  Update the cashrcptitem with the new amount to apply
15879         UPDATE cashrcptitem
15880         SET cashrcptitem_amount = round(cashrcptitem_amount + _applyAmount, 2),
15881             cashrcptitem_discount = round(_discount, 2)
15882         WHERE (cashrcptitem_id=_r.cashrcptitem_id);
15883       ELSE
15884 --  Create a new cashrcptitem
15885         INSERT INTO cashrcptitem
15886         ( cashrcptitem_aropen_id, cashrcptitem_cashrcpt_id,
15887           cashrcptitem_amount, cashrcptitem_discount )
15888         VALUES
15889         ( _r.aropen_id, pCashrcptid, round(_applyAmount, 2), round(_discount, 2) );
15890       END IF;
15891
15892       _amount := (_amount - _applyAmount);
15893       IF (round(_amount, 2) = 0) THEN
15894         EXIT;
15895       END IF;
15896
15897     END IF;
15898   END LOOP;
15899
15900   RETURN 1;
15901
15902 END;
15903 $_$;
15904
15905
15906 ALTER FUNCTION public.applycashreceipttobalance(integer, numeric, integer, boolean) OWNER TO admin;
15907
15908 --
15909 -- TOC entry 1096 (class 1255 OID 146565650)
15910 -- Dependencies: 2654 4536 8
15911 -- Name: araging(date, boolean); Type: FUNCTION; Schema: public; Owner: admin
15912 --
15913
15914 CREATE FUNCTION araging(date, boolean) RETURNS SETOF araging
15915     LANGUAGE plpgsql
15916     AS $_$
15917 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15918 -- See www.xtuple.com/CPAL for the full text of the software license.
15919 DECLARE
15920   pAsOfDate ALIAS FOR $1;
15921   pUseDocDate ALIAS FOR $2;
15922   _row araging%ROWTYPE;
15923
15924 BEGIN
15925
15926   FOR _row IN SELECT *
15927             FROM araging(pAsOfDate, pUseDocDate, true)
15928   LOOP
15929     RETURN NEXT _row;
15930   END LOOP;
15931
15932   RETURN;
15933 END;
15934 $_$;
15935
15936
15937 ALTER FUNCTION public.araging(date, boolean) OWNER TO admin;
15938
15939 --
15940 -- TOC entry 1130 (class 1255 OID 146565651)
15941 -- Dependencies: 2654 4536 8
15942 -- Name: araging(date, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
15943 --
15944
15945 CREATE FUNCTION araging(date, boolean, boolean) RETURNS SETOF araging
15946     LANGUAGE plpgsql
15947     AS $_$
15948 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
15949 -- See www.xtuple.com/CPAL for the full text of the software license.
15950 DECLARE
15951   pAsOfDate ALIAS FOR $1;
15952   pUseDocDate ALIAS FOR $2;
15953   pConvBaseCurr ALIAS FOR $3;
15954   _row araging%ROWTYPE;
15955   _x RECORD;
15956   _returnVal INTEGER;
15957   _asOfDate DATE;
15958 BEGIN
15959
15960   _asOfDate := COALESCE(pAsOfDate,current_date);
15961
15962   FOR _x IN
15963         SELECT
15964         aropen_docdate,
15965         aropen_duedate,
15966         aropen_ponumber,
15967         aropen_docnumber,
15968         aropen_doctype,
15969         cust_id,
15970         cust_name,
15971         cust_number,
15972         cust_custtype_id,
15973         custtype_code,
15974         terms_descrip,
15975
15976         --if pConvBaseCurr is true then use currtobase to convert all amounts to base based on aropen_docdate to ensure the same exchange rate
15977         --otherwise use currtocurr to convert all amounts to customer's currency based on aropen_docdate to ensure the same exchange rate
15978
15979         --today and greater:
15980         CASE WHEN((aropen_duedate >= DATE(_asOfDate))) THEN balance
15981              ELSE 0.0 END AS cur_val,
15982
15983         --0 to 30
15984         CASE WHEN((aropen_duedate >= DATE(_asOfDate)-30) AND (aropen_duedate < DATE(_asOfDate))) THEN balance
15985              ELSE 0.0 END AS thirty_val,
15986
15987         --30-60
15988         CASE WHEN((aropen_duedate >= DATE(_asOfDate)-60) AND (aropen_duedate < DATE(_asOfDate) - 30 )) THEN balance
15989              ELSE 0.0 END AS sixty_val,
15990
15991         --60-90
15992         CASE WHEN((aropen_duedate >= DATE(_asOfDate)-90) AND (aropen_duedate < DATE(_asOfDate) - 60)) THEN balance
15993              ELSE 0.0 END AS ninety_val,
15994
15995         --greater than 90:
15996         CASE WHEN((aropen_duedate > DATE(_asOfDate)-10000) AND (aropen_duedate < DATE(_asOfDate) - 90)) THEN balance
15997              ELSE 0.0 END AS plus_val,
15998
15999         --total amount:
16000         CASE WHEN((aropen_duedate > DATE(_asOfDate)-10000)) THEN balance
16001              ELSE 0.0 END AS total_val,
16002
16003         --AR Open Amount base
16004         aropen_amount
16005
16006         FROM (
16007           SELECT
16008           (((aropen_amount - aropen_paid + COALESCE(SUM(arapply_target_paid),0))) /
16009              CASE WHEN (pConvBaseCurr) THEN aropen_curr_rate
16010                   ELSE currRate(aropen_curr_id, cust_curr_id, aropen_docdate)
16011              END *
16012              CASE WHEN (aropen_doctype IN ('C', 'R')) THEN -1.0
16013                   ELSE 1.0
16014              END) AS balance,
16015           ((aropen_amount) /
16016              CASE WHEN (pConvBaseCurr) THEN aropen_curr_rate
16017                   ELSE currRate(aropen_curr_id, cust_curr_id, aropen_docdate)
16018              END *
16019              CASE WHEN (aropen_doctype IN ('C', 'R')) THEN -1.0
16020                   ELSE 1.0
16021              END) AS aropen_amount,
16022           aropen_docdate,
16023           aropen_duedate,
16024           aropen_ponumber,
16025           aropen_docnumber,
16026           aropen_doctype,
16027           cust_id,
16028           cust_name,
16029           cust_number,
16030           cust_custtype_id,
16031           custtype_code,
16032           COALESCE(arterms.terms_descrip, custterms.terms_descrip, '') AS terms_descrip
16033
16034           FROM aropen
16035             JOIN custinfo ON (cust_id=aropen_cust_id)
16036             JOIN custtype ON (custtype_id=cust_custtype_id)
16037             LEFT OUTER JOIN terms arterms ON (arterms.terms_id=aropen_terms_id)
16038             LEFT OUTER JOIN terms custterms ON (custterms.terms_id=cust_terms_id)
16039             LEFT OUTER JOIN arapply ON (((aropen_id=arapply_target_aropen_id)
16040                                       OR (aropen_id=arapply_source_aropen_id))
16041                                      AND (arapply_distdate>_asOfDate))
16042           WHERE ( (CASE WHEN (pUseDocDate) THEN aropen_docdate ELSE aropen_distdate END <= _asOfDate)
16043           AND (COALESCE(aropen_closedate,_asOfDate+1)>_asOfDate) )
16044           GROUP BY aropen_id,aropen_docdate,aropen_duedate,aropen_ponumber,aropen_docnumber,aropen_doctype,aropen_paid,
16045                    aropen_curr_id,aropen_amount,cust_id,cust_name,cust_number,cust_custtype_id,custtype_code,
16046                    arterms.terms_descrip,custterms.terms_descrip, aropen_curr_rate, aropen_curr_id, cust_curr_id
16047           ORDER BY cust_number, aropen_duedate ) AS data
16048   LOOP
16049         _row.araging_docdate := _x.aropen_docdate;
16050         _row.araging_duedate := _x.aropen_duedate;
16051         _row.araging_ponumber := _x.aropen_ponumber;
16052         _row.araging_docnumber := _x.aropen_docnumber;
16053         _row.araging_doctype := _x.aropen_doctype;
16054         _row.araging_cust_id := _x.cust_id;
16055         _row.araging_cust_number := _x.cust_number;
16056         _row.araging_cust_name := _x.cust_name;
16057         _row.araging_cust_custtype_id := _x.cust_custtype_id;
16058         _row.araging_custtype_code := _x.custtype_code;
16059         _row.araging_terms_descrip := _x.terms_descrip;
16060         _row.araging_aropen_amount := _x.aropen_amount;
16061         _row.araging_cur_val := _x.cur_val;
16062         _row.araging_thirty_val := _x.thirty_val;
16063         _row.araging_sixty_val := _x.sixty_val;
16064         _row.araging_ninety_val := _x.ninety_val;
16065         _row.araging_plus_val := _x.plus_val;
16066         _row.araging_total_val := _x.total_val;
16067         RETURN NEXT _row;
16068   END LOOP;
16069   RETURN;
16070 END;
16071 $_$;
16072
16073
16074 ALTER FUNCTION public.araging(date, boolean, boolean) OWNER TO admin;
16075
16076 --
16077 -- TOC entry 1131 (class 1255 OID 146565652)
16078 -- Dependencies: 4536 8
16079 -- Name: arapplied(integer, date); Type: FUNCTION; Schema: public; Owner: admin
16080 --
16081
16082 CREATE FUNCTION arapplied(integer, date) RETURNS numeric
16083     LANGUAGE plpgsql
16084     AS $_$
16085 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16086 -- See www.xtuple.com/CPAL for the full text of the software license.
16087 DECLARE
16088   pAropenid ALIAS FOR $1;
16089   pDate ALIAS FOR $2;
16090   _amount NUMERIC;
16091
16092 BEGIN
16093
16094   -- Return amount applied to an aropen in base currency item as of the parameter date
16095   SELECT SUM(currtobase(arapply_curr_id,arapply_applied,pDate)) INTO _amount
16096   FROM arapply
16097   WHERE (((arapply_target_aropen_id = pAropenid) OR (arapply_source_aropen_id = pAropenid))
16098   AND (((arapply_journalnumber=0) AND (arapply_postdate <= pDate))
16099   OR EXISTS(SELECT * 
16100              FROM gltrans 
16101              WHERE ((gltrans_journalnumber=arapply_journalnumber)
16102              AND (gltrans_date <= pDate)))));
16103
16104   IF (_amount IS NULL) THEN
16105     RETURN 0;
16106   ELSE
16107     RETURN _amount;
16108   END IF;
16109
16110 END;
16111 $_$;
16112
16113
16114 ALTER FUNCTION public.arapplied(integer, date) OWNER TO admin;
16115
16116 --
16117 -- TOC entry 1132 (class 1255 OID 146565653)
16118 -- Dependencies: 4536 8
16119 -- Name: archivesaleshistory(integer); Type: FUNCTION; Schema: public; Owner: admin
16120 --
16121
16122 CREATE FUNCTION archivesaleshistory(integer) RETURNS integer
16123     LANGUAGE plpgsql
16124     AS $_$
16125 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16126 -- See www.xtuple.com/CPAL for the full text of the software license.
16127 DECLARE
16128   pSohistid ALIAS FOR $1;
16129
16130 BEGIN
16131
16132   INSERT INTO asohist ( asohist_id,
16133                         asohist_cust_id,
16134                         asohist_itemsite_id,
16135                         asohist_shipdate,
16136                         asohist_invcdate,
16137                         asohist_duedate,
16138                         asohist_promisedate,
16139                         asohist_ordernumber,
16140                         asohist_invcnumber,
16141                         asohist_qtyshipped,
16142                         asohist_unitprice,
16143                         asohist_unitcost,
16144                         asohist_billtoname,
16145                         asohist_billtoaddress1,
16146                         asohist_billtoaddress2,
16147                         asohist_billtoaddress3,
16148                         asohist_billtocity,
16149                         asohist_billtostate,
16150                         asohist_billtozip,
16151                         asohist_shiptoname,
16152                         asohist_shiptoaddress1,
16153                         asohist_shiptoaddress2,
16154                         asohist_shiptoaddress3,
16155                         asohist_shiptocity,
16156                         asohist_shiptostate,
16157                         asohist_shiptozip,
16158                         asohist_shipto_id,
16159                         asohist_shipvia,
16160                         asohist_salesrep_id,
16161                         asohist_misc_type,
16162                         asohist_misc_descrip,
16163                         asohist_misc_id,
16164                         asohist_commission,
16165                         asohist_commissionpaid,
16166                         asohist_doctype,
16167                         asohist_orderdate,
16168                         asohist_imported,
16169                         asohist_ponumber,
16170                         asohist_curr_id,
16171                         asohist_taxtype_id,
16172                         asohist_taxzone_id )
16173   SELECT cohist_id,
16174          cohist_cust_id,
16175          cohist_itemsite_id,
16176          cohist_shipdate,
16177          cohist_invcdate,
16178          cohist_duedate,
16179          cohist_promisedate,
16180          cohist_ordernumber,
16181          cohist_invcnumber,
16182          cohist_qtyshipped,
16183          cohist_unitprice,
16184          cohist_unitcost,
16185          cohist_billtoname,
16186          cohist_billtoaddress1,
16187          cohist_billtoaddress2,
16188          cohist_billtoaddress3,
16189          cohist_billtocity,
16190          cohist_billtostate,
16191          cohist_billtozip,
16192          cohist_shiptoname,
16193          cohist_shiptoaddress1,
16194          cohist_shiptoaddress2,
16195          cohist_shiptoaddress3,
16196          cohist_shiptocity,
16197          cohist_shiptostate,
16198          cohist_shiptozip,
16199          cohist_shipto_id,
16200          cohist_shipvia,
16201          cohist_salesrep_id,
16202          cohist_misc_type,
16203          cohist_misc_descrip,
16204          cohist_misc_id,
16205          cohist_commission,
16206          cohist_commissionpaid,
16207          cohist_doctype,
16208          cohist_orderdate,
16209          cohist_imported,
16210          cohist_ponumber,
16211          cohist_curr_id,
16212          cohist_taxtype_id,
16213          cohist_taxzone_id
16214   FROM cohist
16215   WHERE (cohist_id=pSohistid);
16216
16217   INSERT INTO asohisttax ( taxhist_id,
16218                            taxhist_parent_id,
16219                            taxhist_taxtype_id,
16220                            taxhist_tax_id,
16221                            taxhist_basis,
16222                            taxhist_basis_tax_id,
16223                            taxhist_sequence,
16224                            taxhist_percent,
16225                            taxhist_amount,
16226                            taxhist_tax,
16227                            taxhist_docdate,
16228                            taxhist_distdate,
16229                            taxhist_curr_id,
16230                            taxhist_curr_rate,
16231                            taxhist_journalnumber )
16232   SELECT taxhist_id,
16233          taxhist_parent_id,
16234          taxhist_taxtype_id,
16235          taxhist_tax_id,
16236          taxhist_basis,
16237          taxhist_basis_tax_id,
16238          taxhist_sequence,
16239          taxhist_percent,
16240          taxhist_amount,
16241          taxhist_tax,
16242          taxhist_docdate,
16243          taxhist_distdate,
16244          taxhist_curr_id,
16245          taxhist_curr_rate,
16246          taxhist_journalnumber
16247   FROM cohisttax
16248   WHERE (taxhist_parent_id=pSohistid);
16249
16250   DELETE FROM cohisttax
16251   WHERE (taxhist_parent_id=pSohistid);
16252
16253   DELETE FROM cohist
16254   WHERE (cohist_id=pSohistid);
16255
16256   RETURN pSohistid;
16257
16258 END;
16259 $_$;
16260
16261
16262 ALTER FUNCTION public.archivesaleshistory(integer) OWNER TO admin;
16263
16264 --
16265 -- TOC entry 1133 (class 1255 OID 146565654)
16266 -- Dependencies: 4536 8
16267 -- Name: arcurrgain(integer, integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
16268 --
16269
16270 CREATE FUNCTION arcurrgain(integer, integer, numeric, date) RETURNS numeric
16271     LANGUAGE plpgsql
16272     AS $_$
16273 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16274 -- See www.xtuple.com/CPAL for the full text of the software license.
16275 DECLARE
16276   pAropenId ALIAS FOR $1;
16277   pCurrId ALIAS FOR $2;
16278   pValue ALIAS FOR $3;
16279   pDate ALIAS FOR $4;
16280   _start DATE;
16281   _end DATE;
16282   _gain NUMERIC;
16283   _r RECORD;
16284
16285 BEGIN
16286   IF (pAropenId IS NULL OR pValue = 0) THEN
16287     RETURN 0;
16288   END IF;
16289
16290   SELECT aropen_docdate, aropen_curr_id, aropen_curr_rate
16291     INTO _r
16292   FROM aropen
16293   WHERE (aropen_id=pAropenId);
16294
16295   IF (_r.aropen_docdate > pDate) THEN
16296     _gain := (currToBase(pCurrId, pValue, pDate) - currToCurr(pCurrId,_r.aropen_curr_id, pValue, pDate) / _r.aropen_curr_rate) * -1;
16297   ELSE
16298     _gain := currToCurr(pCurrId,_r.aropen_curr_id, pValue, pDate) / _r.aropen_curr_rate - currToBase(pCurrId, pValue, pDate);
16299   END IF;
16300
16301   IF (_gain IS NULL) THEN
16302     RAISE EXCEPTION 'Error processing currency gain/loss.';
16303   END IF;
16304
16305   RETURN _gain;
16306 END;
16307 $_$;
16308
16309
16310 ALTER FUNCTION public.arcurrgain(integer, integer, numeric, date) OWNER TO admin;
16311
16312 --
16313 -- TOC entry 1134 (class 1255 OID 146565655)
16314 -- Dependencies: 8
16315 -- Name: armor(bytea); Type: FUNCTION; Schema: public; Owner: admin
16316 --
16317
16318 CREATE FUNCTION armor(bytea) RETURNS text
16319     LANGUAGE c IMMUTABLE STRICT
16320     AS '$libdir/pgcrypto', 'pg_armor';
16321
16322
16323 ALTER FUNCTION public.armor(bytea) OWNER TO admin;
16324
16325 --
16326 -- TOC entry 202 (class 1259 OID 146565656)
16327 -- Dependencies: 5936 8
16328 -- Name: invbal; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
16329 --
16330
16331 CREATE TABLE invbal (
16332     invbal_id integer NOT NULL,
16333     invbal_period_id integer,
16334     invbal_itemsite_id integer,
16335     invbal_qoh_beginning numeric(18,6) NOT NULL,
16336     invbal_qoh_ending numeric(18,6) NOT NULL,
16337     invbal_qty_in numeric(18,6) NOT NULL,
16338     invbal_qty_out numeric(18,6) NOT NULL,
16339     invbal_value_beginning numeric(12,2) NOT NULL,
16340     invbal_value_ending numeric(12,2) NOT NULL,
16341     invbal_value_in numeric(12,2) NOT NULL,
16342     invbal_value_out numeric(12,2) NOT NULL,
16343     invbal_nn_beginning numeric(18,6) NOT NULL,
16344     invbal_nn_ending numeric(18,6) NOT NULL,
16345     invbal_nn_in numeric(18,6) NOT NULL,
16346     invbal_nn_out numeric(18,6) NOT NULL,
16347     invbal_nnval_beginning numeric(12,2) NOT NULL,
16348     invbal_nnval_ending numeric(12,2) NOT NULL,
16349     invbal_nnval_in numeric(12,2) NOT NULL,
16350     invbal_nnval_out numeric(12,2) NOT NULL,
16351     invbal_dirty boolean DEFAULT true NOT NULL
16352 );
16353
16354
16355 ALTER TABLE public.invbal OWNER TO admin;
16356
16357 --
16358 -- TOC entry 1135 (class 1255 OID 146565660)
16359 -- Dependencies: 2770 4536 8
16360 -- Name: asofinvbal(integer, date); Type: FUNCTION; Schema: public; Owner: admin
16361 --
16362
16363 CREATE FUNCTION asofinvbal(integer, date) RETURNS SETOF invbal
16364     LANGUAGE plpgsql STABLE
16365     AS $_$
16366 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16367 -- See www.xtuple.com/CPAL for the full text of the software license.
16368 DECLARE
16369   pItemsiteId ALIAS FOR $1;
16370   pAsofDate ALIAS FOR $2;
16371   _result invbal%ROWTYPE;
16372   _i RECORD;
16373   _h RECORD;
16374   _r RECORD;
16375   _prevCostmethod TEXT := 'A';
16376   _prevDate TIMESTAMP WITH TIME ZONE;
16377   _runningQty NUMERIC := 0;
16378   _runningNn NUMERIC := 0;
16379   _runningValue NUMERIC := 0;
16380   _runningNnval NUMERIC := 0;
16381
16382 BEGIN
16383   /* This is a base function to gather data.  Because it is STABLE it should only need
16384   to be calculated once, even though it is likely to be called several times by other
16385   functions in parent query to present the various data.
16386   */
16387   
16388   -- First make sure inventory balance is forward updated
16389   PERFORM forwardUpdateItemsite(pItemsiteId);
16390
16391   -- Next find the previous period balace to use as a starting point
16392   SELECT invbal.*, period_start, itemsite_costmethod INTO _i
16393   FROM invbal 
16394     JOIN itemsite ON (invbal_itemsite_id=itemsite_id) 
16395     JOIN period ON (invbal_period_id=period_id)
16396   WHERE ((invbal_itemsite_id=pItemsiteId)
16397     AND  (pAsofDate >= period_start))
16398   ORDER BY period_start DESC
16399   LIMIT 1;
16400
16401   _runningQty := _i.invbal_qoh_beginning;
16402   _runningNn := _i.invbal_nn_beginning;
16403   _runningValue := _i.invbal_value_beginning;
16404   _runningNnval := _i.invbal_nnval_beginning;
16405   _prevDate := _i.period_start;
16406   _prevCostmethod := _i.itemsite_costmethod;
16407
16408   FOR _r IN 
16409     SELECT invhist_id, invhist_created, invhist_invqty, invhist_transtype, invhist_unitcost,
16410       invhist_costmethod, itemsite_item_id, invhistSense(invhist_id) AS sense
16411     FROM invhist
16412       JOIN itemsite ON (itemsite_id=invhist_itemsite_id)
16413     WHERE ((invhist_itemsite_id=pItemsiteId)
16414     AND (invhist_transdate::date BETWEEN _i.period_start AND pAsofdate))
16415     ORDER BY invhist_created, invhist_id
16416   LOOP
16417     -- Update balances changed by any standard cost update between transactions
16418     IF (_prevCostmethod = 'S' AND _runningQty != 0) THEN
16419       FOR _h IN
16420         SELECT costhist_oldcost, costhist_newcost
16421         FROM costhist
16422           JOIN item ON (costhist_item_id=item_id)
16423           JOIN itemsite ON (itemsite_item_id=item_id)
16424         WHERE ((itemsite_id=pItemsiteId)
16425           AND (costhist_date BETWEEN _prevDate AND _r.invhist_created)
16426           AND (costhist_type IN ('S','D')))
16427       LOOP
16428         _runningValue := _runningValue + round((_h.costhist_newcost-_h.costhist_oldcost) * _runningQty,2);
16429         _runningNnval := _runningNnval + round((_h.costhist_newcost-_h.costhist_oldcost) * _runningNn,2);
16430       END LOOP;
16431     END IF;
16432
16433     _prevDate := _r.invhist_created;
16434     _prevCostmethod := _r.invhist_costmethod;
16435     _runningQty := _runningQty + _r.invhist_invqty * _r.sense;
16436     _runningValue := _runningValue + round( _r.invhist_invqty * _r.sense * _r.invhist_unitcost,2);
16437     IF (_r.invhist_transtype = 'NN') THEN
16438       _runningNn := _runningNn + _r.invhist_invqty * -1;
16439       _runningNnval := _runningNnval + round( _r.invhist_invqty * -1 * _r.invhist_unitcost,2);
16440     END IF;
16441     
16442   END LOOP;
16443
16444   _prevDate := COALESCE(_prevDate, _i.period_start);
16445   _prevCostmethod := COALESCE(_r.invhist_costmethod, _i.itemsite_costmethod);
16446   
16447   IF (_prevCostmethod = 'S' AND _runningQty != 0) THEN
16448     FOR _h IN
16449       SELECT costhist_oldcost, costhist_newcost
16450       FROM costhist
16451         JOIN item ON (costhist_item_id=item_id)
16452         JOIN itemsite ON (itemsite_item_id=item_id)
16453       WHERE ((itemsite_id=pItemsiteId)
16454         AND (costhist_date BETWEEN _prevDate AND CAST(pAsofDate + 1 AS TIMESTAMP WITH TIME ZONE))
16455         AND (costhist_type IN ('S','D')))
16456     LOOP
16457       _runningValue := _runningValue + round((_h.costhist_newcost-_h.costhist_oldcost) * _runningQty,2);
16458       _runningNnval := _runningNnval + round((_h.costhist_newcost-_h.costhist_oldcost) * _runningNn,2);
16459     END LOOP;
16460   END IF;
16461
16462   _result := _i;
16463   _result.invbal_qoh_ending := _runningQty;
16464   _result.invbal_value_ending := _runningValue;
16465   _result.invbal_nn_ending := _runningNn;
16466   _result.invbal_nnval_ending := _runningNnval;
16467
16468   RETURN NEXT _result;
16469
16470   RETURN;
16471   
16472 END;
16473 $_$;
16474
16475
16476 ALTER FUNCTION public.asofinvbal(integer, date) OWNER TO admin;
16477
16478 --
16479 -- TOC entry 1136 (class 1255 OID 146565661)
16480 -- Dependencies: 4536 8
16481 -- Name: asofinvnn(integer, date); Type: FUNCTION; Schema: public; Owner: admin
16482 --
16483
16484 CREATE FUNCTION asofinvnn(integer, date) RETURNS numeric
16485     LANGUAGE plpgsql STABLE
16486     AS $_$
16487 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16488 -- See www.xtuple.com/CPAL for the full text of the software license.
16489 DECLARE
16490   pItemsiteId ALIAS FOR $1;
16491   pAsofDate ALIAS FOR $2;
16492   _result NUMERIC;
16493
16494 BEGIN
16495
16496   SELECT invbal_nn_ending INTO _result
16497   FROM asofinvbal(pItemsiteId, pAsofDate);
16498
16499   RETURN COALESCE(_result, 0);
16500   
16501 END;
16502 $_$;
16503
16504
16505 ALTER FUNCTION public.asofinvnn(integer, date) OWNER TO admin;
16506
16507 --
16508 -- TOC entry 1137 (class 1255 OID 146565662)
16509 -- Dependencies: 4536 8
16510 -- Name: asofinvqty(integer, date); Type: FUNCTION; Schema: public; Owner: admin
16511 --
16512
16513 CREATE FUNCTION asofinvqty(integer, date) RETURNS numeric
16514     LANGUAGE plpgsql STABLE
16515     AS $_$
16516 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16517 -- See www.xtuple.com/CPAL for the full text of the software license.
16518 DECLARE
16519   pItemsiteId ALIAS FOR $1;
16520   pAsofDate ALIAS FOR $2;
16521   _result NUMERIC;
16522
16523 BEGIN
16524
16525   SELECT invbal_qoh_ending INTO _result
16526   FROM asofinvbal(pItemsiteId, pAsofDate);
16527
16528   RETURN COALESCE(_result, 0);
16529   
16530 END;
16531 $_$;
16532
16533
16534 ALTER FUNCTION public.asofinvqty(integer, date) OWNER TO admin;
16535
16536 --
16537 -- TOC entry 1138 (class 1255 OID 146565663)
16538 -- Dependencies: 4536 8
16539 -- Name: assessfinancecharge(integer, date, numeric); Type: FUNCTION; Schema: public; Owner: admin
16540 --
16541
16542 CREATE FUNCTION assessfinancecharge(paropenid integer, passessdate date, passessamount numeric) RETURNS integer
16543     LANGUAGE plpgsql
16544     AS $$
16545 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16546 -- See www.xtuple.com/CPAL for the full text of the software license.
16547 DECLARE
16548   _fc           RECORD;
16549   _ar           RECORD;
16550   _invcheadid   INTEGER;
16551
16552 BEGIN
16553
16554   -- cache some information
16555   SELECT * INTO _fc FROM fincharg;
16556   IF (NOT FOUND) THEN
16557     RAISE EXCEPTION 'assessFinanceCharge, configuration not set.';
16558   END IF;
16559
16560   SELECT * INTO _ar FROM aropen WHERE (aropen_id=pAropenid);
16561   IF (NOT FOUND) THEN
16562     RAISE EXCEPTION 'assessFinanceCharge, aropen not found.';
16563   END IF;
16564
16565   -- create invoice head
16566   INSERT INTO invchead
16567     ( invchead_cust_id,
16568       invchead_shipto_id,
16569       invchead_ordernumber,
16570       invchead_orderdate,
16571       invchead_posted,
16572       invchead_printed,
16573       invchead_invcnumber,
16574       invchead_invcdate,
16575       invchead_shipdate,
16576       invchead_ponumber,
16577       invchead_shipvia,
16578       invchead_fob,
16579       invchead_billto_name,
16580       invchead_billto_address1,
16581       invchead_billto_address2,
16582       invchead_billto_address3,
16583       invchead_billto_city,
16584       invchead_billto_state,
16585       invchead_billto_zipcode,
16586       invchead_billto_phone,
16587       invchead_shipto_name,
16588       invchead_shipto_address1,
16589       invchead_shipto_address2,
16590       invchead_shipto_address3,
16591       invchead_shipto_city,
16592       invchead_shipto_state,
16593       invchead_shipto_zipcode,
16594       invchead_shipto_phone,
16595       invchead_salesrep_id,
16596       invchead_commission,
16597       invchead_terms_id,
16598       invchead_freight,
16599       invchead_misc_amount,
16600       invchead_misc_descrip,
16601       invchead_misc_accnt_id,
16602       invchead_payment,
16603       invchead_paymentref,
16604       invchead_notes,
16605       invchead_billto_country,
16606       invchead_shipto_country,
16607       invchead_prj_id,
16608       invchead_curr_id,
16609       invchead_gldistdate,
16610       invchead_recurring,
16611       invchead_recurring_interval,
16612       invchead_recurring_type,
16613       invchead_recurring_until,
16614       invchead_recurring_invchead_id,
16615       invchead_shipchrg_id,
16616       invchead_taxzone_id,
16617       invchead_void,
16618       invchead_saletype_id,
16619       invchead_shipzone_id )
16620   SELECT
16621       invchead_cust_id,
16622       invchead_shipto_id,
16623       invchead_ordernumber,
16624       invchead_orderdate,
16625       FALSE,
16626       FALSE,
16627       fetchInvcNumber(),
16628       pAssessDate,
16629       invchead_shipdate,
16630       invchead_ponumber,
16631       invchead_shipvia,
16632       invchead_fob,
16633       invchead_billto_name,
16634       invchead_billto_address1,
16635       invchead_billto_address2,
16636       invchead_billto_address3,
16637       invchead_billto_city,
16638       invchead_billto_state,
16639       invchead_billto_zipcode,
16640       invchead_billto_phone,
16641       invchead_shipto_name,
16642       invchead_shipto_address1,
16643       invchead_shipto_address2,
16644       invchead_shipto_address3,
16645       invchead_shipto_city,
16646       invchead_shipto_state,
16647       invchead_shipto_zipcode,
16648       invchead_shipto_phone,
16649       invchead_salesrep_id,
16650       0.0,
16651       invchead_terms_id,
16652       0.0,
16653       0.0,
16654       NULL,
16655       NULL,
16656       0.0,
16657       NULL,
16658       '',
16659       invchead_billto_country,
16660       invchead_shipto_country,
16661       invchead_prj_id,
16662       invchead_curr_id,
16663       NULL,
16664       FALSE,
16665       NULL,
16666       NULL,
16667       NULL,
16668       NULL,
16669       invchead_shipchrg_id,
16670       invchead_taxzone_id,
16671       invchead_void,
16672       invchead_saletype_id,
16673       invchead_shipzone_id
16674   FROM invchead
16675   WHERE (invchead_invcnumber=_ar.aropen_docnumber)
16676   RETURNING invchead_id INTO _invcheadid;
16677
16678   -- create invoice item
16679   INSERT INTO invcitem
16680     ( invcitem_invchead_id,
16681       invcitem_linenumber,
16682       invcitem_item_id,
16683       invcitem_warehous_id,
16684       invcitem_custpn,
16685       invcitem_number,
16686       invcitem_descrip,
16687       invcitem_ordered,
16688       invcitem_billed,
16689       invcitem_custprice,
16690       invcitem_price,
16691       invcitem_notes,
16692       invcitem_salescat_id,
16693       invcitem_taxtype_id,
16694       invcitem_qty_uom_id,
16695       invcitem_qty_invuomratio,
16696       invcitem_price_uom_id,
16697       invcitem_price_invuomratio,
16698       invcitem_coitem_id,
16699       invcitem_updateinv,
16700       invcitem_rev_accnt_id )
16701   VALUES
16702     ( _invcheadid,
16703       1,
16704       -1,
16705       -1,
16706       NULL,
16707       _fc.fincharg_markoninvoice,
16708       'Finance Charge Assessment',
16709       1.0,
16710       1.0,
16711       pAssessAmount,
16712       pAssessAmount,
16713       '',
16714       _fc.fincharg_salescat_id,
16715       NULL,
16716       NULL,
16717       1.0,
16718       NULL,
16719       1.0,
16720       NULL,
16721       FALSE,
16722       _fc.fincharg_accnt_id );
16723
16724   -- update aropen
16725   UPDATE aropen SET aropen_fincharg_date = pAssessDate,
16726                     aropen_fincharg_amount = COALESCE(aropen_fincharg_amount, 0.0) + pAssessAmount
16727   WHERE (aropen_id=pAropenid);
16728
16729
16730   RETURN 0;
16731
16732 END;
16733 $$;
16734
16735
16736 ALTER FUNCTION public.assessfinancecharge(paropenid integer, passessdate date, passessamount numeric) OWNER TO admin;
16737
16738 --
16739 -- TOC entry 1139 (class 1255 OID 146565664)
16740 -- Dependencies: 4536 8
16741 -- Name: attachcontact(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
16742 --
16743
16744 CREATE FUNCTION attachcontact(integer, integer) RETURNS integer
16745     LANGUAGE plpgsql
16746     AS $_$
16747 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16748 -- See www.xtuple.com/CPAL for the full text of the software license.
16749 DECLARE
16750   pcntctId    ALIAS FOR $1;
16751   pcrmacctId  ALIAS FOR $2;
16752 BEGIN
16753   UPDATE cntct SET cntct_crmacct_id = pcrmacctId
16754   WHERE cntct_id = pcntctId;
16755
16756   RETURN 0;
16757 END;
16758 $_$;
16759
16760
16761 ALTER FUNCTION public.attachcontact(integer, integer) OWNER TO admin;
16762
16763 --
16764 -- TOC entry 1140 (class 1255 OID 146565665)
16765 -- Dependencies: 4536 8
16766 -- Name: attachquotetoopportunity(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
16767 --
16768
16769 CREATE FUNCTION attachquotetoopportunity(integer, integer) RETURNS integer
16770     LANGUAGE plpgsql
16771     AS $_$
16772 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16773 -- See www.xtuple.com/CPAL for the full text of the software license.
16774 DECLARE
16775   pQuheadid     ALIAS FOR $1;
16776   pOpheadid     ALIAS FOR $2;
16777 BEGIN
16778
16779 -- Check Quote
16780   IF (NOT EXISTS(SELECT quhead_id
16781                  FROM quhead
16782                  WHERE (quhead_id=pQuheadid))) THEN
16783     RETURN -1;
16784   END IF;
16785
16786 -- Check Opportunity
16787   IF (NOT EXISTS(SELECT ophead_id
16788                  FROM ophead
16789                  WHERE (ophead_id=pOpheadid))) THEN
16790     RETURN -2;
16791   END IF;
16792
16793 -- Cannot attach if already attached
16794   IF (EXISTS(SELECT quhead_id
16795              FROM quhead
16796              WHERE ((quhead_id=pQuheadid)
16797                AND  (quhead_ophead_id IS NOT NULL)))) THEN
16798     RETURN -3;
16799   END IF;
16800
16801   UPDATE quhead SET quhead_ophead_id=pOpheadid
16802   WHERE (quhead_id=pQuheadid);
16803
16804   RETURN 0;
16805
16806 END;
16807 $_$;
16808
16809
16810 ALTER FUNCTION public.attachquotetoopportunity(integer, integer) OWNER TO admin;
16811
16812 --
16813 -- TOC entry 1141 (class 1255 OID 146565666)
16814 -- Dependencies: 4536 8
16815 -- Name: attachsalesordertoopportunity(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
16816 --
16817
16818 CREATE FUNCTION attachsalesordertoopportunity(integer, integer) RETURNS integer
16819     LANGUAGE plpgsql
16820     AS $_$
16821 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16822 -- See www.xtuple.com/CPAL for the full text of the software license.
16823 DECLARE
16824   pSoheadid     ALIAS FOR $1;
16825   pOpheadid     ALIAS FOR $2;
16826 BEGIN
16827
16828 -- Check Sales Order
16829   IF (NOT EXISTS(SELECT cohead_id
16830                  FROM cohead
16831                  WHERE (cohead_id=pSoheadid))) THEN
16832     RETURN -1;
16833   END IF;
16834
16835 -- Check Opportunity
16836   IF (NOT EXISTS(SELECT ophead_id
16837                  FROM ophead
16838                  WHERE (ophead_id=pOpheadid))) THEN
16839     RETURN -2;
16840   END IF;
16841
16842 -- Cannot attach if already attached
16843   IF (EXISTS(SELECT cohead_id
16844              FROM cohead
16845              WHERE ((cohead_id=pSoheadid)
16846                AND  (cohead_ophead_id IS NOT NULL)))) THEN
16847     RETURN -3;
16848   END IF;
16849
16850   UPDATE cohead SET cohead_ophead_id=pOpheadid
16851   WHERE (cohead_id=pSoheadid);
16852
16853   RETURN 0;
16854
16855 END;
16856 $_$;
16857
16858
16859 ALTER FUNCTION public.attachsalesordertoopportunity(integer, integer) OWNER TO admin;
16860
16861 --
16862 -- TOC entry 1142 (class 1255 OID 146565667)
16863 -- Dependencies: 4536 8
16864 -- Name: averagesalesprice(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
16865 --
16866
16867 CREATE FUNCTION averagesalesprice(integer, date, date) RETURNS numeric
16868     LANGUAGE plpgsql
16869     AS $_$
16870 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16871 -- See www.xtuple.com/CPAL for the full text of the software license.
16872 DECLARE
16873   pItemsiteid ALIAS FOR $1;
16874   pStartDate ALIAS FOR $2;
16875   pEndDate ALIAS FOR $3;
16876   _p RECORD;
16877
16878 BEGIN
16879 -- Returns value in base currency
16880 -- ToDo: is cohist_shipdate the right DATE to use?
16881   SELECT SUM(cohist_qtyshipped * currToBase(cohist_curr_id, cohist_unitprice,
16882                                             cohist_shipdate)) AS totalsales,
16883          SUM(cohist_qtyshipped) AS totalship INTO _p
16884   FROM cohist
16885   WHERE ( (cohist_itemsite_id=pItemsiteid)
16886    AND (cohist_invcdate BETWEEN pStartDate AND pEndDate) );
16887
16888   IF ( (_p.totalship IS NULL) OR
16889        (_p.totalship = 0) ) THEN
16890     RETURN 0;
16891   ELSE
16892     RETURN (_p.totalsales / _p.totalship);
16893   END IF;
16894
16895 END;
16896 $_$;
16897
16898
16899 ALTER FUNCTION public.averagesalesprice(integer, date, date) OWNER TO admin;
16900
16901 --
16902 -- TOC entry 1143 (class 1255 OID 146565668)
16903 -- Dependencies: 4536 8
16904 -- Name: avgcost(integer); Type: FUNCTION; Schema: public; Owner: admin
16905 --
16906
16907 CREATE FUNCTION avgcost(pitemsiteid integer) RETURNS numeric
16908     LANGUAGE plpgsql
16909     AS $$
16910 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16911 -- See www.xtuple.com/CPAL for the full text of the software license.
16912 DECLARE
16913   _value NUMERIC;
16914   _qoh NUMERIC;
16915   _qohnn NUMERIC;
16916 BEGIN
16917   SELECT itemsite_value, itemsite_qtyonhand, itemsite_nnqoh
16918     INTO _value, _qoh, _qohnn
16919     FROM itemsite
16920    WHERE(itemsite_id=pItemsiteid);
16921   IF (_qoh = 0.0 AND _qohnn = 0.0) THEN
16922     RETURN 0.0;
16923   END IF;
16924   RETURN _value / (_qoh + _qohnn);
16925 END;
16926 $$;
16927
16928
16929 ALTER FUNCTION public.avgcost(pitemsiteid integer) OWNER TO admin;
16930
16931 --
16932 -- TOC entry 1144 (class 1255 OID 146565669)
16933 -- Dependencies: 4536 8
16934 -- Name: balanceitemsite(integer); Type: FUNCTION; Schema: public; Owner: admin
16935 --
16936
16937 CREATE FUNCTION balanceitemsite(integer) RETURNS integer
16938     LANGUAGE plpgsql
16939     AS $_$
16940 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
16941 -- See www.xtuple.com/CPAL for the full text of the software license.
16942 DECLARE
16943   pItemsiteid ALIAS FOR $1;
16944   _itemlocseries INTEGER;
16945   _balanced NUMERIC;
16946   _qoh NUMERIC;
16947   _nnQoh NUMERIC;
16948
16949 BEGIN
16950
16951 --  Make sure that that passed Itemsite is MLC or Lot/Serial controlled
16952   IF ( ( SELECT (NOT ( (itemsite_loccntrl) OR (itemsite_controlmethod IN ('L', 'S')) ))
16953          FROM itemsite
16954          WHERE (itemsite_id=pItemsiteid) ) ) THEN
16955     RETURN 0;
16956   END IF;
16957
16958   IF ( ( SELECT itemsite_freeze
16959            FROM itemsite
16960           WHERE(itemsite_id=pItemsiteid) ) ) THEN
16961     RETURN -1;
16962   END IF;
16963
16964 --  Calculate the Netable portion
16965   SELECT COALESCE(SUM(itemloc_qty), 0) INTO _balanced
16966   FROM itemloc LEFT OUTER JOIN location ON (itemloc_location_id=location_id)
16967   WHERE ( ( (location_id IS NULL) OR (location_netable) )
16968    AND (itemloc_itemsite_id=pItemsiteid) );
16969
16970 --  Post an AD Transaction for the Netable portion
16971   SELECT invAdjustment( itemsite_id, (_balanced - itemsite_qtyonhand),
16972                         'Balance', 'Inventory Balance' ) INTO _itemlocseries
16973   FROM itemsite
16974   WHERE (itemsite_id=pItemsiteid);
16975
16976 --  Post the invtrans records associated with the itemlocdist records
16977   PERFORM postInvhist(itemlocdist_invhist_id)
16978      FROM itemlocdist
16979     WHERE(itemlocdist_series=_itemlocseries);
16980
16981 --  Kill the resultant distribution records
16982   DELETE FROM itemlocdist
16983   WHERE (itemlocdist_series=_itemlocseries);
16984
16985 --  Calculate and write the Non-Netable portion directly
16986   SELECT COALESCE(SUM(itemloc_qty), 0) INTO _nnQoh
16987   FROM itemloc, location
16988   WHERE ( (itemloc_location_id=location_id)
16989    AND (NOT location_netable)
16990    AND (itemloc_itemsite_id=pItemsiteid) );
16991
16992   UPDATE itemsite
16993   SET itemsite_nnqoh = _nnQoh
16994   WHERE (itemsite_id=pItemsiteid);
16995
16996   RETURN 1;
16997
16998 END;
16999 $_$;
17000
17001
17002 ALTER FUNCTION public.balanceitemsite(integer) OWNER TO admin;
17003
17004 --
17005 -- TOC entry 1114 (class 1255 OID 146565670)
17006 -- Dependencies: 4536 8
17007 -- Name: bomcontains(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
17008 --
17009
17010 CREATE FUNCTION bomcontains(integer, integer) RETURNS boolean
17011     LANGUAGE plpgsql
17012     AS $_$
17013 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17014 -- See www.xtuple.com/CPAL for the full text of the software license.
17015 DECLARE
17016   pparentitemid ALIAS FOR $1;
17017   pchilditemid  ALIAS FOR $2;
17018   _bomworksetid INTEGER;
17019   _result       BOOLEAN;
17020
17021 BEGIN
17022   _bomworksetid := indentedWhereUsed(pchilditemid);
17023   _result := EXISTS(SELECT bomwork_id
17024                     FROM bomwork
17025                     WHERE ((bomwork_set_id=_bomworksetid)
17026                       AND  (bomwork_item_id=pparentitemid) ));
17027
17028   PERFORM deleteBOMWorkset(_bomworksetid);
17029
17030   RETURN _result;
17031 END;
17032 $_$;
17033
17034
17035 ALTER FUNCTION public.bomcontains(integer, integer) OWNER TO admin;
17036
17037 --
17038 -- TOC entry 1146 (class 1255 OID 146565671)
17039 -- Dependencies: 4536 8
17040 -- Name: bomhistsequence(integer); Type: FUNCTION; Schema: public; Owner: admin
17041 --
17042
17043 CREATE FUNCTION bomhistsequence(integer) RETURNS text
17044     LANGUAGE plpgsql
17045     AS $_$
17046 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17047 -- See www.xtuple.com/CPAL for the full text of the software license.
17048 DECLARE
17049   pHistid ALIAS FOR $1;
17050   _wid INTEGER;
17051   _seqnum TEXT;
17052   _bomhist RECORD;
17053
17054 BEGIN
17055   _wid := pHistid;
17056
17057   SELECT bomhist_parent_id AS parent,
17058          to_char(bomhist_seqnumber, '00009') AS seq INTO _bomhist
17059     FROM bomhist
17060    WHERE bomhist_seq_id=_wid;
17061
17062   IF (FOUND) THEN
17063     _seqnum := _bomhist.seq;
17064     _wid := _bomhist.parent;
17065
17066     WHILE (_wid != -1) LOOP
17067       SELECT bomhist_parent_id AS parent,
17068              to_char(bomhist_seqnumber, '00009') AS seq INTO _bomhist
17069       FROM bomhist
17070       WHERE bomhist_seq_id=_wid;
17071
17072       IF (FOUND) THEN
17073         _seqnum := _bomhist.seq || '-' || _seqnum;
17074         _wid    := _bomhist.parent;
17075       ELSE
17076         _wid := -1;
17077       END IF;
17078     END LOOP;
17079   ELSE
17080     _seqnum := ''::TEXT;
17081   END IF;
17082
17083   RETURN _seqnum;
17084 END;
17085 $_$;
17086
17087
17088 ALTER FUNCTION public.bomhistsequence(integer) OWNER TO admin;
17089
17090 --
17091 -- TOC entry 203 (class 1259 OID 146565672)
17092 -- Dependencies: 5937 5938 5939 5940 5941 5942 5943 8
17093 -- Name: bomitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
17094 --
17095
17096 CREATE TABLE bomitem (
17097     bomitem_id integer DEFAULT nextval(('bomitem_bomitem_id_seq'::text)::regclass) NOT NULL,
17098     bomitem_parent_item_id integer NOT NULL,
17099     bomitem_seqnumber integer,
17100     bomitem_item_id integer NOT NULL,
17101     bomitem_qtyper numeric(20,8) NOT NULL,
17102     bomitem_scrap numeric(8,4) NOT NULL,
17103     bomitem_status character(1),
17104     bomitem_effective date NOT NULL,
17105     bomitem_expires date NOT NULL,
17106     bomitem_createwo boolean NOT NULL,
17107     bomitem_issuemethod character(1) NOT NULL,
17108     bomitem_schedatwooper boolean NOT NULL,
17109     bomitem_ecn text,
17110     bomitem_moddate date,
17111     bomitem_subtype character(1) NOT NULL,
17112     bomitem_uom_id integer NOT NULL,
17113     bomitem_rev_id integer DEFAULT (-1),
17114     bomitem_booitem_seq_id integer DEFAULT (-1),
17115     bomitem_char_id integer,
17116     bomitem_value text,
17117     bomitem_notes text,
17118     bomitem_ref text,
17119     bomitem_qtyfxd numeric(20,8) DEFAULT 0 NOT NULL,
17120     bomitem_issuewo boolean DEFAULT false NOT NULL,
17121     CONSTRAINT bomitem_bomitem_issuemethod_check CHECK ((((bomitem_issuemethod = 'M'::bpchar) OR (bomitem_issuemethod = 'S'::bpchar)) OR (bomitem_issuemethod = 'L'::bpchar))),
17122     CONSTRAINT bomitem_bomitem_subtype_check CHECK ((((bomitem_subtype = 'N'::bpchar) OR (bomitem_subtype = 'I'::bpchar)) OR (bomitem_subtype = 'B'::bpchar)))
17123 );
17124
17125
17126 ALTER TABLE public.bomitem OWNER TO admin;
17127
17128 --
17129 -- TOC entry 8944 (class 0 OID 0)
17130 -- Dependencies: 203
17131 -- Name: TABLE bomitem; Type: COMMENT; Schema: public; Owner: admin
17132 --
17133
17134 COMMENT ON TABLE bomitem IS 'Bill of Materials (BOM) component Items information';
17135
17136
17137 --
17138 -- TOC entry 8945 (class 0 OID 0)
17139 -- Dependencies: 203
17140 -- Name: COLUMN bomitem.bomitem_qtyfxd; Type: COMMENT; Schema: public; Owner: admin
17141 --
17142
17143 COMMENT ON COLUMN bomitem.bomitem_qtyfxd IS 'The fixed quantity required';
17144
17145
17146 --
17147 -- TOC entry 1147 (class 1255 OID 146565685)
17148 -- Dependencies: 2773 8
17149 -- Name: bomitem(integer); Type: FUNCTION; Schema: public; Owner: admin
17150 --
17151
17152 CREATE FUNCTION bomitem(integer) RETURNS SETOF bomitem
17153     LANGUAGE sql
17154     AS $_$
17155 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17156 -- See www.xtuple.com/CPAL for the full text of the software license.
17157   SELECT * FROM bomitem WHERE ((bomitem_parent_item_id=$1) AND (bomitem_rev_id=getActiveRevId('BOM',$1)));
17158 $_$;
17159
17160
17161 ALTER FUNCTION public.bomitem(integer) OWNER TO admin;
17162
17163 --
17164 -- TOC entry 1148 (class 1255 OID 146565686)
17165 -- Dependencies: 2773 8
17166 -- Name: bomitem(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
17167 --
17168
17169 CREATE FUNCTION bomitem(integer, integer) RETURNS SETOF bomitem
17170     LANGUAGE sql
17171     AS $_$
17172 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17173 -- See www.xtuple.com/CPAL for the full text of the software license.
17174   SELECT * FROM bomitem WHERE ((bomitem_parent_item_id=$1) AND (bomitem_rev_id=$2));
17175 $_$;
17176
17177
17178 ALTER FUNCTION public.bomitem(integer, integer) OWNER TO admin;
17179
17180 --
17181 -- TOC entry 1149 (class 1255 OID 146565687)
17182 -- Dependencies: 4536 8
17183 -- Name: bomlevelbyitem(integer); Type: FUNCTION; Schema: public; Owner: admin
17184 --
17185
17186 CREATE FUNCTION bomlevelbyitem(integer) RETURNS integer
17187     LANGUAGE plpgsql
17188     AS $_$
17189 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17190 -- See www.xtuple.com/CPAL for the full text of the software license.
17191 DECLARE
17192   pItemid ALIAS FOR $1;
17193   _cnt INTEGER;
17194   _result INTEGER;
17195   _bomitem RECORD;
17196
17197 BEGIN
17198   _cnt := 0;
17199
17200   BEGIN
17201   FOR _bomitem IN SELECT bomitem_parent_item_id
17202                     FROM bomitem
17203                    WHERE ((bomitem_item_id=pItemid)
17204                      AND  (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id))
17205                      AND  (CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1)))
17206   LOOP
17207     SELECT bomLevelByItem(_bomitem.bomitem_parent_item_id) + 1 INTO _result;
17208     IF (_result > _cnt) THEN
17209       _cnt := _result;
17210     END IF;
17211   END LOOP;
17212   EXCEPTION WHEN statement_too_complex THEN
17213       RAISE EXCEPTION 'potential recursive BOM found for item_id %', pItemid;
17214   END;
17215
17216   return _cnt;
17217 END;
17218 $_$;
17219
17220
17221 ALTER FUNCTION public.bomlevelbyitem(integer) OWNER TO admin;
17222
17223 --
17224 -- TOC entry 1150 (class 1255 OID 146565688)
17225 -- Dependencies: 4536 8
17226 -- Name: bomlevelbyitem(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
17227 --
17228
17229 CREATE FUNCTION bomlevelbyitem(integer, integer) RETURNS integer
17230     LANGUAGE plpgsql
17231     AS $_$
17232 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17233 -- See www.xtuple.com/CPAL for the full text of the software license.
17234 DECLARE
17235   pItemid ALIAS FOR $1;
17236   pBomrevid ALIAS FOR $2;
17237   _cnt INTEGER;
17238   _result INTEGER;
17239   _bomitem RECORD;
17240
17241 BEGIN
17242   _cnt := 0;
17243
17244   BEGIN
17245   FOR _bomitem IN SELECT bomitem_parent_item_id
17246                     FROM bomitem
17247                    WHERE ((bomitem_item_id=pItemid)
17248                      AND  (bomitem_rev_id=pBomrevid)
17249                      AND  (CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1)))
17250   LOOP
17251     SELECT bomLevelByItem(_bomitem.bomitem_parent_item_id, pBomrevid) + 1 INTO _result;
17252     IF (_result > _cnt) THEN
17253       _cnt := _result;
17254     END IF;
17255   END LOOP;
17256   EXCEPTION WHEN statement_too_complex THEN
17257       RAISE EXCEPTION 'potential recursive BOM found for item_id %', pItemid;
17258   END;
17259
17260   return _cnt;
17261 END;
17262 $_$;
17263
17264
17265 ALTER FUNCTION public.bomlevelbyitem(integer, integer) OWNER TO admin;
17266
17267 --
17268 -- TOC entry 1151 (class 1255 OID 146565689)
17269 -- Dependencies: 4536 8
17270 -- Name: bomworkeffective(integer, date); Type: FUNCTION; Schema: public; Owner: admin
17271 --
17272
17273 CREATE FUNCTION bomworkeffective(integer, date) RETURNS boolean
17274     LANGUAGE plpgsql
17275     AS $_$
17276 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17277 -- See www.xtuple.com/CPAL for the full text of the software license.
17278 DECLARE
17279     workid ALIAS FOR $1;
17280     effdate ALIAS FOR $2;
17281     _wid INTEGER;
17282     _bomwork RECORD;
17283 BEGIN
17284     _wid := workid;
17285     WHILE (_wid != -1) LOOP
17286         SELECT bomwork_parent_id AS parent,
17287                bomwork_effective AS effective
17288           INTO _bomwork
17289           FROM bomwork
17290          WHERE bomwork_id=_wid;
17291
17292          IF (FOUND) THEN
17293              _wid := _bomwork.parent;
17294              IF (_bomwork.effective > effdate) THEN
17295                  RETURN FALSE;
17296              END IF;
17297          ELSE
17298              _wid := -1;
17299          END IF;
17300     END LOOP;
17301     RETURN TRUE;
17302 END;
17303 $_$;
17304
17305
17306 ALTER FUNCTION public.bomworkeffective(integer, date) OWNER TO admin;
17307
17308 --
17309 -- TOC entry 1152 (class 1255 OID 146565690)
17310 -- Dependencies: 4536 8
17311 -- Name: bomworkexpired(integer, date); Type: FUNCTION; Schema: public; Owner: admin
17312 --
17313
17314 CREATE FUNCTION bomworkexpired(integer, date) RETURNS boolean
17315     LANGUAGE plpgsql
17316     AS $_$
17317 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17318 -- See www.xtuple.com/CPAL for the full text of the software license.
17319 DECLARE
17320     workid ALIAS FOR $1;
17321     expdate ALIAS FOR $2;
17322     _wid INTEGER;
17323     _bomwork RECORD;
17324 BEGIN
17325     _wid := workid;
17326     WHILE (_wid != -1) LOOP
17327         SELECT bomwork_parent_id AS parent,
17328                bomwork_expires AS expires
17329           INTO _bomwork
17330           FROM bomwork
17331          WHERE bomwork_id=_wid;
17332
17333          IF (FOUND) THEN
17334              _wid := _bomwork.parent;
17335              IF (_bomwork.expires <= expdate) THEN
17336                  RETURN TRUE;
17337              END IF;
17338          ELSE
17339              _wid := -1;
17340          END IF;
17341     END LOOP;
17342     RETURN FALSE;
17343 END;
17344 $_$;
17345
17346
17347 ALTER FUNCTION public.bomworkexpired(integer, date) OWNER TO admin;
17348
17349 --
17350 -- TOC entry 1153 (class 1255 OID 146565691)
17351 -- Dependencies: 4536 8
17352 -- Name: bomworkitemsequence(integer); Type: FUNCTION; Schema: public; Owner: admin
17353 --
17354
17355 CREATE FUNCTION bomworkitemsequence(integer) RETURNS text
17356     LANGUAGE plpgsql
17357     AS $_$
17358 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17359 -- See www.xtuple.com/CPAL for the full text of the software license.
17360 DECLARE
17361   pWorkid ALIAS FOR $1;
17362   _wid INTEGER;
17363   _seqnum TEXT;
17364   _bomwork RECORD;
17365
17366 BEGIN
17367   _wid := pWorkid;
17368
17369   SELECT bomwork_parent_id AS parent,
17370          item_number AS seq INTO _bomwork
17371     FROM bomwork, item
17372    WHERE ((bomwork_id=_wid)
17373    AND (bomwork_item_id=item_id));
17374
17375   IF (FOUND) THEN
17376     _seqnum := _bomwork.seq;
17377     _wid := _bomwork.parent;
17378
17379     WHILE (_wid != -1) LOOP
17380       SELECT bomwork_parent_id AS parent,
17381              item_number AS seq INTO _bomwork
17382       FROM bomwork, item
17383       WHERE ((bomwork_id=_wid)
17384       AND (bomwork_item_id=item_id));
17385
17386       IF (FOUND) THEN
17387         _seqnum := _bomwork.seq || '-' || _seqnum;
17388         _wid    := _bomwork.parent;
17389       ELSE
17390         _wid := -1;
17391       END IF;
17392     END LOOP;
17393   ELSE
17394     _seqnum := ''::TEXT;
17395   END IF;
17396
17397   RETURN _seqnum;
17398 END;
17399 $_$;
17400
17401
17402 ALTER FUNCTION public.bomworkitemsequence(integer) OWNER TO admin;
17403
17404 --
17405 -- TOC entry 1154 (class 1255 OID 146565692)
17406 -- Dependencies: 4536 8
17407 -- Name: bomworksequence(integer); Type: FUNCTION; Schema: public; Owner: admin
17408 --
17409
17410 CREATE FUNCTION bomworksequence(integer) RETURNS text
17411     LANGUAGE plpgsql
17412     AS $_$
17413 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17414 -- See www.xtuple.com/CPAL for the full text of the software license.
17415 DECLARE
17416   pWorkid ALIAS FOR $1;
17417   _wid INTEGER;
17418   _seqnum TEXT;
17419   _bomwork RECORD;
17420
17421 BEGIN
17422   _wid := pWorkid;
17423
17424   SELECT bomwork_parent_id AS parent,
17425          to_char(bomwork_seqnumber, '00009') AS seq INTO _bomwork
17426     FROM bomwork
17427    WHERE bomwork_id=_wid;
17428
17429   IF (FOUND) THEN
17430     _seqnum := _bomwork.seq;
17431     _wid := _bomwork.parent;
17432
17433     WHILE (_wid != -1) LOOP
17434       SELECT bomwork_parent_id AS parent,
17435              to_char(bomwork_seqnumber, '00009') AS seq INTO _bomwork
17436       FROM bomwork
17437       WHERE bomwork_id=_wid;
17438
17439       IF (FOUND) THEN
17440         _seqnum := _bomwork.seq || '-' || _seqnum;
17441         _wid    := _bomwork.parent;
17442       ELSE
17443         _wid := -1;
17444       END IF;
17445     END LOOP;
17446   ELSE
17447     _seqnum := ''::TEXT;
17448   END IF;
17449
17450   RETURN _seqnum;
17451 END;
17452 $_$;
17453
17454
17455 ALTER FUNCTION public.bomworksequence(integer) OWNER TO admin;
17456
17457 --
17458 -- TOC entry 1155 (class 1255 OID 146565693)
17459 -- Dependencies: 4536 8
17460 -- Name: buildinvbal(integer); Type: FUNCTION; Schema: public; Owner: admin
17461 --
17462
17463 CREATE FUNCTION buildinvbal(integer) RETURNS integer
17464     LANGUAGE plpgsql
17465     AS $_$
17466 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17467 -- See www.xtuple.com/CPAL for the full text of the software license.
17468 DECLARE
17469   pItemsiteId ALIAS FOR $1;
17470   _r RECORD;
17471   _prevCostmethod TEXT := 'A';
17472   _prevDate TIMESTAMP WITH TIME ZONE;
17473   _runningQty NUMERIC := 0;
17474   _runningNn NUMERIC := 0;
17475
17476 BEGIN
17477   -- Validate
17478   IF (SELECT (count(invhist_id) > 0)
17479       FROM invhist
17480       WHERE ((invhist_itemsite_id=pItemsiteId)
17481       AND (NOT invhist_posted))) THEN
17482
17483     SELECT item_number, warehous_code INTO _r
17484     FROM itemsite
17485       JOIN item ON (item_id=itemsite_item_id)
17486       JOIN whsinfo ON (itemsite_warehous_id=warehous_id)
17487     WHERE (itemsite_id=pItemsiteId);
17488     
17489     RAISE EXCEPTION 'Unposted inventory transactions exist for % at % [xtuple: buildInvBal, -1, %, %]',
17490                     _r.item_number, _r.warehous_code,
17491                     _r.item_number, _r.warehous_code;
17492   END IF;
17493
17494   -- Remove any old records
17495   DELETE FROM invbal WHERE invbal_itemsite_id=pItemsiteId;
17496
17497   FOR _r IN 
17498     SELECT invhist.*,
17499       itemsite_item_id, invhistSense(invhist_id) AS sense,
17500       item_number, warehous_code
17501     FROM invhist
17502       JOIN itemsite ON (itemsite_id=invhist_itemsite_id)
17503       JOIN item ON (itemsite_item_id=item_id)
17504       JOIN whsinfo ON (itemsite_warehous_id=warehous_id)
17505     WHERE (invhist_itemsite_id=pItemsiteId)
17506     ORDER BY invhist_created, invhist_id
17507   LOOP
17508     RAISE NOTICE 'Calculating balances for Item % at Site % against transaction %, transtype %, sense %, qty %, %', _r.item_number, _r.warehous_code, _r.invhist_id, _r.invhist_transtype, _r.sense, _r.invhist_invqty, _r.invhist_comments;
17509     -- Update balances changed by any standard cost update between transactions
17510     IF (_prevCostmethod = 'S' AND _runningQty != 0) THEN
17511       PERFORM postValueintoInvBalance(pItemsiteid, costhist_date::date, _runningQty, _runningNn, costhist_oldcost, costhist_newcost )
17512       FROM costhist
17513       WHERE ((costhist_item_id=_r.itemsite_item_id)
17514         AND (costhist_date BETWEEN _prevDate AND _r.invhist_created)
17515         AND (costhist_type IN ('S','D')));
17516     END IF;
17517
17518     -- Post transaction into inventory balance table
17519     PERFORM postIntoInvBalance(_r.invhist_id);
17520
17521     _prevDate := _r.invhist_created;
17522     _prevCostmethod := _r.invhist_costmethod;
17523     _runningQty := _runningQty + _r.invhist_invqty * _r.sense;
17524     IF (_r.invhist_transtype = 'NN') THEN
17525       _runningNn := _runningNn + _r.invhist_invqty * -1;
17526     END IF;
17527     
17528   END LOOP;
17529
17530   -- Update balances changed by any standard cost since last transaction
17531   IF (_prevCostmethod = 'S' AND _runningQty != 0) THEN
17532     PERFORM postValueintoInvBalance(pItemsiteid, costhist_date::date, _runningQty, _runningNn, costhist_oldcost, costhist_newcost )
17533     FROM costhist
17534     WHERE ((costhist_item_id=_r.itemsite_item_id)
17535       AND (costhist_date > _prevDate)
17536       AND (costhist_type IN ('S','D')));
17537   END IF;
17538
17539   -- Forward update changes through all the balances
17540   PERFORM forwardupdateitemsite(pItemsiteId);
17541   
17542   RETURN 1;
17543 END;
17544 $_$;
17545
17546
17547 ALTER FUNCTION public.buildinvbal(integer) OWNER TO admin;
17548
17549 --
17550 -- TOC entry 1156 (class 1255 OID 146565694)
17551 -- Dependencies: 4536 8
17552 -- Name: buildsearchpath(); Type: FUNCTION; Schema: public; Owner: admin
17553 --
17554
17555 CREATE FUNCTION buildsearchpath() RETURNS text
17556     LANGUAGE plpgsql
17557     AS $_$
17558 DECLARE
17559   _path   TEXT    := '';
17560   _schema TEXT;
17561   _seq    INTEGER;
17562 BEGIN
17563   -- get the schemas as ordered by the administrator
17564   SELECT concatagg(quote_ident(schemaord_name) || ',') INTO _path
17565     FROM (SELECT schemaord_name
17566             FROM schemaord
17567             LEFT OUTER JOIN pkghead ON (schemaord_name=pkghead_name)
17568            WHERE (pkghead_id IS NULL
17569                OR (pkghead_id IS NOT NULL AND packageisenabled(pkghead_id)))
17570            ORDER BY schemaord_order
17571          ) AS xtspq;
17572
17573   -- add others that we think/know we need
17574   -- TODO: is there a reason not to include public, api, or packages?
17575   FOR _schema, _seq IN
17576       SELECT pkghead_name AS schema, 0 AS seq
17577         FROM pkghead
17578        WHERE packageisenabled(pkghead_id)
17579       UNION ALL
17580       SELECT 'public', 1
17581       UNION ALL
17582       SELECT 'api', 2
17583       ORDER BY seq, schema
17584   LOOP
17585     IF (_path !~* (E'(^|\\W)' || _schema || E'(\\W|$)')) THEN
17586       _path := _path || ',' || quote_ident(_schema);
17587     END IF;
17588   END LOOP;
17589
17590   -- remove extraneous spaces and commas
17591   _path = BTRIM(REGEXP_REPLACE(_path, '( ?, ?)+', ',', 'g'),
17592                 ', ');
17593
17594   RAISE DEBUG 'buildSearchPath() returning %', _path;
17595
17596   RETURN _path;
17597 END;
17598 $_$;
17599
17600
17601 ALTER FUNCTION public.buildsearchpath() OWNER TO admin;
17602
17603 --
17604 -- TOC entry 8947 (class 0 OID 0)
17605 -- Dependencies: 1156
17606 -- Name: FUNCTION buildsearchpath(); Type: COMMENT; Schema: public; Owner: admin
17607 --
17608
17609 COMMENT ON FUNCTION buildsearchpath() IS 'buildSearchPath() examines the schemaord and pkghead tables to build a search
17610 path string. It ensures that public, api, and all enabled packages are included
17611 even if they are not listed in the schemaord table.
17612 It returns the constructed search_path but does not set it.';
17613
17614
17615 --
17616 -- TOC entry 1157 (class 1255 OID 146565695)
17617 -- Dependencies: 4536 8
17618 -- Name: calccashbudget(integer, integer, character); Type: FUNCTION; Schema: public; Owner: admin
17619 --
17620
17621 CREATE FUNCTION calccashbudget(integer, integer, character) RETURNS numeric
17622     LANGUAGE plpgsql
17623     AS $_$
17624 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17625 -- See www.xtuple.com/CPAL for the full text of the software license.
17626 DECLARE
17627   pAccntId ALIAS FOR $1;
17628   pPeriodId ALIAS FOR $2;
17629   pInterval ALIAS FOR $3;
17630   _accntType CHAR;
17631   _currentBudget NUMERIC;
17632   _priorBudget NUMERIC;
17633   _result NUMERIC;
17634 BEGIN
17635
17636         SELECT accnt_type INTO _accntType
17637         FROM accnt
17638         WHERE (accnt_id=pAccntId);
17639
17640         SELECT COALESCE(SUM(budget_amount),0) INTO _currentBudget
17641         FROM budget
17642         WHERE ((budget_accnt_id=pAccntId)
17643         AND (budget_period_id=pPeriodId));
17644
17645         IF (pInterval='M') THEN
17646         SELECT (COALESCE(SUM(budget_amount),0)) INTO _priorBudget
17647                 FROM budget,
17648                 (SELECT COALESCE(pp.period_id,-1) AS prior_period_id
17649                         FROM period cp, period pp
17650                         WHERE ((cp.period_id=pPeriodId)
17651                         AND (cp.period_start > pp.period_start))
17652                         ORDER BY pp.period_start DESC LIMIT 1) AS data
17653                 WHERE ((budget_accnt_id=pAccntId)
17654                 AND (budget_period_id=prior_period_id));
17655
17656                 ELSE IF (pInterval='Q') THEN
17657                         SELECT (COALESCE(SUM(budget_amount),0)) INTO _priorBudget
17658                         FROM budget,
17659                                 (SELECT COALESCE(pp.period_id,-1) AS prior_period_id
17660                                 FROM period cp, period pp
17661                                 WHERE ((cp.period_id=pPeriodId)
17662                                 AND (cp.period_start > pp.period_start)
17663                                 AND (pp.period_quarter=
17664                                 CASE WHEN cp.period_quarter > 1 THEN
17665                                         cp.period_quarter - 1
17666                                 ELSE 4 END)
17667                                 AND (pp.period_start >= cp.period_start - interval '1 year'))
17668                                 ORDER BY pp.period_start DESC LIMIT 1) AS data
17669                         WHERE ((budget_accnt_id=pAccntId)
17670                         AND (budget_period_id=prior_period_id));
17671
17672
17673                 ELSE
17674                         SELECT (COALESCE(SUM(budget_amount),0)) INTO _priorBudget
17675                         FROM budget,
17676                                 (SELECT pp.period_id AS prior_period_id
17677                         FROM period cp, period pp, yearperiod cy, yearperiod py
17678                         WHERE ((cp.period_id=pPeriodId)
17679                         AND (cp.period_yearperiod_id=cy.yearperiod_id)
17680                         AND (pp.period_yearperiod_id=py.yearperiod_id)
17681                         AND (cy.yearperiod_start > py.yearperiod_start))
17682                         ORDER BY pp.period_start DESC LIMIT 1) AS data
17683                         WHERE ((budget_accnt_id=pAccntId)
17684                         AND (budget_period_id=prior_period_id));
17685
17686                 END IF;
17687         END IF;
17688
17689         IF _accntType='A' THEN
17690                 _result := ((_priorBudget-_currentBudget) * -1 );
17691
17692         ELSE IF (_accntType IN ('L','Q')) THEN
17693                 _result := ((_priorBudget-_currentBudget) *-1);
17694
17695         ELSE RETURN -1;
17696         END IF;
17697   END IF;
17698
17699
17700   RETURN _result;
17701
17702
17703 END;
17704 $_$;
17705
17706
17707 ALTER FUNCTION public.calccashbudget(integer, integer, character) OWNER TO admin;
17708
17709 --
17710 -- TOC entry 1158 (class 1255 OID 146565696)
17711 -- Dependencies: 4536 8
17712 -- Name: calccmheadamt(integer); Type: FUNCTION; Schema: public; Owner: admin
17713 --
17714
17715 CREATE FUNCTION calccmheadamt(integer) RETURNS numeric
17716     LANGUAGE plpgsql
17717     AS $_$
17718 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17719 -- See www.xtuple.com/CPAL for the full text of the software license.
17720 DECLARE
17721   pCmheadid ALIAS FOR $1;
17722   _amount NUMERIC := 0;
17723
17724 BEGIN
17725
17726   SELECT SUM(COALESCE(extprice, 0)) INTO _amount
17727   FROM cmhead JOIN creditmemoitem ON (cmhead_id=cmitem_cmhead_id)
17728   WHERE (cmhead_id=pCmheadid);
17729
17730   RETURN _amount;
17731
17732 END;
17733 $_$;
17734
17735
17736 ALTER FUNCTION public.calccmheadamt(integer) OWNER TO admin;
17737
17738 --
17739 -- TOC entry 1159 (class 1255 OID 146565697)
17740 -- Dependencies: 4536 8
17741 -- Name: calccmheadtax(integer); Type: FUNCTION; Schema: public; Owner: admin
17742 --
17743
17744 CREATE FUNCTION calccmheadtax(integer) RETURNS numeric
17745     LANGUAGE plpgsql
17746     AS $_$
17747 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17748 -- See www.xtuple.com/CPAL for the full text of the software license.
17749 DECLARE
17750   pCmheadid ALIAS FOR $1;
17751   _headamount NUMERIC := 0;
17752   _itemamount NUMERIC := 0;
17753   _amount NUMERIC := 0;
17754
17755 BEGIN
17756
17757   SELECT COALESCE(SUM(taxhist_tax), 0) INTO _headamount
17758   FROM cmhead JOIN cmheadtax ON (taxhist_parent_id=cmhead_id)
17759   WHERE (cmhead_id=pCmheadid);
17760
17761   SELECT SUM(COALESCE(tax, 0)) INTO _itemamount
17762   FROM cmhead JOIN creditmemoitem ON (cmhead_id=cmitem_cmhead_id)
17763   WHERE (cmhead_id=pCmheadid);
17764
17765   _amount := _headamount + _itemamount;
17766   RETURN (_amount * -1.0);
17767
17768 END;
17769 $_$;
17770
17771
17772 ALTER FUNCTION public.calccmheadtax(integer) OWNER TO admin;
17773
17774 --
17775 -- TOC entry 1160 (class 1255 OID 146565698)
17776 -- Dependencies: 4536 8
17777 -- Name: calccobillamt(integer); Type: FUNCTION; Schema: public; Owner: admin
17778 --
17779
17780 CREATE FUNCTION calccobillamt(integer) RETURNS numeric
17781     LANGUAGE plpgsql
17782     AS $_$
17783 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17784 -- See www.xtuple.com/CPAL for the full text of the software license.
17785 DECLARE
17786   pCobillid ALIAS FOR $1;
17787   _amount NUMERIC := 0;
17788
17789 BEGIN
17790
17791   SELECT COALESCE(round((cobill_qty * coitem_qty_invuomratio) *
17792                         (coitem_price / coitem_price_invuomratio), 2), 0) INTO _amount
17793   FROM cobill JOIN coitem ON (coitem_id=cobill_coitem_id)
17794   WHERE (cobill_id=pCobillid);
17795
17796   RETURN _amount;
17797
17798 END;
17799 $_$;
17800
17801
17802 ALTER FUNCTION public.calccobillamt(integer) OWNER TO admin;
17803
17804 --
17805 -- TOC entry 1161 (class 1255 OID 146565699)
17806 -- Dependencies: 4536 8
17807 -- Name: calccobilltax(integer); Type: FUNCTION; Schema: public; Owner: admin
17808 --
17809
17810 CREATE FUNCTION calccobilltax(integer) RETURNS numeric
17811     LANGUAGE plpgsql
17812     AS $_$
17813 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17814 -- See www.xtuple.com/CPAL for the full text of the software license.
17815 DECLARE
17816   pCobillid ALIAS FOR $1;
17817   _amount NUMERIC := 0;
17818
17819 BEGIN
17820
17821   SELECT COALESCE(calculateTax(cobmisc_taxzone_id,
17822                                cobill_taxtype_id,
17823                                cobmisc_shipdate,
17824                                cobmisc_curr_id,
17825                                calcCobillAmt(cobill_id)), 0) INTO _amount
17826   FROM cobill JOIN coitem ON (coitem_id=cobill_coitem_id)
17827               JOIN cobmisc ON (cobmisc_id=cobill_cobmisc_id)
17828   WHERE (cobill_id=pCobillid);
17829
17830   RETURN _amount;
17831
17832 END;
17833 $_$;
17834
17835
17836 ALTER FUNCTION public.calccobilltax(integer) OWNER TO admin;
17837
17838 --
17839 -- TOC entry 1162 (class 1255 OID 146565700)
17840 -- Dependencies: 4536 8
17841 -- Name: calccobmiscamt(integer); Type: FUNCTION; Schema: public; Owner: admin
17842 --
17843
17844 CREATE FUNCTION calccobmiscamt(integer) RETURNS numeric
17845     LANGUAGE plpgsql
17846     AS $_$
17847 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17848 -- See www.xtuple.com/CPAL for the full text of the software license.
17849 DECLARE
17850   pCobmiscid ALIAS FOR $1;
17851   _amount NUMERIC := 0;
17852
17853 BEGIN
17854
17855   SELECT SUM(COALESCE(calcCobillAmt(cobill_id), 0)) INTO _amount
17856   FROM cobmisc JOIN cobill ON (cobmisc_id=cobill_cobmisc_id)
17857   WHERE (cobmisc_id=pCobmiscid);
17858
17859   RETURN _amount;
17860
17861 END;
17862 $_$;
17863
17864
17865 ALTER FUNCTION public.calccobmiscamt(integer) OWNER TO admin;
17866
17867 --
17868 -- TOC entry 1164 (class 1255 OID 146565701)
17869 -- Dependencies: 4536 8
17870 -- Name: calccobmisctax(integer); Type: FUNCTION; Schema: public; Owner: admin
17871 --
17872
17873 CREATE FUNCTION calccobmisctax(integer) RETURNS numeric
17874     LANGUAGE plpgsql
17875     AS $_$
17876 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17877 -- See www.xtuple.com/CPAL for the full text of the software license.
17878 DECLARE
17879   pCobmiscid ALIAS FOR $1;
17880   _amount NUMERIC := 0;
17881
17882 BEGIN
17883
17884   SELECT SUM(
17885          COALESCE(calculateTax(cobmisc_taxzone_id,
17886                                cobill_taxtype_id,
17887                                cobmisc_shipdate,
17888                                cobmisc_curr_id,
17889                                COALESCE(round((cobill_qty * coitem_qty_invuomratio) * (coitem_price / coitem_price_invuomratio), 2), 0))
17890                  , 0)
17891             ) INTO _amount
17892   FROM cobmisc JOIN cobill ON (cobmisc_id=cobill_cobmisc_id)
17893                JOIN coitem ON (coitem_id=cobill_coitem_id)
17894   WHERE (cobmisc_id=pCobmiscid);
17895
17896   RETURN _amount;
17897
17898 END;
17899 $_$;
17900
17901
17902 ALTER FUNCTION public.calccobmisctax(integer) OWNER TO admin;
17903
17904 --
17905 -- TOC entry 1165 (class 1255 OID 146565702)
17906 -- Dependencies: 4536 8
17907 -- Name: calcinvoiceamt(integer); Type: FUNCTION; Schema: public; Owner: admin
17908 --
17909
17910 CREATE FUNCTION calcinvoiceamt(pinvcheadid integer) RETURNS numeric
17911     LANGUAGE plpgsql STABLE
17912     AS $$
17913 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17914 -- See www.xtuple.com/CPAL for the full text of the software license.
17915 BEGIN
17916
17917   RETURN calcInvoiceAmt(pInvcheadid, 'T');
17918
17919 END;
17920 $$;
17921
17922
17923 ALTER FUNCTION public.calcinvoiceamt(pinvcheadid integer) OWNER TO admin;
17924
17925 --
17926 -- TOC entry 1166 (class 1255 OID 146565703)
17927 -- Dependencies: 4536 8
17928 -- Name: calcinvoiceamt(integer, text); Type: FUNCTION; Schema: public; Owner: admin
17929 --
17930
17931 CREATE FUNCTION calcinvoiceamt(pinvcheadid integer, ptype text) RETURNS numeric
17932     LANGUAGE plpgsql STABLE
17933     AS $$
17934 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
17935 -- See www.xtuple.com/CPAL for the full text of the software license.
17936 DECLARE
17937   _subtotal NUMERIC := 0.0;
17938   _cost NUMERIC := 0.0;
17939   _tax NUMERIC := 0.0;
17940   _freight NUMERIC := 0.0;
17941   _misc NUMERIC := 0.0;
17942   _amount NUMERIC := 0.0;
17943
17944 BEGIN
17945
17946   -- pType: S = line item subtotal
17947   --        T = total
17948   --        X = tax
17949   --        M = margin
17950
17951   SELECT COALESCE(SUM(ROUND((invcitem_billed * invcitem_qty_invuomratio) *
17952                             (invcitem_price / COALESCE(invcitem_price_invuomratio, 1.0)), 2)), 0.0),
17953          COALESCE(SUM(ROUND((invcitem_billed * invcitem_qty_invuomratio) *
17954                             COALESCE(coitem_unitcost, itemCost(itemsite_id), 0.0), 2)), 0.0)
17955          INTO _subtotal, _cost
17956   FROM invcitem LEFT OUTER JOIN coitem ON (coitem_id=invcitem_coitem_id)
17957                 LEFT OUTER JOIN itemsite ON (itemsite_item_id=invcitem_item_id AND itemsite_warehous_id=invcitem_warehous_id)
17958   WHERE (invcitem_invchead_id=pInvcheadid);
17959
17960   IF (pType IN ('T', 'X')) THEN
17961     SELECT COALESCE(ROUND(SUM(taxdetail_tax), 2), 0.0) INTO _tax
17962     FROM calculateTaxDetailSummary('I', pInvcheadid, 'T');
17963   END IF;
17964
17965   IF (pType = 'T') THEN
17966     SELECT COALESCE(invchead_freight, 0), COALESCE(invchead_misc_amount, 0)
17967            INTO _freight, _misc
17968     FROM invchead
17969     WHERE (invchead_id=pinvcheadid);
17970   END IF;
17971
17972   _amount := CASE pType WHEN 'S' THEN (_subtotal)
17973                         WHEN 'T' THEN (_subtotal + _tax + _freight + _misc)
17974                         WHEN 'X' THEN (_tax)
17975                         WHEN 'M' THEN (_subtotal - _cost)
17976                         ELSE 0.0
17977              END;
17978
17979   RETURN _amount;
17980
17981 END;
17982 $$;
17983
17984
17985 ALTER FUNCTION public.calcinvoiceamt(pinvcheadid integer, ptype text) OWNER TO admin;
17986
17987 --
17988 -- TOC entry 1167 (class 1255 OID 146565704)
17989 -- Dependencies: 4536 8
17990 -- Name: calcpendingarapplications(integer); Type: FUNCTION; Schema: public; Owner: admin
17991 --
17992
17993 CREATE FUNCTION calcpendingarapplications(integer) RETURNS numeric
17994     LANGUAGE plpgsql STABLE
17995     AS $_$
17996 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
17997 -- See www.xtuple.com/CPAL for the full text of the software license.
17998 DECLARE
17999   paropenid     ALIAS FOR $1;
18000   _arcreditsum  NUMERIC;
18001   _aropencurrid INTEGER;
18002   _cashrcptsum  NUMERIC;
18003   _sense INTEGER;
18004
18005 BEGIN
18006   SELECT aropen_curr_id,
18007     (CASE WHEN aropen_doctype IN ('I','D') THEN 1 ELSE -1 END) 
18008     INTO _aropencurrid, _sense
18009   FROM aropen
18010   WHERE (aropen_id=paropenid);
18011
18012   SELECT SUM(currToCurr(cashrcpt_curr_id, _aropencurrid,
18013                         cashrcptitem_amount + cashrcptitem_discount, coalesce(cashrcpt_applydate, cashrcpt_distdate))) * _sense INTO _cashrcptsum
18014   FROM cashrcptitem, cashrcpt
18015   WHERE ((cashrcptitem_cashrcpt_id=cashrcpt_id)
18016     AND  (NOT cashrcpt_posted)
18017     AND  (NOT cashrcpt_void)
18018     AND  (cashrcptitem_aropen_id=paropenid)
18019     );
18020
18021   SELECT SUM(currToCurr(arcreditapply_curr_id, _aropencurrid,
18022                         arcreditapply_amount, CURRENT_DATE)) INTO _arcreditsum
18023   FROM arcreditapply
18024   WHERE ((arcreditapply_target_aropen_id=paropenid)
18025     );
18026
18027   RETURN round(COALESCE(_cashrcptsum, 0) + COALESCE(_arcreditsum, 0),2);
18028 END;
18029 $_$;
18030
18031
18032 ALTER FUNCTION public.calcpendingarapplications(integer) OWNER TO admin;
18033
18034 --
18035 -- TOC entry 1168 (class 1255 OID 146565705)
18036 -- Dependencies: 4536 8
18037 -- Name: calcpurchaseorderamt(integer); Type: FUNCTION; Schema: public; Owner: admin
18038 --
18039
18040 CREATE FUNCTION calcpurchaseorderamt(ppoheadid integer) RETURNS numeric
18041     LANGUAGE plpgsql
18042     AS $$
18043 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18044 -- See www.xtuple.com/CPAL for the full text of the software license.
18045 BEGIN
18046
18047   RETURN calcPurchaseOrderAmt(pPoheadid, 'T');
18048
18049 END;
18050 $$;
18051
18052
18053 ALTER FUNCTION public.calcpurchaseorderamt(ppoheadid integer) OWNER TO admin;
18054
18055 --
18056 -- TOC entry 1169 (class 1255 OID 146565706)
18057 -- Dependencies: 4536 8
18058 -- Name: calcpurchaseorderamt(integer, text); Type: FUNCTION; Schema: public; Owner: admin
18059 --
18060
18061 CREATE FUNCTION calcpurchaseorderamt(ppoheadid integer, ptype text) RETURNS numeric
18062     LANGUAGE plpgsql
18063     AS $$
18064 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18065 -- See www.xtuple.com/CPAL for the full text of the software license.
18066 DECLARE
18067   _subtotal NUMERIC := 0;
18068   _freightsub NUMERIC := 0;
18069   _tax NUMERIC := 0;
18070   _freight NUMERIC := 0;
18071   _currid INTEGER := 0;
18072   _effdate DATE := CURRENT_DATE;
18073   _amount NUMERIC := 0;
18074
18075 BEGIN
18076
18077   -- pType: S = line item subtotal
18078   --        T = total
18079   --        X = tax
18080
18081   SELECT COALESCE(SUM(ROUND(poitem_qty_ordered * poitem_unitprice, 2)), 0),
18082          COALESCE(SUM(ROUND(poitem_freight, 2)), 0)
18083          INTO _subtotal, _freightsub
18084   FROM poitem
18085   WHERE (poitem_pohead_id=pPoheadid);
18086
18087   SELECT COALESCE(SUM(tax), 0) INTO _tax
18088   FROM ( SELECT COALESCE(ROUND(SUM(taxdetail_tax), 2), 0.0) AS tax
18089          FROM tax JOIN calculateTaxDetailSummary('PO', pPoheadid, 'T') ON (taxdetail_tax_id=tax_id)
18090          GROUP BY tax_id ) AS data;
18091
18092   SELECT COALESCE(pohead_freight, 0), pohead_curr_id, pohead_orderdate
18093          INTO _freight, _currid, _effdate
18094   FROM pohead
18095   WHERE (pohead_id=pPoheadid);
18096
18097   _amount := currToBase(_currid,
18098                         CASE pType WHEN 'S' THEN (_subtotal)
18099                                    WHEN 'T' THEN (_subtotal + _tax + _freight + _freightsub)
18100                                    WHEN 'X' THEN (_tax)
18101                                    ELSE 0.0
18102                         END,
18103                         _effdate);
18104
18105   RETURN _amount;
18106
18107 END;
18108 $$;
18109
18110
18111 ALTER FUNCTION public.calcpurchaseorderamt(ppoheadid integer, ptype text) OWNER TO admin;
18112
18113 --
18114 -- TOC entry 1170 (class 1255 OID 146565707)
18115 -- Dependencies: 4536 8
18116 -- Name: calcpurchaseorderduedate(integer); Type: FUNCTION; Schema: public; Owner: admin
18117 --
18118
18119 CREATE FUNCTION calcpurchaseorderduedate(ppoheadid integer) RETURNS date
18120     LANGUAGE plpgsql
18121     AS $$
18122 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18123 -- See www.xtuple.com/CPAL for the full text of the software license.
18124 DECLARE
18125   _result DATE;
18126 BEGIN
18127
18128   SELECT MIN(poitem_duedate) INTO _result
18129   FROM poitem
18130   WHERE (poitem_pohead_id=pPoheadid);
18131
18132   RETURN _result;
18133
18134 END;
18135 $$;
18136
18137
18138 ALTER FUNCTION public.calcpurchaseorderduedate(ppoheadid integer) OWNER TO admin;
18139
18140 --
18141 -- TOC entry 1171 (class 1255 OID 146565708)
18142 -- Dependencies: 4536 8
18143 -- Name: calcquoteamt(integer); Type: FUNCTION; Schema: public; Owner: admin
18144 --
18145
18146 CREATE FUNCTION calcquoteamt(pquheadid integer) RETURNS numeric
18147     LANGUAGE plpgsql STABLE
18148     AS $$
18149 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18150 -- See www.xtuple.com/CPAL for the full text of the software license.
18151 BEGIN
18152
18153   RETURN calcQuoteAmt(pQuheadid, 'T');
18154
18155 END;
18156 $$;
18157
18158
18159 ALTER FUNCTION public.calcquoteamt(pquheadid integer) OWNER TO admin;
18160
18161 --
18162 -- TOC entry 1173 (class 1255 OID 146565709)
18163 -- Dependencies: 4536 8
18164 -- Name: calcquoteamt(integer, text); Type: FUNCTION; Schema: public; Owner: admin
18165 --
18166
18167 CREATE FUNCTION calcquoteamt(pquheadid integer, ptype text) RETURNS numeric
18168     LANGUAGE plpgsql STABLE
18169     AS $$
18170 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18171 -- See www.xtuple.com/CPAL for the full text of the software license.
18172 DECLARE
18173   _subtotal NUMERIC := 0.0;
18174   _cost NUMERIC := 0.0;
18175   _tax NUMERIC := 0.0;
18176   _freight NUMERIC := 0.0;
18177   _misc NUMERIC := 0.0;
18178   _amount NUMERIC := 0.0;
18179
18180 BEGIN
18181
18182   -- pType: S = line item subtotal
18183   --        T = total
18184   --        X = tax
18185   --        M = margin
18186
18187   SELECT COALESCE(SUM(ROUND((quitem_qtyord * quitem_qty_invuomratio) *
18188                             (quitem_price / quitem_price_invuomratio), 2)), 0.0),
18189          COALESCE(SUM(ROUND((quitem_qtyord * quitem_qty_invuomratio) *
18190                             quitem_unitcost, 2)), 0.0)
18191          INTO _subtotal, _cost
18192   FROM quitem
18193   WHERE (quitem_quhead_id=pQuheadid);
18194
18195   IF (pType IN ('T', 'X')) THEN
18196     SELECT COALESCE(ROUND(SUM(taxdetail_tax), 2), 0.0) INTO _tax
18197     FROM calculateTaxDetailSummary('Q', pQuheadid, 'T');
18198   END IF;
18199
18200   IF (pType = 'T') THEN
18201     SELECT COALESCE(quhead_freight, 0), COALESCE(quhead_misc, 0) INTO _freight, _misc
18202     FROM quhead
18203     WHERE (quhead_id=pQuheadid);
18204   END IF;
18205
18206   _amount := CASE pType WHEN 'S' THEN (_subtotal)
18207                         WHEN 'T' THEN (_subtotal + _tax + _freight + _misc)
18208                         WHEN 'X' THEN (_tax)
18209                         WHEN 'M' THEN (_subtotal - _cost)
18210                         ELSE 0.0
18211              END;
18212
18213   RETURN _amount;
18214
18215 END;
18216 $$;
18217
18218
18219 ALTER FUNCTION public.calcquoteamt(pquheadid integer, ptype text) OWNER TO admin;
18220
18221 --
18222 -- TOC entry 1174 (class 1255 OID 146565710)
18223 -- Dependencies: 4536 8
18224 -- Name: calcsalesorderamt(integer); Type: FUNCTION; Schema: public; Owner: admin
18225 --
18226
18227 CREATE FUNCTION calcsalesorderamt(pcoheadid integer) RETURNS numeric
18228     LANGUAGE plpgsql STABLE
18229     AS $$
18230 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18231 -- See www.xtuple.com/CPAL for the full text of the software license.
18232 BEGIN
18233
18234   RETURN calcSalesOrderAmt(pCoheadid, 'T');
18235
18236 END;
18237 $$;
18238
18239
18240 ALTER FUNCTION public.calcsalesorderamt(pcoheadid integer) OWNER TO admin;
18241
18242 --
18243 -- TOC entry 1175 (class 1255 OID 146565711)
18244 -- Dependencies: 4536 8
18245 -- Name: calcsalesorderamt(integer, text); Type: FUNCTION; Schema: public; Owner: admin
18246 --
18247
18248 CREATE FUNCTION calcsalesorderamt(pcoheadid integer, ptype text) RETURNS numeric
18249     LANGUAGE plpgsql STABLE
18250     AS $$
18251 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18252 -- See www.xtuple.com/CPAL for the full text of the software license.
18253 DECLARE
18254   _subtotal NUMERIC := 0.0;
18255   _cost NUMERIC := 0.0;
18256   _tax NUMERIC := 0.0;
18257   _freight NUMERIC := 0.0;
18258   _misc NUMERIC := 0.0;
18259   _credit NUMERIC := 0.0;
18260   _amount NUMERIC := 0.0;
18261
18262 BEGIN
18263
18264   -- pType: S = line item subtotal
18265   --        T = total
18266   --        B = balance due
18267   --        C = allocated credits
18268   --        X = tax
18269   --        M = margin
18270
18271   SELECT COALESCE(SUM(ROUND((coitem_qtyord * coitem_qty_invuomratio) *
18272                             (coitem_price / coitem_price_invuomratio), 2)), 0.0),
18273          COALESCE(SUM(ROUND((coitem_qtyord * coitem_qty_invuomratio) *
18274                             coitem_unitcost, 2)), 0.0)
18275          INTO _subtotal, _cost
18276   FROM coitem
18277   WHERE (coitem_cohead_id=pCoheadid)
18278     AND (coitem_status != 'X');
18279
18280   IF (pType IN ('T', 'B', 'X')) THEN
18281     SELECT COALESCE(ROUND(SUM(taxdetail_tax), 2), 0.0) INTO _tax
18282     FROM calculateTaxDetailSummary('S', pCoheadid, 'T');
18283   END IF;
18284
18285   IF (pType IN ('T', 'B', 'C')) THEN
18286     SELECT COALESCE(cohead_freight, 0), COALESCE(cohead_misc, 0),
18287            COALESCE(SUM(currToCurr(aropenalloc_curr_id, cohead_curr_id,
18288                                    aropenalloc_amount, CURRENT_DATE)),0)
18289            INTO _freight, _misc, _credit
18290     FROM cohead
18291          LEFT OUTER JOIN aropenalloc ON (aropenalloc_doctype='S' AND aropenalloc_doc_id=cohead_id)
18292     WHERE (cohead_id=pCoheadid)
18293     GROUP BY cohead_freight, cohead_misc, cohead_curr_id;
18294   END IF;
18295
18296   _amount := CASE pType WHEN 'S' THEN (_subtotal)
18297                         WHEN 'T' THEN (_subtotal + _tax + _freight + _misc)
18298                         WHEN 'B' THEN (_subtotal + _tax + _freight + _misc - _credit)
18299                         WHEN 'C' THEN (_credit)
18300                         WHEN 'X' THEN (_tax)
18301                         WHEN 'M' THEN (_subtotal - _cost)
18302                         ELSE 0.0
18303              END;
18304
18305   RETURN _amount;
18306
18307 END;
18308 $$;
18309
18310
18311 ALTER FUNCTION public.calcsalesorderamt(pcoheadid integer, ptype text) OWNER TO admin;
18312
18313 --
18314 -- TOC entry 1176 (class 1255 OID 146565712)
18315 -- Dependencies: 4536 8
18316 -- Name: calcshipfreight(integer); Type: FUNCTION; Schema: public; Owner: admin
18317 --
18318
18319 CREATE FUNCTION calcshipfreight(integer) RETURNS numeric
18320     LANGUAGE plpgsql
18321     AS $_$
18322 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18323 -- See www.xtuple.com/CPAL for the full text of the software license.
18324 DECLARE
18325   pShipheadId ALIAS FOR $1;
18326   _result NUMERIC := 0;
18327   _order RECORD;
18328   _shipment RECORD;
18329   _weights RECORD;
18330   _price RECORD;
18331   _sales RECORD;
18332   _freightid INTEGER;
18333   _totalprice NUMERIC;
18334   _includepkgweight BOOLEAN := FALSE;
18335   _freight RECORD;
18336   _debug BOOLEAN := false;
18337 BEGIN
18338   --Get shipment
18339   SELECT shiphead_order_id, shiphead_order_type, shiphead_freight 
18340   INTO _shipment
18341   FROM shiphead
18342   WHERE (shiphead_id=pShipheadId);
18343
18344   IF (NOT FOUND) THEN
18345     RAISE EXCEPTION 'Shipment not found';
18346   END IF;
18347
18348   IF (_shipment.shiphead_order_type = 'SO') THEN
18349   --Sales Orders
18350   
18351   --Get the order header information
18352     SELECT cust_id AS cust_id,
18353            custtype_id,
18354            custtype_code,
18355            shipto_id,
18356            shipto_num,
18357            cohead_orderdate AS orderdate,
18358            cohead_shipvia AS shipvia,
18359            shipto_shipzone_id AS shipzone_id,
18360            cohead_curr_id AS curr_id,
18361            currConcat(cohead_curr_id) AS currAbbr,
18362            cohead_calcfreight,
18363            cohead_freight
18364     INTO _order
18365     FROM cohead 
18366       JOIN custinfo ON (cust_id=cohead_cust_id)
18367       JOIN custtype ON (custtype_id=cust_custtype_id)
18368       LEFT OUTER JOIN shiptoinfo ON (shipto_id=cohead_shipto_id)
18369     WHERE (cohead_id=_shipment.shiphead_order_id);
18370
18371     IF (NOT FOUND) THEN
18372       RAISE EXCEPTION 'Order not found';
18373     END IF;
18374
18375     IF (_debug) THEN
18376       RAISE NOTICE 'cust_id = %', _order.cust_id;
18377       RAISE NOTICE 'custtype_id = %', _order.custtype_id;
18378       RAISE NOTICE 'shipto_id = %', _order.shipto_id;
18379       RAISE NOTICE 'shipto_num = %', _order.shipto_num;
18380       RAISE NOTICE 'orderdate = %', _order.orderdate;
18381       RAISE NOTICE 'shipvia = %', _order.shipvia;
18382       RAISE NOTICE 'shipzone_id = %', _order.shipzone_id;
18383       RAISE NOTICE 'curr_id = %', _order.curr_id;
18384       RAISE NOTICE 'currAbbr = %', _order.currAbbr;
18385       RAISE NOTICE 'calcfreight = %', _order.cohead_calcfreight;
18386       RAISE NOTICE 'freight = %', _order.cohead_freight;
18387     END IF;
18388
18389     IF (NOT _order.cohead_calcfreight) THEN
18390       SELECT noNeg( _order.cohead_freight -
18391                     COALESCE((SELECT SUM(shiphead_freight)
18392                               FROM shiphead
18393                               WHERE (shiphead_order_id = _shipment.shiphead_order_id)
18394                                 AND (shiphead_shipped='true')), 0) ) INTO _result;
18395       RETURN _result;
18396     END IF;
18397
18398     SELECT fetchMetricBool('IncludePackageWeight') INTO _includepkgweight;
18399
18400     --Calculate Sales Order freight
18401     --Get a list of aggregated weights from sites and
18402     --freight classes used on order lines
18403     FOR _weights IN
18404       SELECT CASE WHEN (_includePkgWeight) THEN
18405                         SUM(shipitem_qty * (item_prodweight + item_packweight))
18406                   ELSE  SUM(shipitem_qty * item_prodweight)
18407              END AS weight,
18408              itemsite_warehous_id, item_freightclass_id
18409       FROM shiphead
18410         JOIN shipitem ON (shipitem_shiphead_id=shiphead_id)
18411         JOIN coitem ON (shipitem_orderitem_id=coitem_id)
18412         JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
18413         JOIN item ON (item_id=itemsite_item_id)
18414       WHERE ( (shiphead_id=pShipheadId)
18415         AND   (item_freightclass_id IS NOT NULL) )
18416       GROUP BY itemsite_warehous_id, item_freightclass_id LOOP
18417
18418     IF (_debug) THEN
18419       RAISE NOTICE '_weights.weight - %', _weights.weight;
18420       RAISE NOTICE '_weights.itemsite_warehous_id = %', _weights.itemsite_warehous_id;
18421       RAISE NOTICE '_weights.item_freightclass_id = %', _weights.item_freightclass_id;
18422     END IF;
18423
18424     -- First get a sales price if any so we when we find other prices
18425     -- we can determine if we want that price or this price.
18426     --  Check for a Sale Price
18427     SELECT ipsfreight_id,
18428            CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, _order.curr_id,
18429                                                            ipsfreight_price, _order.orderdate)
18430                 ELSE currToCurr(ipshead_curr_id, _order.curr_id,
18431                                 (_weights.weight * ipsfreight_price), _order.orderdate)
18432            END AS price
18433            INTO _sales
18434     FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18435                     JOIN sale ON (sale_ipshead_id=ipshead_id)
18436     WHERE ( (ipsfreight_qtybreak <= _weights.weight)
18437       AND   ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=_weights.itemsite_warehous_id))
18438       AND   ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=_weights.item_freightclass_id))
18439       AND   ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=_order.shipzone_id))
18440       AND   ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=_order.shipvia))
18441       AND   (CURRENT_DATE BETWEEN sale_startdate AND sale_enddate) )
18442     ORDER BY ipsfreight_qtybreak DESC, price ASC
18443     LIMIT 1;
18444
18445     IF (_debug) THEN
18446       IF (_sales.price IS NOT NULL) THEN
18447         RAISE NOTICE 'Sales Price found, %', _sales.price;
18448       END IF;
18449     END IF;
18450
18451     --  Check for a Customer Shipto Price
18452     SELECT ipsfreight_id,
18453            CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, _order.curr_id,
18454                                                            ipsfreight_price, _order.orderdate)
18455                 ELSE currToCurr(ipshead_curr_id, _order.curr_id,
18456                                 (_weights.weight * ipsfreight_price), _order.orderdate)
18457            END AS price
18458            INTO _price
18459     FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18460                     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18461     WHERE ( (ipsfreight_qtybreak <= _weights.weight)
18462       AND   ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=_weights.itemsite_warehous_id))
18463       AND   ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=_weights.item_freightclass_id))
18464       AND   ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=_order.shipzone_id))
18465       AND   ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=_order.shipvia))
18466       AND   (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1))
18467       AND   (ipsass_cust_id=_order.cust_id)
18468       AND   (ipsass_shipto_id != -1)
18469       AND   (ipsass_shipto_id=_order.shipto_id) )
18470     ORDER BY ipsfreight_qtybreak DESC, price ASC
18471     LIMIT 1;
18472
18473     IF (_debug) THEN
18474       IF (_price.price IS NOT NULL) THEN
18475         RAISE NOTICE 'Customer Shipto Price found, %', _price.price;
18476       END IF;
18477     END IF;
18478
18479     IF (_price.price IS NULL) THEN
18480     --  Check for a Customer Shipto Pattern Price
18481       SELECT ipsfreight_id,
18482              CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, _order.curr_id,
18483                                                              ipsfreight_price, _order.orderdate)
18484                   ELSE currToCurr(ipshead_curr_id, _order.curr_id,
18485                                   (_weights.weight * ipsfreight_price), _order.orderdate)
18486              END AS price
18487              INTO _price
18488       FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18489                       JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18490       WHERE ( (ipsfreight_qtybreak <= _weights.weight)
18491         AND   (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1))
18492         AND   (ipsass_cust_id=_order.cust_id)
18493         AND   (COALESCE(LENGTH(ipsass_shipto_pattern), 0) > 0)
18494         AND   (_order.shipto_num ~ ipsass_shipto_pattern)
18495         AND   ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=_weights.itemsite_warehous_id))
18496         AND   ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=_weights.item_freightclass_id))
18497         AND   ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=_order.shipzone_id))
18498         AND   ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=_order.shipvia)) )
18499       ORDER BY ipsfreight_qtybreak DESC, price ASC
18500       LIMIT 1;
18501
18502       IF (_debug) THEN
18503         IF (_price.price IS NOT NULL) THEN
18504           RAISE NOTICE 'Customer Shipto Pattern Price found, %', _price.price;
18505         END IF;
18506       END IF;
18507
18508     END IF;
18509
18510     IF (_price.price IS NULL) THEN
18511     --  Check for a Customer Price
18512       SELECT ipsfreight_id,
18513              CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, _order.curr_id,
18514                                                              ipsfreight_price, _order.orderdate)
18515                   ELSE currToCurr(ipshead_curr_id, _order.curr_id,
18516                                   (_weights.weight * ipsfreight_price), _order.orderdate)
18517              END AS price
18518              INTO _price
18519       FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18520                       JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18521       WHERE ( (ipsfreight_qtybreak <= _weights.weight)
18522         AND   ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=_weights.itemsite_warehous_id))
18523         AND   ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=_weights.item_freightclass_id))
18524         AND   ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=_order.shipzone_id))
18525         AND   ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=_order.shipvia))
18526         AND   (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1))
18527         AND   (ipsass_cust_id=_order.cust_id)
18528         AND   (COALESCE(LENGTH(ipsass_shipto_pattern), 0) = 0) )
18529       ORDER BY ipsfreight_qtybreak DESC, price ASC
18530       LIMIT 1;
18531
18532       IF (_debug) THEN
18533         IF (_price.price IS NOT NULL) THEN
18534           RAISE NOTICE 'Customer Price found, %', _price.price;
18535         END IF;
18536       END IF;
18537
18538     END IF;
18539
18540     IF (_price.price IS NULL) THEN
18541     --  Check for a Customer Type Price
18542       SELECT ipsfreight_id,
18543              CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, _order.curr_id,
18544                                                              ipsfreight_price, _order.orderdate)
18545                   ELSE currToCurr(ipshead_curr_id, _order.curr_id,
18546                                   (_weights.weight * ipsfreight_price), _order.orderdate)
18547              END AS price
18548              INTO _price
18549       FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18550                       JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18551       WHERE ( (ipsfreight_qtybreak <= _weights.weight)
18552         AND   ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=_weights.itemsite_warehous_id))
18553         AND   ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=_weights.item_freightclass_id))
18554         AND   ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=_order.shipzone_id))
18555         AND   ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=_order.shipvia))
18556         AND   (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1))
18557         AND   (ipsass_custtype_id=_order.custtype_id) )
18558       ORDER BY ipsfreight_qtybreak DESC, price ASC
18559       LIMIT 1;
18560
18561       IF (_debug) THEN
18562         IF (_price.price IS NOT NULL) THEN
18563           RAISE NOTICE 'Customer Type Price found, %', _price.price;
18564         END IF;
18565       END IF;
18566
18567     END IF;
18568
18569     IF (_price.price IS NULL) THEN
18570     --  Check for a Customer Type Pattern Price
18571       SELECT ipsfreight_id,
18572              CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, _order.curr_id,
18573                                                              ipsfreight_price, _order.orderdate)
18574                   ELSE currToCurr(ipshead_curr_id, _order.curr_id,
18575                                   (_weights.weight * ipsfreight_price), _order.orderdate)
18576              END AS price
18577              INTO _price
18578       FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18579                       JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18580       WHERE ( (ipsfreight_qtybreak <= _weights.weight)
18581         AND   ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=_weights.itemsite_warehous_id))
18582         AND   ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=_weights.item_freightclass_id))
18583         AND   ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=_order.shipzone_id))
18584         AND   ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=_order.shipvia))
18585         AND   (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1))
18586         AND   (COALESCE(LENGTH(ipsass_custtype_pattern), 0) > 0)
18587         AND   (_order.custtype_code ~ ipsass_custtype_pattern) )
18588       ORDER BY ipsfreight_qtybreak DESC, price ASC
18589       LIMIT 1;
18590
18591       IF (_debug) THEN
18592         IF (_price.price IS NOT NULL) THEN
18593           RAISE NOTICE 'Customer Type Pattern Price found, %', _price.price;
18594         END IF;
18595       END IF;
18596
18597     END IF;
18598
18599     -- Select the lowest price  
18600     IF ( (_price.price IS NOT NULL) AND ((_sales.price IS NULL) OR (_price.price < _sales.price)) ) THEN
18601       _freightid := _price.ipsfreight_id;
18602       _totalprice := _price.price;
18603     ELSE
18604       IF ( (_sales.price IS NOT NULL) AND ((_price.price IS NULL) OR (_sales.price <= _price.price)) ) THEN
18605         _freightid := _sales.ipsfreight_id;
18606         _totalprice := _sales.price;
18607       END IF;
18608     END IF;
18609
18610     -- Total
18611     IF (_freightid IS NOT NULL) THEN
18612       _result := _result + _totalprice;
18613     END IF;
18614
18615     END LOOP;
18616     RETURN ROUND(_result,2);
18617   END IF;
18618
18619   IF (_shipment.shiphead_order_type = 'TO') THEN
18620   --Transfer Orders
18621   
18622     SELECT noNeg( (SELECT SUM(toitem_freight) + tohead_freight
18623                    FROM tohead, toitem
18624                    WHERE (toitem_tohead_id=tohead_id)
18625                      AND (tohead_id = _shipment.shiphead_order_id)
18626                    GROUP BY tohead_freight) -
18627                   COALESCE((SELECT SUM(shiphead_freight)
18628                             FROM shiphead
18629                             WHERE (shiphead_order_id = _shipment.shiphead_order_id)
18630                               AND (shiphead_shipped='true')), 0) ) INTO _result;
18631     RETURN _result;
18632   END IF;
18633
18634   RETURN _result;
18635
18636 END;
18637 $_$;
18638
18639
18640 ALTER FUNCTION public.calcshipfreight(integer) OWNER TO admin;
18641
18642 --
18643 -- TOC entry 1177 (class 1255 OID 146565714)
18644 -- Dependencies: 4536 8
18645 -- Name: calctotalslipqty(integer); Type: FUNCTION; Schema: public; Owner: admin
18646 --
18647
18648 CREATE FUNCTION calctotalslipqty(integer) RETURNS numeric
18649     LANGUAGE plpgsql
18650     AS $_$
18651 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18652 -- See www.xtuple.com/CPAL for the full text of the software license.
18653 DECLARE
18654   pTagid ALIAS FOR $1;
18655   _qty NUMERIC := 0;
18656
18657 BEGIN
18658
18659   SELECT SUM(COALESCE(cntslip_qty, 0.0)) INTO _qty
18660   FROM cntslip
18661   WHERE (cntslip_cnttag_id=pTagid);
18662
18663   RETURN _qty;
18664
18665 END;
18666 $_$;
18667
18668
18669 ALTER FUNCTION public.calctotalslipqty(integer) OWNER TO admin;
18670
18671 --
18672 -- TOC entry 1178 (class 1255 OID 146565715)
18673 -- Dependencies: 2681 4536 8
18674 -- Name: calculatefreightdetail(integer, integer, text, integer, integer, text, date, text, integer, character varying, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
18675 --
18676
18677 CREATE FUNCTION calculatefreightdetail(integer, integer, text, integer, integer, text, date, text, integer, character varying, integer, integer, numeric) RETURNS SETOF freightdata
18678     LANGUAGE plpgsql
18679     AS $_$
18680 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
18681 -- See www.xtuple.com/CPAL for the full text of the software license.
18682 DECLARE
18683   pCustId ALIAS FOR $1;
18684   pCustTypeId ALIAS FOR $2;
18685   pCustTypeCode ALIAS FOR $3;
18686   pShiptoId ALIAS FOR $4;
18687   pShipZoneId ALIAS FOR $5;
18688   pShiptoNum ALIAS FOR $6;
18689   pOrderDate ALIAS FOR $7;
18690   pShipVia ALIAS FOR $8;
18691   pCurrId ALIAS FOR $9;
18692   pCurrAbbr ALIAS FOR $10;
18693   pItemSiteWhsId ALIAS FOR $11;
18694   pItemFreightclassId ALIAS FOR $12;
18695   pWeight ALIAS FOR $13;
18696
18697   _row freightData%ROWTYPE;
18698   _price RECORD;
18699   _sales RECORD;
18700   _freightid INTEGER;
18701   _totalprice NUMERIC;
18702   _asof DATE;
18703   _debug BOOLEAN := FALSE;
18704
18705 BEGIN
18706
18707   --Get pricing effectivity metric
18708   IF (SELECT fetchMetricText('soPriceEffective') = 'OrderDate') THEN
18709     _asof := pOrderDate;
18710   ELSE
18711     _asof := CURRENT_DATE;
18712   END IF;
18713
18714   _freightid := NULL;
18715   _totalprice := 0.0;
18716
18717   IF (_debug) THEN
18718     RAISE NOTICE 'pWeight - %', pWeight;
18719     RAISE NOTICE 'pItemSiteWhsId = %', pItemSiteWhsId;
18720     RAISE NOTICE 'pItemFreightclassId = %', pItemFreightclassId;
18721   END IF;
18722
18723 -- First get a sales price if any so when we find other prices
18724 -- we can determine if we want that price or this sales price.
18725 --  Check for a Sale Price
18726   SELECT ipsfreight_id,
18727     CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, pCurrId,
18728         ipsfreight_price, pOrderDate)
18729       ELSE currToCurr(ipshead_curr_id, pCurrId,
18730         (pWeight * ipsfreight_price), pOrderDate)
18731     END AS price
18732   INTO _sales
18733   FROM ipsfreight
18734   JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18735   JOIN sale ON (sale_ipshead_id=ipshead_id)
18736   WHERE ( (ipsfreight_qtybreak <= pWeight)
18737     AND ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=pItemSiteWhsId))
18738     AND ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=pItemFreightclassId))
18739     AND ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=pShipZoneId))
18740     AND ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=pShipVia))
18741     AND (_asof BETWEEN sale_startdate AND sale_enddate)
18742     AND (pCustId IS NOT NULL) )
18743   ORDER BY ipsfreight_qtybreak DESC, price ASC
18744   LIMIT 1;
18745
18746   IF (_debug) THEN
18747     IF (_sales.price IS NOT NULL) THEN
18748       RAISE NOTICE 'Sales Price found, %', _sales.price;
18749     END IF;
18750   END IF;
18751
18752 --  Check for a Customer Shipto Price
18753   SELECT ipsfreight_id,
18754     CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, pCurrId,
18755         ipsfreight_price, pOrderDate)
18756       ELSE currToCurr(ipshead_curr_id, pCurrId,
18757         (pWeight * ipsfreight_price), pOrderDate)
18758     END AS price
18759   INTO _price
18760   FROM ipsfreight
18761   JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18762   JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18763   WHERE ( (ipsfreight_qtybreak <= pWeight)
18764     AND ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=pItemSiteWhsId))
18765     AND ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=pItemFreightclassId))
18766     AND ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=pShipZoneId))
18767     AND ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=pShipVia))
18768     AND (_asof BETWEEN ipshead_effective AND (ipshead_expires - 1))
18769     AND   (ipsass_shipto_id != -1)
18770     AND   (ipsass_shipto_id=pShiptoId) )
18771   ORDER BY ipsfreight_qtybreak DESC, price ASC
18772   LIMIT 1;
18773
18774   IF (_debug) THEN
18775     IF (_price.price IS NOT NULL) THEN
18776       RAISE NOTICE 'Customer Shipto Price found, %', _price.price;
18777     END IF;
18778   END IF;
18779
18780   IF (_price.price IS NULL) THEN
18781 --  Check for a Customer Shipto Pattern Price
18782   SELECT ipsfreight_id,
18783     CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, pCurrId,
18784         ipsfreight_price, pOrderDate)
18785       ELSE currToCurr(ipshead_curr_id, pCurrId,
18786         (pWeight * ipsfreight_price), pOrderDate)
18787     END AS price
18788   INTO _price
18789   FROM ipsfreight
18790   JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18791   JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18792   WHERE ( (ipsfreight_qtybreak <= pWeight)
18793     AND (_asof BETWEEN ipshead_effective AND (ipshead_expires - 1))
18794     AND (ipsass_cust_id=pCustId)
18795     AND (COALESCE(LENGTH(ipsass_shipto_pattern), 0) > 0)
18796     AND (pShiptoNum ~ ipsass_shipto_pattern)
18797     AND ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=pItemSiteWhsId))
18798     AND ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=pItemFreightclassId))
18799     AND ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=pShipZoneId))
18800     AND ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=pShipVia)) )
18801   ORDER BY ipsfreight_qtybreak DESC, price ASC
18802   LIMIT 1;
18803
18804   IF (_debug) THEN
18805     IF (_price.price IS NOT NULL) THEN
18806       RAISE NOTICE 'Customer Shipto Pattern Price found, %', _price.price;
18807     END IF;
18808   END IF;
18809
18810   END IF;
18811
18812   IF (_price.price IS NULL) THEN
18813 --  Check for a Customer Price
18814   SELECT ipsfreight_id,
18815     CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, pCurrId,
18816         ipsfreight_price, pOrderDate)
18817       ELSE currToCurr(ipshead_curr_id, pCurrId,
18818         (pWeight * ipsfreight_price), pOrderDate)
18819     END AS price
18820   INTO _price
18821   FROM ipsfreight
18822   JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18823   JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18824   WHERE ( (ipsfreight_qtybreak <= pWeight)
18825     AND((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=pItemSiteWhsId))
18826     AND ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=pItemFreightclassId))
18827     AND ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=pShipZoneId))
18828     AND ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=pShipVia))
18829     AND (_asof BETWEEN ipshead_effective AND (ipshead_expires - 1))
18830     AND (ipsass_cust_id=pCustId)
18831     AND (COALESCE(LENGTH(ipsass_shipto_pattern), 0) = 0) )
18832   ORDER BY ipsfreight_qtybreak DESC, price ASC
18833   LIMIT 1;
18834
18835   IF (_debug) THEN
18836     IF (_price.price IS NOT NULL) THEN
18837       RAISE NOTICE 'Customer Price found, %', _price.price;
18838     END IF;
18839   END IF;
18840
18841   END IF;
18842
18843   IF (_price.price IS NULL) THEN
18844 --  Check for a Customer Type Price
18845   SELECT ipsfreight_id,
18846     CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, pCurrId,
18847         ipsfreight_price, pOrderDate)
18848       ELSE currToCurr(ipshead_curr_id, pCurrId,
18849         (pWeight * ipsfreight_price), pOrderDate)
18850     END AS price
18851   INTO _price
18852   FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18853                   JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18854   WHERE ( (ipsfreight_qtybreak <= pWeight)
18855     AND ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=pItemSiteWhsId))
18856     AND ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=pItemFreightclassId))
18857     AND ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=pShipZoneId))
18858     AND ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=pShipVia))
18859     AND (_asof BETWEEN ipshead_effective AND (ipshead_expires - 1))
18860     AND (ipsass_custtype_id=pCustTypeId) )
18861   ORDER BY ipsfreight_qtybreak DESC, price ASC
18862   LIMIT 1;
18863
18864   IF (_debug) THEN
18865     IF (_price.price IS NOT NULL) THEN
18866       RAISE NOTICE 'Customer Type Price found, %', _price.price;
18867     END IF;
18868   END IF;
18869
18870   END IF;
18871
18872   IF (_price.price IS NULL) THEN
18873 --  Check for a Customer Type Pattern Price
18874   SELECT ipsfreight_id,
18875     CASE WHEN (ipsfreight_type='F') THEN currToCurr(ipshead_curr_id, pCurrId,
18876         ipsfreight_price, pOrderDate)
18877       ELSE currToCurr(ipshead_curr_id, pCurrId,
18878         (pWeight * ipsfreight_price), pOrderDate)
18879     END AS price
18880   INTO _price
18881   FROM ipsfreight JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18882                   JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
18883   WHERE ( (ipsfreight_qtybreak <= pWeight)
18884     AND ((ipsfreight_warehous_id IS NULL) OR (ipsfreight_warehous_id=pItemSiteWhsId))
18885     AND ((ipsfreight_freightclass_id IS NULL) OR (ipsfreight_freightclass_id=pItemFreightclassId))
18886     AND ((ipsfreight_shipzone_id IS NULL) OR (ipsfreight_shipzone_id=pShipZoneId))
18887     AND ((ipsfreight_shipvia IS NULL) OR (ipsfreight_shipvia=pShipVia))
18888     AND (_asof BETWEEN ipshead_effective AND (ipshead_expires - 1))
18889     AND (COALESCE(LENGTH(ipsass_custtype_pattern), 0) > 0)
18890     AND (pCustTypeCode ~ ipsass_custtype_pattern) )
18891   ORDER BY ipsfreight_qtybreak DESC, price ASC
18892   LIMIT 1;
18893
18894   IF (_debug) THEN
18895     IF (_price.price IS NOT NULL) THEN
18896       RAISE NOTICE 'Customer Type Pattern Price found, %', _price.price;
18897     END IF;
18898   END IF;
18899
18900   END IF;
18901
18902   -- Select the lowest price
18903   IF ( (_price.price IS NOT NULL) AND ((_sales.price IS NULL) OR (_price.price < _sales.price)) ) THEN
18904     _freightid := _price.ipsfreight_id;
18905     _totalprice := _price.price;
18906   ELSE
18907     IF ( (_sales.price IS NOT NULL) AND ((_price.price IS NULL) OR (_sales.price <= _price.price)) ) THEN
18908       _freightid := _sales.ipsfreight_id;
18909       _totalprice := _sales.price;
18910     END IF;
18911   END IF;
18912
18913   IF (_debug) THEN
18914     RAISE NOTICE '_freightid = %', _freightid;
18915     RAISE NOTICE '_totalprice = %', _totalprice;
18916   END IF;
18917
18918   -- Get information for the selected ipsfreight
18919   -- and return
18920   IF (_freightid IS NULL) THEN
18921     _row.freightdata_schedule := 'N/A';
18922     _row.freightdata_from := '';
18923     _row.freightdata_to := '';
18924     _row.freightdata_shipvia := '';
18925     _row.freightdata_freightclass := '';
18926     _row.freightdata_weight := 0;
18927     _row.freightdata_uom := '';
18928     _row.freightdata_price := 0;
18929     _row.freightdata_type := '';
18930     _row.freightdata_total := 0;
18931     _row.freightdata_currency := '';
18932     RETURN NEXT _row;
18933   ELSE
18934     SELECT ipshead_name AS freightdata_schedule,
18935       COALESCE(warehous_code, 'Any') AS freightdata_from,
18936       COALESCE(shipzone_name, 'Any') AS freightdata_to,
18937       COALESCE(ipsfreight_shipvia, 'Any') AS freightdata_shipvia,
18938       COALESCE(freightclass_code, 'Any') AS freightdata_freightclass,
18939       pWeight AS freightdata_weight,
18940       uom_name AS freightdata_uom,
18941       currToCurr(ipshead_curr_id, pCurrId, ipsfreight_price, pOrderDate) AS freightdata_price,
18942       CASE WHEN (ipsfreight_type='F') THEN 'Flat Rate'
18943         ELSE 'Per UOM'
18944       END AS freightdata_type,
18945       _totalprice AS freightdata_total,
18946       pCurrAbbr AS freightdata_currency
18947     INTO _row
18948     FROM ipsfreight
18949       JOIN ipshead ON (ipshead_id=ipsfreight_ipshead_id)
18950       LEFT OUTER JOIN uom ON (uom_item_weight)
18951       LEFT OUTER JOIN whsinfo ON (warehous_id=ipsfreight_warehous_id)
18952       LEFT OUTER JOIN shipzone ON (shipzone_id=ipsfreight_shipzone_id)
18953       LEFT OUTER JOIN freightclass ON (freightclass_id=ipsfreight_freightclass_id)
18954     WHERE (ipsfreight_id=_freightid);
18955
18956     RETURN NEXT _row;
18957   END IF;
18958
18959   RETURN;
18960 END;
18961 $_$;
18962
18963
18964 ALTER FUNCTION public.calculatefreightdetail(integer, integer, text, integer, integer, text, date, text, integer, character varying, integer, integer, numeric) OWNER TO admin;
18965
18966 --
18967 -- TOC entry 1179 (class 1255 OID 146565717)
18968 -- Dependencies: 2708 4536 8
18969 -- Name: calculatesubtax(integer, date, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
18970 --
18971
18972 CREATE FUNCTION calculatesubtax(integer, date, integer, numeric, integer) RETURNS SETOF taxdetail
18973     LANGUAGE plpgsql
18974     AS $_$
18975 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
18976 -- See www.xtuple.com/CPAL for the full text of the software license.
18977 DECLARE
18978   pTaxCodeId ALIAS FOR $1;
18979   pDate ALIAS FOR $2;
18980   pCurrId ALIAS FOR $3;
18981   pAmount ALIAS FOR $4;
18982   pLevel ALIAS FOR $5;
18983   _row taxdetail%ROWTYPE;
18984   _rownumber INTEGER := 1;
18985   _calc_tax Numeric :=0;
18986   _x RECORD;
18987   _y RECORD;
18988
18989 BEGIN
18990   FOR _x IN 
18991
18992   SELECT tax_id, tax_code, tax_descrip, tax_basis_tax_id,
18993     taxrate_id, taxrate_percent, taxrate_curr_id, taxrate_amount,  
18994     taxclass_id, taxclass_code, COALESCE(taxclass_sequence,0) AS taxclass_sequence,
18995     curr_id, curr_abbr
18996   FROM tax, taxrate, taxclass, curr_symbol
18997   WHERE ((tax_id = taxrate_tax_id)
18998   AND (tax_taxclass_id = taxclass_id)
18999   AND (taxrate_curr_id = curr_id)
19000   AND (tax_basis_tax_id = pTaxCodeId)
19001   AND (pDate BETWEEN taxrate_effective AND taxrate_expires)
19002   AND (taxrate_curr_id = pCurrId))
19003   
19004   LOOP
19005     SELECT 
19006       ROUND((_x.taxrate_percent * pAmount + currToCurr(_x.curr_id, pCurrId, _x.taxrate_amount, pDate)), 6) 
19007     INTO _calc_tax;
19008
19009     _row.taxdetail_tax_id = _x.tax_id;
19010     _row.taxdetail_tax_code = _x.tax_code;
19011     _row.taxdetail_tax_descrip = _x.tax_descrip;
19012     _row.taxdetail_tax_basis_tax_id = _x.tax_basis_tax_id ;
19013     _row.taxdetail_taxrate_percent = _x.taxrate_percent;
19014     _row.taxdetail_taxrate_amount = _x.taxrate_amount;
19015     _row.taxdetail_level = pLevel + 1;
19016     _row.taxdetail_taxclass_id = _x.taxclass_id ; 
19017     _row.taxdetail_taxclass_code = _x.taxclass_code;
19018     _row.taxdetail_taxclass_sequence = _x.taxclass_sequence;
19019     _row.taxdetail_tax = _calc_tax;
19020     _row.taxdetail_curr_id = _x.curr_id;
19021     _row.taxdetail_curr_abbr = _x.curr_abbr;
19022
19023     RETURN NEXT _row;
19024     _rownumber := _rownumber + 1;
19025
19026     FOR _y IN  
19027     SELECT * 
19028     FROM calculateSubTax( _x.tax_id, pDate, pCurrId, _calc_tax, pLevel + 1)
19029     LOOP
19030       _row.taxdetail_tax_id = _y.taxdetail_tax_id;
19031       _row.taxdetail_tax_code = _y.taxdetail_tax_code;
19032       _row.taxdetail_tax_descrip = _y.taxdetail_tax_descrip;
19033       _row.taxdetail_tax_basis_tax_id = _y.taxdetail_tax_basis_tax_id ;
19034       _row.taxdetail_taxrate_percent = _y.taxdetail_taxrate_percent;
19035       _row.taxdetail_taxrate_amount = _y.taxdetail_taxrate_amount;
19036       _row.taxdetail_level = _y.taxdetail_level + 1;
19037       _row.taxdetail_taxclass_id = _y.taxdetail_taxclass_id ; 
19038       _row.taxdetail_taxclass_code = _y.taxdetail_taxclass_code;
19039       _row.taxdetail_taxclass_sequence = _y.taxdetail_taxclass_sequence;
19040       _row.taxdetail_tax = _y.taxdetail_tax;
19041       _row.taxdetail_curr_id = _y.taxdetail_curr_id;
19042       _row.taxdetail_curr_abbr = _y.taxdetail_curr_abbr;
19043       
19044       RETURN NEXT _row;
19045       _rownumber := _rownumber + 1;
19046
19047     END LOOP;
19048
19049   END LOOP;
19050
19051 END;
19052 $_$;
19053
19054
19055 ALTER FUNCTION public.calculatesubtax(integer, date, integer, numeric, integer) OWNER TO admin;
19056
19057 --
19058 -- TOC entry 1180 (class 1255 OID 146565718)
19059 -- Dependencies: 4536 8
19060 -- Name: calculatetax(integer, integer, date, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
19061 --
19062
19063 CREATE FUNCTION calculatetax(integer, integer, date, integer, numeric) RETURNS numeric
19064     LANGUAGE plpgsql
19065     AS $_$
19066 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19067 -- See www.xtuple.com/CPAL for the full text of the software license.
19068 DECLARE
19069   pTaxZoneId ALIAS FOR  $1;
19070   pTaxTypeId ALIAS FOR  $2;
19071   pDate ALIAS FOR  $3;
19072   pCurrId ALIAS FOR $4;
19073   pAmount ALIAS FOR $5;
19074   _tottax numeric := 0;  -- total tax
19075   
19076 BEGIN
19077
19078   SELECT COALESCE(ROUND(SUM(taxdetail_tax),6),0)
19079     INTO _tottax 
19080   FROM calculateTaxDetail(pTaxZoneId, pTaxTypeId, pDate, pCurrId, pAmount);
19081
19082   RETURN _tottax;
19083   
19084 END;
19085 $_$;
19086
19087
19088 ALTER FUNCTION public.calculatetax(integer, integer, date, integer, numeric) OWNER TO admin;
19089
19090 --
19091 -- TOC entry 1181 (class 1255 OID 146565719)
19092 -- Dependencies: 2708 4536 8
19093 -- Name: calculatetaxdetail(integer, integer, date, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
19094 --
19095
19096 CREATE FUNCTION calculatetaxdetail(integer, integer, date, integer, numeric) RETURNS SETOF taxdetail
19097     LANGUAGE plpgsql
19098     AS $_$
19099 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19100 -- See www.xtuple.com/CPAL for the full text of the software license.
19101 DECLARE
19102   pTaxZoneId ALIAS FOR  $1;
19103   pTaxTypeId ALIAS FOR  $2;
19104   pDate ALIAS FOR  $3;
19105   pCurrId ALIAS FOR $4;
19106   pAmount ALIAS FOR $5;
19107   _row taxdetail%ROWTYPE;
19108   _x RECORD;
19109   _y RECORD;
19110   _z RECORD;
19111   _currcum numeric := 0;  -- Current cumulative tax
19112   _currseq numeric := 0;  -- Current group sequence
19113   _prevcum numeric := 0;  -- Previous cumulative tax
19114   _tax numeric := 0;      -- Calculated tax amount
19115   _taxbasis numeric := 0;  -- Used for calculating sub taxes
19116
19117 BEGIN
19118
19119   IF ((COALESCE(pTaxTypeId,-1) = -1) OR (COALESCE(pTaxZoneId,-1) = -1)) THEN
19120     RETURN;
19121   END IF;
19122
19123   SELECT DISTINCT
19124     COALESCE(taxass_taxzone_id, -1) AS taxzone_id,
19125     COALESCE(taxass_taxtype_id, -1) AS taxtype_id,
19126     taxass_tax_id,
19127     CASE
19128       WHEN ((taxass_taxzone_id IS NOT NULL) AND (taxass_taxtype_id IS NOT NULL)) THEN
19129         0
19130       WHEN ((taxass_taxzone_id IS NOT NULL) AND (taxass_taxtype_id IS NULL)) THEN
19131         1
19132       WHEN ((taxass_taxzone_id IS NULL) AND (taxass_taxtype_id IS NOT NULL)) THEN
19133         2
19134       ELSE
19135         3
19136     END AS sequence
19137     INTO _x
19138   FROM taxass
19139   WHERE  ((COALESCE(taxass_taxzone_id, pTaxZoneId, -1) = COALESCE(pTaxZoneId,-1))
19140   AND    (COALESCE(taxass_taxtype_id, pTaxTypeId, -1) = COALESCE(pTaxTypeId,-1)))
19141   ORDER BY sequence LIMIT 1;
19142
19143   --Now loop through each tax detail record and return calculated result
19144   FOR _y IN
19145     SELECT  --the data required by taxdetail type.  Coalesce group sequence to 0 if no class.
19146     tax_id
19147     ,tax_code
19148     ,tax_descrip
19149     ,tax_basis_tax_id
19150     ,taxrate_percent
19151     ,taxrate_amount
19152     ,0 as taxdetail_level 
19153     ,taxclass_id
19154     ,taxclass_code
19155     ,COALESCE(taxclass_sequence, 0) AS taxclass_sequence
19156     ,0 as taxdetail_tax
19157     ,curr_id
19158     ,curr_abbr  
19159     FROM taxass, taxclass RIGHT OUTER JOIN tax  
19160       LEFT OUTER JOIN taxrate ON (taxrate_tax_id=tax_id)
19161     ON (tax_taxclass_id=taxclass_id),
19162     curr_symbol 
19163     WHERE 
19164     taxass_tax_id=tax_id
19165     AND taxrate_curr_id=curr_id
19166     AND COALESCE(taxass_taxzone_id, -1) = _x.taxzone_id
19167     AND COALESCE(taxass_taxtype_id, -1) = _x.taxtype_id
19168     AND pDate BETWEEN COALESCE(taxrate_effective, startoftime()) AND COALESCE(taxrate_expires, endoftime())
19169     ORDER BY COALESCE(taxclass_sequence, 0)
19170   LOOP
19171     -- If sequence has changed, cache the previous cumulative tax
19172     IF (_currseq != _x.sequence) THEN
19173       _prevcum := _currcum;
19174     END IF;
19175
19176     -- Calculate the tax amount.  Convert currency for flat rate amounts
19177     SELECT 
19178     ROUND((_y.taxrate_percent * (pAmount + _prevcum) + currToCurr(_y.curr_id, pCurrId, _y.taxrate_amount, pDate)), 6) 
19179     INTO _tax
19180     FROM tax JOIN  taxrate ON (tax_id = taxrate_tax_id)
19181     WHERE (tax_id=_x.taxass_tax_id)
19182     AND (pDate BETWEEN COALESCE(taxrate_effective, startoftime()) AND COALESCE(taxrate_expires, endoftime()));
19183
19184     --Map fields to _row
19185
19186     _row.taxdetail_tax_id := _y.tax_id;
19187     _row.taxdetail_tax_code := _y.tax_code;
19188     _row.taxdetail_tax_descrip := _y.tax_descrip;
19189     _row.taxdetail_tax_basis_tax_id := _y.tax_basis_tax_id;
19190     _row.taxdetail_taxrate_percent := _y.taxrate_percent;
19191     _row.taxdetail_taxrate_amount := _y.taxrate_amount;
19192     _row.taxdetail_level := _y.taxdetail_level;
19193     _row.taxdetail_taxclass_id := _y.taxclass_id;
19194     _row.taxdetail_taxclass_code := _y.taxclass_code;
19195     _row.taxdetail_taxclass_sequence := _y.taxclass_sequence;
19196     _row.taxdetail_tax := _tax;
19197     _row.taxdetail_curr_id := _y.curr_id;
19198     _row.taxdetail_curr_abbr := _y.curr_abbr;
19199   
19200     RETURN NEXT _row;
19201
19202     -- Increment cumulative balance and sequence number
19203     IF(_y.taxclass_sequence <> 0) THEN
19204       _currcum := _currcum + _tax;
19205     END IF;
19206     _currseq := _y.taxclass_sequence;
19207
19208     -- Loop to Calculate sub taxes
19209     FOR _z IN
19210     SELECT *
19211     FROM calculateSubTax(_y.tax_id,pDate, pCurrId, _tax, 0)
19212     LOOP
19213      --Mapping of data
19214     _row.taxdetail_tax_id := _z.taxdetail_tax_id;
19215     _row.taxdetail_tax_code := _z.taxdetail_tax_code;
19216     _row.taxdetail_tax_descrip := _z.taxdetail_tax_descrip;
19217     _row.taxdetail_tax_basis_tax_id := _z.taxdetail_tax_basis_tax_id;
19218     _row.taxdetail_taxrate_percent := _z.taxdetail_taxrate_percent;
19219     _row.taxdetail_taxrate_amount := _z.taxdetail_taxrate_amount;
19220     _row.taxdetail_level := _z.taxdetail_level;
19221     _row.taxdetail_taxclass_id := _z.taxdetail_taxclass_id;
19222     _row.taxdetail_taxclass_code := _z.taxdetail_taxclass_code;
19223     _row.taxdetail_taxclass_sequence := _z.taxdetail_taxclass_sequence;
19224     _row.taxdetail_tax := _z.taxdetail_tax;
19225     _row.taxdetail_curr_id := _z.taxdetail_curr_id;
19226     _row.taxdetail_curr_abbr := _z.taxdetail_curr_abbr;
19227
19228      RETURN NEXT _row;
19229      --Add to cumulative counter (_curcum)
19230      _currcum := _currcum + _z.taxdetail_tax ;
19231
19232     END LOOP;
19233
19234    END LOOP;
19235  
19236 END;
19237  $_$;
19238
19239
19240 ALTER FUNCTION public.calculatetaxdetail(integer, integer, date, integer, numeric) OWNER TO admin;
19241
19242 --
19243 -- TOC entry 1182 (class 1255 OID 146565720)
19244 -- Dependencies: 2708 4536 8
19245 -- Name: calculatetaxdetailline(text, integer); Type: FUNCTION; Schema: public; Owner: admin
19246 --
19247
19248 CREATE FUNCTION calculatetaxdetailline(text, integer) RETURNS SETOF taxdetail
19249     LANGUAGE plpgsql
19250     AS $_$
19251 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19252 -- See www.xtuple.com/CPAL for the full text of the software license.
19253 DECLARE
19254   pOrderType ALIAS FOR $1;
19255   pOrderId ALIAS FOR $2;
19256   _row taxdetail%ROWTYPE;
19257   _qry text;
19258   _totaltax numeric;
19259   _y RECORD;
19260   _table text;
19261   
19262 BEGIN
19263    _totaltax=0.0;
19264
19265    IF pOrderType = 'II' THEN
19266      _table := 'invcitemtax';
19267    ELSIF pOrderType = 'BI' THEN
19268      _table := 'cobilltax';
19269    ELSIF pOrderType = 'CI' THEN
19270      _table := 'cmitemtax';
19271    ELSIF pOrderType = 'VI' THEN
19272      _table := 'voitemtax';
19273    ELSIF pOrderType = 'TI' THEN
19274      _table := 'toitemtax';
19275    ELSIF pOrderType = 'AR' THEN
19276      _table := 'aropentax';
19277    ELSIF pOrderType = 'AP' THEN
19278      _table := 'apopentax';
19279    END IF;
19280      
19281    _qry := 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, COALESCE(taxhist_sequence,0) AS taxhist_sequence
19282             FROM taxhist 
19283              JOIN tax ON (taxhist_tax_id=tax_id) 
19284              JOIN pg_class ON (pg_class.oid=taxhist.tableoid) 
19285             WHERE ( (taxhist_parent_id = ' || pOrderId || ')
19286              AND (relname=''' || _table || ''') );';
19287     
19288    FOR _y IN  EXECUTE _qry
19289    LOOP
19290      _row.taxdetail_tax_id=_y.tax_id;
19291      _row.taxdetail_tax_code = _y.tax_code;
19292      _row.taxdetail_tax_descrip = _y.tax_descrip;
19293      _row.taxdetail_tax = _y.taxhist_tax;
19294      _row.taxdetail_level= 0 ;
19295      _row.taxdetail_taxclass_sequence= _y.taxhist_sequence;
19296      _totaltax = _totaltax + _y.taxhist_tax;
19297      RETURN NEXT _row;
19298    END LOOP;
19299  END;
19300 $_$;
19301
19302
19303 ALTER FUNCTION public.calculatetaxdetailline(text, integer) OWNER TO admin;
19304
19305 --
19306 -- TOC entry 1183 (class 1255 OID 146565721)
19307 -- Dependencies: 2708 4536 8
19308 -- Name: calculatetaxdetailsummary(text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
19309 --
19310
19311 CREATE FUNCTION calculatetaxdetailsummary(text, integer, text) RETURNS SETOF taxdetail
19312     LANGUAGE plpgsql
19313     AS $_$
19314 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19315 -- See www.xtuple.com/CPAL for the full text of the software license.
19316 DECLARE
19317   pOrderType ALIAS FOR $1;
19318   pOrderId ALIAS FOR $2;
19319   pDisplayType ALIAS FOR $3;
19320   _row taxdetail%ROWTYPE;
19321   _qry text := '';
19322   _qry1 text;
19323   _totaltax numeric;
19324   _x RECORD;
19325   _y RECORD;
19326   _table text;
19327   
19328 BEGIN
19329  _totaltax=0.0;
19330  IF pOrderType IN ('S','Q','RA','PO') THEN
19331    
19332    IF pOrderType = 'S' THEN
19333      _qry := 'SELECT ' || 'COALESCE(cohead_taxzone_id, -1) AS taxzone_id, cohead_orderdate AS order_date,
19334                 cohead_curr_id AS curr_id, COALESCE(coitem_taxtype_id, -1) AS taxtype_id,
19335                 ROUND((coitem_qtyord * coitem_qty_invuomratio) * (coitem_price / coitem_price_invuomratio),2) AS amount
19336               FROM cohead, coitem
19337               WHERE ( (coitem_cohead_id = ' || pOrderId || ')
19338                AND (' || 'cohead_id = coitem_cohead_id) 
19339                AND ( coitem_status != ''X'') )';
19340    ELSEIF  pOrderType = 'Q' THEN
19341      _qry := 'SELECT ' || 'COALESCE(quhead_taxzone_id, -1) AS taxzone_id, quhead_quotedate AS order_date,
19342                 quhead_curr_id AS curr_id, COALESCE(quitem_taxtype_id, -1) AS taxtype_id, 
19343                 ROUND((quitem_qtyord * quitem_qty_invuomratio) * (quitem_price / quitem_price_invuomratio),2) AS amount
19344               FROM quhead, quitem 
19345               WHERE ( (quitem_quhead_id = ' || pOrderId || ')
19346                AND (quhead_id = quitem_quhead_id) )'; 
19347    ELSEIF  pOrderType = 'RA' THEN
19348      _qry := 'SELECT ' || 'COALESCE(rahead_taxzone_id, -1) AS taxzone_id, rahead_authdate AS order_date,
19349                 rahead_curr_id AS curr_id, COALESCE(raitem_taxtype_id, -1) AS taxtype_id, 
19350                 ROUND((raitem_qtyauthorized * raitem_qty_invuomratio) * (raitem_unitprice / raitem_price_invuomratio),2) AS amount
19351               FROM rahead, raitem 
19352               WHERE ( (raitem_rahead_id = ' || pOrderId || ')
19353                AND (rahead_id = raitem_rahead_id) )';
19354    ELSEIF  pOrderType = 'PO' THEN
19355      _qry := 'SELECT ' || 'COALESCE(pohead_taxzone_id, -1) AS taxzone_id, pohead_orderdate AS order_date,
19356                 pohead_curr_id AS curr_id, COALESCE(poitem_taxtype_id, -1) AS taxtype_id, 
19357                 ROUND(poitem_qty_ordered * poitem_unitprice, 2) AS amount
19358               FROM pohead, poitem 
19359               WHERE ( (poitem_pohead_id = ' || pOrderId || ')
19360                AND (pohead_id = poitem_pohead_id) )'; 
19361   END IF;
19362
19363   FOR _x IN EXECUTE _qry
19364   LOOP  
19365     _qry1 := 'SELECT * from calculatetaxdetail(' || _x.taxzone_id || ',' || _x.taxtype_id || ',''' || _x.order_date || ''',' || _x.curr_id  || ',' || _x.amount || ')';
19366     FOR _y IN  EXECUTE _qry1
19367     LOOP
19368       _row.taxdetail_tax_id=_y.taxdetail_tax_id;
19369       _row.taxdetail_tax_code = _y.taxdetail_tax_code;
19370       _row.taxdetail_tax_descrip = _y.taxdetail_tax_descrip;
19371       _row.taxdetail_tax = _y.taxdetail_tax;
19372       _row.taxdetail_level=_y.taxdetail_level;
19373       _row.taxdetail_taxclass_sequence= _y.taxdetail_taxclass_sequence;
19374       _totaltax = _totaltax + _y.taxdetail_tax;
19375       RETURN NEXT _row;
19376     END LOOP;
19377   END LOOP;
19378
19379   IF pDisplayType = 'T' AND pOrderType <> 'PO' THEN
19380    IF pOrderType = 'S' THEN 
19381     _qry := 'SELECT COALESCE(cohead_taxzone_id, -1) AS taxzone_id, cohead_orderdate AS order_date,
19382                cohead_curr_id AS curr_id, cohead_freight AS freight
19383              FROM cohead WHERE cohead_id = ' || pOrderId ;
19384    ELSEIF  pOrderType = 'Q' THEN 
19385     _qry := 'SELECT COALESCE(quhead_taxzone_id, -1) AS taxzone_id, quhead_quotedate AS order_date,
19386                quhead_curr_id AS curr_id, COALESCE(quhead_freight,0) AS freight
19387              FROM quhead WHERE quhead_id = ' || pOrderId;
19388    ELSEIF pOrderType = 'RA' THEN
19389     _qry := 'SELECT COALESCE(rahead_taxzone_id, -1) AS taxzone_id, COALESCE(rahead_authdate,CURRENT_DATE) AS order_date,
19390                rahead_curr_id AS curr_id, COALESCE(rahead_freight,0) AS freight
19391              FROM rahead WHERE rahead_id = ' || pOrderId;
19392    END IF;
19393
19394   FOR _x IN EXECUTE _qry
19395   LOOP
19396      _qry1 := 'SELECT * from calculatetaxdetail(' || _x.taxzone_id || ', getfreighttaxtypeid(),''' || _x.order_date || ''',' || _x.curr_id  || ',' || _x.freight || ')';
19397     FOR _y IN  EXECUTE _qry1
19398     LOOP
19399        _row.taxdetail_tax_id=_y.taxdetail_tax_id;
19400        _row.taxdetail_tax_code = _y.taxdetail_tax_code;
19401        _row.taxdetail_tax_descrip = _y.taxdetail_tax_descrip;
19402        _row.taxdetail_tax = _y.taxdetail_tax;
19403        _row.taxdetail_level=_y.taxdetail_level;
19404        _row.taxdetail_taxclass_sequence= _y.taxdetail_taxclass_sequence;
19405        _totaltax = _totaltax + _y.taxdetail_tax;
19406        RETURN NEXT _row;
19407      END LOOP;
19408    END LOOP;
19409   END IF;
19410   
19411  ELSEIF pOrderType IN ('I','B','CM', 'VO','TO') THEN
19412    IF (pOrderType='I') THEN
19413      _table := 'invcheadtax';
19414    ELSIF (pOrderType='B') THEN
19415      _table := 'cobmisctax';
19416    ELSIF (pOrderType='CM') THEN
19417      _table := 'cmheadtax';
19418    ELSIF (pOrderType='VO') THEN
19419      _table := 'voheadtax';
19420    ELSIF (pOrderType='TO') THEN
19421      _table := 'tohead';
19422    END IF;
19423    
19424    IF pOrderType = 'I' AND (pDisplayType IN ('L','T')) THEN
19425      _qry := 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19426               FROM invchead, invcitemtax LEFT OUTER JOIN tax ON (taxhist_tax_id=tax_id)
19427                LEFT OUTER JOIN invcitem ON (invcitem_id=taxhist_parent_id) 
19428               WHERE invcitem_invchead_id = ' || pOrderId || ' 
19429                AND invchead_id = invcitem_invchead_id ';
19430    ELSIF pOrderType = 'B' AND (pDisplayType IN ('L','T')) THEN
19431     _qry := 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19432              FROM cobmisc, cobilltax LEFT OUTER JOIN tax ON (taxhist_tax_id=tax_id)
19433              LEFT OUTER JOIN cobill ON (cobill_id=taxhist_parent_id)
19434              WHERE cobill_cobmisc_id = ' || pOrderId || ' 
19435              AND cobmisc_id = cobill_cobmisc_id ';
19436    ELSIF pOrderType = 'CM' AND (pDisplayType IN ('L','T')) THEN
19437     _qry := 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19438              FROM cmhead, cmitemtax LEFT OUTER JOIN tax ON (taxhist_tax_id=tax_id)
19439              LEFT OUTER JOIN cmitem ON (cmitem_id=taxhist_parent_id)
19440              WHERE cmitem_cmhead_id = ' || pOrderId || ' 
19441              AND cmhead_id = cmitem_cmhead_id ';
19442    ELSIF pOrderType = 'VO' AND (pDisplayType IN ('L','T')) THEN
19443     _qry := 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19444              FROM vohead, voitemtax LEFT OUTER JOIN tax ON (taxhist_tax_id=tax_id)
19445              LEFT OUTER JOIN voitem ON (voitem_id=taxhist_parent_id)
19446              WHERE voitem_vohead_id = ' || pOrderId || ' 
19447              AND vohead_id = voitem_vohead_id ';
19448    ELSIF pOrderType = 'TO' AND (pDisplayType IN ('L','T')) THEN
19449     _qry := 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19450              FROM tohead, toitemtax LEFT OUTER JOIN tax ON (taxhist_tax_id=tax_id)
19451              LEFT OUTER JOIN toitem ON (toitem_id=taxhist_parent_id)
19452              WHERE toitem_tohead_id = ' || pOrderId || ' 
19453              AND tohead_id = toitem_tohead_id ';
19454    END IF;
19455    IF pDisplayType IN ('F','T') AND pOrderType <> 'VO' THEN
19456      IF (length(_qry) > 0) THEN
19457        _qry := _qry || ' UNION ALL ';
19458      END IF;
19459      _qry := _qry || 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19460               FROM taxhist 
19461                JOIN tax ON (taxhist_tax_id=tax_id)
19462                JOIN pg_class ON (pg_class.oid=taxhist.tableoid)
19463               WHERE ( (taxhist_parent_id = ' || pOrderId || ') 
19464                AND (taxhist_taxtype_id=getfreighttaxtypeid())
19465                AND (relname=''' || _table || ''') )';
19466    END IF;
19467    IF pDisplayType IN ('A','T') THEN
19468      IF (length(_qry) > 0) THEN
19469        _qry := _qry || ' UNION ALL ';
19470      END IF;
19471      _qry := _qry || 'SELECT taxhist_tax_id as tax_id, tax_code, tax_descrip, taxhist_tax, taxhist_sequence
19472               FROM taxhist 
19473                JOIN tax ON (taxhist_tax_id=tax_id)
19474                JOIN pg_class ON (pg_class.oid=taxhist.tableoid)
19475               WHERE ( (taxhist_parent_id = ' || pOrderId || ') 
19476                AND (taxhist_taxtype_id=getadjustmenttaxtypeid())
19477                AND (relname=''' || _table || ''') )';
19478
19479    END IF;
19480    FOR _y IN  EXECUTE _qry
19481    LOOP
19482      _row.taxdetail_tax_id=_y.tax_id;
19483      _row.taxdetail_tax_code = _y.tax_code;
19484      _row.taxdetail_tax_descrip = _y.tax_descrip;
19485      _row.taxdetail_tax = _y.taxhist_tax;
19486      _row.taxdetail_level= 0 ;
19487      _row.taxdetail_taxclass_sequence= COALESCE(_y.taxhist_sequence,0);
19488      _totaltax = _totaltax + _y.taxhist_tax;
19489      RETURN NEXT _row;
19490    END LOOP;
19491  END IF;
19492  END;
19493 $_$;
19494
19495
19496 ALTER FUNCTION public.calculatetaxdetailsummary(text, integer, text) OWNER TO admin;
19497
19498 --
19499 -- TOC entry 1184 (class 1255 OID 146565723)
19500 -- Dependencies: 4536 8
19501 -- Name: calculatetaxhist(text, integer, integer, integer, date, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
19502 --
19503
19504 CREATE FUNCTION calculatetaxhist(text, integer, integer, integer, date, integer, numeric) RETURNS boolean
19505     LANGUAGE plpgsql
19506     AS $_$
19507 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19508 -- See www.xtuple.com/CPAL for the full text of the software license.
19509 DECLARE
19510   pTableName ALIAS FOR $1;
19511   pParentId  ALIAS FOR $2;
19512   pTaxZoneId ALIAS FOR $3;
19513   pTaxTypeId ALIAS FOR $4;
19514   pDate      ALIAS FOR $5;
19515   pCurrId    ALIAS FOR $6;
19516   pAmount    ALIAS FOR $7;
19517   _qry TEXT;
19518   
19519 BEGIN
19520   IF (pTableName IS NULL) THEN
19521     RAISE EXCEPTION 'A table name is required to calculate tax history';
19522   ELSEIF (pParentId IS NULL) THEN
19523     RAISE EXCEPTION 'A parent ID is required to calculate tax history';
19524   ELSEIF (pDate IS NULL) THEN
19525     RAISE EXCEPTION 'A date is required to calculate tax history';
19526   ELSEIF (pAmount IS NULL) THEN
19527      RAISE EXCEPTION 'An amount is required to calculate tax history';
19528   END IF;
19529
19530   -- Build a query that deletes any previous tax history for this document record
19531   _qry := 'DELETE FROM ' || pTableName || ' WHERE taxhist_parent_id = ' || pParentId || ' AND taxhist_taxtype_id <> getadjustmenttaxtypeid();';
19532   EXECUTE _qry;
19533
19534   -- Next, build and execute query that inserts new rows.
19535   _qry := 'INSERT INTO ' || pTableName || ' (
19536              taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id, taxhist_basis,
19537              taxhist_basis_tax_id, taxhist_sequence, taxhist_percent, 
19538              taxhist_amount, taxhist_tax, taxhist_docdate)
19539            SELECT ' || pParentId || ',';
19540   IF (pTaxTypeId IS NULL) THEN
19541     _qry := _qry || 'NULL';
19542   ELSE
19543     _qry := _qry || pTaxTypeId;
19544   END If;
19545   _qry := _qry || ', taxdetail_tax_id,' || pAmount || ', 
19546              taxdetail_tax_basis_tax_id, taxdetail_taxclass_sequence, taxdetail_taxrate_percent,
19547              taxdetail_taxrate_amount, taxdetail_tax, ''' || pDate || '''
19548            FROM calculatetaxdetail(' || COALESCE(pTaxZoneId,-1) || ',' || COALESCE(pTaxTypeId,-1) ||',''' || pDate || ''',' || pCurrId || ',' || pAmount || ');';
19549   EXECUTE _qry;
19550
19551   RETURN true;
19552 END;
19553 $_$;
19554
19555
19556 ALTER FUNCTION public.calculatetaxhist(text, integer, integer, integer, date, integer, numeric) OWNER TO admin;
19557
19558 --
19559 -- TOC entry 1185 (class 1255 OID 146565724)
19560 -- Dependencies: 4536 8
19561 -- Name: calcvoucheramt(integer); Type: FUNCTION; Schema: public; Owner: admin
19562 --
19563
19564 CREATE FUNCTION calcvoucheramt(integer) RETURNS numeric
19565     LANGUAGE plpgsql
19566     AS $_$
19567 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19568 -- See www.xtuple.com/CPAL for the full text of the software license.
19569 DECLARE
19570   pVoucherid ALIAS FOR $1;
19571   _amount NUMERIC := 0;
19572
19573 BEGIN
19574
19575   SELECT SUM(COALESCE(vodist_amount, 0)) INTO _amount
19576   FROM vodist
19577   WHERE (vodist_vohead_id=pVoucherid);
19578
19579   RETURN _amount;
19580
19581 END;
19582 $_$;
19583
19584
19585 ALTER FUNCTION public.calcvoucheramt(integer) OWNER TO admin;
19586
19587 --
19588 -- TOC entry 1186 (class 1255 OID 146565725)
19589 -- Dependencies: 4536 8
19590 -- Name: calcvoucherfreight(integer); Type: FUNCTION; Schema: public; Owner: admin
19591 --
19592
19593 CREATE FUNCTION calcvoucherfreight(integer) RETURNS numeric
19594     LANGUAGE plpgsql
19595     AS $_$
19596 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19597 -- See www.xtuple.com/CPAL for the full text of the software license.
19598 DECLARE
19599   pVoucherid ALIAS FOR $1;
19600   _amount NUMERIC := 0;
19601
19602 BEGIN
19603
19604   SELECT SUM(COALESCE(voitem_freight, 0)) INTO _amount
19605   FROM voitem
19606   WHERE (voitem_vohead_id=pVoucherid);
19607
19608   RETURN _amount;
19609
19610 END;
19611 $_$;
19612
19613
19614 ALTER FUNCTION public.calcvoucherfreight(integer) OWNER TO admin;
19615
19616 --
19617 -- TOC entry 1187 (class 1255 OID 146565726)
19618 -- Dependencies: 4536 8
19619 -- Name: calcvouchertax(integer); Type: FUNCTION; Schema: public; Owner: admin
19620 --
19621
19622 CREATE FUNCTION calcvouchertax(integer) RETURNS numeric
19623     LANGUAGE plpgsql
19624     AS $_$
19625 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19626 -- See www.xtuple.com/CPAL for the full text of the software license.
19627 DECLARE
19628   pVoucherid ALIAS FOR $1;
19629   _amount NUMERIC := 0;
19630
19631 BEGIN
19632
19633   SELECT COALESCE(calculateTax(vohead_taxzone_id,
19634                                vohead_taxtype_id,
19635                                vohead_docdate,
19636                                vohead_curr_id,
19637                                calcVoucherAmt(vohead_id)), 0) INTO _amount
19638   FROM vohead
19639   WHERE (vohead_id=pVoucherid);
19640
19641   RETURN _amount;
19642
19643 END;
19644 $_$;
19645
19646
19647 ALTER FUNCTION public.calcvouchertax(integer) OWNER TO admin;
19648
19649 --
19650 -- TOC entry 1188 (class 1255 OID 146565727)
19651 -- Dependencies: 4536 8
19652 -- Name: calcwooperstartstub(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
19653 --
19654
19655 CREATE FUNCTION calcwooperstartstub(integer, integer) RETURNS date
19656     LANGUAGE plpgsql
19657     AS $_$
19658 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19659 -- See www.xtuple.com/CPAL for the full text of the software license.
19660 DECLARE
19661   pWoId         ALIAS FOR $1;
19662   pBooitemSeqId ALIAS FOR $2;
19663   _result       DATE;
19664 BEGIN
19665
19666   IF ( SELECT ((metric_value='t') AND packageIsEnabled('xtmfg'))
19667          FROM metric
19668         WHERE(metric_name='Routings') ) THEN
19669     RETURN xtmfg.calcWooperStart(pWoId, pBooitemSeqId);
19670   END IF;
19671   RETURN null;
19672 END;
19673 $_$;
19674
19675
19676 ALTER FUNCTION public.calcwooperstartstub(integer, integer) OWNER TO admin;
19677
19678 --
19679 -- TOC entry 1189 (class 1255 OID 146565728)
19680 -- Dependencies: 4536 8
19681 -- Name: cancelbillingselection(integer); Type: FUNCTION; Schema: public; Owner: admin
19682 --
19683
19684 CREATE FUNCTION cancelbillingselection(integer) RETURNS integer
19685     LANGUAGE plpgsql
19686     AS $_$
19687 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19688 -- See www.xtuple.com/CPAL for the full text of the software license.
19689 DECLARE
19690   pCobmiscid ALIAS FOR $1;
19691
19692 BEGIN
19693
19694   IF ( ( SELECT cobmisc_posted
19695          FROM cobmisc
19696          WHERE (cobmisc_id=pCobmiscid) ) ) THEN
19697     RETURN -1;
19698   END IF;
19699
19700   DELETE FROM cobill
19701   WHERE (cobill_cobmisc_id=pCobmiscid); 
19702
19703   DELETE FROM cobmisc
19704   WHERE (cobmisc_id=pCobmiscid);
19705
19706   RETURN 1;
19707
19708 END;
19709 $_$;
19710
19711
19712 ALTER FUNCTION public.cancelbillingselection(integer) OWNER TO admin;
19713
19714 --
19715 -- TOC entry 1190 (class 1255 OID 146565729)
19716 -- Dependencies: 4536 8
19717 -- Name: changeaccountingperioddates(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
19718 --
19719
19720 CREATE FUNCTION changeaccountingperioddates(integer, date, date) RETURNS integer
19721     LANGUAGE plpgsql
19722     AS $_$
19723 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19724 -- See www.xtuple.com/CPAL for the full text of the software license.
19725 DECLARE
19726   pPeriodid ALIAS FOR $1;
19727   pStartDate ALIAS FOR $2;
19728   pEndDate ALIAS FOR $3;
19729   _check INTEGER;
19730   _r RECORD;
19731
19732 BEGIN
19733
19734 --  Check to make sure that the passed period is not closed
19735   IF ( ( SELECT period_closed
19736          FROM period
19737          WHERE (period_id=pPeriodid) ) ) THEN
19738     RETURN -1;
19739   END IF;
19740
19741 --  Check to make sure that the passed start date does not fall
19742 --  into another period
19743   SELECT period_id INTO _check
19744   FROM period
19745   WHERE ( (pStartDate BETWEEN period_start AND period_end)
19746     AND (period_id <> pPeriodid) )
19747   LIMIT 1;
19748   IF (FOUND) THEN
19749     RETURN -2;
19750   END IF;
19751
19752 --  Check to make sure that the passed end date does not fall
19753 --  into another period
19754   SELECT period_id INTO _check
19755   FROM period
19756   WHERE ( (pEndDate BETWEEN period_start AND period_end)
19757     AND (period_id <> pPeriodid) )
19758   LIMIT 1;
19759   IF (FOUND) THEN
19760     RETURN -3;
19761   END IF;
19762
19763 --  Check to make sure that the new passed start and end dates do not
19764 --  orphan a posted G/L Transaction
19765   SELECT gltrans_id INTO _check
19766   FROM gltrans, period
19767   WHERE ( (gltrans_date BETWEEN period_start AND period_end)
19768    AND (gltrans_posted)
19769    AND (NOT (gltrans_date BETWEEN pStartDate AND pEndDate))
19770    AND (period_id=pPeriodid) )
19771   LIMIT 1;
19772   IF (FOUND) THEN
19773     RETURN -4;
19774   END IF;
19775
19776 --  Alter the start and end dates of the pass period
19777   UPDATE period
19778   SET period_start=pStartDate, period_end=pEndDate
19779   WHERE (period_id=pPeriodid);
19780
19781 --  Post any unposted G/L Transactions into the period
19782   FOR _r IN SELECT DISTINCT gltrans_sequence
19783             FROM gltrans
19784             WHERE ( (NOT gltrans_posted)
19785              AND (gltrans_date BETWEEN pStartDate AND pEndDate) ) LOOP
19786     PERFORM postIntoTrialBalance(_r.gltrans_sequence);
19787   END LOOP;
19788
19789 --  All done
19790   RETURN 1;
19791
19792 END;
19793 $_$;
19794
19795
19796 ALTER FUNCTION public.changeaccountingperioddates(integer, date, date) OWNER TO admin;
19797
19798 --
19799 -- TOC entry 1192 (class 1255 OID 146565730)
19800 -- Dependencies: 4536 8
19801 -- Name: changeaccountingyearperioddates(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
19802 --
19803
19804 CREATE FUNCTION changeaccountingyearperioddates(integer, date, date) RETURNS integer
19805     LANGUAGE plpgsql
19806     AS $_$
19807 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19808 -- See www.xtuple.com/CPAL for the full text of the software license.
19809 DECLARE
19810   pPeriodid ALIAS FOR $1;
19811   pStartDate ALIAS FOR $2;
19812   pEndDate ALIAS FOR $3;
19813   _check INTEGER;
19814   _checkBool BOOLEAN;
19815   _r RECORD;
19816
19817 BEGIN
19818
19819 --  Check to make sure that the passed yearperiod is not closed
19820   IF ( ( SELECT yearperiod_closed
19821          FROM yearperiod
19822          WHERE (yearperiod_id=pPeriodid) ) ) THEN
19823     RETURN -1;
19824   END IF;
19825
19826 --  Check to make sure that the passed start date does not fall
19827 --  into another yearperiod
19828   SELECT yearperiod_id INTO _check
19829   FROM yearperiod
19830   WHERE ( (pStartDate BETWEEN yearperiod_start AND yearperiod_end)
19831     AND (yearperiod_id <> pPeriodid) )
19832   LIMIT 1;
19833   IF (FOUND) THEN
19834     RETURN -2;
19835   END IF;
19836
19837 --  Check to make sure that the passed end date does not fall
19838 --  into another yearperiod
19839   SELECT yearperiod_id INTO _check
19840   FROM yearperiod
19841   WHERE ( (pEndDate BETWEEN yearperiod_start AND yearperiod_end)
19842     AND (yearperiod_id <> pPeriodid) )
19843   LIMIT 1;
19844   IF (FOUND) THEN
19845     RETURN -3;
19846   END IF;
19847
19848 --  Check to make sure that the passed yearperiod is not closed
19849   IF ( ( SELECT (count(period_id) > 0)
19850          FROM period
19851          WHERE ((period_yearperiod_id=pPeriodid)
19852           AND (period_start < pStartDate OR period_end > pEndDate)) ) ) THEN
19853     RETURN -4;
19854   END IF;
19855
19856 --  Make sure that the passed start is prior to the end date
19857   SELECT (pStartDate > pEndDate) INTO _checkBool;
19858   IF (_checkBool) THEN
19859     RETURN -5;
19860   END IF;
19861
19862
19863 --  Alter the start and end dates of the pass period
19864   UPDATE yearperiod
19865   SET yearperiod_start=pStartDate, yearperiod_end=pEndDate
19866   WHERE (yearperiod_id=pPeriodid);
19867
19868 --  All done
19869   RETURN 1;
19870
19871 END;
19872 $_$;
19873
19874
19875 ALTER FUNCTION public.changeaccountingyearperioddates(integer, date, date) OWNER TO admin;
19876
19877 --
19878 -- TOC entry 1193 (class 1255 OID 146565731)
19879 -- Dependencies: 4536 8
19880 -- Name: changefkeypointers(text, text, integer, integer, text[], boolean); Type: FUNCTION; Schema: public; Owner: admin
19881 --
19882
19883 CREATE FUNCTION changefkeypointers(text, text, integer, integer, text[], boolean) RETURNS integer
19884     LANGUAGE plpgsql
19885     AS $_$
19886 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19887 -- See www.xtuple.com/CPAL for the full text of the software license.
19888 DECLARE
19889   pSchema       ALIAS FOR $1;
19890   pTable        ALIAS FOR $2;
19891   pSourceId     ALIAS FOR $3;
19892   pTargetId     ALIAS FOR $4;
19893   pIgnore       ALIAS FOR $5;
19894   _purge        BOOLEAN := COALESCE($6, FALSE);
19895
19896   _counter      INTEGER := 0;
19897   _count1       INTEGER := 0;
19898   _fk           RECORD;
19899   _pk           TEXT[];
19900
19901 BEGIN
19902   -- for all foreign keys that point to pSchema.pTable
19903   FOR _fk IN
19904     EXECUTE 'SELECT fkeyns.nspname AS schemaname, fkeytab.relname AS tablename,
19905                     conkey, attname, typname
19906                FROM pg_constraint
19907                JOIN pg_class     basetab ON (confrelid=basetab.oid)
19908                JOIN pg_namespace basens  ON (basetab.relnamespace=basens.oid)
19909                JOIN pg_class     fkeytab ON (conrelid=fkeytab.oid)
19910                JOIN pg_namespace fkeyns  ON (fkeytab.relnamespace=fkeyns.oid)
19911                JOIN pg_attribute         ON (attrelid=conrelid AND attnum=conkey[1])
19912                JOIN pg_type              ON (atttypid=pg_type.oid)
19913               WHERE basetab.relname = ' || quote_literal(pTable)  || '
19914                 AND basens.nspname  = ' || quote_literal(pSchema) || '
19915                 AND fkeytab.relname NOT IN (''' || ARRAY_TO_STRING(pIgnore, ''', ''') || ''')'
19916   LOOP
19917     IF (ARRAY_UPPER(_fk.conkey, 1) > 1) THEN
19918       RAISE EXCEPTION 'Cannot change the foreign key in %.% that refers to %.% because the foreign key constraint has multiple columns. [xtuple: changefkeypointers, -1, %.%, %.%]',
19919         _fk.schemaname, _fk.tablename, pSchema, pTable,
19920         _fk.schemaname, _fk.tablename, pSchema, pTable;
19921     END IF;
19922     
19923     -- optionally make a backup copy of the data
19924     IF (NOT _purge) THEN
19925       -- determine the primary key column of the fkey table
19926       _pk := primaryKeyFields(_fk.schemaname, _fk.tablename);
19927       IF (ARRAY_UPPER(_pk, 1) > 1) THEN
19928         RAISE EXCEPTION 'Cannot change foreign key references in %.% because it has a composite primary key. Try setting the purge option. [xtuple: changefkeypointers, -4, %.%]',
19929                         _fk.schemaname, _fk.tablename, _fk.schemaname, _fk.tablename;
19930       END IF;
19931
19932       -- make the backup copy
19933       EXECUTE 'INSERT INTO mrgundo (
19934                      mrgundo_schema,      mrgundo_table,
19935                      mrgundo_pkey_col,    mrgundo_pkey_id,
19936                      mrgundo_col,         mrgundo_value,      mrgundo_type,
19937                      mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id
19938              ) SELECT ' || quote_literal(_fk.schemaname) || ', '
19939                         || quote_literal(_fk.tablename)  || ', '
19940                         || quote_literal(_pk[1])         || ', ' 
19941                         || _pk[1]                        || ', '
19942                         || quote_literal(_fk.attname)    || ', ' 
19943                         || _fk.attname                   || ', ' 
19944                         || quote_literal(_fk.typname)    || ', '
19945                         || quote_literal(pSchema)        || ', '
19946                         || quote_literal(pTable)         || ', '
19947                         || pTargetId                     || '
19948                  FROM ' || _fk.schemaname || '.' || _fk.tablename ||
19949               ' WHERE ('|| _fk.attname    || '=' || pSourceId || ');';
19950     END IF;
19951
19952     -- actually change the foreign keys to point to the desired base table record
19953     EXECUTE 'UPDATE '  || _fk.schemaname || '.' || _fk.tablename ||
19954               ' SET '  || _fk.attname    || '=' || pTargetId ||
19955             ' WHERE (' || _fk.attname    || '=' || pSourceId || ');';
19956
19957     GET DIAGNOSTICS _count1 = ROW_COUNT;
19958     _counter := _counter + _count1;
19959   END LOOP;
19960
19961   RETURN _counter;
19962 END;
19963 $_$;
19964
19965
19966 ALTER FUNCTION public.changefkeypointers(text, text, integer, integer, text[], boolean) OWNER TO admin;
19967
19968 --
19969 -- TOC entry 8948 (class 0 OID 0)
19970 -- Dependencies: 1193
19971 -- Name: FUNCTION changefkeypointers(text, text, integer, integer, text[], boolean); Type: COMMENT; Schema: public; Owner: admin
19972 --
19973
19974 COMMENT ON FUNCTION changefkeypointers(text, text, integer, integer, text[], boolean) IS 'Change the data in all tables with foreign key relationships so they point to the pSchema.pTable record with primary key pTargetId instead of the record with primary key pSourceId. Ignore any tables listed in pIgnore. If the final arg is TRUE, make a backup copy of the original data in the mrgundo table.';
19975
19976
19977 --
19978 -- TOC entry 1194 (class 1255 OID 146565732)
19979 -- Dependencies: 4536 8
19980 -- Name: changepoitemduedate(integer, date); Type: FUNCTION; Schema: public; Owner: admin
19981 --
19982
19983 CREATE FUNCTION changepoitemduedate(ppoitemid integer, pdate date) RETURNS integer
19984     LANGUAGE plpgsql
19985     AS $$
19986 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
19987 -- See www.xtuple.com/CPAL for the full text of the software license.
19988 BEGIN
19989
19990   RETURN changePoitemDueDate(pPoitemid, pDate, false);
19991
19992 END;
19993 $$;
19994
19995
19996 ALTER FUNCTION public.changepoitemduedate(ppoitemid integer, pdate date) OWNER TO admin;
19997
19998 --
19999 -- TOC entry 1195 (class 1255 OID 146565733)
20000 -- Dependencies: 4536 8
20001 -- Name: changepoitemduedate(integer, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
20002 --
20003
20004 CREATE FUNCTION changepoitemduedate(ppoitemid integer, pdate date, pbyso boolean) RETURNS integer
20005     LANGUAGE plpgsql
20006     AS $$
20007 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20008 -- See www.xtuple.com/CPAL for the full text of the software license.
20009 BEGIN
20010
20011   IF ( ( SELECT (poitem_status IN ('C'))
20012          FROM poitem
20013          WHERE (poitem_id=pPoitemid) ) ) THEN
20014     RETURN -1;
20015   END IF;
20016
20017   UPDATE poitem
20018   SET poitem_duedate=pDate
20019   WHERE (poitem_id=pPoitemid);
20020
20021   IF (pBySO) THEN
20022     --Generate the PoItemUpdatedBySo event
20023     PERFORM postEvent('PoItemUpdatedBySo', 'P', poitem_id,
20024                       itemsite_warehous_id,
20025                       (pohead_number || '-'|| poitem_linenumber || ': ' || item_number),
20026                       NULL, NULL, NULL, NULL)
20027     FROM poitem JOIN pohead ON (pohead_id=poitem_pohead_id)
20028                 JOIN itemsite ON (itemsite_id=poitem_itemsite_id)
20029                 JOIN item ON (item_id=itemsite_item_id)
20030     WHERE (poitem_id=pPoitemid)
20031       AND (poitem_duedate <= (CURRENT_DATE + itemsite_eventfence));
20032   END IF;
20033
20034   RETURN pPoitemid;
20035
20036 END;
20037 $$;
20038
20039
20040 ALTER FUNCTION public.changepoitemduedate(ppoitemid integer, pdate date, pbyso boolean) OWNER TO admin;
20041
20042 --
20043 -- TOC entry 1196 (class 1255 OID 146565734)
20044 -- Dependencies: 4536 8
20045 -- Name: changepoitemqty(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
20046 --
20047
20048 CREATE FUNCTION changepoitemqty(ppoitemid integer, pqty numeric) RETURNS integer
20049     LANGUAGE plpgsql
20050     AS $$
20051 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20052 -- See www.xtuple.com/CPAL for the full text of the software license.
20053 BEGIN
20054
20055   RETURN changePoitemQty(pPoitemid, pQty, false);
20056
20057 END;
20058 $$;
20059
20060
20061 ALTER FUNCTION public.changepoitemqty(ppoitemid integer, pqty numeric) OWNER TO admin;
20062
20063 --
20064 -- TOC entry 1197 (class 1255 OID 146565735)
20065 -- Dependencies: 4536 8
20066 -- Name: changepoitemqty(integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
20067 --
20068
20069 CREATE FUNCTION changepoitemqty(ppoitemid integer, pqty numeric, pbyso boolean) RETURNS integer
20070     LANGUAGE plpgsql
20071     AS $$
20072 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20073 -- See www.xtuple.com/CPAL for the full text of the software license.
20074 DECLARE
20075
20076 BEGIN
20077
20078   IF ( ( SELECT (poitem_status IN ('C'))
20079          FROM poitem
20080          WHERE (poitem_id=pPoitemid) ) ) THEN
20081     RETURN -1;
20082   END IF;
20083
20084   UPDATE poitem
20085   SET poitem_qty_ordered=pQty
20086   WHERE (poitem_id=pPoitemid);
20087
20088   IF (pBySO) THEN
20089     --Generate the PoItemUpdatedBySo event
20090     PERFORM postEvent('PoItemUpdatedBySo', 'P', poitem_id,
20091                       itemsite_warehous_id,
20092                       (pohead_number || '-'|| poitem_linenumber || ': ' || item_number),
20093                       NULL, NULL, NULL, NULL)
20094     FROM poitem JOIN pohead ON (pohead_id=poitem_pohead_id)
20095                 JOIN itemsite ON (itemsite_id=poitem_itemsite_id)
20096                 JOIN item ON (item_id=itemsite_item_id)
20097     WHERE (poitem_id=pPoitemid)
20098       AND (poitem_duedate <= (CURRENT_DATE + itemsite_eventfence));
20099   END IF;
20100
20101   RETURN pPoitemid;
20102
20103 END;
20104 $$;
20105
20106
20107 ALTER FUNCTION public.changepoitemqty(ppoitemid integer, pqty numeric, pbyso boolean) OWNER TO admin;
20108
20109 --
20110 -- TOC entry 1198 (class 1255 OID 146565736)
20111 -- Dependencies: 4536 8
20112 -- Name: changeprdate(integer, date); Type: FUNCTION; Schema: public; Owner: admin
20113 --
20114
20115 CREATE FUNCTION changeprdate(integer, date) RETURNS integer
20116     LANGUAGE plpgsql
20117     AS $_$
20118 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20119 -- See www.xtuple.com/CPAL for the full text of the software license.
20120 DECLARE
20121   pPrid ALIAS FOR $1;
20122   pDueDate ALIAS FOR $2;
20123
20124 BEGIN
20125
20126   UPDATE pr
20127   SET pr_duedate=pDueDate
20128   WHERE (pr_id=pPrid);
20129
20130   RETURN 0;
20131
20132 END;
20133 $_$;
20134
20135
20136 ALTER FUNCTION public.changeprdate(integer, date) OWNER TO admin;
20137
20138 --
20139 -- TOC entry 1199 (class 1255 OID 146565737)
20140 -- Dependencies: 4536 8
20141 -- Name: changeprqty(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
20142 --
20143
20144 CREATE FUNCTION changeprqty(integer, numeric) RETURNS boolean
20145     LANGUAGE plpgsql
20146     AS $_$
20147 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20148 -- See www.xtuple.com/CPAL for the full text of the software license.
20149 DECLARE
20150   pPrid ALIAS FOR $1;
20151   pQty ALIAS FOR $2;
20152
20153 BEGIN
20154
20155   UPDATE pr
20156   SET pr_qtyreq=pQty
20157   WHERE (pr_id=pPrid);
20158
20159   RETURN TRUE;
20160
20161 END;
20162 $_$;
20163
20164
20165 ALTER FUNCTION public.changeprqty(integer, numeric) OWNER TO admin;
20166
20167 --
20168 -- TOC entry 1200 (class 1255 OID 146565738)
20169 -- Dependencies: 4536 8
20170 -- Name: changeprqty(integer, date); Type: FUNCTION; Schema: public; Owner: admin
20171 --
20172
20173 CREATE FUNCTION changeprqty(integer, date) RETURNS integer
20174     LANGUAGE plpgsql
20175     AS $_$
20176 DECLARE
20177   pPrid ALIAS FOR $1;
20178   pDueDate ALIAS FOR $2;
20179
20180 BEGIN
20181
20182   UPDATE pr
20183   SET pr_duedate=pDueDate
20184   WHERE (pr_id=pPrid);
20185
20186   RETURN 0;
20187
20188 END;
20189 $_$;
20190
20191
20192 ALTER FUNCTION public.changeprqty(integer, date) OWNER TO admin;
20193
20194 --
20195 -- TOC entry 1201 (class 1255 OID 146565739)
20196 -- Dependencies: 4536 8
20197 -- Name: changepseudofkeypointers(text, text, text, integer, text, text, integer, text, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
20198 --
20199
20200 CREATE FUNCTION changepseudofkeypointers(text, text, text, integer, text, text, integer, text, text, boolean) RETURNS integer
20201     LANGUAGE plpgsql
20202     AS $_$
20203 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20204 -- See www.xtuple.com/CPAL for the full text of the software license.
20205 DECLARE
20206   pSchema       ALIAS FOR $1;
20207   pTable        ALIAS FOR $2;
20208   pFkeyCol      ALIAS FOR $3;
20209   pSourceId     ALIAS FOR $4;
20210   pBaseSchema   ALIAS FOR $5;
20211   pBaseTable    ALIAS FOR $6;
20212   pTargetId     ALIAS FOR $7;
20213   pTypeCol      ALIAS FOR $8;
20214   pType         ALIAS FOR $9;
20215   _purge        BOOLEAN := COALESCE($10, FALSE);
20216
20217   _counter      INTEGER := 0;
20218   _coltype      TEXT;
20219   _pk           TEXT[];
20220
20221 BEGIN
20222   IF (NOT _purge) THEN
20223     EXECUTE 'SELECT typname
20224                FROM pg_type
20225                JOIN pg_attribute ON (pg_type.oid=atttypid)
20226                JOIN pg_class     ON (attrelid=pg_class.oid)
20227                JOIN pg_namespace ON (relnamespace=pg_namespace.oid)
20228               WHERE (relname=' || quote_literal(pTable)   || ')
20229                 AND (nspname=' || quote_literal(pSchema)  || ')
20230                 AND (attname=' || quote_literal(pFkeyCol) || ')' INTO _coltype;
20231
20232     _pk := primaryKeyFields(pSchema, pTable);
20233     IF (ARRAY_UPPER(_pk, 1) > 1) THEN
20234        RAISE EXCEPTION 'Cannot change pseudo-foreign key references in %.% because it has a composite primary key. Try setting the purge option. [xtuple: changepseudofkeypointers, -1, %.%',
20235                         pSchema, pTable, pSchema, pTable;
20236     END IF;
20237
20238     EXECUTE 'INSERT INTO mrgundo (
20239                      mrgundo_schema,      mrgundo_table,
20240                      mrgundo_pkey_col,    mrgundo_pkey_id,
20241                      mrgundo_col,         mrgundo_value,      mrgundo_type,
20242                      mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id
20243            ) SELECT ' || quote_literal(pSchema)     || ', '
20244                       || quote_literal(pTable)      || ', '
20245                       || quote_literal(_pk[1])      || ', ' 
20246                       || quote_ident(_pk[1])        || ', '
20247                       || quote_literal(pFkeyCol)    || ', ' 
20248                       || quote_ident(pFkeyCol)      || ', ' 
20249                       || quote_literal(_coltype)    || ', '
20250                       || quote_literal(pBaseSchema) || ', '
20251                       || quote_literal(pBaseTable)  || ', '
20252                       || pTargetId                  || '
20253                FROM '  || quote_ident(pSchema)  || '.' || quote_ident(pTable) || '
20254               WHERE (('|| quote_ident(pFkeyCol) || '=' || pSourceId || ')
20255                  AND ('|| quote_ident(pTypeCol) || '=' || quote_literal(pType) || '));';
20256   END IF;
20257
20258   -- actually change the foreign keys to point to the desired base table record
20259   EXECUTE 'UPDATE '  || quote_ident(pSchema)  || '.' || quote_ident(pTable) ||
20260             ' SET '  || quote_ident(pFkeyCol) || '=' || pTargetId ||
20261           ' WHERE ((' || quote_ident(pFkeyCol) || '=' || pSourceId || ')
20262                AND (' || quote_ident(pTypeCol) || '=' || quote_literal(pType) || '));';
20263
20264   GET DIAGNOSTICS _counter = ROW_COUNT;
20265
20266   RETURN _counter;
20267 END;
20268 $_$;
20269
20270
20271 ALTER FUNCTION public.changepseudofkeypointers(text, text, text, integer, text, text, integer, text, text, boolean) OWNER TO admin;
20272
20273 --
20274 -- TOC entry 8949 (class 0 OID 0)
20275 -- Dependencies: 1201
20276 -- Name: FUNCTION changepseudofkeypointers(text, text, text, integer, text, text, integer, text, text, boolean); Type: COMMENT; Schema: public; Owner: admin
20277 --
20278
20279 COMMENT ON FUNCTION changepseudofkeypointers(text, text, text, integer, text, text, integer, text, text, boolean) IS 'Change the data in pSchema.pTable with a pseudo-foreign key relationship to another (unnamed) table. Make pSchema.pTable point to the record with primary key pTargetId instead of the record with primary key pSourceId. pSchema.pTable cannot have a true foreign key relationship because it holds data that can point to any of several tables. The pType value in the pTypeCol column describes which table the data refer to (e.g. "T" may indicate that the current record refers to a "cntct"). If the final arg is TRUE, make a backup copy of the data in the mrgundo table.';
20280
20281
20282 --
20283 -- TOC entry 1202 (class 1255 OID 146565740)
20284 -- Dependencies: 4536 8
20285 -- Name: changepurchasedropship(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
20286 --
20287
20288 CREATE FUNCTION changepurchasedropship(pcoitemid integer, ppoitemid integer, pdropship boolean) RETURNS integer
20289     LANGUAGE plpgsql
20290     AS $$
20291 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20292 -- See www.xtuple.com/CPAL for the full text of the software license.
20293 DECLARE
20294   _s RECORD;
20295   _w RECORD;
20296   _p RECORD;
20297   _result INTEGER;
20298   _poitemid INTEGER;
20299
20300 BEGIN
20301
20302   -- Check for existing poitem for this coitem
20303   SELECT * INTO _p
20304   FROM poitem JOIN pohead ON (pohead_id=poitem_pohead_id)
20305   WHERE (poitem_id=pPoitemId)
20306     AND (poitem_order_id=pCoitemId)
20307     AND (poitem_order_type='S');
20308   IF (NOT FOUND) THEN
20309     RAISE EXCEPTION 'Change Purchase Drop Ship PO not found';
20310   END IF;
20311
20312   SELECT * INTO _s
20313   FROM coitem JOIN cohead ON (cohead_id = coitem_cohead_id)
20314     LEFT OUTER JOIN shiptoinfo ON (cohead_shipto_id = shipto_id)
20315     LEFT OUTER JOIN cntct ON (shipto_cntct_id = cntct_id)
20316     LEFT OUTER JOIN addr ON (shipto_addr_id = addr_id)
20317   WHERE (coitem_id = pCoitemId);
20318   IF (NOT FOUND) THEN
20319     RETURN -1;
20320   END IF;
20321
20322   IF (_p.pohead_status != 'U') THEN
20323     RETURN -3;
20324   END IF;
20325
20326   SELECT deletePoitem(_p.poitem_id) INTO _result;
20327   IF (_result < 0) THEN
20328     RETURN _result;
20329   END IF;
20330
20331   SELECT createPurchaseToSale(_s.coitem_id, _p.poitem_itemsrc_id,
20332                               pDropShip, _s.coitem_qtyord,
20333                               _s.coitem_scheddate, _p.poitem_unitprice)
20334      INTO _poitemid;
20335   
20336   RETURN _poitemid;
20337
20338 END;
20339 $$;
20340
20341
20342 ALTER FUNCTION public.changepurchasedropship(pcoitemid integer, ppoitemid integer, pdropship boolean) OWNER TO admin;
20343
20344 --
20345 -- TOC entry 1203 (class 1255 OID 146565741)
20346 -- Dependencies: 4536 8
20347 -- Name: changewodates(integer, date, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
20348 --
20349
20350 CREATE FUNCTION changewodates(integer, date, date, boolean) RETURNS integer
20351     LANGUAGE plpgsql
20352     AS $_$
20353 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20354 -- See www.xtuple.com/CPAL for the full text of the software license.
20355 DECLARE 
20356   pWoid ALIAS FOR $1;
20357   pStartDate ALIAS FOR $2;
20358   pDueDate ALIAS FOR $3;
20359   changeChildren ALIAS FOR $4;
20360   _p RECORD;
20361   returnCode INTEGER;
20362   _vtemp NUMERIC;
20363
20364 BEGIN
20365
20366   SELECT wo_status, wo_startdate, itemsite_warehous_id INTO _p
20367   FROM wo
20368   Inner Join itemsite on
20369       wo_itemsite_id=itemsite_id
20370   WHERE (wo_id=pWoid);
20371
20372   IF (_p.wo_status = 'C') THEN 
20373     returnCode := 0;
20374
20375   ELSIF (_p.wo_status IN ('R','I')) THEN
20376     PERFORM postEvent('RWoDueDateRequestChange', 'W', wo_id,
20377                       itemsite_warehous_id, formatWoNumber(wo_id),
20378                       NULL, NULL, pDueDate, wo_duedate)
20379     FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
20380             JOIN item ON (item_id=itemsite_item_id)
20381     WHERE (wo_id=pWoid);
20382
20383      returnCode := 0;
20384
20385   END IF;
20386   
20387 --  Reschedule operations if routings enabled
20388   IF (fetchMetricBool('Routings')) THEN
20389
20390 --    Reschedule wooper
20391     IF (fetchMetricBool('UseSiteCalendar')) THEN
20392       UPDATE xtmfg.wooper
20393       SET wooper_scheduled = calculatenextworkingdate(itemsite_warehous_id,DATE(pStartDate),
20394                              CAST(calculateworkdays(itemsite_warehous_id, DATE(wo_startdate), DATE(wooper_scheduled)) as INTEGER))
20395       FROM wo JOIN itemsite ON (wo_itemsite_id=itemsite_id)
20396       WHERE ( (wooper_wo_id=wo_id)
20397         AND   (wo_id=pWoid) );
20398     ELSE
20399       UPDATE xtmfg.wooper
20400       SET wooper_scheduled = (wooper_scheduled::DATE + (pStartDate - wo_startdate))
20401       FROM wo
20402       WHERE ( (wooper_wo_id=wo_id)
20403         AND   (wo_id=pWoid) );
20404     END IF;
20405
20406 --    Reschedule any womatl that is linked to wooper items
20407 --    and is set to be scheduled with the wooper in question
20408     UPDATE womatl
20409     SET womatl_duedate=wooper_scheduled
20410     FROM xtmfg.wooper
20411     WHERE ( (womatl_schedatwooper)
20412      AND (womatl_wooper_id=wooper_id)
20413      AND (womatl_wo_id=pWoid) );
20414
20415   END IF;
20416
20417 -- Reschedule any womatl that is not linked to wooper items
20418   UPDATE womatl
20419   SET womatl_duedate=pStartDate
20420   WHERE ( (NOT womatl_schedatwooper)
20421    AND (womatl_wo_id=pWoid) );
20422
20423 --  Reschedule the W/O
20424   UPDATE wo
20425   SET wo_startdate=pStartDate,
20426       wo_duedate=pDueDate
20427   WHERE (wo_id=pWoid);
20428
20429 --  Do the same for the children
20430   IF (changeChildren) THEN
20431     SELECT MAX(changeWoDates(wo_id, (pStartDate - itemsite_leadtime), pStartDate, TRUE)) INTO returnCode
20432     FROM wo, itemsite
20433     WHERE ( (wo_itemsite_id=itemsite_id)
20434      AND (wo_ordtype='W')
20435      AND (wo_ordid=pWoid) );
20436   END IF;
20437
20438   IF (returnCode IS NULL) THEN
20439     returnCode := 0;
20440   END IF;
20441
20442   RETURN returnCode;
20443
20444 END;
20445 $_$;
20446
20447
20448 ALTER FUNCTION public.changewodates(integer, date, date, boolean) OWNER TO admin;
20449
20450 --
20451 -- TOC entry 1204 (class 1255 OID 146565742)
20452 -- Dependencies: 4536 8
20453 -- Name: changewoproject(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
20454 --
20455
20456 CREATE FUNCTION changewoproject(integer, integer, boolean) RETURNS integer
20457     LANGUAGE plpgsql
20458     AS $_$
20459 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20460 -- See www.xtuple.com/CPAL for the full text of the software license.
20461 DECLARE
20462   pWoid ALIAS FOR $1;
20463   pPrjid ALIAS FOR $2;
20464   changeChildren ALIAS FOR $3;
20465   woStatus CHAR(1);
20466   _result INTEGER;
20467
20468 BEGIN
20469
20470   SELECT wo_status INTO woStatus
20471   FROM wo
20472   WHERE (wo_id=pWoid);
20473
20474   UPDATE wo
20475   SET wo_prj_id=pPrjid
20476   WHERE (wo_id=pWoid);
20477
20478   IF (woStatus = 'E' AND changeChildren) THEN
20479     _result := ( SELECT MIN(changeWoProject(wo_id, pPrjid, TRUE))
20480                    FROM womatl, wo
20481                   WHERE ((womatl_itemsite_id=wo_itemsite_id)
20482                     AND (wo_ordtype='W')
20483                     AND (womatl_wo_id=pWoid)
20484                     AND (wo_ordid=pWoid)) );
20485
20486     UPDATE pr SET pr_prj_id=pPrjid
20487       FROM womatl
20488      WHERE ((womatl_wo_id=pWoid)
20489        AND  (pr_order_type='W')
20490        AND  (pr_order_id=womatl_id));
20491   ELSE
20492     _result = 1;
20493   END IF;
20494
20495   RETURN _result;
20496 END;
20497 $_$;
20498
20499
20500 ALTER FUNCTION public.changewoproject(integer, integer, boolean) OWNER TO admin;
20501
20502 --
20503 -- TOC entry 1205 (class 1255 OID 146565743)
20504 -- Dependencies: 4536 8
20505 -- Name: changewoqty(integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
20506 --
20507
20508 CREATE FUNCTION changewoqty(integer, numeric, boolean) RETURNS integer
20509     LANGUAGE plpgsql
20510     AS $_$
20511 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20512 -- See www.xtuple.com/CPAL for the full text of the software license.
20513 DECLARE
20514   pWoid ALIAS FOR $1;
20515   pQty ALIAS FOR $2;
20516   changeChildren ALIAS FOR $3;
20517   _r RECORD;
20518   _result INTEGER := 1;
20519
20520 BEGIN
20521
20522   SELECT wo_qtyord, wo_status, item_fractional INTO _r
20523   FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
20524           JOIN item ON (item_id=itemsite_item_id)
20525   WHERE (wo_id=pWoid);
20526
20527   IF (_r.wo_qtyord = pQty) THEN
20528     RETURN 0;
20529   END IF;
20530
20531   IF (NOT _r.wo_status IN ('O','E','R','I')) THEN
20532     RETURN 1;
20533   END IF;
20534
20535   IF (_r.wo_status IN ('R','I')) THEN
20536     PERFORM postEvent('RWoQtyRequestChange', 'W', wo_id,
20537                       itemsite_warehous_id, formatWoNumber(wo_id),
20538                       pQty, wo_qtyord, NULL, NULL)
20539     FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
20540             JOIN item ON (item_id=itemsite_item_id)
20541     WHERE (wo_id=pWoid);
20542
20543      _result = 0;
20544   END IF;
20545
20546   UPDATE wo
20547   SET wo_qtyord=roundQty(_r.item_fractional, pQty)
20548   WHERE (wo_id=pWoid);
20549
20550   UPDATE womatl
20551   SET womatl_qtyreq=(womatl_qtyfxd + wo_qtyord * womatl_qtyper) * (1 + womatl_scrap)
20552   FROM wo, itemsite
20553   WHERE ((womatl_wo_id=wo_id)
20554     AND  (womatl_itemsite_id=itemsite_id)
20555     AND  (wo_id=pWoid));
20556
20557   IF (fetchMetricBool('Routings')) THEN
20558
20559       UPDATE xtmfg.wooper
20560          SET wooper_rntime = CASE WHEN ((booitem_rnqtyper = 0) OR (booitem_invproduomratio = 0)) THEN 0
20561                                   WHEN (NOT booitem_rnrpt) THEN 0
20562                                   ELSE ( ( booitem_rntime /
20563                                            booitem_rnqtyper /
20564                                            booitem_invproduomratio ) * wo_qtyord )
20565                              END
20566         FROM xtmfg.booitem, wo
20567        WHERE ((wooper_wo_id=wo_id)
20568          AND  (wooper_booitem_id=booitem_id)
20569          AND  (wo_id=pWoid));
20570   END IF;
20571
20572   IF (changeChildren) THEN
20573     _result := ( SELECT MIN(changeWoQty(wo_id, womatl_qtyreq, TRUE))
20574                  FROM womatl, wo
20575                  WHERE ((womatl_itemsite_id=wo_itemsite_id)
20576                   AND (wo_ordtype='W')
20577                   AND (womatl_wo_id=pWoid)
20578                   AND (wo_ordid=pWoid)) );
20579   END IF;
20580
20581   RETURN _result;
20582 END;
20583 $_$;
20584
20585
20586 ALTER FUNCTION public.changewoqty(integer, numeric, boolean) OWNER TO admin;
20587
20588 --
20589 -- TOC entry 1206 (class 1255 OID 146565744)
20590 -- Dependencies: 4536 8
20591 -- Name: characteristicstostring(text, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
20592 --
20593
20594 CREATE FUNCTION characteristicstostring(text, integer, text, text) RETURNS text
20595     LANGUAGE plpgsql
20596     AS $_$
20597 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20598 -- See www.xtuple.com/CPAL for the full text of the software license.
20599 DECLARE
20600   pTargetType ALIAS FOR $1;
20601   pTargetId ALIAS FOR $2;
20602   pValKeySep ALIAS FOR $3;
20603   pPairSep ALIAS FOR $4;
20604   _string TEXT := '';
20605   _extra BOOLEAN := false;
20606   _r RECORD;
20607 BEGIN
20608   FOR _r IN SELECT char_name, charass_value
20609               FROM charass, char
20610              WHERE ((charass_char_id=char_id)
20611                AND  (charass_target_type=pTargetType)
20612                AND  (charass_target_id=pTargetId)) LOOP
20613     IF(_extra) THEN
20614       _string := _string || pPairSep;
20615     END IF;
20616     _extra := true;
20617
20618     _string := _string || _r.char_name || pValKeySep || _r.charass_value;
20619   END LOOP;
20620
20621   RETURN _string;
20622 END;
20623 $_$;
20624
20625
20626 ALTER FUNCTION public.characteristicstostring(text, integer, text, text) OWNER TO admin;
20627
20628 --
20629 -- TOC entry 1191 (class 1255 OID 146565745)
20630 -- Dependencies: 4536 8
20631 -- Name: checkcreditmemositeprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
20632 --
20633
20634 CREATE FUNCTION checkcreditmemositeprivs(integer) RETURNS boolean
20635     LANGUAGE plpgsql
20636     AS $_$
20637 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20638 -- See www.xtuple.com/CPAL for the full text of the software license.
20639 DECLARE
20640   pCmheadid ALIAS FOR $1;
20641   _check    BOOLEAN;
20642   _result   INTEGER;
20643
20644 BEGIN
20645
20646   IF (NOT fetchMetricBool('MultiWhs')) THEN
20647     RETURN true;
20648   END IF;
20649
20650   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
20651     RETURN true;
20652   END IF;
20653
20654   SELECT COALESCE(COUNT(*), 0) INTO _result
20655     FROM ( SELECT cmitem_id
20656              FROM cmitem JOIN itemsite ON (itemsite_id=cmitem_itemsite_id)
20657             WHERE ( (cmitem_cmhead_id=pCmheadid)
20658               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
20659                                                     FROM usrsite
20660                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
20661          ) AS data;
20662   IF (_result > 0) THEN
20663     RETURN false;
20664   END IF;
20665
20666   RETURN true;
20667 END;
20668 $_$;
20669
20670
20671 ALTER FUNCTION public.checkcreditmemositeprivs(integer) OWNER TO admin;
20672
20673 --
20674 -- TOC entry 1207 (class 1255 OID 146565746)
20675 -- Dependencies: 2660 4536 8
20676 -- Name: checkdetailformatted(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
20677 --
20678
20679 CREATE FUNCTION checkdetailformatted(integer, integer) RETURNS SETOF checkdata
20680     LANGUAGE plpgsql
20681     AS $_$
20682 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20683 -- See www.xtuple.com/CPAL for the full text of the software license.
20684 DECLARE
20685   pCheckheadid ALIAS FOR $1;
20686   pMaxLines ALIAS FOR $2;
20687   _row checkdata%ROWTYPE;
20688   _checkhead RECORD;
20689   _checkdetail RECORD;
20690   _rowcount INTEGER := 0;
20691   _page INTEGER := 1;
20692   _docnumber TEXT := '';
20693   _docreference TEXT := '';
20694   _docdate TEXT := '';
20695   _docamount TEXT := '';
20696   _docdiscount TEXT := '';
20697   _docnetamount TEXT := '';
20698 BEGIN
20699
20700 -- Check header information
20701   SELECT checkhead_number AS checknumber,
20702          INITCAP(spellAmount(checkhead_amount, curr_id)) AS checkwords,
20703          formatDate(checkhead_checkdate) AS checkdate,
20704          formatMoney(checkhead_amount) AS checkamount,
20705          curr_symbol AS checkcurrsymbol,
20706          curr_abbr AS checkcurrabbr,
20707          curr_name AS checkcurrname,
20708          CASE WHEN checkhead_recip_type = 'C' THEN (SELECT cust_name
20709                                                       FROM custinfo
20710                                                      WHERE cust_id=checkhead_recip_id)
20711               WHEN checkhead_recip_type = 'T' THEN (SELECT taxauth_name
20712                                                       FROM taxauth
20713                                                      WHERE taxauth_id=checkhead_recip_id)
20714               WHEN checkhead_recip_type = 'V' THEN
20715                                   COALESCE((SELECT vendaddr_name
20716                                               FROM vendaddrinfo
20717                                              WHERE((UPPER(vendaddr_code)='REMIT')
20718                                                AND (vendaddr_vend_id=checkhead_recip_id))),
20719                                            (SELECT vend_name
20720                                               FROM vendinfo
20721                                              WHERE(vend_id=checkhead_recip_id)))
20722          END AS checkpayto,
20723          formatAddr(CASE WHEN checkhead_recip_type = 'C' THEN
20724                                                   (SELECT cntct_addr_id
20725                                                    FROM cntct, custinfo
20726                                                     WHERE((cust_cntct_id=cntct_id)
20727                                                       AND (cust_id=checkhead_recip_id)))
20728                          WHEN checkhead_recip_type = 'T' THEN 
20729                                                   (SELECT taxauth_addr_id
20730                                                      FROM taxauth
20731                                                     WHERE(taxauth_id=checkhead_recip_id))
20732                          WHEN checkhead_recip_type = 'V' THEN
20733                                  COALESCE((SELECT vendaddr_addr_id
20734                                              FROM vendaddrinfo
20735                                             WHERE((UPPER(vendaddr_code)='REMIT')
20736                                               AND (vendaddr_vend_id=checkhead_recip_id))),
20737                                           (SELECT vend_addr_id
20738                                              FROM vendinfo
20739                                             WHERE(vend_id=checkhead_recip_id)))
20740                     END) AS checkaddress,
20741          checkhead_for AS checkmemo
20742     INTO _checkhead
20743     FROM checkhead, curr_symbol
20744    WHERE((checkhead_curr_id = curr_id)
20745      AND (checkhead_id=pCheckheadid) );
20746   IF (NOT FOUND) THEN
20747     RETURN;
20748   END IF;
20749
20750   _row.checkdata_page := _page;
20751   _row.checkdata_checknumber := _checkhead.checknumber;
20752   _row.checkdata_checkwords := _checkhead.checkwords;
20753   _row.checkdata_checkdate := _checkhead.checkdate;
20754   _row.checkdata_checkamount := _checkhead.checkamount;
20755   _row.checkdata_checkcurrsymbol := _checkhead.checkcurrsymbol;
20756   _row.checkdata_checkcurrabbr := _checkhead.checkcurrabbr;
20757   _row.checkdata_checkcurrname := _checkhead.checkcurrname;
20758   _row.checkdata_checkpayto := _checkhead.checkpayto;
20759   _row.checkdata_checkaddress := _checkhead.checkaddress;
20760   _row.checkdata_checkmemo := _checkhead.checkmemo;
20761
20762 -- Check item details
20763   FOR _checkdetail IN 
20764   SELECT  --VOUCHER-------------
20765     1 AS ord,
20766     1 AS sequence_value,
20767     checkitem_invcnumber,
20768     checkitem_ponumber,
20769     formatMoney(checkitem_amount) AS docnetamount,
20770     'Invoice#: ' || vohead_invcnumber AS docnumber,
20771     formatDate(vohead_docdate) AS docdate,
20772     vohead_reference AS docreference,
20773     'Voucher: ' || checkitem_vouchernumber AS vouchernumber,
20774     formatMoney(apopen_amount) AS docamount,
20775     formatMoney(checkitem_discount) AS docdiscount
20776   FROM checkitem, vohead, apopen
20777   WHERE ((checkitem_checkhead_id=pCheckheadid)
20778     AND  (checkitem_vouchernumber = vohead_number)
20779     AND  (apopen_docnumber = checkitem_vouchernumber)
20780     AND  (apopen_doctype = 'V'))
20781   
20782   UNION
20783   
20784   SELECT --DEBIT MEMO -------------------------
20785     2 AS ord,
20786     1 AS sequence_value,
20787     checkitem_invcnumber,
20788     checkitem_ponumber,
20789     formatMoney(checkitem_amount) AS f_amount,
20790     'Debit Memo PO#: ' || checkitem_ponumber AS doc_number,
20791     ''  AS f_docdate,
20792     'Debit Memo: ' || checkitem_vouchernumber AS doc_reference,
20793     checkitem_vouchernumber AS vouchernumber,
20794     formatMoney(apopen_amount) AS amount,
20795     formatMoney(checkitem_discount) AS disc_cred
20796   FROM checkitem, apopen
20797   WHERE ((checkitem_checkhead_id=pCheckheadid)
20798     AND  (checkitem_apopen_id = apopen_id)
20799     AND  (apopen_doctype = 'D'))
20800   
20801   UNION
20802   
20803   SELECT --CREDIT MEMO -------------------------
20804     2 AS ord,
20805     1 AS sequence_value,
20806     checkitem_invcnumber,
20807     checkitem_ponumber,
20808     formatMoney(checkitem_amount * -1.0) AS f_amount,
20809     'Credit Memo PO#: ' || checkitem_ponumber AS doc_number,
20810     ''  AS f_docdate,
20811     'Credit Memo: ' || checkitem_vouchernumber AS doc_reference,
20812     checkitem_vouchernumber AS vouchernumber,
20813     '' AS amount,
20814     formatMoney(checkitem_amount) AS disc_cred
20815   FROM checkitem, apopen
20816   WHERE ((checkitem_checkhead_id=pCheckheadid)
20817     AND  (checkitem_apopen_id = apopen_id)
20818     AND  (apopen_doctype = 'C'))
20819   
20820   UNION
20821   
20822   SELECT --CREDITs FOR VOUCHERS-----------------
20823     3 AS ord,
20824     1 AS sequence_value,
20825     checkitem_invcnumber,
20826     checkitem_ponumber,
20827     formatMoney(checkitem_amount) AS f_amount,
20828     'Invoice#: ' || vohead_invcnumber AS doc_number,
20829     formatDate(vohead_docdate) AS f_docdate,
20830     'Credit Applied: ' || apapply_source_doctype || ' ' ||
20831                           apapply_source_docnumber AS doc_reference,
20832     'Voucher: ' || checkitem_vouchernumber AS vouchernumber,
20833     '' AS amount,
20834     formatMoney((apapply_amount)) AS disc_cred
20835   FROM checkitem, vohead, apapply
20836   WHERE ((checkitem_checkhead_id=pCheckheadid)
20837     AND  (checkitem_vouchernumber = vohead_number)
20838     AND  (apapply_target_docnumber = checkitem_vouchernumber)
20839     AND  (apapply_target_doctype = 'V')
20840     AND  (apapply_source_doctype = 'C'))
20841   
20842   UNION 
20843   
20844   SELECT --CREDITs FOR DEBIT MEMOS-----------
20845     3 AS ord,
20846     1 AS sequence_value,
20847     checkitem_invcnumber,
20848     checkitem_ponumber,
20849     formatMoney(checkitem_amount) AS f_amount,
20850     'Debit Memo PO#: ' || checkitem_ponumber AS doc_number,
20851     '' AS f_docdate,
20852     'Credit Applied: ' || apapply_source_doctype || ' ' ||
20853                           apapply_source_docnumber AS doc_reference,
20854     'Debit Memo: ' || checkitem_vouchernumber AS vouchernumber,
20855     '' AS amount,
20856     formatMoney((apapply_amount)) AS disc_cred
20857   FROM checkitem, apopen, apapply
20858   WHERE ((checkitem_checkhead_id=pCheckheadid)
20859     AND  (checkitem_vouchernumber = apopen_docnumber)
20860     AND  (apopen_doctype = 'D')
20861     AND  (apapply_target_docnumber = checkitem_vouchernumber)
20862     AND  (apapply_target_doctype = 'D')
20863     AND  (apapply_source_doctype = 'C'))
20864   
20865   UNION 
20866   
20867   SELECT --NON-VENDOR-----------------------
20868     4 AS ord,
20869     1 AS sequence_value,
20870     checkitem_invcnumber,
20871     checkitem_ponumber,
20872     formatMoney(checkitem_amount) AS f_amount,
20873     checkitem_invcnumber AS doc_number,
20874     formatDate(checkitem_docdate) AS f_docdate,
20875     '' AS doc_reference,
20876     '' AS vouchernumber,
20877     '' AS amount,
20878     '' AS disc_cred
20879   FROM checkhead LEFT OUTER JOIN
20880        checkitem ON (checkitem_checkhead_id=checkhead_id)
20881   WHERE ((checkhead_id=pCheckheadid) 
20882     AND  (checkhead_recip_type != 'V')) LOOP
20883     IF (_rowcount = pMaxLines) THEN
20884       _row.checkdata_docnumber := _docnumber;
20885       _row.checkdata_docreference := _docreference;
20886       _row.checkdata_docdate := _docdate;
20887       _row.checkdata_docamount := _docamount;
20888       _row.checkdata_docdiscount := _docdiscount;
20889       _row.checkdata_docnetamount := _docnetamount;
20890       RETURN NEXT _row;
20891
20892 -- update/reset some variables
20893       _rowcount = 0;
20894       _page := _page + 1;
20895       _docnumber := '';
20896       _docreference := '';
20897       _docdate := '';
20898       _docamount := '';
20899       _docdiscount := '';
20900       _docnetamount := '';
20901
20902       _row.checkdata_page := _page;
20903       _row.checkdata_checknumber := _checkhead.checknumber;
20904       _row.checkdata_checkwords := 'VOID VOID PAGE '||_page||' OF CHECK #'||_checkhead.checknumber||' VOID VOID';
20905       _row.checkdata_checkdate := 'VOID VOID VOID';
20906       _row.checkdata_checkamount := 'VOID VOID VOID';
20907       --_row.checkdata_checkcurrsymbol := _checkhead.checkcurrsymbol;
20908       --_row.checkdata_checkcurrabbr := _checkhead.checkcurrabbr;
20909       --_row.checkdata_checkcurrname := _checkhead.checkcurrname;
20910       _row.checkdata_checkpayto := 'VOID VOID VOID';
20911       --_row.checkdata_checkaddress := _checkhead.checkaddress;
20912       _row.checkdata_checkmemo := 'VOID VOID PAGE '||_page||' OF CHECK #'||_checkhead.checknumber||' VOID VOID';
20913     END IF;
20914
20915     _rowcount := _rowcount + 1;
20916     _docnumber := _docnumber || _checkdetail.docnumber || E'\n';
20917     _docreference := _docreference || _checkdetail.docreference || E'\n';
20918     _docdate := _docdate || _checkdetail.docdate || E'\n';
20919     _docamount := _docamount || _checkdetail.docamount || E'\n';
20920     _docdiscount := _docdiscount || _checkdetail.docdiscount || E'\n';
20921     _docnetamount := _docnetamount || _checkdetail.docnetamount || E'\n';
20922   END LOOP;
20923
20924   _row.checkdata_docnumber := _docnumber;
20925   _row.checkdata_docreference := _docreference;
20926   _row.checkdata_docdate := _docdate;
20927   _row.checkdata_docamount := _docamount;
20928   _row.checkdata_docdiscount := _docdiscount;
20929   _row.checkdata_docnetamount := _docnetamount;
20930
20931   RETURN NEXT _row;
20932   RETURN;
20933 END;
20934 $_$;
20935
20936
20937 ALTER FUNCTION public.checkdetailformatted(integer, integer) OWNER TO admin;
20938
20939 --
20940 -- TOC entry 1208 (class 1255 OID 146565748)
20941 -- Dependencies: 4536 8
20942 -- Name: checkinvoicesiteprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
20943 --
20944
20945 CREATE FUNCTION checkinvoicesiteprivs(integer) RETURNS boolean
20946     LANGUAGE plpgsql STABLE
20947     AS $_$
20948 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20949 -- See www.xtuple.com/CPAL for the full text of the software license.
20950 DECLARE
20951   pInvcheadid ALIAS FOR $1;
20952   _check    BOOLEAN;
20953   _result   INTEGER;
20954
20955 BEGIN
20956
20957   IF (NOT fetchMetricBool('MultiWhs')) THEN
20958     RETURN true;
20959   END IF;
20960
20961   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
20962     RETURN true;
20963   END IF;
20964
20965   SELECT COALESCE(COUNT(*), 0) INTO _result
20966     FROM ( SELECT invcitem_id
20967              FROM invcitem
20968             WHERE ( (invcitem_invchead_id=pInvcheadid)
20969               AND   (invcitem_warehous_id <> -1)
20970               AND   (invcitem_warehous_id NOT IN (SELECT usrsite_warehous_id
20971                                                     FROM usrsite
20972                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
20973          ) AS data;
20974   IF (_result > 0) THEN
20975     RETURN false;
20976   END IF;
20977
20978   RETURN true;
20979 END;
20980 $_$;
20981
20982
20983 ALTER FUNCTION public.checkinvoicesiteprivs(integer) OWNER TO admin;
20984
20985 --
20986 -- TOC entry 1209 (class 1255 OID 146565749)
20987 -- Dependencies: 4536 8
20988 -- Name: checkpositeprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
20989 --
20990
20991 CREATE FUNCTION checkpositeprivs(integer) RETURNS boolean
20992     LANGUAGE plpgsql STABLE
20993     AS $_$
20994 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
20995 -- See www.xtuple.com/CPAL for the full text of the software license.
20996 DECLARE
20997   pPoheadid ALIAS FOR $1;
20998   _check    BOOLEAN;
20999   _result   INTEGER;
21000
21001 BEGIN
21002
21003   IF (NOT fetchMetricBool('MultiWhs')) THEN
21004     RETURN true;
21005   END IF;
21006
21007   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
21008     RETURN true;
21009   END IF;
21010
21011   SELECT COALESCE(COUNT(*), 0) INTO _result
21012     FROM ( SELECT poitem_id
21013              FROM poitem, itemsite
21014             WHERE ( (poitem_pohead_id=pPoheadid)
21015               AND   (poitem_itemsite_id=itemsite_id)
21016               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
21017                                                     FROM usrsite
21018                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
21019            UNION
21020            SELECT pohead_warehous_id
21021              FROM pohead
21022             WHERE ( (pohead_id=pPoheadid)
21023               AND   (pohead_warehous_id NOT IN (SELECT usrsite_warehous_id
21024                                                   FROM usrsite
21025                                                  WHERE (usrsite_username=getEffectiveXtUser()))) )
21026          ) AS data;
21027   IF (_result > 0) THEN
21028     RETURN false;
21029   END IF;
21030
21031   RETURN true;
21032 END;
21033 $_$;
21034
21035
21036 ALTER FUNCTION public.checkpositeprivs(integer) OWNER TO admin;
21037
21038 --
21039 -- TOC entry 1210 (class 1255 OID 146565750)
21040 -- Dependencies: 4536 8
21041 -- Name: checkprivilege(text); Type: FUNCTION; Schema: public; Owner: admin
21042 --
21043
21044 CREATE FUNCTION checkprivilege(text) RETURNS boolean
21045     LANGUAGE plpgsql STABLE
21046     AS $_$
21047 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21048 -- See www.xtuple.com/CPAL for the full text of the software license.
21049 DECLARE
21050   pPrivilege ALIAS FOR $1;
21051   _result TEXT;
21052 BEGIN
21053   SELECT priv_id INTO _result
21054     FROM priv, grppriv, usrgrp
21055    WHERE((usrgrp_grp_id=grppriv_grp_id)
21056      AND (grppriv_priv_id=priv_id)
21057      AND (priv_name=pPrivilege)
21058      AND (usrgrp_username=getEffectiveXtUser()));
21059   IF (FOUND) THEN
21060     RETURN true;
21061   END IF;
21062
21063   SELECT priv_id INTO _result
21064   FROM priv, usrpriv
21065   WHERE ((priv_id=usrpriv_priv_id)
21066   AND (priv_name=pPrivilege)
21067   AND (usrpriv_username=getEffectiveXtUser()));
21068   
21069   IF (FOUND) THEN
21070     RETURN true;
21071   ELSE
21072     RETURN false;
21073   END IF;
21074 END;
21075 $_$;
21076
21077
21078 ALTER FUNCTION public.checkprivilege(text) OWNER TO admin;
21079
21080 --
21081 -- TOC entry 1211 (class 1255 OID 146565751)
21082 -- Dependencies: 4536 8
21083 -- Name: checkquotesiteprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
21084 --
21085
21086 CREATE FUNCTION checkquotesiteprivs(integer) RETURNS boolean
21087     LANGUAGE plpgsql STABLE
21088     AS $_$
21089 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21090 -- See www.xtuple.com/CPAL for the full text of the software license.
21091 DECLARE
21092   pQuheadid ALIAS FOR $1;
21093
21094 BEGIN
21095
21096   RETURN checkQuoteSitePrivs(pQuheadid, NULL);
21097
21098 END;
21099 $_$;
21100
21101
21102 ALTER FUNCTION public.checkquotesiteprivs(integer) OWNER TO admin;
21103
21104 --
21105 -- TOC entry 1212 (class 1255 OID 146565752)
21106 -- Dependencies: 4536 8
21107 -- Name: checkquotesiteprivs(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
21108 --
21109
21110 CREATE FUNCTION checkquotesiteprivs(integer, integer) RETURNS boolean
21111     LANGUAGE plpgsql STABLE
21112     AS $_$
21113 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21114 -- See www.xtuple.com/CPAL for the full text of the software license.
21115 DECLARE
21116   pQuheadid ALIAS FOR $1;
21117   pWarehousid ALIAS FOR $2;
21118   _result   INTEGER := 0;
21119
21120 BEGIN
21121
21122 --  RAISE NOTICE 'checkQuoteSitePrivs, pQuheadid = %', pQuheadid;
21123 --  RAISE NOTICE 'checkQuoteSitePrivs, pWarehousid = %', pWarehousid;
21124
21125   IF (NOT fetchMetricBool('MultiWhs')) THEN
21126     RETURN true;
21127   END IF;
21128
21129   IF ( (NOT fetchUsrPrefBool('selectedSites')) AND (pWarehousid IS NULL) ) THEN
21130     RETURN true;
21131   END IF;
21132
21133   IF (pWarehousid IS NULL) THEN
21134     SELECT COALESCE(COUNT(*), 0) INTO _result
21135     FROM quitem JOIN itemsite ON (itemsite_id=quitem_itemsite_id)
21136                 JOIN site() ON (warehous_id=itemsite_warehous_id)
21137     WHERE (quitem_quhead_id=pQuheadid);
21138   ELSE
21139     SELECT COALESCE(COUNT(*), 0) INTO _result
21140     FROM quitem JOIN itemsite ON (itemsite_id=quitem_itemsite_id)
21141                 JOIN site() ON (warehous_id=itemsite_warehous_id)
21142     WHERE ( (quitem_quhead_id=pQuheadid)
21143       AND   (itemsite_warehous_id=pWarehousid) );
21144   END IF;
21145
21146   IF (_result > 0) THEN
21147     RETURN true;
21148   END IF;
21149
21150   RETURN false;
21151
21152 END;
21153 $_$;
21154
21155
21156 ALTER FUNCTION public.checkquotesiteprivs(integer, integer) OWNER TO admin;
21157
21158 --
21159 -- TOC entry 1213 (class 1255 OID 146565753)
21160 -- Dependencies: 4536 8
21161 -- Name: checkrasiteprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
21162 --
21163
21164 CREATE FUNCTION checkrasiteprivs(integer) RETURNS boolean
21165     LANGUAGE plpgsql STABLE
21166     AS $_$
21167 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21168 -- See www.xtuple.com/CPAL for the full text of the software license.
21169 DECLARE
21170   pRaheadid ALIAS FOR $1;
21171   _check    BOOLEAN;
21172   _result   INTEGER;
21173
21174 BEGIN
21175
21176   IF (NOT fetchMetricBool('MultiWhs')) THEN
21177     RETURN true;
21178   END IF;
21179
21180   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
21181     RETURN true;
21182   END IF;
21183
21184   SELECT COALESCE(COUNT(*), 0) INTO _result
21185     FROM ( SELECT raitem_id
21186              FROM raitem, itemsite
21187             WHERE ( (raitem_rahead_id=pRaheadid)
21188               AND   (raitem_itemsite_id=itemsite_id)
21189               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
21190                                                     FROM usrsite
21191                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
21192            UNION
21193            SELECT raitem_id
21194              FROM raitem, itemsite
21195             WHERE ( (raitem_rahead_id=pRaheadid)
21196               AND   (raitem_coitem_itemsite_id=itemsite_id)
21197               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
21198                                                   FROM usrsite
21199                                                  WHERE (usrsite_username=getEffectiveXtUser()))) )
21200          ) AS data;
21201   IF (_result > 0) THEN
21202     RETURN false;
21203   END IF;
21204
21205   RETURN true;
21206 END;
21207 $_$;
21208
21209
21210 ALTER FUNCTION public.checkrasiteprivs(integer) OWNER TO admin;
21211
21212 --
21213 -- TOC entry 1216 (class 1255 OID 146565754)
21214 -- Dependencies: 4536 8
21215 -- Name: checkshipmentsiteprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
21216 --
21217
21218 CREATE FUNCTION checkshipmentsiteprivs(integer) RETURNS boolean
21219     LANGUAGE plpgsql
21220     AS $_$
21221 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21222 -- See www.xtuple.com/CPAL for the full text of the software license.
21223 DECLARE
21224   pShipheadid ALIAS FOR $1;
21225   _check    BOOLEAN;
21226   _result   INTEGER;
21227
21228 BEGIN
21229
21230   IF (NOT fetchMetricBool('MultiWhs')) THEN
21231     RETURN true;
21232   END IF;
21233
21234   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
21235     RETURN true;
21236   END IF;
21237
21238   SELECT COALESCE(COUNT(*), 0) INTO _result
21239     FROM ( SELECT coitem_id
21240              FROM shipitem, coitem, itemsite
21241             WHERE ( (shipitem_shiphead_id=pShipheadid)
21242               AND   (coitem_id=shipitem_orderitem_id)
21243               AND   (coitem_itemsite_id=itemsite_id)
21244               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
21245                                                     FROM usrsite
21246                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
21247            UNION
21248            SELECT cohead_warehous_id
21249              FROM shipitem, coitem, cohead
21250             WHERE ( (shipitem_shiphead_id=pShipheadid)
21251               AND   (coitem_id=shipitem_orderitem_id)
21252               AND   (cohead_id=coitem_cohead_id)
21253               AND   (cohead_warehous_id NOT IN (SELECT usrsite_warehous_id
21254                                                   FROM usrsite
21255                                                  WHERE (usrsite_username=getEffectiveXtUser()))) )
21256          ) AS data;
21257   IF (_result > 0) THEN
21258     RETURN false;
21259   END IF;
21260
21261   RETURN true;
21262 END;
21263 $_$;
21264
21265
21266 ALTER FUNCTION public.checkshipmentsiteprivs(integer) OWNER TO admin;
21267
21268 --
21269 -- TOC entry 1217 (class 1255 OID 146565755)
21270 -- Dependencies: 4536 8
21271 -- Name: checksositeprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
21272 --
21273
21274 CREATE FUNCTION checksositeprivs(integer) RETURNS boolean
21275     LANGUAGE plpgsql STABLE
21276     AS $_$
21277 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21278 -- See www.xtuple.com/CPAL for the full text of the software license.
21279 DECLARE
21280   pSoheadid ALIAS FOR $1;
21281   _check    BOOLEAN;
21282   _result   INTEGER;
21283
21284 BEGIN
21285
21286   IF (NOT fetchMetricBool('MultiWhs')) THEN
21287     RETURN true;
21288   END IF;
21289
21290   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
21291     RETURN true;
21292   END IF;
21293
21294   SELECT COALESCE(COUNT(*), 0) INTO _result
21295     FROM ( SELECT coitem_id
21296              FROM coitem, itemsite
21297             WHERE ( (coitem_cohead_id=pSoheadid)
21298               AND   (coitem_itemsite_id=itemsite_id)
21299               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
21300                                                     FROM usrsite
21301                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
21302            UNION
21303            SELECT cohead_warehous_id
21304              FROM cohead
21305             WHERE ( (cohead_id=pSoheadid)
21306               AND   (cohead_warehous_id NOT IN (SELECT usrsite_warehous_id
21307                                                   FROM usrsite
21308                                                  WHERE (usrsite_username=getEffectiveXtUser()))) )
21309          ) AS data;
21310   IF (_result > 0) THEN
21311     RETURN false;
21312   END IF;
21313
21314   RETURN true;
21315 END;
21316 $_$;
21317
21318
21319 ALTER FUNCTION public.checksositeprivs(integer) OWNER TO admin;
21320
21321 --
21322 -- TOC entry 1218 (class 1255 OID 146565756)
21323 -- Dependencies: 4536 8
21324 -- Name: checkvouchersiteprivs(integer); Type: FUNCTION; Schema: public; Owner: admin
21325 --
21326
21327 CREATE FUNCTION checkvouchersiteprivs(integer) RETURNS boolean
21328     LANGUAGE plpgsql STABLE
21329     AS $_$
21330 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21331 -- See www.xtuple.com/CPAL for the full text of the software license.
21332 DECLARE
21333   pVoheadid ALIAS FOR $1;
21334   _check    BOOLEAN;
21335   _result   INTEGER;
21336
21337 BEGIN
21338
21339   IF (NOT fetchMetricBool('MultiWhs')) THEN
21340     RETURN true;
21341   END IF;
21342
21343   IF (NOT fetchUsrPrefBool('selectedSites')) THEN
21344     RETURN true;
21345   END IF;
21346
21347   SELECT COALESCE(COUNT(*), 0) INTO _result
21348     FROM ( SELECT voitem_id
21349              FROM voitem, poitem, itemsite
21350             WHERE ( (voitem_vohead_id=pVoheadid)
21351               AND   (poitem_id=voitem_poitem_id)
21352               AND   (poitem_itemsite_id=itemsite_id)
21353               AND   (itemsite_warehous_id NOT IN (SELECT usrsite_warehous_id
21354                                                     FROM usrsite
21355                                                    WHERE (usrsite_username=getEffectiveXtUser()))) )
21356            UNION
21357            SELECT pohead_warehous_id
21358              FROM vohead, pohead
21359             WHERE ( (vohead_id=pVoheadid)
21360               AND   (pohead_id=vohead_pohead_id)
21361               AND   (pohead_warehous_id NOT IN (SELECT usrsite_warehous_id
21362                                                   FROM usrsite
21363                                                  WHERE (usrsite_username=getEffectiveXtUser()))) )
21364          ) AS data;
21365   IF (_result > 0) THEN
21366     RETURN false;
21367   END IF;
21368
21369   RETURN true;
21370 END;
21371 $_$;
21372
21373
21374 ALTER FUNCTION public.checkvouchersiteprivs(integer) OWNER TO admin;
21375
21376 --
21377 -- TOC entry 1219 (class 1255 OID 146565757)
21378 -- Dependencies: 4536 8
21379 -- Name: clearnumberissue(text, integer); Type: FUNCTION; Schema: public; Owner: admin
21380 --
21381
21382 CREATE FUNCTION clearnumberissue(psequence text, pnumber integer) RETURNS boolean
21383     LANGUAGE plpgsql
21384     AS $$
21385 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21386 -- See www.xtuple.com/CPAL for the full text of the software license.
21387 DECLARE
21388   __seqiss      seqiss[];
21389   __newiss      seqiss[] := ARRAY[]::seqiss[];
21390   _i            INTEGER;
21391   _result       BOOLEAN := FALSE;
21392   _interval     TEXT := fetchMetricText('NumberIssueResetIntervalDays') || ' day';
21393   _number       INTEGER;
21394 BEGIN
21395   -- get the sequence to update
21396   SELECT orderseq_seqiss INTO __seqiss
21397   FROM orderseq
21398   WHERE (orderseq_name=psequence);
21399
21400   IF (NOT FOUND) THEN
21401     RAISE EXCEPTION 'Invalid orderseq_name %', psequence;
21402   END IF;
21403
21404   IF(ARRAY_LENGTH(COALESCE(__seqiss,__newiss),1) IS NULL) THEN
21405     RETURN FALSE;
21406   END IF;
21407
21408   -- build a new array sans the number we are releasing
21409   FOR _i IN 1..ARRAY_LENGTH(__seqiss,1)
21410   LOOP
21411     IF((__seqiss[_i]).seqiss_number = pnumber) THEN
21412       _result = TRUE;
21413     -- don't bother re-adding stale numbers
21414     ELSIF (now() - _interval::INTERVAL > (__seqiss[_i]).seqiss_time) THEN
21415       IF (_number IS NULL) THEN
21416         _number := (__seqiss[_i]).seqiss_number;
21417       ELSE 
21418         _number := LEAST((__seqiss[_i]).seqiss_number, _number);
21419       END IF;
21420     ELSE
21421       __newiss := __newiss || __seqiss[_i];
21422     END IF;
21423   END LOOP;
21424
21425   -- update the order sequence with the result
21426   UPDATE orderseq SET
21427     orderseq_seqiss = __newiss
21428   WHERE (orderseq_name=psequence);
21429
21430   -- reset to any cleared stale number
21431   IF(_number IS NOT NULL) THEN
21432     UPDATE orderseq SET
21433       orderseq_number = _number
21434     WHERE (orderseq_name=psequence);
21435   END IF;
21436   
21437   RETURN _result;
21438 END;
21439 $$;
21440
21441
21442 ALTER FUNCTION public.clearnumberissue(psequence text, pnumber integer) OWNER TO admin;
21443
21444 --
21445 -- TOC entry 1220 (class 1255 OID 146565758)
21446 -- Dependencies: 4536 8
21447 -- Name: clearnumberissue(text, text); Type: FUNCTION; Schema: public; Owner: admin
21448 --
21449
21450 CREATE FUNCTION clearnumberissue(psequence text, pnumber text) RETURNS boolean
21451     LANGUAGE plpgsql
21452     AS $$
21453 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21454 -- See www.xtuple.com/CPAL for the full text of the software license.
21455 DECLARE
21456   _castpnumber  INTEGER;
21457 BEGIN
21458   -- for now, order numbers in the database are text but usually
21459   -- string representations of integers. allow for the occasional non-integer.
21460   BEGIN
21461     _castpnumber  := CAST(pnumber AS INTEGER);
21462   EXCEPTION WHEN cannot_coerce OR
21463                  invalid_text_representation
21464   THEN
21465     RAISE DEBUG 'clearNumberIssue(%, %) received an unexpected pnumber',
21466                   psequence, pnumber;
21467     RETURN FALSE;
21468   END;
21469
21470   RETURN clearNumberIssue(psequence, _castpnumber);
21471 END;
21472 $$;
21473
21474
21475 ALTER FUNCTION public.clearnumberissue(psequence text, pnumber text) OWNER TO admin;
21476
21477 --
21478 -- TOC entry 1221 (class 1255 OID 146565759)
21479 -- Dependencies: 4536 8
21480 -- Name: clearpayment(integer); Type: FUNCTION; Schema: public; Owner: admin
21481 --
21482
21483 CREATE FUNCTION clearpayment(integer) RETURNS integer
21484     LANGUAGE plpgsql
21485     AS $_$
21486 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21487 -- See www.xtuple.com/CPAL for the full text of the software license.
21488 DECLARE
21489   pApselectid ALIAS FOR $1;
21490
21491 BEGIN
21492
21493   DELETE FROM apselect
21494   WHERE (apselect_id=pApselectid);
21495
21496   RETURN 1;
21497
21498 END;
21499 $_$;
21500
21501
21502 ALTER FUNCTION public.clearpayment(integer) OWNER TO admin;
21503
21504 --
21505 -- TOC entry 1223 (class 1255 OID 146565760)
21506 -- Dependencies: 4536 8
21507 -- Name: closeaccountingperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
21508 --
21509
21510 CREATE FUNCTION closeaccountingperiod(integer) RETURNS integer
21511     LANGUAGE plpgsql
21512     AS $_$
21513 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21514 -- See www.xtuple.com/CPAL for the full text of the software license.
21515 DECLARE
21516   pPeriodid ALIAS FOR $1;
21517   _r RECORD;
21518   _nextPeriodid INTEGER;
21519   _trialbalid INTEGER;
21520   _ending NUMERIC;
21521   _currYear INTEGER;
21522   _nextYear INTEGER;
21523 BEGIN
21524
21525 --  Bypass error checking is this the the initial period
21526   IF ( NOT ( SELECT period_initial
21527              FROM period
21528              WHERE (period_id=pPeriodid) ) ) THEN
21529
21530 --  Check to make use that the period is not already closed
21531     IF ( ( SELECT period_closed
21532            FROM period
21533            WHERE (period_id=pPeriodid) ) ) THEN
21534       RETURN -1;
21535     END IF;
21536
21537 --  Make sure that the day before this period belongs to another period
21538     SELECT prev.period_id AS periodid, prev.period_closed AS closed INTO _r
21539     FROM period AS prev, period AS curr
21540     WHERE ( (prev.period_end = (curr.period_start - 1))
21541      AND (curr.period_id=pPeriodid) );
21542     IF (NOT FOUND) THEN
21543       RETURN -2;
21544     END IF;
21545
21546 --  Make sure that the previous period is closed
21547     IF (NOT _r.closed) THEN
21548       RETURN -3;
21549     END IF;
21550
21551   END IF;
21552
21553 --  Make sure that there the next period is defined
21554   SELECT next.period_id INTO _nextPeriodid
21555   FROM period AS next, period AS curr
21556   WHERE ( (next.period_start = (curr.period_end + 1))
21557    AND (curr.period_id=pPeriodid) );
21558   IF (NOT FOUND) THEN
21559     RETURN -4;
21560   END IF;
21561
21562 --  Make sure that the user is not trying to prematurely close the Period
21563   IF ( ( SELECT (period_end >= CURRENT_DATE)
21564          FROM period
21565          WHERE (period_id=pPeriodid) ) ) THEN
21566     RETURN -5;
21567   END IF;
21568
21569   SELECT yearperiod_id INTO _currYear
21570     FROM yearperiod, period
21571    WHERE ((period_end BETWEEN yearperiod_start and yearperiod_end)
21572      AND  (period_id=pPeriodid));
21573   IF (NOT FOUND) THEN
21574     _currYear := -1;
21575   END IF;
21576
21577   SELECT yearperiod_id INTO _nextYear
21578     FROM yearperiod, period
21579    WHERE ((period_end BETWEEN yearperiod_start and yearperiod_end)
21580      AND  (period_id=_nextPeriodid));
21581   IF (NOT FOUND) THEN
21582     RETURN -6;
21583   END IF;
21584
21585 --  Walk through the entire COA, calculating the ending balance and pushing
21586 --  it to the beginning balance for the next period
21587   FOR _r IN SELECT accnt_id, accnt_type IN ('E', 'R') AS revexp,
21588                    trialbal_id, trialbal_beginning,
21589                    trialbal_credits, trialbal_debits
21590             FROM accnt LEFT OUTER JOIN trialbal ON ( (trialbal_accnt_id=accnt_id) AND (trialbal_period_id=pPeriodid) )
21591             ORDER BY accnt_id LOOP
21592     IF (_r.trialbal_id IS NULL) THEN
21593       _ending = 0;
21594
21595       INSERT INTO trialbal
21596       ( trialbal_period_id, trialbal_accnt_id,
21597         trialbal_beginning, trialbal_ending, trialbal_dirty,
21598         trialbal_credits, trialbal_debits )
21599       VALUES
21600       ( pPeriodid, _r.accnt_id,
21601         0, 0, FALSE,
21602         0, 0 );
21603     ELSE
21604       _ending = (_r.trialbal_beginning - _r.trialbal_debits + _r.trialbal_credits);
21605
21606       UPDATE trialbal
21607       SET trialbal_ending=_ending,
21608           trialbal_dirty = FALSE
21609       WHERE (trialbal_id=_r.trialbal_id);
21610
21611       PERFORM forwardUpdateTrialBalance(_r.trialbal_id);
21612     END IF;
21613
21614     IF (_r.revexp AND _currYear != _nextYear) THEN
21615       _ending := 0;
21616     END IF;
21617
21618 --  Find the trialbal record for the next period
21619     SELECT trialbal_id INTO _trialbalid
21620     FROM trialbal
21621     WHERE ( (trialbal_period_id=_nextPeriodid)
21622      AND (trialbal_accnt_id=_r.accnt_id) );
21623     IF (FOUND) THEN
21624       UPDATE trialbal
21625       SET trialbal_beginning = (_ending + trialbal_yearend),
21626           trialbal_ending = (_ending + trialbal_yearend - trialbal_debits + trialbal_credits)
21627       WHERE (trialbal_id=_trialbalid);
21628     ELSE
21629       INSERT INTO trialbal
21630       ( trialbal_period_id, trialbal_accnt_id,
21631         trialbal_beginning, trialbal_ending, trialbal_dirty,
21632         trialbal_credits, trialbal_debits )
21633       VALUES(_nextPeriodid, _r.accnt_id,
21634              _ending, _ending, TRUE,
21635              0, 0 );
21636     END IF;
21637
21638   END LOOP;
21639
21640 --  Set the period_closed flag
21641   UPDATE period
21642   SET period_closed=TRUE
21643   WHERE (period_id=pPeriodid);
21644
21645   RETURN pPeriodid;
21646
21647 END;
21648 $_$;
21649
21650
21651 ALTER FUNCTION public.closeaccountingperiod(integer) OWNER TO admin;
21652
21653 --
21654 -- TOC entry 1224 (class 1255 OID 146565761)
21655 -- Dependencies: 4536 8
21656 -- Name: closeaccountingyearperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
21657 --
21658
21659 CREATE FUNCTION closeaccountingyearperiod(integer) RETURNS integer
21660     LANGUAGE plpgsql
21661     AS $_$
21662 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21663 -- See www.xtuple.com/CPAL for the full text of the software license.
21664 DECLARE
21665   pYearPeriodid ALIAS FOR $1;
21666   _result INTEGER;
21667 BEGIN
21668
21669 --  Check to make sure that the yearperiod is not already closed
21670   IF ( ( SELECT yearperiod_closed
21671            FROM yearperiod
21672           WHERE (yearperiod_id=pYearPeriodid) ) ) THEN
21673     RETURN -1;
21674   END IF;
21675
21676   IF ( ( SELECT (count(period_id) > 0)
21677            FROM period
21678           WHERE ((period_yearperiod_id=pYearPeriodid)
21679            AND (NOT period_closed)) ) ) THEN
21680     RETURN -10;
21681   END IF;
21682
21683   IF ( ( SELECT (count(yearperiod_id) > 0)
21684            FROM yearperiod
21685           WHERE ((yearperiod_end< (
21686             SELECT yearperiod_end 
21687             FROM yearperiod 
21688             WHERE (yearperiod_id=pYearPeriodId))
21689           )
21690            AND (NOT yearperiod_closed)) ) ) THEN
21691     RETURN -11;
21692   END IF;
21693
21694 --  Should we check for a previous yearperiod existing already ?
21695 --  If so then we should return -2 if one does not.
21696
21697 --  If we did the previous yearperiod we should check to make sure that
21698 --  it is also closed. Returning -3 if it is not.
21699
21700 --  Make sure that the user is not trying to prematurely close the YearPeriod
21701   IF ( ( SELECT (yearperiod_end >= CURRENT_DATE)
21702            FROM yearperiod
21703           WHERE (yearperiod_id=pYearPeriodid) ) ) THEN
21704     RETURN -5;
21705   END IF;
21706
21707 --  Update the year end Retained Earnings
21708   SELECT updateRetainedEarnings(pYearPeriodid) INTO _result;
21709   IF (_result < 0) THEN
21710     RETURN _result;
21711   END IF;
21712
21713   UPDATE yearperiod
21714     SET yearperiod_closed = TRUE
21715   WHERE yearperiod_id = pYearPeriodid;
21716
21717   RETURN 0;
21718
21719 END;
21720 $_$;
21721
21722
21723 ALTER FUNCTION public.closeaccountingyearperiod(integer) OWNER TO admin;
21724
21725 --
21726 -- TOC entry 1225 (class 1255 OID 146565762)
21727 -- Dependencies: 4536 8
21728 -- Name: closepo(integer); Type: FUNCTION; Schema: public; Owner: admin
21729 --
21730
21731 CREATE FUNCTION closepo(integer) RETURNS integer
21732     LANGUAGE plpgsql
21733     AS $_$
21734 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21735 -- See www.xtuple.com/CPAL for the full text of the software license.
21736 DECLARE
21737   pPoheadid ALIAS FOR $1;
21738
21739 BEGIN
21740
21741   UPDATE poitem
21742   SET poitem_status='C'
21743   WHERE (poitem_pohead_id=pPoheadid);
21744
21745 -- _poitemTrigger will close pohead when the last poitem is closed
21746 --  UPDATE pohead
21747 --  SET pohead_status='C'
21748 --  WHERE (pohead_id=pPoheadid);
21749
21750   RETURN 1;
21751
21752 END;
21753 $_$;
21754
21755
21756 ALTER FUNCTION public.closepo(integer) OWNER TO admin;
21757
21758 --
21759 -- TOC entry 1226 (class 1255 OID 146565763)
21760 -- Dependencies: 4536 8
21761 -- Name: closewo(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
21762 --
21763
21764 CREATE FUNCTION closewo(integer, boolean) RETURNS integer
21765     LANGUAGE plpgsql
21766     AS $_$
21767 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21768 -- See www.xtuple.com/CPAL for the full text of the software license.
21769 DECLARE
21770   pWoid ALIAS FOR $1;
21771   pPostMaterialVariances ALIAS FOR $2;
21772
21773 BEGIN
21774   
21775   RETURN closeWo(pWoid, pPostMaterialVariances, CURRENT_DATE);
21776 END;
21777 $_$;
21778
21779
21780 ALTER FUNCTION public.closewo(integer, boolean) OWNER TO admin;
21781
21782 --
21783 -- TOC entry 1227 (class 1255 OID 146565764)
21784 -- Dependencies: 4536 8
21785 -- Name: closewo(integer, boolean, date); Type: FUNCTION; Schema: public; Owner: admin
21786 --
21787
21788 CREATE FUNCTION closewo(integer, boolean, date) RETURNS integer
21789     LANGUAGE plpgsql
21790     AS $_$
21791 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21792 -- See www.xtuple.com/CPAL for the full text of the software license.
21793 DECLARE
21794   pWoid ALIAS FOR $1;
21795   pPostMaterialVariances ALIAS FOR $2;
21796   pTransDate ALIAS FOR $3;
21797   _woNumber TEXT;
21798   _check CHAR;
21799   _itemlocSeries INTEGER := 0;
21800
21801 BEGIN
21802
21803   --Comment this out
21804   --In addition to IssueToShipping driving PostProduction,
21805   --not PostProduction can drive IssueToShipping.
21806   --Must allow closing of Job items
21807
21808   --If this is item type Job then we cannot close here
21809   --SELECT itemsite_costmethod INTO _check
21810   --FROM wo,itemsite
21811   --WHERE ((wo_id=pWoid)
21812   --AND (wo_itemsite_id=itemsite_id)
21813   --AND (itemsite_costmethod = 'J'));
21814   --IF (FOUND) THEN
21815   --  RAISE EXCEPTION 'Work orders for Job items are closed when all quantities are shipped';
21816   --END IF;
21817
21818   SELECT formatWoNumber(pWoid) INTO _woNumber;
21819
21820 -- If there are any tools issued on this job then we cannot close here
21821   IF ( SELECT (count(*) > 0)
21822        FROM womatl
21823        JOIN itemsite ON (womatl_itemsite_id=itemsite_id)
21824        JOIN item ON ((itemsite_item_id=item_id) AND (item_type='T'))
21825        WHERE ((womatl_wo_id=pWoid)
21826          AND  (womatl_qtyiss > 0)) ) THEN
21827     RAISE EXCEPTION 'All Tools must be returned before the W/O can be closed';
21828   END IF;
21829
21830 --  Distribute any remaining wo_wipvalue to G/L - debit Inventory Cost, credit WIP
21831   PERFORM insertGLTransaction( 'W/O', 'WO', _woNumber, ('Manufacturing Inventory Cost Variance for ' || item_number),
21832                                getPrjAccntId(wo_prj_id, costcat_wip_accnt_id), 
21833                                getPrjAccntId(wo_prj_id, costcat_invcost_accnt_id), -1,
21834                                COALESCE(wo_wipvalue, 0), pTransDate )
21835   FROM wo, itemsite, item, costcat
21836   WHERE ( (wo_itemsite_id=itemsite_id)
21837    AND (itemsite_item_id=item_id)
21838    AND (itemsite_costcat_id=costcat_id)
21839    AND (wo_id=pWoid) );
21840
21841 --  Distribute any remaining wo_brdvalue to G/L - debit Inventory Cost, credit WIP
21842   PERFORM insertGLTransaction( 'W/O', 'WO', _woNumber, ('Breeder Inventory Cost Variance for ' || item_number),
21843                                getPrjAccntId(wo_prj_id, costcat_wip_accnt_id),
21844                                CASE WHEN(itemsite_costmethod='A') THEN costcat_asset_accnt_id
21845                                     ELSE getPrjAccntId(wo_prj_id, costcat_invcost_accnt_id)
21846                                END,
21847                                -1,
21848                                COALESCE(wo_brdvalue, 0), pTransDate )
21849   FROM wo, itemsite, item, costcat
21850   WHERE ( (wo_itemsite_id=itemsite_id)
21851    AND (itemsite_item_id=item_id)
21852    AND (itemsite_costcat_id=costcat_id)
21853    AND (wo_id=pWoid) );
21854
21855 --  Don't bother with posting variances if the qtyrcv is 0 as
21856 --  they are meaningless.
21857   IF ( ( SELECT wo_qtyrcv
21858          FROM wo
21859          WHERE (wo_id=pWoid) ) > 0 ) THEN
21860
21861     IF (pPostMaterialVariances) THEN
21862 --  Post womatl variances
21863     INSERT INTO womatlvar ( womatlvar_number, womatlvar_subnumber, womatlvar_posted,
21864         womatlvar_parent_itemsite_id, womatlvar_component_itemsite_id,
21865         womatlvar_qtyord, womatlvar_qtyrcv,
21866         womatlvar_qtyiss, womatlvar_qtyfxd, womatlvar_qtyper,
21867         womatlvar_scrap, womatlvar_wipscrap, womatlvar_bomitem_id,
21868         womatlvar_notes, womatlvar_ref )
21869       SELECT wo_number, wo_subnumber, pTransDate,
21870              wo_itemsite_id, womatl_itemsite_id,
21871              wo_qtyord, wo_qtyrcv,
21872              itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyiss),
21873              itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyfxd),
21874              itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyper),
21875              womatl_scrap,
21876              itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtywipscrap),
21877              womatl_bomitem_id,
21878              womatl_notes, womatl_ref             
21879       FROM wo, womatl, itemsite, item
21880       WHERE ((womatl_wo_id=wo_id)
21881        AND (womatl_itemsite_id=itemsite_id)
21882        AND (itemsite_item_id=item_id)
21883        AND (item_type <> 'T')      
21884        AND (wo_id=pWoid));
21885     END IF;
21886   END IF;
21887
21888 --  Delete any P/R's created for this W/O
21889   PERFORM deletePr('W', womatl_id)
21890   FROM womatl
21891   WHERE (womatl_wo_id=pWoid);
21892
21893   UPDATE wo
21894   SET wo_wipvalue = 0, wo_brdvalue=0,
21895       wo_status='C'
21896   WHERE (wo_id=pWoid);
21897
21898   RETURN 1;
21899 END;
21900 $_$;
21901
21902
21903 ALTER FUNCTION public.closewo(integer, boolean, date) OWNER TO admin;
21904
21905 --
21906 -- TOC entry 204 (class 1259 OID 146565765)
21907 -- Dependencies: 5945 8
21908 -- Name: cntct; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
21909 --
21910
21911 CREATE TABLE cntct (
21912     cntct_id integer NOT NULL,
21913     cntct_crmacct_id integer,
21914     cntct_addr_id integer,
21915     cntct_first_name text,
21916     cntct_last_name text,
21917     cntct_honorific text,
21918     cntct_initials text,
21919     cntct_active boolean DEFAULT true,
21920     cntct_phone text,
21921     cntct_phone2 text,
21922     cntct_fax text,
21923     cntct_email text,
21924     cntct_webaddr text,
21925     cntct_notes text,
21926     cntct_title text,
21927     cntct_number text NOT NULL,
21928     cntct_middle text,
21929     cntct_suffix text,
21930     cntct_owner_username text,
21931     cntct_name text
21932 );
21933
21934
21935 ALTER TABLE public.cntct OWNER TO admin;
21936
21937 --
21938 -- TOC entry 8950 (class 0 OID 0)
21939 -- Dependencies: 204
21940 -- Name: TABLE cntct; Type: COMMENT; Schema: public; Owner: admin
21941 --
21942
21943 COMMENT ON TABLE cntct IS 'Contact - information on how to reach a living person';
21944
21945
21946 --
21947 -- TOC entry 1228 (class 1255 OID 146565772)
21948 -- Dependencies: 2777 4536 8
21949 -- Name: cntct(); Type: FUNCTION; Schema: public; Owner: admin
21950 --
21951
21952 CREATE FUNCTION cntct() RETURNS SETOF cntct
21953     LANGUAGE plpgsql
21954     AS $$
21955 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
21956 -- See www.xtuple.com/CPAL for the full text of the software license.
21957 DECLARE
21958   _row cntct%ROWTYPE;
21959   _priv TEXT;
21960   _grant BOOLEAN;
21961
21962 BEGIN
21963   -- This query will give us the most permissive privilege the user has been granted
21964   SELECT privilege, granted INTO _priv, _grant
21965   FROM privgranted 
21966   WHERE privilege IN ('MaintainAllContacts','ViewAllContacts','MaintainPersonalContacts','ViewPersonalContacts')
21967   ORDER BY granted DESC, sequence
21968   LIMIT 1;
21969
21970   -- If have an 'All' privilege return all results
21971   IF (_priv ~ 'All' AND _grant) THEN
21972     FOR _row IN 
21973       SELECT * FROM cntct
21974     LOOP
21975       RETURN NEXT _row;
21976     END LOOP;
21977   -- Otherwise if have any other grant, must be personal privilege.
21978   ELSIF (_grant) THEN
21979     FOR _row IN 
21980       SELECT * FROM cntct 
21981       WHERE cntct_owner_username = getEffectiveXtUser()
21982     LOOP
21983       RETURN NEXT _row;
21984     END LOOP;
21985   END IF;
21986
21987   RETURN;
21988
21989 END;
21990 $$;
21991
21992
21993 ALTER FUNCTION public.cntct() OWNER TO admin;
21994
21995 --
21996 -- TOC entry 8952 (class 0 OID 0)
21997 -- Dependencies: 1228
21998 -- Name: FUNCTION cntct(); Type: COMMENT; Schema: public; Owner: admin
21999 --
22000
22001 COMMENT ON FUNCTION cntct() IS 'A table function that returns Contact results according to privilege settings.';
22002
22003
22004 --
22005 -- TOC entry 1229 (class 1255 OID 146565773)
22006 -- Dependencies: 2663 4536 8
22007 -- Name: cntctdups(text, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
22008 --
22009
22010 CREATE FUNCTION cntctdups(text, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS SETOF cntctdup
22011     LANGUAGE plpgsql
22012     AS $_$
22013 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22014 -- See www.xtuple.com/CPAL for the full text of the software license.
22015 DECLARE
22016   pSearchText ALIAS FOR $1;
22017   pSearchContactName ALIAS FOR $2;
22018   pSearchPhone ALIAS FOR $3;
22019   pSearchEmail ALIAS FOR $4;
22020   pSearchNumber ALIAS FOR $5;
22021   pSearchName ALIAS FOR $6;
22022   pShowInactive ALIAS FOR $7;
22023   pIgnoreBlanks ALIAS FOR $8;
22024   pIndentedDups ALIAS FOR $9;
22025   pCheckHnfc ALIAS FOR $10;
22026   pCheckFirst ALIAS FOR $11;
22027   pCheckMiddle ALIAS FOR $12;
22028   pCheckLast ALIAS FOR $13;
22029   pCheckSuffix ALIAS FOR $14;
22030   pCheckPhone ALIAS FOR $15;
22031   pCheckEmail ALIAS FOR $16;
22032   _cntct cntctdup%ROWTYPE;
22033   _cntctdup cntctdup%ROWTYPE;
22034   _rec RECORD;
22035   _operator TEXT := '';
22036   _clause TEXT;
22037   _qry  TEXT := '';
22038   _return BOOLEAN := true;
22039   _text TEXT;
22040   _first BOOLEAN := true;
22041
22042 BEGIN
22043   -- Validate
22044   IF (pIndentedDups AND NOT pCheckHnfc AND NOT pCheckFirst AND NOT pCheckMiddle AND 
22045       NOT pCheckLast AND NOT pCheckSuffix AND NOT pCheckEmail AND NOT pCheckPhone) THEN
22046     RETURN;
22047   END IF;
22048
22049   _text = quote_literal(pSearchText);
22050
22051   IF (pIndentedDups) THEN
22052     _qry := 'SELECT 
22053         -1 AS cntct_id,
22054         -1 AS cntct_crmacct_id,
22055         -1 AS cntct_addr_id,';
22056     IF (NOT pCheckFirst) THEN
22057       _qry := _qry || ''''' AS ';
22058     END IF;
22059     _qry := _qry || ' cntct_first_name,';
22060     IF (NOT pCheckLast) THEN
22061       _qry := _qry || ''''' AS ';
22062     END IF;
22063     _qry := _qry || ' cntct_last_name,';
22064     IF (NOT pCheckHnfc) THEN
22065       _qry := _qry || ''''' AS ';
22066     END IF;
22067     _qry := _qry || ' cntct_honorific,';
22068     _qry := _qry || ' '''' AS cntct_initials,';
22069     _qry := _qry || ' NULL AS cntct_active,';
22070     IF (NOT pCheckPhone) THEN
22071       _qry := _qry || ''''' AS ';
22072     END IF;
22073     _qry := _qry || ' cntct_phone,';
22074     IF (NOT pCheckPhone) THEN
22075       _qry := _qry || ''''' AS ';
22076     END IF;
22077     _qry := _qry || ' cntct_phone2,';
22078     _qry := _qry || ' '''' AS cntct_fax,';
22079     IF (NOT pCheckEmail) THEN
22080       _qry := _qry || ''''' AS ';
22081     END IF;
22082     _qry := _qry || ' cntct_email,';
22083     _qry := _qry || ' '''' AS cntct_webaddr,';
22084     _qry := _qry || ' '''' AS cntct_notes,';
22085     _qry := _qry || ' '''' AS cntct_title,';
22086     _qry := _qry || ' '''' AS cntct_number,';
22087     IF (NOT pCheckMiddle) THEN
22088       _qry := _qry || ''''' AS ';
22089     END IF;
22090     _qry := _qry || ' cntct_middle,';
22091     IF (NOT pCheckSuffix) THEN
22092       _qry := _qry || ''''' AS ';
22093     END IF;
22094     _qry := _qry || ' cntct_suffix,';
22095     _qry := _qry || ' '''' AS cntct_owner_username,';
22096     _qry := _qry || ' '''' AS cntct_name,';
22097     _qry := _qry || ' '''' AS crmacct_number, ';
22098     _qry := _qry || ' '''' AS crmacct_name, ';
22099     _qry := _qry || ' NULL AS addr_id,
22100                 NULL AS addr_active,
22101                 '''' AS addr_line1,
22102                 '''' AS addr_line2,
22103                 '''' AS addr_line3,
22104                 '''' AS addr_city,
22105                 '''' AS addr_state,
22106                 '''' AS addr_postalcode,
22107                 '''' AS addr_country,
22108                 '''' AS addr_notes,
22109                 '''' AS addr_number,
22110                 cntctdup_level FROM (';
22111   END IF;
22112     _clause := 'SELECT 
22113                 cntct_id,
22114                 cntct_crmacct_id,
22115                 cntct_addr_id,
22116                 UPPER(cntct_first_name) AS cntct_first_name,
22117                 UPPER(cntct_last_name) AS cntct_last_name,
22118                 UPPER(cntct_honorific) AS cntct_honorific,
22119                 cntct_initials,
22120                 cntct_active,
22121                 cntct_phone,
22122                 cntct_phone2,
22123                 cntct_fax,
22124                 UPPER(cntct_email) AS cntct_email,
22125                 cntct_webaddr,
22126                 cntct_notes,
22127                 cntct_title,
22128                 cntct_number,
22129                 UPPER(cntct_middle) AS cntct_middle,
22130                 UPPER(cntct_suffix) AS cntct_suffix,
22131                 cntct_owner_username,
22132                 cntct_name,
22133                 crmacct_number, 
22134                 crmacct_name,
22135                 addr.*,
22136                 0 AS cntctdup_level
22137              FROM cntct()
22138                LEFT OUTER JOIN crmacct ON (cntct_crmacct_id=crmacct_id) 
22139                LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id) 
22140              WHERE ';
22141
22142   IF (NOT pIndentedDups) THEN
22143     WHILE position('UPPER' in _clause) > 0
22144     LOOP
22145       _clause := regexp_replace(_clause, 'UPPER', '');
22146     END LOOP;
22147   END IF;
22148
22149   _qry := _qry || _clause;
22150            
22151   IF (NOT pShowInactive) THEN
22152     _qry := _qry || ' cntct_active AND ';
22153   END IF;
22154
22155   IF (pIgnoreBlanks) THEN
22156     _qry := _qry || ' (COALESCE(LENGTH(cntct_first_name || cntct_last_name),0) > 0) AND ';
22157   END IF;
22158
22159     _qry := _qry || '(false ';
22160
22161   IF (pSearchNumber) THEN
22162     _qry := _qry || ' OR (crmacct_number ~* ' || quote_literal(pSearchText) || ') ';
22163   END IF;
22164
22165   IF (pSearchName) THEN
22166     _qry := _qry || ' OR (crmacct_name ~* ' || quote_literal(pSearchText) || ') ';
22167   END IF;
22168
22169   IF (pSearchContactName) THEN
22170     _qry := _qry || ' OR (cntct_first_name || '' '' || cntct_last_name ~* ' || quote_literal(pSearchText) || ') ';
22171   END IF;
22172   
22173   IF (pSearchPhone) THEN
22174     _qry := _qry || ' OR (cntct_phone || '' '' || cntct_phone2 || '' '' || cntct_fax ~* ' || quote_literal(pSearchText) || ') ';
22175   END IF;
22176
22177   IF (pSearchEmail) THEN
22178     _qry := _qry || ' OR (cntct_email ~* ' || quote_literal(pSearchText) || ') ';
22179   END IF;
22180
22181   _qry := _qry || ' ) ';
22182   
22183   IF (pIndentedDups) THEN
22184     _qry := _qry || ') data';
22185     _clause := ' GROUP BY cntctdup_level';
22186     IF (pCheckHnfc) THEN
22187       _clause := _clause || ',cntct_honorific';
22188     END IF;
22189     IF (pCheckFirst) THEN
22190       _clause := _clause || ',cntct_first_name';
22191     END IF;
22192     IF (pCheckMiddle) THEN
22193       _clause := _clause || ',cntct_middle';
22194     END IF;
22195     IF (pCheckLast) THEN
22196       _clause := _clause || ',cntct_last_name';
22197     END IF;
22198     IF (pCheckSuffix) THEN
22199       _clause := _clause || ',cntct_suffix';
22200     END IF;
22201     IF (pCheckEmail) THEN
22202       _clause := _clause || ',cntct_email';
22203     END IF;
22204     IF (pCheckPhone) THEN
22205       _clause := _clause || ',cntct_phone';
22206       _clause := _clause || ',cntct_phone2';
22207     END IF;
22208
22209     _qry := _qry || _clause; 
22210
22211     _clause := ' HAVING(';
22212     IF (pCheckHnfc) THEN
22213       _clause := _clause || 'OR COUNT(cntct_honorific) > 1 ';
22214     END IF;
22215     IF (pCheckFirst) THEN
22216       _clause := _clause || 'OR COUNT(cntct_first_name) > 1 ';
22217     END IF;
22218     IF (pCheckMiddle) THEN
22219       _clause := _clause || 'OR COUNT(cntct_middle) > 1 ';
22220     END IF;
22221     IF (pCheckLast) THEN
22222       _clause := _clause || 'OR COUNT(cntct_last_name) > 1 ';
22223     END IF;
22224     IF (pCheckSuffix) THEN
22225       _clause := _clause || 'OR COUNT(cntct_suffix) > 1 ';
22226     END IF;
22227     IF (pCheckEmail) THEN
22228       _clause := _clause || 'OR COUNT(cntct_email) > 1 ';
22229     END IF;
22230     IF (pCheckPhone) THEN
22231       _clause := _clause || 'OR (COUNT(cntct_phone) > 1 AND LENGTH(cntct_phone) > 0) ';
22232       _clause := _clause || 'OR (COUNT(cntct_phone2) > 1 AND LENGTH(cntct_phone2) > 0) ';
22233     END IF;
22234     _clause := _clause || ') ';
22235     _clause := overlay(_clause placing '' from 9 for 2);
22236
22237     IF (pCheckHnfc) THEN
22238       _clause := _clause || 'AND LENGTH(cntct_honorific) > 0 ';
22239     END IF;
22240     IF (pCheckFirst) THEN
22241       _clause := _clause || 'AND LENGTH(cntct_first_name) > 0  ';
22242     END IF;
22243     IF (pCheckMiddle) THEN
22244       _clause := _clause || 'AND LENGTH(cntct_middle) > 0  ';
22245     END IF;
22246     IF (pCheckLast) THEN
22247       _clause := _clause || 'AND LENGTH(cntct_last_name) > 0  ';
22248     END IF;
22249     IF (pCheckSuffix) THEN
22250       _clause := _clause || 'AND LENGTH(cntct_suffix) > 0  ';
22251     END IF;
22252     IF (pCheckEmail) THEN
22253       _clause := _clause || 'AND LENGTH(cntct_email) > 0  ';
22254     END IF;
22255     
22256     _qry := _qry || _clause;
22257   END IF;
22258
22259   _qry := _qry || ' ORDER BY cntct_last_name, cntct_first_name;'; 
22260
22261 -- raise exception '%',_qry;
22262   FOR _cntct IN
22263     EXECUTE _qry
22264   LOOP
22265
22266     RETURN NEXT _cntct;
22267
22268     -- If duplicates, get duplicates
22269     IF (pIndentedDups) THEN
22270     
22271       _qry := 'SELECT                
22272                  cntct.*,
22273                  crmacct_number, 
22274                  crmacct_name,
22275                  addr.*,
22276                  1 AS cntctdup_level
22277                FROM cntct()
22278                  LEFT OUTER JOIN crmacct ON (cntct_crmacct_id=crmacct_id) 
22279                  LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
22280                WHERE (true) ';
22281
22282       IF (pCheckHnfc) THEN
22283         _qry := _qry || ' AND (UPPER(cntct_honorific)=' || quote_literal(_cntct.cntct_honorific) || ')';
22284       END IF;
22285
22286       IF (pCheckFirst) THEN
22287         _qry := _qry || ' AND (UPPER(cntct_first_name)=' || quote_literal(_cntct.cntct_first_name) || ')';
22288       END IF;
22289
22290       IF (pCheckMiddle) THEN
22291         _qry := _qry || ' AND (UPPER(cntct_middle)=' || quote_literal(_cntct.cntct_middle) || ')';
22292       END IF;
22293
22294       IF (pCheckLast) THEN
22295         _qry := _qry || ' AND (UPPER(cntct_last_name)=' || quote_literal(_cntct.cntct_last_name) || ')';
22296       END IF;
22297
22298       IF (pCheckSuffix) THEN
22299         _qry := _qry || ' AND (UPPER(cntct_suffix)=' ||  quote_literal(_cntct.cntct_suffix) || ')';
22300       END IF;
22301
22302       IF (pCheckPhone) THEN
22303         _qry := _qry || ' AND (cntct_phone=' || quote_literal(_cntct.cntct_phone)  || ')';
22304       END IF;
22305
22306       IF (pCheckEmail) THEN
22307         _qry := _qry || ' AND (UPPER(cntct_email)=' || quote_literal(_cntct.cntct_email) || ')';
22308       END IF;
22309
22310 -- raise exception '%',_qry;
22311       FOR _cntctdup IN
22312         EXECUTE _qry
22313       LOOP
22314         RETURN NEXT _cntctdup;
22315       END LOOP;
22316
22317     END IF;
22318     
22319   END LOOP;
22320
22321   RETURN;
22322 END;
22323 $_$;
22324
22325
22326 ALTER FUNCTION public.cntctdups(text, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
22327
22328 --
22329 -- TOC entry 1230 (class 1255 OID 146565775)
22330 -- Dependencies: 4536 8
22331 -- Name: cntctmerge(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
22332 --
22333
22334 CREATE FUNCTION cntctmerge(integer, integer, boolean) RETURNS boolean
22335     LANGUAGE plpgsql
22336     AS $_$
22337 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22338 -- See www.xtuple.com/CPAL for the full text of the software license.
22339 DECLARE
22340   pSourceCntctId ALIAS FOR $1;
22341   pTargetCntctId ALIAS FOR $2;
22342   pPurge ALIAS FOR $3;
22343   _fk           RECORD;
22344   _pk           RECORD;
22345   _sel          RECORD;
22346   _seq          INTEGER;
22347   _col          TEXT;
22348   _pkcol        TEXT;
22349   _qry          TEXT;
22350   _multi        BOOLEAN;
22351
22352 BEGIN
22353   -- Validate
22354   IF (pSourceCntctId IS NULL) THEN
22355     RAISE EXCEPTION 'Source contact id can not be null';
22356   ELSIF (pTargetCntctId IS NULL) THEN
22357     RAISE EXCEPTION 'Target contact id can not be null';
22358   ELSIF (pPurge IS NULL) THEN
22359     RAISE EXCEPTION 'Purge flag can not be null';
22360   END IF;
22361   
22362   -- Determine where this contact is used by analyzing foreign key linkages and update each
22363   FOR _fk IN
22364     SELECT pg_namespace.nspname AS schemaname, con.relname AS tablename, conkey AS seq, conrelid AS class_id 
22365     FROM pg_constraint, pg_class f, pg_class con, pg_namespace
22366     WHERE confrelid=f.oid
22367     AND conrelid=con.oid
22368     AND f.relname = 'cntct'
22369     AND con.relnamespace=pg_namespace.oid
22370     AND con.relname NOT IN ('cntctsel', 'cntctmrgd', 'mrghist','trgthist')
22371   LOOP
22372     -- Validate
22373     IF (ARRAY_UPPER(_fk.seq,1) > 1) THEN
22374       RAISE EXCEPTION 'Updates to tables where the contact is one of multiple foreign key columns is not supported. Error on Table: %',
22375         pg_namespace.nspname || '.' || con.relname;
22376     END IF;
22377     
22378     _seq := _fk.seq[1];
22379
22380     -- Get the specific column name
22381     SELECT attname INTO _col
22382     FROM pg_attribute, pg_class
22383     WHERE ((attrelid=pg_class.oid)
22384     AND (pg_class.oid=_fk.class_id)
22385     AND (attnum=_seq));
22386
22387     IF (NOT pPurge) THEN
22388     -- Cache what we're going to do so we can restore if need be.
22389     -- Start by determining the primary key column for this table.
22390       _multi := false;
22391       _qry := 'SELECT pg_attribute.attname AS key
22392                FROM pg_attribute, pg_class 
22393                WHERE pg_class.relnamespace = (
22394                  SELECT oid 
22395                  FROM pg_namespace 
22396                  WHERE pg_namespace.nspname = ''' || _fk.schemaname || ''') 
22397                 AND  pg_class.oid IN (
22398                  SELECT indexrelid 
22399                  FROM pg_index 
22400                  WHERE indisprimary = true 
22401                   AND indrelid IN (
22402                     SELECT oid 
22403                     FROM pg_class 
22404                     WHERE lower(relname) = ''' || _fk.tablename || ''')) 
22405                 AND pg_attribute.attrelid = pg_class.oid 
22406                 AND pg_attribute.attisdropped = false 
22407                ORDER BY pg_attribute.attnum;';
22408
22409       FOR _pk IN 
22410         EXECUTE _qry
22411       LOOP
22412         IF (_multi) THEN
22413           RAISE EXCEPTION 'Reference tables with composite primary keys not supported.  Try the merge and purge option.';
22414         END IF;
22415         _pkcol := _pk.key;
22416         _multi := true;
22417       END LOOP;
22418
22419       -- Gather and store the history
22420       _qry := 'INSERT INTO mrghist 
22421                SELECT ' || pSourceCntctId || ', ''' 
22422                         || _fk.schemaname || '.' || _fk.tablename || ''', ''' 
22423                         || _pkcol || ''', ' 
22424                         || _pkcol || ', '''
22425                         || _col || ''' 
22426                FROM ' || _fk.schemaname || '.' || _fk.tablename || '
22427                WHERE (' || _col || '=' || pSourceCntctId || ');';
22428                    --           raise exception '%',_qry;
22429       EXECUTE _qry;
22430       
22431     END IF;
22432
22433     -- Merge references
22434     _qry := 'UPDATE ' || _fk.schemaname || '.' || _fk.tablename ||
22435             ' SET ' || _col || '=' || pTargetCntctId ||
22436             ' WHERE (' || _col || '=' || pSourceCntctId || ');';
22437             
22438     EXECUTE _qry;
22439          
22440   END LOOP;
22441
22442   -- Merge cases with no foreign key
22443   IF (NOT pPurge) THEN
22444     INSERT INTO mrghist 
22445     SELECT pSourceCntctId,
22446       'comment',
22447       'comment_id', 
22448       comment_id,
22449       'comment_source_id'
22450     FROM comment
22451     WHERE ((comment_source_id= pSourceCntctId)
22452     AND (comment_source='T'));
22453
22454     INSERT INTO mrghist 
22455     SELECT pSourceCntctId,
22456       'docass',
22457       'docass_id', 
22458       docass_id,
22459       'docass_source_id'
22460     FROM docass
22461     WHERE ((docass_source_id= pSourceCntctId)
22462     AND (docass_source_type='T'));
22463
22464     INSERT INTO mrghist 
22465     SELECT pSourceCntctId,
22466       'docass',
22467       'docass_id', 
22468       docass_id,
22469       'docass_target_id'
22470     FROM docass
22471     WHERE ((docass_target_id= pSourceCntctId)
22472     AND (docass_target_type='T'));
22473
22474     INSERT INTO mrghist 
22475     SELECT pSourceCntctId,
22476       'vendinfo',
22477       'vend_id', 
22478       vend_id,
22479       'vend_cntct1_id'
22480     FROM vendinfo
22481     WHERE (vend_cntct1_id=pSourceCntctId);
22482
22483     INSERT INTO mrghist 
22484     SELECT pSourceCntctId,
22485       'vendinfo',
22486       'vend_id', 
22487       vend_id,
22488       'vend_cntct2_id'
22489     FROM vendinfo
22490     WHERE (vend_cntct2_id=pSourceCntctId);
22491
22492     IF (fetchMetricBool('EnableBatchManager') AND packageIsEnabled('xtbatch')) THEN
22493       INSERT INTO mrghist 
22494       SELECT pSourceCntctId,
22495       'xtbatch.emlassc',
22496       'emlassc_id', 
22497       emlassc_id,
22498       'emlassc_assc_id'
22499       FROM xtbatch.emlassc
22500       WHERE ((emlassc_assc_id= pSourceCntctId)
22501       AND (emlassc_type='T'));
22502     END IF;
22503   END IF;
22504
22505   UPDATE comment
22506   SET comment_source_id = pTargetCntctId
22507   WHERE ((comment_source = 'T')
22508    AND (comment_source_id = pSourceCntctId));
22509
22510   UPDATE docass
22511   SET docass_source_id = pTargetCntctId
22512   WHERE ((docass_source_type = 'T')
22513    AND (docass_source_id = pSourceCntctId));
22514
22515   UPDATE docass
22516   SET docass_target_id = pTargetCntctId
22517   WHERE ((docass_target_type = 'T')
22518    AND (docass_target_id = pSourceCntctId));
22519
22520   UPDATE vendinfo
22521   SET vend_cntct1_id = pTargetCntctId
22522   WHERE (vend_cntct1_id = pSourceCntctId);
22523
22524   UPDATE vendinfo
22525   SET vend_cntct2_id = pTargetCntctId
22526   WHERE (vend_cntct2_id = pSourceCntctId);
22527
22528   IF (fetchMetricBool('EnableBatchManager') AND packageIsEnabled('xtbatch')) THEN
22529     UPDATE xtbatch.emlassc
22530     SET emlassc_assc_id = pTargetCntctId
22531     WHERE ((emlassc_type = 'T')
22532      AND (emlassc_assc_id = pSourceCntctId));
22533   END IF;
22534
22535   IF (NOT pPurge) THEN
22536   -- Record that this has been merged if not already
22537     IF (SELECT (COUNT(cntctmrgd_cntct_id) = 0) 
22538         FROM cntctmrgd
22539         WHERE (cntctmrgd_cntct_id=pSourceCntctId)) THEN
22540       INSERT INTO cntctmrgd VALUES (pSourceCntctId,false);
22541     END IF;
22542   END IF;
22543
22544  -- Merge field detail to target
22545   SELECT * INTO _sel 
22546   FROM cntctsel 
22547     JOIN cntct ON (cntctsel_cntct_id=cntct_id)
22548   WHERE (cntctsel_cntct_id=pSourceCntctId);
22549   
22550   IF (FOUND) THEN
22551     IF (_sel.cntctsel_mrg_crmacct_id) THEN
22552       IF (NOT pPurge) THEN
22553         INSERT INTO trgthist
22554         SELECT pSourceCntctId,pTargetCntctId,'cntct_crmacct_id', cntct_crmacct_id::text || '::integer'
22555         FROM cntct
22556         WHERE (cntct_id=pTargetCntctId);
22557       END IF;
22558       UPDATE cntct SET cntct_crmacct_id=_sel.cntct_crmacct_id WHERE (cntct_id=pTargetCntctId);
22559     END IF;
22560     IF (_sel.cntctsel_mrg_addr_id) THEN
22561       IF (NOT pPurge) THEN
22562         INSERT INTO trgthist
22563         SELECT pSourceCntctId,pTargetCntctId,'cntct_addr_id', cntct_addr_id::text || '::integer'
22564         FROM cntct
22565         WHERE (cntct_id=pTargetCntctId);
22566       END IF;
22567       UPDATE cntct SET cntct_addr_id=_sel.cntct_addr_id WHERE (cntct_id=pTargetCntctId);
22568     END IF;
22569     IF (_sel.cntctsel_mrg_first_name) THEN
22570       IF (NOT pPurge) THEN
22571         INSERT INTO trgthist
22572         SELECT pSourceCntctId,pTargetCntctId,'cntct_first_name', '''' || cntct_first_name || ''''
22573         FROM cntct
22574         WHERE (cntct_id=pTargetCntctId);
22575       END IF;
22576       UPDATE cntct SET cntct_first_name=_sel.cntct_first_name WHERE (cntct_id=pTargetCntctId);
22577     END IF;
22578     IF (_sel.cntctsel_mrg_last_name) THEN
22579       IF (NOT pPurge) THEN
22580         INSERT INTO trgthist
22581         SELECT pSourceCntctId,pTargetCntctId,'cntct_last_name', '''' || cntct_last_name || ''''
22582         FROM cntct
22583         WHERE (cntct_id=pTargetCntctId);
22584       END IF;
22585       UPDATE cntct SET cntct_last_name=_sel.cntct_last_name WHERE (cntct_id=pTargetCntctId);
22586     END IF;
22587     IF (_sel.cntctsel_mrg_honorific) THEN
22588       IF (NOT pPurge) THEN
22589         INSERT INTO trgthist
22590         SELECT pSourceCntctId,pTargetCntctId,'cntct_honorific', '''' || cntct_honorific || ''''
22591         FROM cntct
22592         WHERE (cntct_id=pTargetCntctId);
22593       END IF;
22594       UPDATE cntct SET cntct_honorific=_sel.cntct_honorific WHERE (cntct_id=pTargetCntctId);
22595     END IF;
22596     IF (_sel.cntctsel_mrg_initials) THEN
22597       IF (NOT pPurge) THEN
22598         INSERT INTO trgthist
22599         SELECT pSourceCntctId,pTargetCntctId,'cntct_initials', '''' || cntct_initials || ''''
22600         FROM cntct
22601         WHERE (cntct_id=pTargetCntctId);
22602       END IF;
22603       UPDATE cntct SET cntct_initials=_sel.cntct_initials WHERE (cntct_id=pTargetCntctId);
22604     END IF;
22605     IF (_sel.cntctsel_mrg_phone) THEN
22606       IF (NOT pPurge) THEN
22607         INSERT INTO trgthist
22608         SELECT pSourceCntctId,pTargetCntctId,'cntct_phone', '''' || cntct_phone || ''''
22609         FROM cntct
22610         WHERE (cntct_id=pTargetCntctId);
22611       END IF;
22612       UPDATE cntct SET cntct_phone=_sel.cntct_phone WHERE (cntct_id=pTargetCntctId);
22613     END IF;
22614     IF (_sel.cntctsel_mrg_phone2) THEN
22615       IF (NOT pPurge) THEN
22616         INSERT INTO trgthist
22617         SELECT pSourceCntctId,pTargetCntctId,'cntct_phone2', '''' || cntct_phone2 || ''''
22618         FROM cntct
22619         WHERE (cntct_id=pTargetCntctId);
22620       END IF;
22621       UPDATE cntct SET cntct_phone2=_sel.cntct_phone2 WHERE (cntct_id=pTargetCntctId);
22622     END IF;
22623     IF (_sel.cntctsel_mrg_fax)  THEN
22624       IF (NOT pPurge) THEN
22625         INSERT INTO trgthist
22626         SELECT pSourceCntctId,pTargetCntctId,'cntct_fax', '''' || cntct_fax || ''''
22627         FROM cntct
22628         WHERE (cntct_id=pTargetCntctId);
22629       END IF;
22630       UPDATE cntct SET cntct_fax=_sel.cntct_fax WHERE (cntct_id=pTargetCntctId);
22631     END IF;
22632     IF (_sel.cntctsel_mrg_email)  THEN
22633       IF (NOT pPurge) THEN
22634         INSERT INTO trgthist
22635         SELECT pSourceCntctId,pTargetCntctId,'cntct_email', '''' || cntct_email || ''''
22636         FROM cntct
22637         WHERE (cntct_id=pTargetCntctId);
22638       END IF;
22639       UPDATE cntct SET cntct_email=_sel.cntct_email WHERE (cntct_id=pTargetCntctId);
22640     END IF;
22641     IF (_sel.cntctsel_mrg_webaddr) THEN
22642       IF (NOT pPurge) THEN
22643         INSERT INTO trgthist
22644         SELECT pSourceCntctId,pTargetCntctId,'cntct_webaddr', '''' || cntct_webaddr || ''''
22645         FROM cntct
22646         WHERE (cntct_id=pTargetCntctId);
22647       END IF;
22648       UPDATE cntct SET cntct_webaddr=_sel.cntct_webaddr WHERE (cntct_id=pTargetCntctId);
22649     END IF;
22650     IF (_sel.cntctsel_mrg_notes) THEN
22651       IF (NOT pPurge) THEN
22652         INSERT INTO trgthist
22653         SELECT pSourceCntctId,pTargetCntctId,'cntct_notes', '''' || cntct_notes || ''''
22654         FROM cntct
22655         WHERE (cntct_id=pTargetCntctId);
22656       END IF;
22657       UPDATE cntct SET cntct_notes=cntct_notes || '
22658
22659       ' || _sel.cntct_notes WHERE (cntct_id=pTargetCntctId);
22660     END IF;
22661     IF (_sel.cntctsel_mrg_title) THEN
22662       IF (NOT pPurge) THEN
22663         INSERT INTO trgthist
22664         SELECT pSourceCntctId,pTargetCntctId,'cntct_title', '''' || cntct_title || ''''
22665         FROM cntct
22666         WHERE (cntct_id=pTargetCntctId);
22667       END IF;
22668       UPDATE cntct SET cntct_title=_sel.cntct_title WHERE (cntct_id=pTargetCntctId);
22669     END IF;
22670     IF (_sel.cntctsel_mrg_middle) THEN
22671       IF (NOT pPurge) THEN
22672         INSERT INTO trgthist
22673         SELECT pSourceCntctId,pTargetCntctId,'cntct_middle', '''' || cntct_middle || ''''
22674         FROM cntct
22675         WHERE (cntct_id=pTargetCntctId);
22676       END IF;
22677       UPDATE cntct SET cntct_middle=_sel.cntct_middle WHERE (cntct_id=pTargetCntctId);
22678     END IF;
22679     IF (_sel.cntctsel_mrg_suffix) THEN
22680       IF (NOT pPurge) THEN
22681         INSERT INTO trgthist
22682         SELECT pSourceCntctId,pTargetCntctId,'cntct_suffix', '''' || cntct_suffix || ''''
22683         FROM cntct
22684         WHERE (cntct_id=pTargetCntctId);
22685       END IF;
22686       UPDATE cntct SET cntct_suffix=_sel.cntct_suffix WHERE (cntct_id=pTargetCntctId);
22687     END IF;
22688     IF (_sel.cntctsel_mrg_owner_username) THEN
22689       IF (NOT pPurge) THEN
22690         INSERT INTO trgthist
22691         SELECT pSourceCntctId,pTargetCntctId,'cntct_owner_username', '''' || cntct_owner_username || ''''
22692         FROM cntct
22693         WHERE (cntct_id=pTargetCntctId);
22694       END IF;
22695       UPDATE cntct SET cntct_owner_username=_sel.cntct_owner_username WHERE (cntct_id=pTargetCntctId);
22696     END IF;
22697   ELSE
22698     RAISE EXCEPTION 'Source Contact not Found';
22699   END IF;
22700
22701   -- Disposition source contact
22702   IF (pPurge) THEN
22703     DELETE FROM cntct WHERE cntct_id = pSourceCntctId;
22704   END IF;
22705
22706   -- Deactivate contact
22707   UPDATE cntct SET cntct_active = false WHERE (cntct_id=pSourceCntctId);
22708   
22709   -- Clean up
22710   DELETE FROM cntctsel WHERE (cntctsel_cntct_id=pSourceCntctId);
22711
22712   RETURN true;
22713 END;
22714 $_$;
22715
22716
22717 ALTER FUNCTION public.cntctmerge(integer, integer, boolean) OWNER TO admin;
22718
22719 --
22720 -- TOC entry 1231 (class 1255 OID 146565777)
22721 -- Dependencies: 4536 8
22722 -- Name: cntctrestore(integer); Type: FUNCTION; Schema: public; Owner: admin
22723 --
22724
22725 CREATE FUNCTION cntctrestore(integer) RETURNS boolean
22726     LANGUAGE plpgsql
22727     AS $_$
22728 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22729 -- See www.xtuple.com/CPAL for the full text of the software license.
22730 DECLARE
22731   pCntctId ALIAS FOR $1;
22732   _r RECORD;
22733   _qry TEXT;
22734
22735 BEGIN
22736   -- Validate
22737   SELECT * INTO _r FROM cntctmrgd WHERE (cntctmrgd_cntct_id=pCntctId);
22738   IF (NOT FOUND) THEN
22739     RETURN false;
22740   END IF;
22741   
22742   -- Gather the list of affected records
22743   FOR _r IN
22744     SELECT * FROM mrghist
22745     WHERE (mrghist_cntct_id=pCntctId)
22746   LOOP
22747     -- Restore the old references
22748     _qry := 'UPDATE ' || _r.mrghist_table ||
22749             ' SET ' || _r.mrghist_cntct_col || '=' || pCntctId ||
22750             ' WHERE (' || _r.mrghist_pkey_col || '=' || _r.mrghist_pkey_id || ');';
22751     
22752    EXECUTE _qry;
22753          
22754   END LOOP;
22755
22756   -- Gather the list of affected fields
22757   FOR _r IN
22758     SELECT * FROM trgthist
22759     WHERE (trgthist_src_cntct_id=pCntctId)
22760   LOOP
22761     -- Restore the old values
22762     _qry := 'UPDATE cntct
22763               SET ' || _r.trgthist_col || '=' || _r.trgthist_value ||
22764             ' WHERE (cntct_id=' || _r.trgthist_trgt_cntct_id || ');';
22765     
22766    EXECUTE _qry;
22767          
22768   END LOOP;
22769
22770   -- Clean up
22771   UPDATE cntct SET cntct_active=true WHERE (cntct_id=pCntctId);
22772   DELETE FROM mrghist WHERE (mrghist_cntct_id=pCntctId);
22773   DELETE FROM trgthist WHERE (trgthist_src_cntct_id=pCntctId);
22774   DELETE FROM cntctmrgd WHERE (cntctmrgd_cntct_id=pCntctId);
22775
22776   RETURN true;
22777
22778 END;
22779 $_$;
22780
22781
22782 ALTER FUNCTION public.cntctrestore(integer) OWNER TO admin;
22783
22784 --
22785 -- TOC entry 1232 (class 1255 OID 146565778)
22786 -- Dependencies: 4536 8
22787 -- Name: cntctselect(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
22788 --
22789
22790 CREATE FUNCTION cntctselect(integer, boolean) RETURNS boolean
22791     LANGUAGE plpgsql
22792     AS $_$
22793 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22794 -- See www.xtuple.com/CPAL for the full text of the software license.
22795 DECLARE
22796   pCntctId ALIAS FOR $1;
22797   pTarget ALIAS FOR $2;
22798
22799 BEGIN
22800   -- If target, delete any other targets
22801   IF (pTarget) THEN
22802     DELETE FROM cntctsel WHERE cntctsel_target;
22803   END IF;
22804   
22805   -- Delete any previous selection of this contact
22806   DELETE FROM cntctsel WHERE cntctsel_cntct_id=pCntctId;
22807
22808   -- Add this contact in appropriate selection state
22809   INSERT INTO cntctsel VALUES (pCntctId,pTarget);
22810
22811   RETURN true;
22812 END;
22813 $_$;
22814
22815
22816 ALTER FUNCTION public.cntctselect(integer, boolean) OWNER TO admin;
22817
22818 --
22819 -- TOC entry 1233 (class 1255 OID 146565779)
22820 -- Dependencies: 4536 8
22821 -- Name: cntctselectcol(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
22822 --
22823
22824 CREATE FUNCTION cntctselectcol(integer, integer) RETURNS boolean
22825     LANGUAGE plpgsql
22826     AS $_$
22827 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22828 -- See www.xtuple.com/CPAL for the full text of the software license.
22829 DECLARE
22830   pCntctId ALIAS FOR $1;
22831   pColNumber ALIAS FOR $2;
22832
22833 BEGIN
22834
22835   IF (pColNumber = 2 OR pColNumber = 3) THEN
22836     UPDATE cntctsel SET cntctsel_mrg_crmacct_id=false WHERE (cntctsel_mrg_crmacct_id AND cntctsel_cntct_id != pCntctId);
22837     UPDATE cntctsel SET cntctsel_mrg_crmacct_id=true WHERE (cntctsel_cntct_id = pCntctId);
22838     RETURN true;
22839   ELSIF (pColNumber = 4) THEN
22840     UPDATE cntctsel SET cntctsel_mrg_honorific=false WHERE (cntctsel_mrg_honorific AND cntctsel_cntct_id != pCntctId);
22841     UPDATE cntctsel SET cntctsel_mrg_honorific=true WHERE (cntctsel_cntct_id = pCntctId);
22842     RETURN true;
22843   ELSIF (pColNumber = 5) THEN
22844     UPDATE cntctsel SET cntctsel_mrg_first_name=false WHERE (cntctsel_mrg_first_name AND cntctsel_cntct_id != pCntctId);
22845     UPDATE cntctsel SET cntctsel_mrg_first_name=true WHERE (cntctsel_cntct_id = pCntctId);
22846     RETURN true;
22847   ELSIF (pColNumber = 6) THEN
22848     UPDATE cntctsel SET cntctsel_mrg_middle=false WHERE (cntctsel_mrg_middle AND cntctsel_cntct_id != pCntctId);
22849     UPDATE cntctsel SET cntctsel_mrg_middle=true WHERE (cntctsel_cntct_id = pCntctId);
22850     RETURN true;
22851   ELSIF (pColNumber = 7) THEN
22852     UPDATE cntctsel SET cntctsel_mrg_last_name=false WHERE (cntctsel_mrg_last_name AND cntctsel_cntct_id != pCntctId);
22853     UPDATE cntctsel SET cntctsel_mrg_last_name=true WHERE (cntctsel_cntct_id = pCntctId);
22854     RETURN true;
22855   ELSIF (pColNumber = 8) THEN
22856     UPDATE cntctsel SET cntctsel_mrg_suffix=false WHERE (cntctsel_mrg_suffix AND cntctsel_cntct_id != pCntctId);
22857     UPDATE cntctsel SET cntctsel_mrg_suffix=true WHERE (cntctsel_cntct_id = pCntctId);
22858     RETURN true;
22859   ELSIF (pColNumber = 9) THEN
22860     UPDATE cntctsel SET cntctsel_mrg_initials=false WHERE (cntctsel_mrg_initials AND cntctsel_cntct_id != pCntctId);
22861     UPDATE cntctsel SET cntctsel_mrg_initials=true WHERE (cntctsel_cntct_id = pCntctId);
22862     RETURN true;
22863   ELSIF (pColNumber = 10) THEN
22864     UPDATE cntctsel SET cntctsel_mrg_phone=false WHERE (cntctsel_mrg_phone AND cntctsel_cntct_id != pCntctId);
22865     UPDATE cntctsel SET cntctsel_mrg_phone=true WHERE (cntctsel_cntct_id = pCntctId);
22866     RETURN true;
22867   ELSIF (pColNumber = 11) THEN
22868     UPDATE cntctsel SET cntctsel_mrg_phone2=false WHERE (cntctsel_mrg_phone2 AND cntctsel_cntct_id != pCntctId);
22869     UPDATE cntctsel SET cntctsel_mrg_phone2=true WHERE (cntctsel_cntct_id = pCntctId);
22870     RETURN true;
22871   ELSIF (pColNumber = 12) THEN
22872     UPDATE cntctsel SET cntctsel_mrg_fax=false WHERE (cntctsel_mrg_fax AND cntctsel_cntct_id != pCntctId);
22873     UPDATE cntctsel SET cntctsel_mrg_fax=true WHERE (cntctsel_cntct_id = pCntctId);
22874     RETURN true;
22875   ELSIF (pColNumber = 13) THEN
22876     UPDATE cntctsel SET cntctsel_mrg_email=false WHERE (cntctsel_mrg_email AND cntctsel_cntct_id != pCntctId);
22877     UPDATE cntctsel SET cntctsel_mrg_email=true WHERE (cntctsel_cntct_id = pCntctId);
22878     RETURN true;
22879   ELSIF (pColNumber = 14) THEN
22880     UPDATE cntctsel SET cntctsel_mrg_webaddr=false WHERE (cntctsel_mrg_webaddr AND cntctsel_cntct_id != pCntctId);
22881     UPDATE cntctsel SET cntctsel_mrg_webaddr=true WHERE (cntctsel_cntct_id = pCntctId);
22882     RETURN true;
22883   ELSIF (pColNumber = 15) THEN
22884     UPDATE cntctsel SET cntctsel_mrg_title=false WHERE (cntctsel_mrg_title AND cntctsel_cntct_id != pCntctId);
22885     UPDATE cntctsel SET cntctsel_mrg_title=true WHERE (cntctsel_cntct_id = pCntctId);
22886     RETURN true;
22887   ELSIF (pColNumber = 16) THEN
22888     UPDATE cntctsel SET cntctsel_mrg_owner_username=false WHERE (cntctsel_mrg_owner_username AND cntctsel_cntct_id != pCntctId);
22889     UPDATE cntctsel SET cntctsel_mrg_owner_username=true WHERE (cntctsel_cntct_id = pCntctId);
22890     RETURN true;
22891   ELSIF (pColNumber = 17) THEN
22892     UPDATE cntctsel SET cntctsel_mrg_notes=false WHERE (cntctsel_mrg_notes AND cntctsel_cntct_id != pCntctId);
22893     UPDATE cntctsel SET cntctsel_mrg_notes=true WHERE (cntctsel_cntct_id = pCntctId);
22894     RETURN true;
22895   ELSIF (pColNumber >= 18) THEN
22896     UPDATE cntctsel SET cntctsel_mrg_addr_id=false WHERE (cntctsel_mrg_addr_id AND cntctsel_cntct_id != pCntctId);
22897     UPDATE cntctsel SET cntctsel_mrg_addr_id=true WHERE (cntctsel_cntct_id = pCntctId);
22898     RETURN true;
22899   END IF;
22900
22901   RETURN false;
22902 END;
22903 $_$;
22904
22905
22906 ALTER FUNCTION public.cntctselectcol(integer, integer) OWNER TO admin;
22907
22908 --
22909 -- TOC entry 1234 (class 1255 OID 146565780)
22910 -- Dependencies: 4536 8
22911 -- Name: cntctused(integer); Type: FUNCTION; Schema: public; Owner: admin
22912 --
22913
22914 CREATE FUNCTION cntctused(integer) RETURNS boolean
22915     LANGUAGE plpgsql
22916     AS $_$
22917 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22918 -- See www.xtuple.com/CPAL for the full text of the software license.
22919 DECLARE
22920   pCntctId ALIAS FOR $1;
22921   _fk RECORD;
22922   _r RECORD;
22923   _seq INTEGER;
22924   _col TEXT;
22925   _qry TEXT;
22926
22927 BEGIN
22928   -- Determine where this contact is used by analyzing foreign key linkages
22929   -- but ignore child tables and those with impermanent relationships
22930   FOR _fk IN
22931     SELECT pg_namespace.nspname AS schemaname, con.relname AS tablename, conkey AS seq, conrelid AS class_id 
22932     FROM pg_constraint, pg_class f, pg_class con, pg_namespace
22933     WHERE confrelid=f.oid
22934     AND conrelid=con.oid
22935     AND f.relname = 'cntct'
22936     AND con.relnamespace=pg_namespace.oid
22937     AND con.relname NOT IN ('cntctaddr', 'cntctdata', 'cntcteml',
22938                             'cohead',    'pohead',    'quhead',   'tohead',
22939                             'cntctsel',  'cntctmrgd', 'mrghist',  'trgthist')
22940   LOOP
22941     -- Validate
22942     IF (ARRAY_UPPER(_fk.seq,1) > 1) THEN
22943       RAISE EXCEPTION 'Cannot check dependencies when the contact is one of multiple foreign key columns (%.%) [xtuple: fkeycheck, -1, %, %]',
22944         _fk.nspname, _fk.relname, _fk.nspname, _fk.relname;
22945     END IF;
22946     
22947     _seq := _fk.seq[1];
22948
22949     -- Get the specific column name
22950     SELECT attname INTO _col
22951     FROM pg_attribute, pg_class
22952     WHERE ((attrelid=pg_class.oid)
22953     AND (pg_class.oid=_fk.class_id)
22954     AND (attnum=_seq));
22955
22956     -- See if there are dependencies
22957     _qry := 'SELECT * 
22958             FROM ' || _fk.schemaname || '.' || _fk.tablename || '
22959             WHERE ('|| _col || '=' || pCntctId || ');';
22960
22961     FOR _r IN 
22962       EXECUTE _qry
22963     LOOP
22964       RETURN true;
22965     END LOOP;
22966          
22967   END LOOP;
22968
22969   RETURN false;
22970
22971 END;
22972 $_$;
22973
22974
22975 ALTER FUNCTION public.cntctused(integer) OWNER TO admin;
22976
22977 --
22978 -- TOC entry 1235 (class 1255 OID 146565781)
22979 -- Dependencies: 4536 8
22980 -- Name: coheadstatecolor(integer); Type: FUNCTION; Schema: public; Owner: admin
22981 --
22982
22983 CREATE FUNCTION coheadstatecolor(integer) RETURNS text
22984     LANGUAGE plpgsql
22985     AS $_$
22986 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
22987 -- See www.xtuple.com/CPAL for the full text of the software license.
22988 DECLARE
22989   pCoheadId     ALIAS FOR $1;
22990   _shipheadid   INTEGER;
22991   _result       TEXT := '';
22992
22993 BEGIN
22994   
22995   IF (pCoheadid IS NULL) THEN
22996     RAISE EXCEPTION 'Customer Id is required.';
22997   END IF;
22998   
22999   SELECT 
23000     shiphead_id INTO _shipheadid
23001   FROM cohead
23002     JOIN shiphead ON ((shiphead_order_id=cohead_id)
23003                   AND (shiphead_order_type='SO'))
23004     JOIN shipitem ON (shiphead_id=shipitem_shiphead_id)
23005   WHERE ((cohead_id=pCoheadId)
23006     AND (NOT shipitem_invoiced))
23007   ORDER BY shiphead_id DESC
23008   LIMIT 1;
23009
23010   IF (FOUND) THEN
23011     SELECT 
23012       CASE 
23013         WHEN ((shiphead_shipped) 
23014          AND (COALESCE(shiphead_order_id,0) > 0) 
23015          AND (SUM(noNeg(coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned)) <= 0)) THEN 
23016            'altemphasis'
23017         WHEN ((COALESCE(cobmisc_cohead_id,0) > 0)       
23018          AND (SUM(noNeg(coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned)) > 0)) THEN 
23019            'error' 
23020         WHEN (NOT shiphead_shipped) THEN 
23021           'emphasis' 
23022        END INTO _result
23023     FROM cohead
23024       JOIN coitem ON (cohead_id=coitem_cohead_id)
23025       JOIN shiphead ON ((shiphead_order_id=cohead_id)
23026                     AND (shiphead_order_type='SO'))
23027       JOIN shipitem ON (shiphead_id=shipitem_shiphead_id)
23028       LEFT OUTER JOIN (SELECT DISTINCT cobmisc_cohead_id FROM cobmisc) AS cobmisc ON (cobmisc_cohead_id=cohead_id) 
23029     WHERE (shiphead_id=_shipheadid)
23030     GROUP BY shiphead_id,shiphead_shipped,shiphead_order_id,cobmisc_cohead_id
23031     ORDER BY shiphead_id DESC;
23032   ELSE
23033     _result := '';
23034   END IF;
23035   
23036   RETURN _result;
23037   
23038 END;
23039 $_$;
23040
23041
23042 ALTER FUNCTION public.coheadstatecolor(integer) OWNER TO admin;
23043
23044 --
23045 -- TOC entry 1237 (class 1255 OID 146565782)
23046 -- Dependencies: 4536 8
23047 -- Name: compareversion(text, text); Type: FUNCTION; Schema: public; Owner: admin
23048 --
23049
23050 CREATE FUNCTION compareversion(text, text DEFAULT split_part(version(), ' '::text, 2)) RETURNS integer
23051     LANGUAGE plpgsql STABLE
23052     AS $_$
23053 DECLARE
23054   _leftVersion ALIAS FOR $1;
23055   _rightVersion ALIAS FOR $2;
23056   _leftMajor SMALLINT;
23057   _leftMinor SMALLINT;
23058   _leftPatch SMALLINT;
23059   _rightMajor SMALLINT;
23060   _rightMinor SMALLINT;
23061   _rightPatch SMALLINT;
23062   _returnCode SMALLINT;
23063   DEBUG BOOLEAN := false;
23064 BEGIN
23065
23066 -- left
23067 SELECT  substring(_leftVersion FROM $$(\d+)\.\d+\.\d+$$)::SMALLINT, 
23068         substring(_leftVersion FROM $$\d+\.(\d+)\.\d+$$)::SMALLINT, 
23069         substring(_leftVersion FROM $$\d+\.\d+\.(\d+)$$)::SMALLINT 
23070         INTO _leftMajor, _leftMinor, _leftPatch;
23071
23072 IF (DEBUG)
23073   THEN RAISE NOTICE 'Left Version --> % Major --> % Minor --> % Patch --> % ', _leftVersion, _leftMajor, _leftMinor, _leftPatch;
23074 END IF;
23075
23076 -- right
23077 SELECT  substring(_rightVersion FROM $$(\d+)\.\d+\.\d+$$)::SMALLINT, 
23078         substring(_rightVersion FROM $$\d+\.(\d+)\.\d+$$)::SMALLINT, 
23079         substring(_rightVersion FROM $$\d+\.\d+\.(\d+)$$)::SMALLINT 
23080         INTO _rightMajor, _rightMinor, _rightPatch;
23081
23082 IF (DEBUG)
23083  THEN RAISE NOTICE 'Right Version --> % Major --> % Minor --> % Patch --> % ', _rightVersion, _rightMajor, _rightMinor, _rightPatch;
23084 END IF;
23085
23086 -- check major version
23087 IF (_leftMajor > _rightMajor) THEN _returnCode := 1;
23088 ELSIF (_leftMajor < _rightMajor) THEN _returnCode := -1;
23089 ELSIF (_leftMajor = _rightMajor) THEN
23090   -- if major is equal, check minor version
23091   IF (_leftMinor > _rightMinor) THEN _returnCode := 1;
23092   ELSIF (_leftMinor < _rightMinor) THEN _returnCode := -1;
23093   ELSIF (_leftMinor = _rightMinor) THEN
23094     -- if major and minor are equal, check patch version
23095     IF (_leftPatch > _rightPatch) THEN _returnCode := 1;
23096     ELSIF (_leftPatch < _rightPatch) THEN _returnCode := -1;
23097     ELSIF (_leftPatch = _rightPatch) THEN _returnCode := 0;
23098     END IF;
23099   END IF;
23100 -- if we somehow don't match those three operators it probably means someone passed in a version that wasn't in numerical major.minor.patch format
23101 ELSE RAISE EXCEPTION 'One or more of the version parameters is invalid. Expected numerical Major.Minor.Patch version string. Left --> % Right --> %', _leftVersion, _rightVersion;
23102 END IF;
23103
23104 RETURN _returnCode;
23105
23106 END;
23107 $_$;
23108
23109
23110 ALTER FUNCTION public.compareversion(text, text) OWNER TO admin;
23111
23112 --
23113 -- TOC entry 1238 (class 1255 OID 146565783)
23114 -- Dependencies: 4536 8
23115 -- Name: concataggsfunc(text, text); Type: FUNCTION; Schema: public; Owner: admin
23116 --
23117
23118 CREATE FUNCTION concataggsfunc(text, text) RETURNS text
23119     LANGUAGE plpgsql
23120     AS $_$
23121 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23122 -- See www.xtuple.com/CPAL for the full text of the software license.
23123 DECLARE
23124   prevstate     ALIAS FOR $1;
23125   newval        ALIAS FOR $2;
23126 BEGIN
23127   RETURN prevstate || newval;
23128 END;
23129 $_$;
23130
23131
23132 ALTER FUNCTION public.concataggsfunc(text, text) OWNER TO admin;
23133
23134 --
23135 -- TOC entry 1239 (class 1255 OID 146565784)
23136 -- Dependencies: 4536 8
23137 -- Name: consolidatelocations(integer); Type: FUNCTION; Schema: public; Owner: admin
23138 --
23139
23140 CREATE FUNCTION consolidatelocations(integer) RETURNS integer
23141     LANGUAGE plpgsql
23142     AS $_$
23143 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23144 -- See www.xtuple.com/CPAL for the full text of the software license.
23145 DECLARE
23146   pItemsiteid ALIAS FOR $1;
23147   _r RECORD;
23148
23149 BEGIN
23150
23151   UPDATE itemloc
23152   SET itemloc_consolflag = TRUE
23153   WHERE (itemloc_itemsite_id=pItemsiteid);
23154
23155   FOR _r IN SELECT itemloc_location_id, SUM(itemloc_qty) AS qty
23156             FROM itemloc
23157             WHERE (itemloc_itemsite_id=pItemsiteid)
23158             GROUP BY itemloc_location_id LOOP
23159     INSERT INTO itemloc
23160     ( itemloc_itemsite_id, itemloc_location_id,
23161       itemloc_expiration, itemloc_qty, itemloc_consolflag )
23162     VALUES
23163     ( pItemsiteid, _r.itemloc_location_id,
23164       endOfTime(), _r.qty, FALSE );
23165   END LOOP;
23166
23167   DELETE FROM itemloc
23168   WHERE ( (itemloc_itemsite_id=pItemsiteid)
23169    AND (itemloc_consolflag) );
23170
23171   RETURN 1;
23172
23173 END;
23174 $_$;
23175
23176
23177 ALTER FUNCTION public.consolidatelocations(integer) OWNER TO admin;
23178
23179 --
23180 -- TOC entry 1240 (class 1255 OID 146565785)
23181 -- Dependencies: 4536 8
23182 -- Name: convertcustomertoprospect(integer); Type: FUNCTION; Schema: public; Owner: admin
23183 --
23184
23185 CREATE FUNCTION convertcustomertoprospect(integer) RETURNS integer
23186     LANGUAGE plpgsql
23187     AS $_$
23188 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23189 -- See www.xtuple.com/CPAL for the full text of the software license.
23190 DECLARE
23191   pCustId     ALIAS FOR $1;
23192   _c          RECORD;
23193 BEGIN
23194   SELECT * INTO _c
23195   FROM custinfo
23196   WHERE (cust_id=pCustId);
23197
23198   INSERT INTO prospect (
23199         prospect_id, prospect_active, prospect_number,
23200         prospect_name, prospect_cntct_id, prospect_taxzone_id,
23201         prospect_salesrep_id, prospect_warehous_id, prospect_comments
23202   ) VALUES (
23203        _c.cust_id, _c.cust_active, _c.cust_number,
23204        _c.cust_name, _c.cust_cntct_id, _c.cust_taxzone_id,
23205        CASE WHEN(_c.cust_salesrep_id > 0) THEN _c.cust_salesrep_id
23206             ELSE NULL
23207        END,
23208        CASE WHEN(_c.cust_preferred_warehous_id > 0) THEN _c.cust_preferred_warehous_id
23209             ELSE NULL
23210        END,
23211        _c.cust_comments);
23212
23213   DELETE FROM custinfo WHERE (cust_id=pCustId);
23214
23215   RETURN pCustId;
23216 END;
23217 $_$;
23218
23219
23220 ALTER FUNCTION public.convertcustomertoprospect(integer) OWNER TO admin;
23221
23222 --
23223 -- TOC entry 1241 (class 1255 OID 146565786)
23224 -- Dependencies: 4536 8
23225 -- Name: convertprospecttocustomer(integer); Type: FUNCTION; Schema: public; Owner: admin
23226 --
23227
23228 CREATE FUNCTION convertprospecttocustomer(integer) RETURNS integer
23229     LANGUAGE plpgsql
23230     AS $_$
23231 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23232 -- See www.xtuple.com/CPAL for the full text of the software license.
23233 BEGIN
23234   RETURN convertProspectToCustomer($1, FALSE);
23235 END;
23236 $_$;
23237
23238
23239 ALTER FUNCTION public.convertprospecttocustomer(integer) OWNER TO admin;
23240
23241 --
23242 -- TOC entry 1242 (class 1255 OID 146565787)
23243 -- Dependencies: 4536 8
23244 -- Name: convertprospecttocustomer(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
23245 --
23246
23247 CREATE FUNCTION convertprospecttocustomer(integer, boolean) RETURNS integer
23248     LANGUAGE plpgsql
23249     AS $_$
23250 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23251 -- See www.xtuple.com/CPAL for the full text of the software license.
23252 DECLARE
23253   pProspectId ALIAS FOR $1;
23254   pdoquotes   ALIAS FOR $2;
23255   _p          RECORD;
23256   _q          RECORD;
23257
23258 BEGIN
23259   SELECT * INTO _p
23260   FROM prospect
23261   WHERE (prospect_id=pProspectId);
23262
23263   IF (EXISTS(SELECT cust_id FROM custinfo WHERE cust_id=pProspectId)) THEN
23264     RAISE EXCEPTION '[xtuple: convertProspectToCustomer, -10]';
23265   END IF;
23266
23267   INSERT INTO custinfo (
23268         cust_id, cust_active, cust_number,
23269         cust_name, cust_cntct_id, cust_taxzone_id,
23270         cust_comments, cust_creditstatus,
23271         cust_salesrep_id, cust_preferred_warehous_id,
23272         cust_terms_id,
23273         cust_custtype_id, cust_shipform_id,
23274         cust_shipvia, cust_balmethod,
23275         cust_ffshipto, cust_backorder,
23276         cust_partialship, cust_creditlmt,
23277         cust_creditrating, cust_commprcnt,
23278         cust_discntprcnt, cust_blanketpos,
23279         cust_shipchrg_id, cust_ffbillto,
23280         cust_usespos, cust_emaildelivery,
23281         cust_autoupdatestatus,cust_autoholdorders,
23282         cust_soemaildelivery) 
23283   SELECT
23284       _p.prospect_id, _p.prospect_active, _p.prospect_number,
23285       _p.prospect_name, _p.prospect_cntct_id, _p.prospect_taxzone_id,
23286       _p.prospect_comments, 'G',
23287       COALESCE(_p.prospect_salesrep_id, salesrep_id),
23288       COALESCE(_p.prospect_warehous_id, -1),
23289       FetchMetricValue('DefaultTerms'),
23290       FetchMetricValue('DefaultCustType'),
23291       FetchMetricValue('DefaultShipFormId'),
23292       COALESCE(FetchMetricValue('DefaultShipViaId'),-1),
23293       FetchMetricText('DefaultBalanceMethod'),
23294       FetchMetricBool('DefaultFreeFormShiptos'),
23295       FetchMetricBool('DefaultBackOrders'),
23296       FetchMetricBool('DefaultPartialShipments'),
23297       FetchMetricValue('SOCreditLimit'),
23298       FetchMetricText('SOCreditRate'),
23299       salesrep_commission,
23300       0, false, -1,false,false,false,false,
23301       false, false
23302   FROM salesrep WHERE (salesrep_id=FetchMetricValue('DefaultSalesRep'));
23303
23304   DELETE FROM prospect WHERE (prospect_id=pprospectId);
23305
23306   IF (pdoquotes) THEN
23307     BEGIN
23308       FOR _q IN SELECT quhead_number, convertQuote(quhead_id) AS err
23309                   FROM quhead
23310                  WHERE ((COALESCE(quhead_expire, endOfTime()) >= CURRENT_DATE)
23311                     AND (quhead_cust_id=pProspectId)) LOOP
23312         IF (_q.err < 0) THEN
23313           RAISE NOTICE 'Quote % for % didn''t convert to a Sales Order [xtuple: convertQuote, %]',
23314                        _q.quhead_number, _p.prospect_number, _q.err;
23315         END IF;
23316       END LOOP;
23317     EXCEPTION WHEN OTHERS THEN
23318       RAISE NOTICE 'Ignored errors convering quotes: % %', SQLSTATE, SQLERRM;
23319     END;
23320   END IF;
23321
23322   RETURN pProspectId;
23323 END;
23324 $_$;
23325
23326
23327 ALTER FUNCTION public.convertprospecttocustomer(integer, boolean) OWNER TO admin;
23328
23329 --
23330 -- TOC entry 1243 (class 1255 OID 146565788)
23331 -- Dependencies: 4536 8
23332 -- Name: convertquote(integer); Type: FUNCTION; Schema: public; Owner: admin
23333 --
23334
23335 CREATE FUNCTION convertquote(integer) RETURNS integer
23336     LANGUAGE plpgsql
23337     AS $_$
23338 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23339 -- See www.xtuple.com/CPAL for the full text of the software license.
23340 DECLARE
23341   pQuheadid ALIAS FOR $1;
23342   _soheadid INTEGER;
23343   _soitemid INTEGER;
23344   _orderid INTEGER;
23345   _ordertype CHARACTER(1);
23346   _creditstatus TEXT;
23347   _usespos BOOLEAN := false;
23348   _blanketpos BOOLEAN := true;
23349   _showConvertedQuote BOOLEAN := false;
23350   _prospectid   INTEGER;
23351   _r RECORD;
23352   _soNum TEXT;
23353
23354 BEGIN
23355
23356 -- Check to make sure the quote has not expired
23357   IF (SELECT COALESCE(quhead_expire, endOfTime()) < CURRENT_DATE
23358         FROM quhead
23359        WHERE(quhead_id=pQuheadid)) THEN
23360     RETURN -6;
23361   END IF;
23362
23363 --  Check to make sure that all of the quote items have a valid itemsite
23364   SELECT quitem_id INTO _r
23365     FROM quitem LEFT OUTER JOIN itemsite ON (quitem_itemsite_id=itemsite_id)
23366    WHERE ((itemsite_id IS NULL)
23367      AND  (quitem_quhead_id=pQuheadid));
23368   IF (FOUND) THEN
23369     PERFORM postEvent('CannotConvertQuote', 'Q', quhead_id,
23370                       quhead_warehous_id, quhead_number,
23371                       NULL, NULL, NULL, NULL)
23372     FROM quhead
23373     WHERE (quhead_id=pQuheadid);
23374
23375     RETURN -1;
23376   END IF;
23377
23378   SELECT cust_creditstatus, cust_usespos, cust_blanketpos
23379     INTO _creditstatus, _usespos, _blanketpos
23380   FROM quhead, custinfo
23381   WHERE ((quhead_cust_id=cust_id)
23382     AND  (quhead_id=pQuheadid));
23383
23384   IF (NOT FOUND) THEN
23385     SELECT prospect_id INTO _prospectid
23386     FROM quhead, prospect
23387     WHERE ((quhead_cust_id=prospect_id)
23388       AND  (quhead_id=pQuheadid));
23389     IF (NOT FOUND) THEN
23390       RETURN -2;
23391     ELSE
23392       RETURN -3;
23393     END IF;
23394   ELSIF (_creditstatus = 'H' AND NOT checkPrivilege('CreateSOForHoldCustomer')) THEN
23395     RETURN -4;
23396   ELSIF (_creditstatus = 'W' AND NOT checkPrivilege('CreateSOForWarnCustomer')) THEN
23397     RETURN -5;
23398   END IF;
23399
23400   IF ( (_usespos) AND (NOT _blanketpos) ) THEN
23401     PERFORM cohead_id
23402     FROM quhead JOIN cohead ON ( (cohead_cust_id=quhead_cust_id) AND
23403                                  (UPPER(cohead_custponumber)=UPPER(quhead_custponumber)) )
23404     WHERE (quhead_id=pQuheadid);
23405     IF (FOUND) THEN
23406       RAISE EXCEPTION 'Duplicate Customer PO';
23407     END IF;
23408   END IF;
23409   
23410   PERFORM quhead_number, cohead_id 
23411   FROM quhead, cohead 
23412   WHERE quhead_id = pQuheadid
23413   AND cohead_number = quhead_number;
23414
23415   IF (FOUND) THEN
23416     SELECT fetchSoNumber() INTO _soNum;
23417   ELSE
23418     SELECT quhead_number INTO _soNum
23419     FROM quhead
23420     WHERE quhead_id = pQuheadid;
23421   END IF;
23422
23423   SELECT NEXTVAL('cohead_cohead_id_seq') INTO _soheadid;
23424   INSERT INTO cohead
23425   ( cohead_id, cohead_number, cohead_cust_id,
23426     cohead_orderdate, cohead_packdate,
23427     cohead_custponumber, cohead_warehous_id,
23428     cohead_billtoname, cohead_billtoaddress1,
23429     cohead_billtoaddress2, cohead_billtoaddress3,
23430     cohead_billtocity, cohead_billtostate, cohead_billtozipcode,
23431     cohead_billtocountry,
23432     cohead_shipto_id, cohead_shiptoname, cohead_shiptoaddress1,
23433     cohead_shiptoaddress2, cohead_shiptoaddress3,
23434     cohead_shiptocity, cohead_shiptostate, cohead_shiptozipcode,
23435     cohead_shiptocountry,
23436     cohead_salesrep_id, cohead_commission,
23437     cohead_terms_id, cohead_shipchrg_id, cohead_shipform_id,
23438     cohead_fob, cohead_shipvia,
23439     cohead_ordercomments, cohead_shipcomments,
23440     cohead_freight, cohead_misc, cohead_misc_accnt_id, cohead_misc_descrip,
23441     cohead_holdtype, cohead_wasquote, cohead_quote_number, cohead_prj_id,
23442     cohead_curr_id, cohead_taxzone_id, cohead_taxtype_id,
23443     cohead_shipto_cntct_id, cohead_shipto_cntct_honorific, cohead_shipto_cntct_first_name,
23444     cohead_shipto_cntct_middle, cohead_shipto_cntct_last_name, cohead_shipto_cntct_suffix,
23445     cohead_shipto_cntct_phone, cohead_shipto_cntct_title, cohead_shipto_cntct_fax, 
23446     cohead_shipto_cntct_email,
23447     cohead_billto_cntct_id, cohead_billto_cntct_honorific,
23448     cohead_billto_cntct_first_name, cohead_billto_cntct_middle, cohead_billto_cntct_last_name, 
23449     cohead_billto_cntct_suffix, cohead_billto_cntct_phone, cohead_billto_cntct_title, 
23450     cohead_billto_cntct_fax, cohead_billto_cntct_email, cohead_ophead_id,
23451     cohead_calcfreight, cohead_saletype_id, cohead_shipzone_id )
23452   SELECT _soheadid, _soNum, quhead_cust_id,
23453          CURRENT_DATE, quhead_packdate,
23454          quhead_custponumber, quhead_warehous_id,
23455          quhead_billtoname, quhead_billtoaddress1,
23456          quhead_billtoaddress2, quhead_billtoaddress3,
23457          quhead_billtocity, quhead_billtostate, quhead_billtozip,
23458          quhead_billtocountry,
23459          quhead_shipto_id, quhead_shiptoname, quhead_shiptoaddress1,
23460          quhead_shiptoaddress2, quhead_shiptoaddress3,
23461          quhead_shiptocity, quhead_shiptostate, quhead_shiptozipcode,
23462          quhead_shiptocountry,
23463          quhead_salesrep_id, quhead_commission,
23464          quhead_terms_id, cust_shipchrg_id, cust_shipform_id,
23465          quhead_fob, quhead_shipvia,
23466          quhead_ordercomments, quhead_shipcomments,
23467          quhead_freight, quhead_misc, quhead_misc_accnt_id, quhead_misc_descrip,
23468          'N', TRUE, quhead_number, quhead_prj_id,
23469          quhead_curr_id, quhead_taxzone_id, quhead_taxtype_id,
23470          quhead_shipto_cntct_id, quhead_shipto_cntct_honorific,
23471          quhead_shipto_cntct_first_name, quhead_shipto_cntct_middle, quhead_shipto_cntct_last_name,
23472          quhead_shipto_cntct_suffix, quhead_shipto_cntct_phone, quhead_shipto_cntct_title,
23473          quhead_shipto_cntct_fax, quhead_shipto_cntct_email, quhead_billto_cntct_id,
23474          quhead_billto_cntct_honorific, quhead_billto_cntct_first_name, quhead_billto_cntct_middle,
23475          quhead_billto_cntct_last_name, quhead_billto_cntct_suffix, quhead_billto_cntct_phone,
23476          quhead_billto_cntct_title, quhead_billto_cntct_fax, quhead_billto_cntct_email, quhead_ophead_id,
23477          quhead_calcfreight, quhead_saletype_id, quhead_shipzone_id
23478   FROM quhead JOIN custinfo ON (cust_id=quhead_cust_id)
23479   WHERE (quhead_id=pQuheadid);
23480
23481   UPDATE url SET url_source_id = _soheadid,
23482                  url_source = 'S'
23483   WHERE ((url_source='Q') AND (url_source_id = pQuheadid));
23484
23485   UPDATE imageass SET imageass_source_id = _soheadid,
23486                       imageass_source = 'S'
23487   WHERE ((imageass_source='Q') AND (imageass_source_id = pQuheadid));
23488
23489   UPDATE docass SET docass_source_id = _soheadid,
23490                     docass_source_type = 'S'
23491   WHERE ((docass_source_type='Q') AND (docass_source_id = pQuheadid));
23492
23493   -- Copy Comments
23494   INSERT INTO comment
23495   ( comment_cmnttype_id, comment_source, comment_source_id, comment_date, comment_user, comment_text, comment_public )
23496   SELECT comment_cmnttype_id, 'S', _soheadid, comment_date, comment_user, ('Quote-' || comment_text), comment_public
23497   FROM comment
23498   WHERE ( (comment_source='Q')
23499     AND   (comment_source_id=pQuheadid) );
23500
23501   FOR _r IN SELECT quitem.*,
23502                    quhead_number, quhead_prj_id,
23503                    itemsite_item_id, itemsite_leadtime,
23504                    itemsite_createsopo, itemsite_createsopr,
23505                    item_type, COALESCE(quitem_itemsrc_id, itemsrc_id, -1) AS itemsrcid
23506             FROM quhead JOIN quitem ON (quitem_quhead_id=quhead_id)
23507                         JOIN itemsite ON (itemsite_id=quitem_itemsite_id)
23508                         JOIN item ON (item_id=itemsite_item_id)
23509                         LEFT OUTER JOIN itemsrc ON ( (itemsrc_item_id=item_id) AND
23510                                                      (itemsrc_default) )
23511             WHERE (quhead_id=pQuheadid)
23512             ORDER BY quitem_linenumber LOOP
23513
23514     SELECT NEXTVAL('coitem_coitem_id_seq') INTO _soitemid;
23515
23516     INSERT INTO coitem
23517     ( coitem_id, coitem_cohead_id, coitem_linenumber, coitem_itemsite_id,
23518       coitem_status, coitem_scheddate, coitem_promdate,
23519       coitem_price, coitem_custprice, 
23520       coitem_qtyord, coitem_qtyshipped, coitem_qtyreturned,
23521       coitem_qty_uom_id, coitem_qty_invuomratio,
23522       coitem_price_uom_id, coitem_price_invuomratio,
23523       coitem_unitcost, coitem_prcost,
23524       coitem_custpn, coitem_memo, coitem_taxtype_id, coitem_order_id )
23525     VALUES
23526     ( _soitemid, _soheadid, _r.quitem_linenumber, _r.quitem_itemsite_id,
23527       'O', _r.quitem_scheddate, _r.quitem_promdate,
23528       _r.quitem_price, _r.quitem_custprice,
23529       _r.quitem_qtyord, 0, 0,
23530       _r.quitem_qty_uom_id, _r.quitem_qty_invuomratio,
23531       _r.quitem_price_uom_id, _r.quitem_price_invuomratio,
23532       stdcost(_r.itemsite_item_id), _r.quitem_prcost,
23533       _r.quitem_custpn, _r.quitem_memo, _r.quitem_taxtype_id, -1 );
23534
23535     IF (fetchMetricBool('enablextcommissionission')) THEN
23536       PERFORM xtcommission.getSalesReps(quhead_cust_id, quhead_shipto_id,
23537                                         _r.itemsite_item_id, _r.quitem_price,
23538                                         _soitemid, 'SalesItem')
23539       FROM quhead
23540       WHERE (quhead_id=pQuheadid);
23541     END IF;
23542
23543     INSERT INTO charass
23544           (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default, charass_price)
23545     SELECT 'SI', _soitemid, charass_char_id, charass_value, charass_default, charass_price
23546       FROM charass
23547      WHERE ((charass_target_type='QI')
23548        AND  (charass_target_id=_r.quitem_id));
23549
23550     -- Copy Comments
23551     INSERT INTO comment
23552     ( comment_cmnttype_id, comment_source, comment_source_id, comment_date, comment_user, comment_text )
23553     SELECT comment_cmnttype_id, 'SI', _soitemid, comment_date, comment_user, ('Quote-' || comment_text)
23554     FROM comment
23555     WHERE ( (comment_source='QI')
23556       AND   (comment_source_id=_r.quitem_id) );
23557
23558     _orderid := -1;
23559     _ordertype := '';
23560     IF (_r.quitem_createorder) THEN
23561
23562       IF (_r.item_type IN ('M')) THEN
23563         SELECT createWo( CAST(_r.quhead_number AS INTEGER), supply.itemsite_id, 1, (_r.quitem_qtyord * _r.quitem_qty_invuomratio),
23564                          _r.itemsite_leadtime, _r.quitem_scheddate, _r.quitem_memo, 'S', _soitemid, _r.quhead_prj_id ) INTO _orderId
23565         FROM itemsite sold, itemsite supply
23566         WHERE ((sold.itemsite_item_id=supply.itemsite_item_id)
23567          AND (supply.itemsite_warehous_id=_r.quitem_order_warehous_id)
23568          AND (sold.itemsite_id=_r.quitem_itemsite_id) );
23569         _orderType := 'W';
23570
23571         INSERT INTO charass
23572               (charass_target_type, charass_target_id, charass_char_id, charass_value)
23573         SELECT 'W', _orderId, charass_char_id, charass_value
23574           FROM charass
23575          WHERE ((charass_target_type='QI')
23576            AND  (charass_target_id=_r.quitem_id));
23577
23578       ELSIF ( (_r.item_type IN ('P', 'O')) AND (_r.itemsite_createsopr) ) THEN
23579         SELECT createPr( CAST(_r.quhead_number AS INTEGER), _r.quitem_itemsite_id, (_r.quitem_qtyord * _r.quitem_qty_invuomratio),
23580                          _r.quitem_scheddate, '', 'S', _soitemid ) INTO _orderId;
23581         _orderType := 'R';
23582         UPDATE pr SET pr_prj_id=_r.quhead_prj_id WHERE pr_id=_orderId;
23583       ELSIF ( (_r.item_type IN ('P', 'O')) AND (_r.itemsite_createsopo) ) THEN
23584         IF (_r.quitem_prcost=0) THEN
23585           SELECT createPurchaseToSale(_soitemid, _r.itemsrcid, _r.quitem_dropship) INTO _orderId;
23586         ELSE
23587           SELECT createPurchaseToSale(_soitemid, _r.itemsrcid, _r.quitem_dropship, _r.quitem_prcost) INTO _orderId;
23588         END IF;
23589         _orderType := 'P';
23590       END IF;
23591
23592       UPDATE coitem SET coitem_order_type=_ordertype, coitem_order_id=_orderid
23593       WHERE (coitem_id=_soitemid);
23594
23595     END IF;
23596
23597   END LOOP;
23598
23599   SELECT metric_value INTO _showConvertedQuote
23600   FROM metric WHERE metric_name = 'ShowQuotesAfterSO';
23601
23602   IF (_showConvertedQuote) THEN
23603     UPDATE quhead
23604     SET quhead_status= 'C'
23605     WHERE (quhead_id = pQuheadid);
23606   ELSE
23607   PERFORM deleteQuote(pQuheadid);
23608   END IF;
23609
23610   RETURN _soheadid;
23611
23612 END;
23613 $_$;
23614
23615
23616 ALTER FUNCTION public.convertquote(integer) OWNER TO admin;
23617
23618 --
23619 -- TOC entry 1244 (class 1255 OID 146565790)
23620 -- Dependencies: 4536 8
23621 -- Name: convertquotetoinvoice(integer); Type: FUNCTION; Schema: public; Owner: admin
23622 --
23623
23624 CREATE FUNCTION convertquotetoinvoice(integer) RETURNS integer
23625     LANGUAGE plpgsql
23626     AS $_$
23627 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23628 -- See www.xtuple.com/CPAL for the full text of the software license.
23629 DECLARE
23630   pQuheadid ALIAS FOR $1;
23631   _iheadid INTEGER;
23632   _iitemid INTEGER;
23633   _orderid INTEGER;
23634   _ordertype CHARACTER(1);
23635   _creditstatus TEXT;
23636   _usespos BOOLEAN := false;
23637   _blanketpos BOOLEAN := true;
23638   _showConvertedQuote BOOLEAN := false;
23639   _prospectid   INTEGER;
23640   _r RECORD;
23641   _inNum TEXT;
23642
23643 BEGIN
23644
23645 -- Check to make sure the quote has not expired
23646   IF (SELECT COALESCE(quhead_expire, endOfTime()) < CURRENT_DATE
23647         FROM quhead
23648        WHERE(quhead_id=pQuheadid)) THEN
23649     RETURN -6;
23650   END IF;
23651
23652 --  Check to make sure that all of the quote items have a valid itemsite
23653   SELECT quitem_id INTO _r
23654     FROM quitem LEFT OUTER JOIN itemsite ON (quitem_itemsite_id=itemsite_id)
23655    WHERE ((itemsite_id IS NULL)
23656      AND  (quitem_quhead_id=pQuheadid));
23657   IF (FOUND) THEN
23658     PERFORM postEvent('CannotConvertQuote', 'Q', quhead_id,
23659                       quhead_warehous_id, quhead_number,
23660                       NULL, NULL, NULL, NULL)
23661     FROM quhead
23662     WHERE (quhead_id=pQuheadid);
23663
23664     RETURN -1;
23665   END IF;
23666
23667 -- Get Credit Stat, Uses POs and Blanket POs
23668
23669   SELECT cust_creditstatus, cust_usespos, cust_blanketpos
23670     INTO _creditstatus, _usespos, _blanketpos
23671   FROM quhead, custinfo
23672   WHERE ((quhead_cust_id=cust_id)
23673     AND  (quhead_id=pQuheadid));
23674
23675 -- Check to see if customer or prospect
23676
23677   IF (NOT FOUND) THEN
23678     SELECT prospect_id INTO _prospectid
23679     FROM quhead, prospect
23680     WHERE ((quhead_cust_id=prospect_id)
23681       AND  (quhead_id=pQuheadid));
23682     IF (NOT FOUND) THEN
23683       RETURN -2;
23684     ELSE
23685       RETURN -3;
23686     END IF;
23687   ELSIF (_creditstatus = 'H' AND NOT hasPriv('CreateSOForHoldCustomer')) THEN
23688     RETURN -4;
23689   ELSIF (_creditstatus = 'W' AND NOT hasPriv('CreateSOForWarnCustomer')) THEN
23690     RETURN -5;
23691   END IF;
23692
23693 -- PO/blanket PO checks
23694
23695   IF ( (_usespos) AND (NOT _blanketpos) ) THEN
23696     PERFORM invchead_id
23697     FROM quhead JOIN invchead ON ( (invchead_cust_id=quhead_cust_id) AND
23698                                  (UPPER(invchead_custponumber)=UPPER(quhead_custponumber)) )
23699     WHERE (quhead_id=pQuheadid);
23700     IF (FOUND) THEN
23701       RAISE EXCEPTION 'Duplicate Customer PO';
23702     END IF;
23703   END IF;
23704
23705 --Check to see if an invoice exists with the quote number
23706   
23707   PERFORM quhead_number, invchead_id 
23708   FROM quhead, invchead 
23709   WHERE quhead_id = pQuheadid
23710   AND invchead_invcnumber = quhead_number;
23711
23712 -- If it does then get a new Invoice number otherwise use the quote number as the invoice number
23713
23714   IF (FOUND) THEN
23715     SELECT fetchinvcnumber() INTO _inNum;
23716   ELSE
23717     SELECT quhead_number INTO _inNum
23718     FROM quhead
23719     WHERE quhead_id = pQuheadid;
23720   END IF;
23721
23722 --Insert quote info into invoice tables
23723
23724   SELECT NEXTVAL('invchead_invchead_id_seq') INTO _iheadid;
23725   INSERT INTO invchead
23726   ( invchead_ordernumber, invchead_shipdate, invchead_recurring,
23727     invchead_id, invchead_invcnumber, invchead_cust_id,
23728     invchead_orderdate, invchead_ponumber, 
23729     invchead_billto_name, invchead_billto_address1,
23730     invchead_billto_address2, invchead_billto_address3,
23731     invchead_billto_city, invchead_billto_state, invchead_billto_zipcode, invchead_billto_country,
23732     invchead_shipto_id, invchead_shipto_name, invchead_shipto_address1,
23733     invchead_shipto_address2, invchead_shipto_address3,
23734     invchead_shipto_city, invchead_shipto_state, invchead_shipto_zipcode, invchead_shipto_country, 
23735     invchead_salesrep_id, invchead_commission,
23736     invchead_terms_id, invchead_shipchrg_id, invchead_fob, invchead_shipvia,
23737     invchead_notes, invchead_freight, 
23738     invchead_misc_amount, invchead_misc_accnt_id, invchead_misc_descrip,
23739     invchead_prj_id, invchead_curr_id, invchead_taxzone_id,
23740     invchead_posted, invchead_printed, invchead_invcdate,
23741     invchead_saletype_id, invchead_shipzone_id
23742     --invchead_taxtype_id,
23743     --invchead_shipto_cntct_id, invchead_shipto_cntct_honorific, invchead_shipto_cntct_first_name,
23744     --invchead_shipto_cntct_middle, invchead_shipto_cntct_last_name, invchead_shipto_cntct_suffix,
23745     --invchead_shipto_cntct_phone, invchead_shipto_cntct_title, invchead_shipto_cntct_fax, 
23746     --invchead_shipto_cntct_email,
23747     --invchead_billto_cntct_id, invchead_billto_cntct_honorific,
23748     --invchead_billto_cntct_first_name, invchead_billto_cntct_middle, invchead_billto_cntct_last_name, 
23749     --invchead_billto_cntct_suffix, invchead_billto_cntct_phone, invchead_billto_cntct_title, 
23750     --invchead_billto_cntct_fax, invchead_billto_cntct_email, 
23751     --invchead_ophead_id,
23752     --invchead_calcfreight 
23753     )
23754   SELECT quhead_number, quhead_packdate, 'f',
23755          _iheadid, _inNum, quhead_cust_id,
23756          CURRENT_DATE, quhead_custponumber, 
23757          quhead_billtoname, quhead_billtoaddress1,
23758          quhead_billtoaddress2, quhead_billtoaddress3,
23759          quhead_billtocity, quhead_billtostate, quhead_billtozip, quhead_billtocountry,
23760          quhead_shipto_id, quhead_shiptoname, quhead_shiptoaddress1,
23761          quhead_shiptoaddress2, quhead_shiptoaddress3,
23762          quhead_shiptocity, quhead_shiptostate, quhead_shiptozipcode, quhead_shiptocountry,
23763          quhead_salesrep_id, quhead_commission,
23764          quhead_terms_id, cust_shipchrg_id, quhead_fob, quhead_shipvia,
23765          quhead_ordercomments,  quhead_freight,
23766          quhead_misc, quhead_misc_accnt_id, quhead_misc_descrip,
23767          quhead_prj_id, quhead_curr_id, quhead_taxzone_id,
23768          'f','f',current_date,
23769          quhead_saletype_id, quhead_shipzone_id
23770          --quhead_shipto_cntct_id, quhead_shipto_cntct_honorific,
23771          --quhead_shipto_cntct_first_name, quhead_shipto_cntct_middle, quhead_shipto_cntct_last_name,
23772          --quhead_shipto_cntct_suffix, quhead_shipto_cntct_phone, quhead_shipto_cntct_title,
23773          --quhead_shipto_cntct_fax, quhead_shipto_cntct_email, quhead_billto_cntct_id,
23774          --quhead_billto_cntct_honorific, quhead_billto_cntct_first_name, quhead_billto_cntct_middle,
23775          --quhead_billto_cntct_last_name, quhead_billto_cntct_suffix, quhead_billto_cntct_phone,
23776          --quhead_billto_cntct_title, quhead_billto_cntct_fax, quhead_billto_cntct_email, quhead_ophead_id,
23777          --quhead_calcfreight
23778   FROM quhead JOIN custinfo ON (cust_id=quhead_cust_id)
23779   WHERE (quhead_id=pQuheadid);
23780
23781 -- Attachments on Invoice not supported but leaving this in for future use:
23782 /*
23783   UPDATE url SET url_source_id = _iheadid,
23784                  url_source = 'I'
23785   WHERE ((url_source='Q') AND (url_source_id = pQuheadid));
23786
23787   UPDATE imageass SET imageass_source_id = _iheadid,
23788                       imageass_source = 'I'
23789   WHERE ((imageass_source='Q') AND (imageass_source_id = pQuheadid));
23790
23791   UPDATE docass SET docass_source_id = _iheadid,
23792                     docass_source_type = 'I'
23793   WHERE ((docass_source_type='Q') AND (docass_source_id = pQuheadid));
23794 */
23795
23796
23797 -- Comments not supported on Invoice but leaving this in for future use:
23798
23799 /*  
23800   INSERT INTO comment
23801   ( comment_cmnttype_id, comment_source, comment_source_id, comment_date, comment_user, comment_text, comment_public )
23802   SELECT comment_cmnttype_id, 'I', _iheadid, comment_date, comment_user, ('Quote-' || comment_text), comment_public
23803   FROM comment
23804   WHERE ( (comment_source='Q')
23805     AND   (comment_source_id=pQuheadid) );
23806 */
23807
23808   FOR _r IN SELECT quitem.*,
23809                    quhead_number, quhead_prj_id,
23810                    itemsite_item_id, itemsite_leadtime,
23811                    itemsite_createsopo, itemsite_createsopr,
23812                    item_type, COALESCE(quitem_itemsrc_id, itemsrc_id, -1) AS itemsrcid
23813             FROM quhead JOIN quitem ON (quitem_quhead_id=quhead_id)
23814                         JOIN itemsite ON (itemsite_id=quitem_itemsite_id)
23815                         JOIN item ON (item_id=itemsite_item_id)
23816                         LEFT OUTER JOIN itemsrc ON ( (itemsrc_item_id=item_id) AND
23817                                                      (itemsrc_default) )
23818             WHERE (quhead_id=pQuheadid) LOOP
23819
23820     SELECT NEXTVAL('invcitem_invcitem_id_seq') INTO _iitemid;
23821
23822     INSERT INTO invcitem
23823     ( invcitem_id, invcitem_invchead_id, invcitem_linenumber, 
23824       invcitem_item_id,
23825       invcitem_warehous_id,
23826       --invcitem_status, 
23827       --invcitem_scheddate, invcitem_promdate,
23828       invcitem_price, invcitem_custprice, 
23829       invcitem_ordered, invcitem_billed,
23830       invcitem_qty_uom_id, invcitem_qty_invuomratio,
23831       invcitem_price_uom_id, invcitem_price_invuomratio,
23832       invcitem_custpn, invcitem_notes, invcitem_taxtype_id )
23833     VALUES
23834     ( _iitemid, _iheadid, _r.quitem_linenumber, 
23835       (SELECT itemsite_item_id FROM itemsite WHERE itemsite_id = _r.quitem_itemsite_id),
23836       (SELECT itemsite_warehous_id FROM itemsite WHERE itemsite_id = _r.quitem_itemsite_id),
23837       --'O', 
23838       --_r.quitem_scheddate, _r.quitem_promdate,
23839       _r.quitem_price, _r.quitem_custprice,
23840       _r.quitem_qtyord, _r.quitem_qtyord,
23841       _r.quitem_qty_uom_id, _r.quitem_qty_invuomratio,
23842       _r.quitem_price_uom_id, _r.quitem_price_invuomratio,
23843       _r.quitem_custpn, _r.quitem_memo, _r.quitem_taxtype_id );
23844
23845     IF (fetchMetricBool('enablextcommissionission')) THEN
23846       PERFORM xtcommission.getSalesReps(quhead_cust_id, quhead_shipto_id,
23847                                         _r.itemsite_item_id, _r.quitem_price,
23848                                         _iitemid, 'InvoiceItem')
23849       FROM quhead
23850       WHERE (quhead_id=pQuheadid);
23851     END IF;
23852
23853 -- Chracteristics not supported on Invoice but leaving in for future use:
23854
23855 /*
23856     INSERT INTO charass
23857           (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default, charass_price)
23858     SELECT 'SI', _iitemid, charass_char_id, charass_value, charass_default, charass_price
23859       FROM charass
23860      WHERE ((charass_target_type='QI')
23861        AND  (charass_target_id=_r.quitem_id));
23862 */
23863
23864
23865 -- Comments not supported but leaving in for future use
23866
23867 /*
23868     INSERT INTO comment
23869     ( comment_cmnttype_id, comment_source, comment_source_id, comment_date, comment_user, comment_text )
23870     SELECT comment_cmnttype_id, 'SI', _iitemid, comment_date, comment_user, ('Quote-' || comment_text)
23871     FROM comment
23872     WHERE ( (comment_source='QI')
23873       AND   (comment_source_id=_r.quitem_id) );
23874 */
23875
23876     _orderid := -1;
23877     _ordertype := '';
23878     IF (_r.quitem_createorder) THEN
23879
23880       IF (_r.item_type IN ('M')) THEN
23881         SELECT createWo( CAST(_r.quhead_number AS INTEGER), supply.itemsite_id, 1, (_r.quitem_qtyord * _r.quitem_qty_invuomratio),
23882                          _r.itemsite_leadtime, _r.quitem_scheddate, _r.quitem_memo, 'Q', _iitemid, _r.quhead_prj_id ) INTO _orderId
23883         FROM itemsite sold, itemsite supply
23884         WHERE ((sold.itemsite_item_id=supply.itemsite_item_id)
23885          AND (supply.itemsite_warehous_id=_r.quitem_order_warehous_id)
23886          AND (sold.itemsite_id=_r.quitem_itemsite_id) );
23887         _orderType := 'W';
23888
23889         INSERT INTO charass
23890               (charass_target_type, charass_target_id, charass_char_id, charass_value)
23891         SELECT 'W', _orderId, charass_char_id, charass_value
23892           FROM charass
23893          WHERE ((charass_target_type='QI')
23894            AND  (charass_target_id=_r.quitem_id));
23895
23896       ELSIF ( (_r.item_type IN ('P', 'O')) AND (_r.itemsite_createsopr) ) THEN
23897         SELECT createPr( CAST(_r.quhead_number AS INTEGER), _r.quitem_itemsite_id, (_r.quitem_qtyord * _r.quitem_qty_invuomratio),
23898                          _r.quitem_scheddate, '', 'S', _iitemid ) INTO _orderId;
23899         _orderType := 'R';
23900         UPDATE pr SET pr_prj_id=_r.quhead_prj_id WHERE pr_id=_orderId;
23901       ELSIF ( (_r.item_type IN ('P', 'O')) AND (_r.itemsite_createsopo) ) THEN
23902         IF (_r.quitem_prcost=0) THEN
23903 -- For now quote to invoice/dropship will not be supported but with the creation of a createPurchaseToQuote() version of createPurchaseToSale()
23904 -- it can be
23905 --          SELECT createPurchaseToSale(_iitemid, _r.itemsrcid, _r.quitem_dropship) INTO _orderId;
23906             RAISE EXCEPTION 'Quote contains one or more dropship items that may not be converted from a Quote to an Invoice';
23907         ELSE
23908 -- For now quote to invoice/dropship will not be supported but with the creation of a createPurchaseToQuote() version of createPurchaseToSale()
23909 -- it can be
23910 --          SELECT createPurchaseToSale(_iitemid, _r.itemsrcid, _r.quitem_dropship, _r.quitem_prcost) INTO _orderId;
23911             RAISE EXCEPTION 'Quote contains one or more dropship items that may not be converted from a Quote to an Invoice';
23912         END IF;
23913         _orderType := 'P';
23914       END IF;
23915
23916 --      UPDATE invcitem SET invcitem_order_type=_ordertype, invcitem_order_id=_orderid
23917 --      WHERE (invcitem_id=_iitemid);
23918
23919     END IF;
23920
23921   END LOOP;
23922
23923   SELECT metric_value INTO _showConvertedQuote
23924   FROM metric WHERE metric_name = 'ShowQuotesAfterSO';
23925
23926   IF (_showConvertedQuote) THEN
23927     UPDATE quhead
23928     SET quhead_status= 'C'
23929     WHERE (quhead_id = pQuheadid);
23930   ELSE
23931      PERFORM deleteQuote(pQuheadid);
23932   END IF;
23933
23934   RETURN _iheadid;
23935
23936 END;
23937 $_$;
23938
23939
23940 ALTER FUNCTION public.convertquotetoinvoice(integer) OWNER TO admin;
23941
23942 --
23943 -- TOC entry 1245 (class 1255 OID 146565792)
23944 -- Dependencies: 4536 8
23945 -- Name: copybom(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
23946 --
23947
23948 CREATE FUNCTION copybom(psitemid integer, ptitemid integer) RETURNS integer
23949     LANGUAGE plpgsql
23950     AS $$
23951 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23952 -- See www.xtuple.com/CPAL for the full text of the software license.
23953 DECLARE
23954   _result INTEGER;
23955
23956 BEGIN
23957
23958   SELECT copyBOM (pSItemid, PTItemid, FALSE) into _result;
23959
23960   RETURN _result;
23961
23962 END;
23963 $$;
23964
23965
23966 ALTER FUNCTION public.copybom(psitemid integer, ptitemid integer) OWNER TO admin;
23967
23968 --
23969 -- TOC entry 1248 (class 1255 OID 146565793)
23970 -- Dependencies: 4536 8
23971 -- Name: copybom(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
23972 --
23973
23974 CREATE FUNCTION copybom(psitemid integer, ptitemid integer, pcopyusedat boolean) RETURNS integer
23975     LANGUAGE plpgsql
23976     AS $$
23977 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
23978 -- See www.xtuple.com/CPAL for the full text of the software license.
23979 DECLARE
23980   _bh RECORD;
23981   _bi RECORD;
23982   _bomheadfound BOOLEAN := FALSE;
23983   _bomheadid INTEGER;
23984   _bomitemid INTEGER;
23985   _bomworksetid INTEGER;
23986   _temp INTEGER;
23987   _schedatwooper BOOLEAN;
23988   _booitemseqid INTEGER;
23989
23990 BEGIN
23991
23992 --  Cache source bomhead
23993   SELECT * INTO _bh
23994   FROM bomhead
23995   WHERE ((bomhead_item_id=pSItemid)
23996     AND  (bomhead_rev_id=getActiveRevID('BOM', pSItemid)));
23997
23998 --  bomhead may not exist
23999 --  IF (NOT FOUND) THEN
24000 --    RETURN -1;
24001 --  END IF;
24002     IF (FOUND) THEN
24003       _bomheadfound := TRUE;
24004     END IF;
24005
24006 --  Make sure that source bomitems exist
24007   SELECT bomitem_id INTO _bomitemid
24008   FROM bomitem
24009   WHERE ((bomitem_parent_item_id=pSItemid)
24010     AND  (bomitem_rev_id=getActiveRevID('BOM', pSItemid)))
24011   LIMIT 1;
24012
24013   IF (NOT FOUND) THEN
24014     RETURN -2;
24015   END IF;
24016
24017 --  Make sure that target bomitems do not exist
24018   SELECT bomitem_id INTO _bomitemid
24019   FROM bomitem
24020   WHERE ((bomitem_parent_item_id=pTItemid)
24021     AND  (bomitem_rev_id= -1))
24022   LIMIT 1;
24023
24024   IF (FOUND) THEN
24025     RETURN -3;
24026   END IF;
24027
24028 --  Make sure that the parent is not used in the component at some level
24029   IF ( SELECT (item_type IN ('M', 'F'))
24030        FROM item
24031        WHERE (item_id=pSItemid) ) THEN
24032     SELECT indentedWhereUsed(pTItemid) INTO _bomworksetid;
24033     SELECT bomwork_id INTO _temp
24034     FROM bomwork
24035     WHERE ( (bomwork_set_id=_bomworksetid)
24036      AND (bomwork_item_id=pSItemid) )
24037     LIMIT 1;
24038     IF (FOUND) THEN
24039       PERFORM deleteBOMWorkset(_bomworksetid);
24040       RETURN -4;
24041     END IF;
24042     PERFORM deleteBOMWorkset(_bomworksetid);
24043   END IF;
24044
24045 --  Check for existing target bomhead
24046   SELECT bomhead_id INTO _bomheadid
24047   FROM bomhead
24048   WHERE ((bomhead_item_id=pTItemid)
24049     AND  (bomhead_rev_id= -1));
24050
24051   IF (NOT FOUND) THEN
24052     IF (_bomheadfound) THEN
24053       INSERT INTO bomhead
24054       ( bomhead_item_id, bomhead_serial, bomhead_docnum,
24055         bomhead_batchsize, bomhead_requiredqtyper )
24056       VALUES
24057       ( pTItemid, _bh.bomhead_serial, _bh.bomhead_docnum,
24058         _bh.bomhead_batchsize, _bh.bomhead_requiredqtyper );
24059     END IF;
24060   END IF;
24061
24062   FOR _bi IN SELECT bomitem.*
24063              FROM bomitem(pSItemid) 
24064              WHERE (bomitem_expires>CURRENT_DATE) LOOP
24065
24066     SELECT NEXTVAL('bomitem_bomitem_id_seq') INTO _bomitemid;
24067
24068     IF (pCopyUsedAt) THEN
24069       _schedatwooper := _bi.bomitem_schedatwooper;
24070       _booitemseqid := _bi.bomitem_booitem_seq_id;
24071     ELSE
24072       _schedatwooper := FALSE;
24073       _booitemseqid := -1;
24074     END IF;
24075
24076     INSERT INTO bomitem
24077     ( bomitem_id, bomitem_parent_item_id, bomitem_seqnumber, bomitem_item_id,
24078       bomitem_uom_id, bomitem_qtyfxd, bomitem_qtyper, bomitem_scrap, bomitem_schedatwooper,
24079       bomitem_booitem_seq_id,
24080       bomitem_effective, bomitem_expires, bomitem_ecn,
24081       bomitem_createwo, bomitem_issuemethod, bomitem_moddate, bomitem_subtype,
24082       bomitem_notes, bomitem_ref )
24083     VALUES
24084     ( _bomitemid, pTItemid, _bi.bomitem_seqnumber, _bi.bomitem_item_id,
24085       _bi.bomitem_uom_id, _bi.bomitem_qtyfxd, _bi.bomitem_qtyper, _bi.bomitem_scrap, _schedatwooper,
24086       _booitemseqid,
24087       CURRENT_DATE, _bi.bomitem_expires, _bi.bomitem_ecn,
24088       _bi.bomitem_createwo, _bi.bomitem_issuemethod, CURRENT_DATE, _bi.bomitem_subtype,
24089       _bi.bomitem_notes, _bi.bomitem_ref );
24090
24091     INSERT INTO bomitemsub
24092     ( bomitemsub_bomitem_id, bomitemsub_item_id,
24093       bomitemsub_uomratio, bomitemsub_rank )
24094     SELECT _bomitemid, bomitemsub_item_id,
24095            bomitemsub_uomratio, bomitemsub_rank
24096     FROM bomitemsub
24097     WHERE (bomitemsub_bomitem_id=_bi.bomitem_id);
24098
24099   END LOOP;
24100
24101   RETURN pTItemid;
24102
24103 END;
24104 $$;
24105
24106
24107 ALTER FUNCTION public.copybom(psitemid integer, ptitemid integer, pcopyusedat boolean) OWNER TO admin;
24108
24109 --
24110 -- TOC entry 1249 (class 1255 OID 146565794)
24111 -- Dependencies: 4536 8
24112 -- Name: copybudget(integer, text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
24113 --
24114
24115 CREATE FUNCTION copybudget(integer, text, text, integer) RETURNS integer
24116     LANGUAGE plpgsql
24117     AS $_$
24118 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24119 -- See www.xtuple.com/CPAL for the full text of the software license.
24120 DECLARE
24121   pBudgheadid ALIAS FOR $1;
24122   pName ALIAS FOR $2;
24123   pDescrip ALIAS FOR $3;
24124   pInterval ALIAS FOR $4;
24125   _budgheadid INTEGER;
24126   _periodid INTEGER;
24127   _result INTEGER;
24128
24129 BEGIN
24130   SELECT 1 INTO _result
24131     FROM budgitem
24132    WHERE ((budgitem_budghead_id=pBudgheadid)
24133      AND  (nextPeriodByInterval(budgitem_period_id, pInterval)=-1))
24134   LIMIT 1;
24135   IF (FOUND) THEN
24136     RETURN -1;
24137   END IF;
24138
24139   SELECT nextval('budghead_budghead_id_seq') INTO _budgheadid;
24140   INSERT INTO budghead
24141         (budghead_id, budghead_name, budghead_descrip)
24142   VALUES(_budgheadid, pName, pDescrip);
24143
24144   INSERT INTO budgitem (budgitem_budghead_id, budgitem_period_id,
24145                         budgitem_accnt_id, budgitem_amount)
24146   SELECT _budgheadid, nextPeriodByInterval(budgitem_period_id, pInterval),
24147          budgitem_accnt_id, budgitem_amount
24148     FROM budgitem
24149    WHERE (budgitem_budghead_id=pBudgheadid);
24150
24151   RETURN _budgheadid;
24152 END;
24153 $_$;
24154
24155
24156 ALTER FUNCTION public.copybudget(integer, text, text, integer) OWNER TO admin;
24157
24158 --
24159 -- TOC entry 1250 (class 1255 OID 146565795)
24160 -- Dependencies: 4536 8
24161 -- Name: copycmd(integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
24162 --
24163
24164 CREATE FUNCTION copycmd(integer, text, text) RETURNS integer
24165     LANGUAGE plpgsql
24166     AS $_$
24167 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24168 -- See www.xtuple.com/CPAL for the full text of the software license.
24169 DECLARE
24170   pCmdId        ALIAS FOR $1;
24171   pModule       ALIAS FOR $2;
24172   pTitle        ALIAS FOR $3;
24173   _cmdId        INTEGER;
24174 BEGIN
24175     SELECT nextval('cmd_cmd_id_seq') INTO _cmdId;
24176
24177     INSERT INTO cmd 
24178       SELECT _cmdId, pModule, pTitle, cmd_descrip, cmd_privname, cmd_executable
24179       FROM cmd
24180       WHERE (cmd_id=pCmdId);
24181
24182     INSERT INTO cmdarg (cmdarg_cmd_id, cmdarg_order, cmdarg_arg)
24183       SELECT _cmdId, cmdarg_order, cmdarg_arg
24184       FROM cmdarg
24185       WHERE (cmdarg_cmd_id=pCmdId);
24186
24187     RETURN 1;
24188 END;
24189 $_$;
24190
24191
24192 ALTER FUNCTION public.copycmd(integer, text, text) OWNER TO admin;
24193
24194 --
24195 -- TOC entry 1251 (class 1255 OID 146565796)
24196 -- Dependencies: 4536 8
24197 -- Name: copycontract(integer, text, date, date); Type: FUNCTION; Schema: public; Owner: admin
24198 --
24199
24200 CREATE FUNCTION copycontract(pcontrctid integer, pnumber text, peffective date, pexpires date) RETURNS integer
24201     LANGUAGE plpgsql
24202     AS $$
24203 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24204 -- See www.xtuple.com/CPAL for the full text of the software license.
24205 DECLARE
24206   _contrctid INTEGER;
24207   _itemsrcid INTEGER;
24208   _r RECORD;
24209
24210 BEGIN
24211
24212   INSERT INTO contrct
24213   ( contrct_number,
24214     contrct_vend_id,
24215     contrct_descrip,
24216     contrct_effective,
24217     contrct_expires,
24218     contrct_note )
24219   SELECT
24220     pNumber,
24221     contrct_vend_id,
24222     contrct_descrip,
24223     pEffective,
24224     pExpires,
24225     contrct_note
24226   FROM contrct
24227   WHERE (contrct_id=pContrctid)
24228   RETURNING contrct_id INTO _contrctid;
24229
24230   FOR _r IN
24231   SELECT * FROM itemsrc WHERE (itemsrc_contrct_id=pContrctid)
24232   LOOP
24233   INSERT INTO itemsrc
24234     ( itemsrc_item_id,
24235       itemsrc_vend_id,
24236       itemsrc_vend_item_number,
24237       itemsrc_vend_item_descrip,
24238       itemsrc_comments,
24239       itemsrc_vend_uom,
24240       itemsrc_invvendoruomratio,
24241       itemsrc_minordqty,
24242       itemsrc_multordqty,
24243       itemsrc_leadtime,
24244       itemsrc_ranking,
24245       itemsrc_active,
24246       itemsrc_manuf_name,
24247       itemsrc_manuf_item_number,
24248       itemsrc_manuf_item_descrip,
24249       itemsrc_default,
24250       itemsrc_upccode,
24251       itemsrc_effective,
24252       itemsrc_expires,
24253       itemsrc_contrct_id )
24254     VALUES
24255     ( _r.itemsrc_item_id,
24256       _r.itemsrc_vend_id,
24257       _r.itemsrc_vend_item_number,
24258       _r.itemsrc_vend_item_descrip,
24259       _r.itemsrc_comments,
24260       _r.itemsrc_vend_uom,
24261       _r.itemsrc_invvendoruomratio,
24262       _r.itemsrc_minordqty,
24263       _r.itemsrc_multordqty,
24264       _r.itemsrc_leadtime,
24265       _r.itemsrc_ranking,
24266       _r.itemsrc_active,
24267       _r.itemsrc_manuf_name,
24268       _r.itemsrc_manuf_item_number,
24269       _r.itemsrc_manuf_item_descrip,
24270       _r.itemsrc_default,
24271       _r.itemsrc_upccode,
24272       pEffective,
24273       pExpires,
24274       _contrctid )
24275     RETURNING itemsrc_id INTO _itemsrcid;
24276
24277   INSERT INTO itemsrcp
24278     ( itemsrcp_itemsrc_id,
24279       itemsrcp_qtybreak,
24280       itemsrcp_price,
24281       itemsrcp_updated,
24282       itemsrcp_curr_id,
24283       itemsrcp_dropship,
24284       itemsrcp_warehous_id,
24285       itemsrcp_type,
24286       itemsrcp_discntprcnt,
24287       itemsrcp_fixedamtdiscount )
24288     SELECT
24289       _itemsrcid,
24290       itemsrcp_qtybreak,
24291       itemsrcp_price,
24292       CURRENT_DATE,
24293       itemsrcp_curr_id,
24294       itemsrcp_dropship,
24295       itemsrcp_warehous_id,
24296       itemsrcp_type,
24297       itemsrcp_discntprcnt,
24298       itemsrcp_fixedamtdiscount
24299     FROM itemsrcp
24300     WHERE (itemsrcp_itemsrc_id=_r.itemsrc_id);
24301
24302   END LOOP;
24303
24304   RETURN _contrctid;
24305
24306 END;
24307 $$;
24308
24309
24310 ALTER FUNCTION public.copycontract(pcontrctid integer, pnumber text, peffective date, pexpires date) OWNER TO admin;
24311
24312 --
24313 -- TOC entry 1252 (class 1255 OID 146565797)
24314 -- Dependencies: 4536 8
24315 -- Name: copyfinancialgroup(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
24316 --
24317
24318 CREATE FUNCTION copyfinancialgroup(integer, integer, integer) RETURNS integer
24319     LANGUAGE plpgsql
24320     AS $_$
24321 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24322 -- See www.xtuple.com/CPAL for the full text of the software license.
24323 DECLARE
24324   pSourceGroup ALIAS FOR $1;
24325   pFlheadid ALIAS FOR $2;
24326   pParentFlgrpid ALIAS FOR $3;
24327
24328   _flgrpid INTEGER;
24329
24330 BEGIN
24331
24332   SELECT nextval('flgrp_flgrp_id_seq') INTO _flgrpid;
24333
24334 -- Copy the group item
24335   INSERT INTO flgrp
24336          (flgrp_id, flgrp_flhead_id, flgrp_flgrp_id,
24337           flgrp_order, flgrp_name, flgrp_descrip,
24338           flgrp_subtotal, flgrp_summarize, flgrp_subtract,
24339           flgrp_showstart, flgrp_showend,
24340           flgrp_showdelta, flgrp_showbudget, flgrp_showdiff, flgrp_showcustom,
24341           flgrp_showstartprcnt, flgrp_showendprcnt,
24342           flgrp_showdeltaprcnt, flgrp_showbudgetprcnt, flgrp_showdiffprcnt, flgrp_showcustomprcnt,
24343           flgrp_usealtsubtotal, flgrp_altsubtotal,flgrp_prcnt_flgrp_id)
24344   SELECT _flgrpid, pFlheadid, pParentFlgrpid,
24345          flgrp_order, flgrp_name, flgrp_descrip,
24346          flgrp_subtotal, flgrp_summarize, flgrp_subtract,
24347          flgrp_showstart, flgrp_showend,
24348          flgrp_showdelta, flgrp_showbudget, flgrp_showdiff, flgrp_showcustom,
24349          flgrp_showstartprcnt, flgrp_showendprcnt,
24350          flgrp_showdeltaprcnt, flgrp_showbudgetprcnt, flgrp_showdiffprcnt, flgrp_showcustomprcnt,
24351          flgrp_usealtsubtotal, flgrp_altsubtotal,flgrp_prcnt_flgrp_id
24352     FROM flgrp
24353    WHERE (flgrp_id=pSourceGroup);
24354
24355 -- Store temporary cross ref info
24356    
24357    EXECUTE ' INSERT INTO tmp_flgrpxref' || getEffectiveXtUser() || ' (flgrpxref_oldid,flgrpxref_newid) VALUES (' || pSourceGroup || ',' || _flgrpid || ');';
24358
24359 -- Copy any children flitems
24360   INSERT INTO flitem
24361          (flitem_flhead_id, flitem_flgrp_id,
24362           flitem_order, flitem_accnt_id, flitem_showstart,
24363           flitem_showend, flitem_showdelta, flitem_showbudget, flitem_showdiff, flitem_showcustom,
24364           flitem_subtract, flitem_showstartprcnt,
24365           flitem_showendprcnt, flitem_showdeltaprcnt,
24366           flitem_showbudgetprcnt, flitem_showdiffprcnt, flitem_showcustomprcnt,
24367           flitem_custom_source, flitem_company, flitem_profit, flitem_number,
24368           flitem_sub, flitem_type, flitem_subaccnttype_code, flitem_prcnt_flgrp_id)
24369   SELECT pFlheadid, _flgrpid,
24370          flitem_order, flitem_accnt_id, flitem_showstart,
24371          flitem_showend, flitem_showdelta, flitem_showbudget, flitem_showdiff, flitem_showcustom,
24372          flitem_subtract, flitem_showstartprcnt,
24373          flitem_showendprcnt, flitem_showdeltaprcnt,
24374          flitem_showbudgetprcnt, flitem_showdiffprcnt, flitem_showcustomprcnt,
24375          flitem_custom_source, flitem_company, flitem_profit, flitem_number,
24376           flitem_sub, flitem_type, flitem_subaccnttype_code, flitem_prcnt_flgrp_id
24377     FROM flitem
24378    WHERE (flitem_flgrp_id=pSourceGroup);
24379
24380 -- Copy any children flspecs
24381   INSERT INTO flspec
24382          (flspec_flhead_id, flspec_flgrp_id,
24383           flspec_order, flspec_name, flspec_type, flspec_showstart,
24384           flspec_showend, flspec_showdelta, flspec_showbudget, flspec_showdiff, flspec_showcustom,
24385           flspec_subtract, flspec_showstartprcnt,
24386           flspec_showendprcnt, flspec_showdeltaprcnt,
24387           flspec_showbudgetprcnt, flspec_showdiffprcnt, flspec_showcustomprcnt,
24388           flspec_custom_source, flspec_prcnt_flgrp_id)
24389   SELECT pFlheadid, _flgrpid,
24390          flspec_order, flspec_name, flspec_type, flspec_showstart,
24391          flspec_showend, flspec_showdelta, flspec_showbudget, flspec_showdiff, flspec_showcustom,
24392          flspec_subtract, flspec_showstartprcnt,
24393          flspec_showendprcnt, flspec_showdeltaprcnt,
24394          flspec_showbudgetprcnt, flspec_showdiffprcnt, flspec_showcustomprcnt,
24395          flspec_custom_source, flspec_prcnt_flgrp_id
24396     FROM flspec
24397    WHERE (flspec_flgrp_id=pSourceGroup);
24398
24399 -- Copy the groups
24400   PERFORM copyFinancialGroup(flgrp_id, pFlheadid, _flgrpid)
24401      FROM flgrp
24402     WHERE (flgrp_flgrp_id=pSourceGroup);
24403
24404   RETURN _flgrpid;
24405 END;
24406 $_$;
24407
24408
24409 ALTER FUNCTION public.copyfinancialgroup(integer, integer, integer) OWNER TO admin;
24410
24411 --
24412 -- TOC entry 1253 (class 1255 OID 146565798)
24413 -- Dependencies: 4536 8
24414 -- Name: copyfinanciallayout(integer, text); Type: FUNCTION; Schema: public; Owner: admin
24415 --
24416
24417 CREATE FUNCTION copyfinanciallayout(integer, text) RETURNS integer
24418     LANGUAGE plpgsql
24419     AS $_$
24420 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24421 -- See www.xtuple.com/CPAL for the full text of the software license.
24422 DECLARE
24423   pSourceFlheadid ALIAS FOR $1;
24424   pDestName ALIAS FOR $2;
24425
24426   _flheadid INTEGER;
24427   _tblName TEXT;
24428
24429 BEGIN
24430
24431 -- Check for the flhead to be copy that it exists
24432   PERFORM flhead_id
24433      FROM flhead
24434     WHERE (flhead_id=pSourceFlheadid);
24435   IF (NOT FOUND) THEN
24436     RETURN -1;
24437   END IF;
24438
24439 -- Check that the name is valid
24440   IF (pDestName IS NULL OR pDestName = '') THEN
24441     RETURN -2;
24442   END IF;
24443
24444 -- Check for the name to copy to does not exist
24445   PERFORM flhead_id
24446      FROM flhead
24447     WHERE (flhead_name=pDestName);
24448   IF (FOUND) THEN
24449     RETURN -3;
24450   END IF;
24451
24452 -- Copy the flhead record
24453   SELECT nextval('flhead_flhead_id_seq') INTO _flheadid;
24454   INSERT INTO flhead
24455          (flhead_id, flhead_name, flhead_descrip,
24456           flhead_showtotal, flhead_showstart,
24457           flhead_showend, flhead_showdelta, flhead_showbudget,
24458           flhead_showdiff, flhead_showcustom,
24459           flhead_custom_label,
24460           flhead_usealttotal, flhead_alttotal,
24461           flhead_usealtbegin, flhead_altbegin,
24462           flhead_usealtend, flhead_altend,
24463           flhead_usealtdebits, flhead_altdebits,
24464           flhead_usealtcredits, flhead_altcredits,
24465           flhead_usealtbudget, flhead_altbudget,
24466           flhead_usealtdiff, flhead_altdiff,
24467           flhead_type, flhead_active, flhead_sys
24468 )
24469   SELECT _flheadid, pDestName, flhead_descrip,
24470          flhead_showtotal, flhead_showstart,
24471          flhead_showend, flhead_showdelta, flhead_showbudget,
24472          flhead_showdiff, flhead_showcustom,
24473          flhead_custom_label,
24474          flhead_usealttotal, flhead_alttotal,
24475          flhead_usealtbegin, flhead_altbegin,
24476          flhead_usealtend, flhead_altend,
24477          flhead_usealtdebits, flhead_altdebits,
24478          flhead_usealtcredits, flhead_altcredits,
24479          flhead_usealtbudget, flhead_altbudget,
24480          flhead_usealtdiff, flhead_altdiff,
24481          flhead_type, flhead_active, false
24482     FROM flhead
24483    WHERE (flhead_id=pSourceFlheadid);
24484
24485 -- Create temporary table so old and new group ids can be stored
24486  SELECT relname FROM pg_class INTO _tblName
24487  WHERE relname = 'tmp_flgrpxref';
24488  IF (_tblName IS NULL) THEN
24489   EXECUTE 'CREATE TEMPORARY TABLE tmp_flgrpxref' || getEffectiveXtUser() || ' 
24490   (
24491         flgrpxref_oldid int4,
24492         flgrpxref_newid int4
24493   ) ON COMMIT DROP;';
24494   END IF;
24495
24496 -- Copy the top level groups
24497   PERFORM copyFinancialGroup(flgrp_id, _flheadid, -1)
24498      FROM flgrp
24499     WHERE ((flgrp_flhead_id=pSourceFlheadid)
24500       AND  (flgrp_flgrp_id=-1));
24501
24502 -- Update Group Percent settings
24503   EXECUTE 'UPDATE flgrp
24504   SET flgrp_prcnt_flgrp_id=flgrpxref_newid
24505   FROM tmp_flgrpxref' || getEffectiveXtUser() || ' 
24506   WHERE ((flgrp_flhead_id=' || _flheadid || ')
24507   AND (flgrp_prcnt_flgrp_id=flgrpxref_oldid));';
24508
24509   EXECUTE 'UPDATE flitem
24510   SET flitem_prcnt_flgrp_id=flgrpxref_newid
24511   FROM tmp_flgrpxref' || getEffectiveXtUser() || ' 
24512   WHERE ((flitem_flhead_id=' || _flheadid || ')
24513   AND (flitem_prcnt_flgrp_id=flgrpxref_oldid));';
24514
24515   EXECUTE 'UPDATE flspec
24516   SET flspec_prcnt_flgrp_id=flgrpxref_newid
24517   FROM tmp_flgrpxref' || getEffectiveXtUser() || ' 
24518   WHERE ((flspec_flhead_id=' || _flheadid || ')
24519   AND (flspec_prcnt_flgrp_id=flgrpxref_oldid));';
24520
24521 -- Copy Column Layounts
24522   INSERT INTO flcol
24523         (flcol_flhead_id,
24524         flcol_name,
24525         flcol_descrip,
24526         flcol_report_id,
24527         flcol_month,
24528         flcol_quarter,
24529         flcol_year,
24530         flcol_showdb,
24531         flcol_prcnt,
24532         flcol_priortype,
24533         flcol_priormonth,
24534         flcol_priorquarter,
24535         flcol_prioryear,
24536         flcol_priorprcnt,
24537         flcol_priordiff,
24538         flcol_priordiffprcnt,
24539         flcol_budget,
24540         flcol_budgetprcnt,
24541         flcol_budgetdiff,
24542         flcol_budgetdiffprcnt
24543 )
24544 SELECT
24545         _flheadid,flcol_name,flcol_descrip,
24546         flcol_report_id,flcol_month,flcol_quarter,
24547         flcol_year,flcol_showdb,flcol_prcnt,
24548         flcol_priortype,flcol_priormonth,flcol_priorquarter,
24549         flcol_prioryear,flcol_priorprcnt,flcol_priordiff,
24550         flcol_priordiffprcnt,flcol_budget,flcol_budgetprcnt,
24551         flcol_budgetdiff,flcol_budgetdiffprcnt
24552 FROM flcol
24553 WHERE (flcol_flhead_id=pSourceFlheadid);
24554
24555   RETURN _flheadid;
24556 END;
24557 $_$;
24558
24559
24560 ALTER FUNCTION public.copyfinanciallayout(integer, text) OWNER TO admin;
24561
24562 --
24563 -- TOC entry 1214 (class 1255 OID 146565799)
24564 -- Dependencies: 4536 8
24565 -- Name: copyglseries(integer); Type: FUNCTION; Schema: public; Owner: admin
24566 --
24567
24568 CREATE FUNCTION copyglseries(integer) RETURNS integer
24569     LANGUAGE plpgsql
24570     AS $_$
24571 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24572 -- See www.xtuple.com/CPAL for the full text of the software license.
24573 DECLARE
24574   pSequence ALIAS FOR $1;
24575   _sequence INTEGER := fetchGLSequence();
24576   _journal INTEGER;     
24577
24578 BEGIN
24579
24580   SELECT gltrans_journalnumber INTO _journal
24581   FROM gltrans
24582   WHERE ( gltrans_sequence=pSequence )
24583   LIMIT 1;
24584
24585   IF (FOUND) THEN
24586     INSERT INTO glseries
24587     ( glseries_sequence, glseries_source, glseries_doctype, glseries_docnumber,
24588       glseries_notes, glseries_accnt_id, glseries_amount, glseries_distdate )
24589     SELECT _sequence, gltrans_source, gltrans_doctype, gltrans_docnumber,
24590            gltrans_notes, gltrans_accnt_id,
24591            gltrans_amount, gltrans_date
24592     FROM gltrans
24593     WHERE ( gltrans_sequence=pSequence );
24594   ELSE
24595     RAISE EXCEPTION 'g/l transaction sequence not found';
24596   END IF;
24597
24598   RETURN _sequence;
24599 END;
24600 $_$;
24601
24602
24603 ALTER FUNCTION public.copyglseries(integer) OWNER TO admin;
24604
24605 --
24606 -- TOC entry 1236 (class 1255 OID 146565800)
24607 -- Dependencies: 4536 8
24608 -- Name: copyincdt(integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
24609 --
24610
24611 CREATE FUNCTION copyincdt(integer, timestamp with time zone) RETURNS integer
24612     LANGUAGE plpgsql
24613     AS $_$
24614 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24615 -- See www.xtuple.com/CPAL for the full text of the software license.
24616 DECLARE
24617   pparentid   ALIAS FOR $1;
24618   ptimestamp  TIMESTAMP WITH TIME ZONE := COALESCE($2, CURRENT_TIMESTAMP);
24619
24620   _alarmid    INTEGER;
24621   _incdtid    INTEGER;
24622   _todoitemid INTEGER;
24623
24624 BEGIN
24625   INSERT INTO incdt(incdt_number,          incdt_crmacct_id,
24626                     incdt_cntct_id,        incdt_summary,
24627                     incdt_descrip,         incdt_item_id,
24628                     incdt_timestamp,       incdt_incdtcat_id,
24629                     incdt_incdtseverity_id,incdt_incdtpriority_id,
24630                     incdt_owner_username,  incdt_recurring_incdt_id
24631            ) SELECT fetchIncidentNumber(), incdt_crmacct_id,
24632                     incdt_cntct_id,        incdt_summary,
24633                     incdt_descrip,         incdt_item_id,
24634                     ptimestamp,            incdt_incdtcat_id,
24635                     incdt_incdtseverity_id,incdt_incdtpriority_id,
24636                     incdt_owner_username,  incdt_recurring_incdt_id
24637                FROM incdt
24638               WHERE (incdt_id=pparentid)
24639   RETURNING incdt_id INTO _incdtid;
24640
24641   IF (_incdtid IS NULL) THEN
24642     RETURN -10;
24643   END IF;
24644
24645   SELECT MIN(copyTodoitem(todoitem_id, CAST(ptimestamp AS DATE), _incdtid))
24646             INTO _todoitemid
24647     FROM todoitem
24648    WHERE (todoitem_incdt_id=pparentid);
24649
24650   IF (_todoitemid < 0) THEN
24651     RETURN _todoitemid;
24652   END IF;
24653
24654   SELECT saveAlarm(NULL, NULL, CAST(ptimestamp AS DATE),
24655                    CAST(alarm_time - DATE_TRUNC('day',alarm_time) AS TIME),
24656                    alarm_time_offset,
24657                    alarm_time_qualifier,
24658                    alarm_event_recipient  IS NOT NULL, alarm_event_recipient,
24659                    alarm_email_recipient  IS NOT NULL, alarm_email_recipient,
24660                    alarm_sysmsg_recipient IS NOT NULL, alarm_sysmsg_recipient,
24661                    'INCDT', _incdtid, 'CHANGEONE')
24662     INTO _alarmid
24663     FROM alarm
24664    WHERE ((alarm_source='INCDT')
24665       AND (alarm_source_id=pparentid));
24666
24667    IF (_alarmid < 0) THEN
24668      RETURN _alarmid;
24669    END IF;
24670
24671    INSERT INTO docass (docass_source_id, docass_source_type,
24672                        docass_target_id, docass_target_type, docass_purpose
24673               ) SELECT _incdtid,       'INCDT',
24674                        docass_target_id, docass_target_type, docass_purpose
24675                   FROM docass
24676                  WHERE ((docass_source_id=pparentid)
24677                     AND (docass_source_type='INCDT'));
24678
24679   RETURN _incdtid;
24680 END;
24681 $_$;
24682
24683
24684 ALTER FUNCTION public.copyincdt(integer, timestamp with time zone) OWNER TO admin;
24685
24686 --
24687 -- TOC entry 1255 (class 1255 OID 146565801)
24688 -- Dependencies: 4536 8
24689 -- Name: copyinvoice(integer, date); Type: FUNCTION; Schema: public; Owner: admin
24690 --
24691
24692 CREATE FUNCTION copyinvoice(integer, date) RETURNS integer
24693     LANGUAGE plpgsql
24694     AS $_$
24695 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24696 -- See www.xtuple.com/CPAL for the full text of the software license.
24697 DECLARE
24698   pInvcheadid ALIAS FOR $1;
24699   _invcheadid INTEGER;
24700   _invcnumber TEXT;
24701   _invcdate DATE := COALESCE($2, CURRENT_DATE);
24702   _i RECORD;
24703   _l RECORD;
24704   _invcitemid INTEGER;
24705
24706 BEGIN
24707   SELECT *
24708     INTO _i
24709     FROM invchead
24710    WHERE(invchead_id=pInvcheadid);
24711   IF(NOT FOUND) THEN
24712     RETURN -1;
24713   END IF;
24714
24715   _invcnumber := fetchInvcNumber();
24716   _invcheadid := nextval('invchead_invchead_id_seq');
24717
24718   INSERT INTO invchead
24719         (invchead_id,
24720          invchead_cust_id, invchead_shipto_id,
24721          invchead_ordernumber, invchead_orderdate,
24722          invchead_posted, invchead_printed,
24723          invchead_invcnumber, invchead_invcdate, invchead_shipdate,
24724          invchead_ponumber, invchead_shipvia,
24725          invchead_fob, invchead_billto_name,
24726          invchead_billto_address1, invchead_billto_address2,
24727          invchead_billto_address3, invchead_billto_city,
24728          invchead_billto_state, invchead_billto_zipcode,
24729          invchead_billto_phone, invchead_shipto_name,
24730          invchead_shipto_address1, invchead_shipto_address2,
24731          invchead_shipto_address3, invchead_shipto_city,
24732          invchead_shipto_state, invchead_shipto_zipcode,
24733          invchead_shipto_phone, invchead_salesrep_id,
24734          invchead_commission,
24735          invchead_terms_id, invchead_freight,
24736          invchead_misc_amount,
24737          invchead_misc_descrip, invchead_misc_accnt_id,
24738          invchead_payment, invchead_paymentref,
24739          invchead_notes,
24740          invchead_billto_country, invchead_shipto_country,
24741          invchead_prj_id, invchead_curr_id,
24742          invchead_taxzone_id,
24743          invchead_recurring_invchead_id,
24744          invchead_saletype_id, invchead_shipzone_id)
24745   VALUES(_invcheadid,
24746          _i.invchead_cust_id, _i.invchead_shipto_id,
24747          _i.invchead_ordernumber, _i.invchead_orderdate,
24748          false, false,
24749          _invcnumber, _invcdate, _i.invchead_shipdate,
24750          _i.invchead_ponumber, _i.invchead_shipvia,
24751          _i.invchead_fob, _i.invchead_billto_name,
24752          _i.invchead_billto_address1, _i.invchead_billto_address2,
24753          _i.invchead_billto_address3, _i.invchead_billto_city,
24754          _i.invchead_billto_state, _i.invchead_billto_zipcode,
24755          _i.invchead_billto_phone, _i.invchead_shipto_name,
24756          _i.invchead_shipto_address1, _i.invchead_shipto_address2,
24757          _i.invchead_shipto_address3, _i.invchead_shipto_city,
24758          _i.invchead_shipto_state, _i.invchead_shipto_zipcode,
24759          _i.invchead_shipto_phone, _i.invchead_salesrep_id,
24760          _i.invchead_commission,
24761          _i.invchead_terms_id, _i.invchead_freight,
24762          _i.invchead_misc_amount,
24763          _i.invchead_misc_descrip, _i.invchead_misc_accnt_id,
24764          _i.invchead_payment, _i.invchead_paymentref,
24765          _i.invchead_notes,
24766          _i.invchead_billto_country, _i.invchead_shipto_country,
24767          _i.invchead_prj_id, _i.invchead_curr_id,
24768          _i.invchead_taxzone_id,
24769          _i.invchead_recurring_invchead_id,
24770          _i.invchead_saletype_id, _i.invchead_shipzone_id);
24771
24772   FOR _l IN SELECT *
24773             FROM invcitem
24774             WHERE (invcitem_invchead_id=pInvcheadid) LOOP
24775     SELECT NEXTVAL('invcitem_invcitem_id_seq') INTO _invcitemid;
24776
24777     INSERT INTO invcitem
24778         (invcitem_id, invcitem_invchead_id,
24779          invcitem_linenumber, invcitem_item_id,
24780          invcitem_warehous_id, invcitem_custpn,
24781          invcitem_number, invcitem_descrip,
24782          invcitem_ordered, invcitem_billed,
24783          invcitem_custprice, invcitem_price,
24784          invcitem_notes, invcitem_salescat_id,
24785          invcitem_taxtype_id,
24786          invcitem_qty_uom_id, invcitem_qty_invuomratio,
24787          invcitem_price_uom_id, invcitem_price_invuomratio,
24788          invcitem_coitem_id)
24789     VALUES
24790         (_invcitemid, _invcheadid,
24791          _l.invcitem_linenumber, _l.invcitem_item_id,
24792          _l.invcitem_warehous_id, _l.invcitem_custpn,
24793          _l.invcitem_number, _l.invcitem_descrip,
24794          _l.invcitem_ordered, _l.invcitem_billed,
24795          _l.invcitem_custprice, _l.invcitem_price,
24796          _l.invcitem_notes, _l.invcitem_salescat_id,
24797          _l.invcitem_taxtype_id,
24798          _l.invcitem_qty_uom_id, _l.invcitem_qty_invuomratio,
24799          _l.invcitem_price_uom_id, _l.invcitem_price_invuomratio,
24800          _l.invcitem_coitem_id);
24801
24802   END LOOP;
24803
24804   RETURN _invcheadid;
24805 END;
24806 $_$;
24807
24808
24809 ALTER FUNCTION public.copyinvoice(integer, date) OWNER TO admin;
24810
24811 --
24812 -- TOC entry 1256 (class 1255 OID 146565802)
24813 -- Dependencies: 4536 8
24814 -- Name: copyitem(integer, text); Type: FUNCTION; Schema: public; Owner: admin
24815 --
24816
24817 CREATE FUNCTION copyitem(integer, text) RETURNS integer
24818     LANGUAGE plpgsql
24819     AS $_$
24820 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24821 -- See www.xtuple.com/CPAL for the full text of the software license.
24822 DECLARE
24823   pSItemid ALIAS FOR $1;
24824   pTItemNumber ALIAS FOR $2;
24825   _itemid INTEGER;
24826   _r RECORD;
24827   _id INTEGER;
24828
24829 BEGIN
24830
24831   SELECT NEXTVAL('item_item_id_seq') INTO _itemid;
24832   INSERT INTO item
24833   ( item_id, item_number, item_descrip1, item_descrip2,
24834     item_classcode_id, item_type,
24835     item_active, item_picklist, item_sold, item_fractional,
24836     item_maxcost, item_prodweight, item_packweight,
24837     item_prodcat_id,item_exclusive, item_listprice, item_listcost,
24838     item_config, item_comments, item_extdescrip,
24839     item_upccode, item_inv_uom_id, item_price_uom_id )
24840   SELECT _itemid, pTItemNumber, item_descrip1, item_descrip2,
24841          item_classcode_id, item_type,
24842          item_active, item_picklist, item_sold, item_fractional,
24843          item_maxcost, item_prodweight, item_packweight,
24844          item_prodcat_id, item_exclusive, item_listprice, item_listcost,
24845          item_config, item_comments, item_extdescrip,
24846          item_upccode, item_inv_uom_id, item_price_uom_id
24847   FROM item
24848   WHERE (item_id=pSItemid);
24849
24850   INSERT INTO imageass
24851   (imageass_source_id, imageass_source, imageass_image_id, imageass_purpose)
24852   SELECT _itemid, 'I', imageass_image_id, imageass_purpose
24853   FROM imageass
24854   WHERE ((imageass_source_id=pSItemid)
24855   AND (imageass_source='I'));
24856   
24857   INSERT INTO url
24858   (url_source_id, url_source, url_title, url_url)
24859   SELECT _itemid, 'I', url_title, url_url
24860   FROM url
24861   WHERE ((url_source_id=pSItemid)
24862   AND (url_source='I'));
24863
24864   INSERT INTO itemtax
24865         (itemtax_item_id, itemtax_taxzone_id, itemtax_taxtype_id)
24866   SELECT _itemid, itemtax_taxzone_id, itemtax_taxtype_id
24867     FROM itemtax
24868    WHERE(itemtax_item_id=pSItemid);
24869
24870   INSERT INTO charass
24871   ( charass_target_type, charass_target_id,
24872     charass_char_id, charass_value )
24873   SELECT 'I', _itemid, charass_char_id, charass_value
24874   FROM charass
24875   WHERE ( (charass_target_type='I')
24876    AND (charass_target_id=pSItemid) );
24877
24878   FOR _r IN SELECT itemuomconv_id,
24879                    itemuomconv_from_uom_id,
24880                    itemuomconv_from_value,
24881                    itemuomconv_to_uom_id,
24882                    itemuomconv_to_value,
24883                    itemuomconv_fractional
24884               FROM itemuomconv
24885              WHERE(itemuomconv_item_id=pSItemid) LOOP
24886     SELECT nextval('itemuomconv_itemuomconv_id_seq') INTO _id;
24887     INSERT INTO itemuomconv
24888           (itemuomconv_id, itemuomconv_item_id,
24889            itemuomconv_from_uom_id, itemuomconv_from_value,
24890            itemuomconv_to_uom_id, itemuomconv_to_value,
24891            itemuomconv_fractional)
24892     VALUES(_id, _itemid,
24893            _r.itemuomconv_from_uom_id, _r.itemuomconv_from_value,
24894            _r.itemuomconv_to_uom_id, _r.itemuomconv_to_value,
24895            _r.itemuomconv_fractional);
24896
24897     INSERT INTO itemuom
24898           (itemuom_itemuomconv_id, itemuom_uomtype_id)
24899     SELECT _id, itemuom_uomtype_id
24900       FROM itemuom
24901      WHERE(itemuom_itemuomconv_id=_r.itemuomconv_id);
24902   END LOOP;
24903
24904   RETURN _itemid;
24905
24906 END;
24907 $_$;
24908
24909
24910 ALTER FUNCTION public.copyitem(integer, text) OWNER TO admin;
24911
24912 --
24913 -- TOC entry 1259 (class 1255 OID 146565805)
24914 -- Dependencies: 4536 8
24915 -- Name: copyitem(integer, text, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
24916 --
24917
24918 CREATE FUNCTION copyitem(integer, text, boolean, boolean) RETURNS integer
24919     LANGUAGE plpgsql
24920     AS $_$
24921 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24922 -- See www.xtuple.com/CPAL for the full text of the software license.
24923 DECLARE
24924   pSItemid      ALIAS FOR $1;
24925   pTItemNumber  ALIAS FOR $2;
24926   pCopyBOM      ALIAS FOR $3;
24927   pCopyCosts    ALIAS FOR $4;
24928
24929   _itemid       INTEGER;
24930 BEGIN
24931
24932   _itemid := copyItem(pSItemid, pTItemNumber);
24933
24934   IF (pCopyBOM) THEN
24935     PERFORM copyBOM(pSItemid, _itemid, FALSE);
24936   END IF;
24937
24938   IF (pCopyCosts) THEN
24939     INSERT INTO itemcost
24940     ( itemcost_item_id, itemcost_costelem_id, itemcost_lowlevel,
24941       itemcost_stdcost, itemcost_posted,
24942       itemcost_actcost, itemcost_curr_id, itemcost_updated )
24943     SELECT _itemid, itemcost_costelem_id, itemcost_lowlevel,
24944       itemcost_stdcost, CURRENT_DATE,
24945       itemcost_actcost, itemcost_curr_id, CURRENT_DATE
24946     FROM itemcost
24947     WHERE (itemcost_item_id=pSItemid);
24948   END IF;
24949
24950   RETURN _itemid;
24951
24952 END;
24953 $_$;
24954
24955
24956 ALTER FUNCTION public.copyitem(integer, text, boolean, boolean) OWNER TO admin;
24957
24958 --
24959 -- TOC entry 1257 (class 1255 OID 146565803)
24960 -- Dependencies: 4536 8
24961 -- Name: copyitem(integer, text, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
24962 --
24963
24964 CREATE FUNCTION copyitem(integer, text, boolean, boolean, boolean) RETURNS integer
24965     LANGUAGE plpgsql
24966     AS $_$
24967 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24968 -- See www.xtuple.com/CPAL for the full text of the software license.
24969 DECLARE
24970   pSItemid ALIAS FOR $1;
24971   pTItemNumber ALIAS FOR $2;
24972   pCopyBOM ALIAS FOR $3;
24973   pCopyBOO ALIAS FOR $4;        -- deprecated - xtmfg-specific
24974   pCopyCosts ALIAS FOR $5;
24975 BEGIN
24976   RAISE NOTICE 'copyItem(INTEGER, TEXT, BOOLEAN, BOOLEAN, BOOLEAN) has been deprecated.  Use copyItem(INTEGER, TEXT) or copyItem(INTEGER, TEXT, BOOLEAN, BOOLEAN) or a package-specific version instead.';
24977   RETURN copyItem(pSItemid, pTItemNumber, pCopyBOM, pCopyCosts);
24978 END;
24979 $_$;
24980
24981
24982 ALTER FUNCTION public.copyitem(integer, text, boolean, boolean, boolean) OWNER TO admin;
24983
24984 --
24985 -- TOC entry 1258 (class 1255 OID 146565804)
24986 -- Dependencies: 4536 8
24987 -- Name: copyitem(integer, text, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
24988 --
24989
24990 CREATE FUNCTION copyitem(integer, text, boolean, boolean, boolean, boolean) RETURNS integer
24991     LANGUAGE plpgsql
24992     AS $_$
24993 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
24994 -- See www.xtuple.com/CPAL for the full text of the software license.
24995 DECLARE
24996   pSItemid ALIAS FOR $1;
24997   pTItemNumber ALIAS FOR $2;
24998   pCopyBOM ALIAS FOR $3;
24999   pCopyBOO ALIAS FOR $4;        -- deprecated - xtmfg-specific
25000   pCopyCosts ALIAS FOR $5;
25001   pCopyUsedAt ALIAS FOR $6;     -- deprecated - xtmfg-specific
25002 BEGIN
25003   RETURN copyItem(pSItemid, pTItemNumber, pCopyBOM, pCopyCosts);
25004 END;
25005 $_$;
25006
25007
25008 ALTER FUNCTION public.copyitem(integer, text, boolean, boolean, boolean, boolean) OWNER TO admin;
25009
25010 --
25011 -- TOC entry 1260 (class 1255 OID 146565806)
25012 -- Dependencies: 4536 8
25013 -- Name: copyitemsite(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
25014 --
25015
25016 CREATE FUNCTION copyitemsite(pitemsiteid integer, pdestwhsid integer) RETURNS integer
25017     LANGUAGE plpgsql
25018     AS $$
25019 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25020 -- See www.xtuple.com/CPAL for the full text of the software license.
25021
25022 BEGIN
25023
25024   RETURN copyItemSite(pitemsiteid, pdestwhsid, NULL);
25025
25026 END;
25027 $$;
25028
25029
25030 ALTER FUNCTION public.copyitemsite(pitemsiteid integer, pdestwhsid integer) OWNER TO admin;
25031
25032 --
25033 -- TOC entry 1261 (class 1255 OID 146565807)
25034 -- Dependencies: 4536 8
25035 -- Name: copyitemsite(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
25036 --
25037
25038 CREATE FUNCTION copyitemsite(pitemsiteid integer, pdestwhsid integer, pdestitemid integer) RETURNS integer
25039     LANGUAGE plpgsql
25040     AS $_$
25041 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25042 -- See www.xtuple.com/CPAL for the full text of the software license.
25043 DECLARE
25044   pitemsiteid   ALIAS FOR $1;
25045   pdestwhsid    ALIAS FOR $2;
25046   _destwhs      whsinfo%ROWTYPE;
25047   _new          itemsite%ROWTYPE;
25048
25049 BEGIN
25050   -- make a copy of the old itemsite
25051   SELECT * INTO _new
25052   FROM itemsite
25053   WHERE (itemsite_id=pitemsiteid);
25054   IF (NOT FOUND) THEN
25055     RETURN -1;
25056   END IF;
25057
25058   -- if there is no dest warehouse then perhaps the user is manually copying it
25059   IF (pdestwhsid IS NOT NULL) THEN
25060     SELECT * INTO _destwhs
25061     FROM whsinfo
25062     WHERE (warehous_id=pdestwhsid);
25063     IF (NOT FOUND) THEN
25064       RETURN -2;
25065     END IF;
25066   END IF;
25067
25068   IF (NOT checkPrivilege('MaintainItemSites')) THEN
25069     RETURN -3;
25070   END IF;
25071
25072   SELECT itemsite_id INTO _new.itemsite_id
25073   FROM itemsite
25074   WHERE ((itemsite_item_id=COALESCE(pdestitemid, _new.itemsite_item_id))
25075     AND  (itemsite_warehous_id=pdestwhsid OR
25076           (itemsite_warehous_id IS NULL AND pdestwhsid IS NULL)));
25077   IF (FOUND) THEN
25078     RETURN _new.itemsite_id;
25079   END IF;
25080
25081   -- now override the things we know have to change
25082   _new.itemsite_id              := NEXTVAL('itemsite_itemsite_id_seq');
25083   _new.itemsite_warehous_id     := pdestwhsid;
25084   _new.itemsite_qtyonhand       := 0;
25085   _new.itemsite_value           := 0;
25086   _new.itemsite_datelastcount   := NULL;
25087   _new.itemsite_datelastused    := NULL;
25088   _new.itemsite_nnqoh           := 0;
25089   _new.itemsite_location_id    := -1;
25090
25091   IF (_destwhs.warehous_transit) THEN
25092     _new.itemsite_reorderlevel  := 0;
25093     _new.itemsite_ordertoqty    := 0;
25094     _new.itemsite_soldranking   := NULL;
25095     _new.itemsite_posupply      := FALSE;
25096     _new.itemsite_wosupply      := FALSE;
25097     _new.itemsite_loccntrl      := FALSE;
25098     _new.itemsite_safetystock   := 0;
25099     _new.itemsite_minordqty     := 0;
25100     _new.itemsite_multordqty    := 0;
25101     _new.itemsite_leadtime      := 0;
25102     _new.itemsite_controlmethod := 'R';
25103     IF(_new.itemsite_costmethod='N') THEN
25104       _new.itemsite_costmethod := 'S';
25105     END IF;
25106     _new.itemsite_active        := TRUE;
25107     -- ? _new.itemsite_plancode_id      := -1;
25108     -- ? _new.itemsite_costcat_id       := -1;
25109     _new.itemsite_eventfence    := 1;
25110     _new.itemsite_sold          := FALSE;
25111     _new.itemsite_stocked       := FALSE;
25112     _new.itemsite_location_id   := -1;
25113     _new.itemsite_useparams     := FALSE;
25114     _new.itemsite_useparamsmanual := FALSE;
25115     _new.itemsite_createpr      := FALSE;
25116     _new.itemsite_location      := NULL;
25117     _new.itemsite_location_comments := NULL;
25118     _new.itemsite_notes         := 'Transit Warehouse';
25119     _new.itemsite_nnqoh         := 0;
25120     _new.itemsite_createwo      := FALSE;
25121     _new.itemsite_costcat_id    := _destwhs.warehous_costcat_id;
25122   END IF;
25123
25124   INSERT INTO itemsite (
25125     itemsite_id,                        itemsite_item_id,
25126     itemsite_warehous_id,               itemsite_qtyonhand,
25127     itemsite_costmethod,                itemsite_value,
25128     itemsite_reorderlevel,              itemsite_ordertoqty,
25129     itemsite_cyclecountfreq,            itemsite_datelastcount,
25130     itemsite_datelastused,
25131     itemsite_posupply,                  itemsite_wosupply,
25132     itemsite_loccntrl,
25133     itemsite_safetystock,               itemsite_minordqty,
25134     itemsite_multordqty,                itemsite_leadtime,
25135     itemsite_abcclass,                  itemsite_issuemethod,
25136     itemsite_controlmethod,             itemsite_active,
25137     itemsite_plancode_id,               itemsite_costcat_id,
25138     itemsite_eventfence,                itemsite_sold,
25139     itemsite_stocked,                   itemsite_freeze,
25140     itemsite_location_id,
25141     itemsite_useparams,                 itemsite_useparamsmanual,
25142     itemsite_soldranking,               itemsite_createpr,
25143     itemsite_location,                  itemsite_location_comments,
25144     itemsite_notes,                     itemsite_perishable,
25145     itemsite_nnqoh,                     itemsite_autoabcclass,
25146     itemsite_ordergroup,                itemsite_disallowblankwip,
25147     itemsite_maxordqty,                 itemsite_mps_timefence,
25148     itemsite_createwo,                  itemsite_warrpurc,
25149     itemsite_autoreg,
25150     itemsite_planning_type,             itemsite_supply_itemsite_id
25151   ) VALUES (
25152     _new.itemsite_id,                   COALESCE(pdestitemid, _new.itemsite_item_id),
25153     _new.itemsite_warehous_id,          _new.itemsite_qtyonhand,
25154     _new.itemsite_costmethod,           _new.itemsite_value,
25155     _new.itemsite_reorderlevel,         _new.itemsite_ordertoqty,
25156     _new.itemsite_cyclecountfreq,       _new.itemsite_datelastcount,
25157     _new.itemsite_datelastused,
25158     _new.itemsite_posupply,             _new.itemsite_wosupply,
25159     _new.itemsite_loccntrl,
25160     _new.itemsite_safetystock,          _new.itemsite_minordqty,
25161     _new.itemsite_multordqty,           _new.itemsite_leadtime,
25162     _new.itemsite_abcclass,             _new.itemsite_issuemethod,
25163     _new.itemsite_controlmethod,        _new.itemsite_active,
25164     _new.itemsite_plancode_id,          _new.itemsite_costcat_id,
25165     _new.itemsite_eventfence,           _new.itemsite_sold,
25166     _new.itemsite_stocked,              _new.itemsite_freeze,
25167     _new.itemsite_location_id,
25168     _new.itemsite_useparams,            _new.itemsite_useparamsmanual,
25169     _new.itemsite_soldranking,          _new.itemsite_createpr,
25170     _new.itemsite_location,             _new.itemsite_location_comments,
25171     _new.itemsite_notes,                _new.itemsite_perishable,
25172     _new.itemsite_nnqoh,                _new.itemsite_autoabcclass,
25173     _new.itemsite_ordergroup,           _new.itemsite_disallowblankwip,
25174     _new.itemsite_maxordqty,            _new.itemsite_mps_timefence,
25175     _new.itemsite_createwo,             _new.itemsite_warrpurc,
25176     _new.itemsite_autoreg,
25177     _new.itemsite_planning_type,        _new.itemsite_supply_itemsite_id
25178     );
25179
25180   RETURN _new.itemsite_id;
25181 END;
25182 $_$;
25183
25184
25185 ALTER FUNCTION public.copyitemsite(pitemsiteid integer, pdestwhsid integer, pdestitemid integer) OWNER TO admin;
25186
25187 --
25188 -- TOC entry 1246 (class 1255 OID 146565808)
25189 -- Dependencies: 4536 8
25190 -- Name: copylocale(integer); Type: FUNCTION; Schema: public; Owner: admin
25191 --
25192
25193 CREATE FUNCTION copylocale(integer) RETURNS integer
25194     LANGUAGE plpgsql
25195     AS $_$
25196 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25197 -- See www.xtuple.com/CPAL for the full text of the software license.
25198 DECLARE
25199   pLocaleid ALIAS FOR $1;
25200   _localecode TEXT;
25201   _localeid INTEGER;
25202
25203 BEGIN
25204
25205   SELECT locale_code INTO _localecode
25206   FROM locale
25207   WHERE (locale_id=pLocaleid);
25208
25209   IF (NOT FOUND) THEN
25210     RAISE EXCEPTION 'Attempt to copy a non-existent locale-id.';
25211   END IF;
25212
25213   IF (EXISTS(SELECT locale_id
25214              FROM locale
25215              WHERE (locale_code = (_localecode || '-COPY')))) THEN
25216     RAISE EXCEPTION 'Attempt to copy a Locale Code that already exists.';
25217   END IF;
25218
25219   SELECT NEXTVAL('locale_locale_id_seq') INTO _localeid;
25220
25221   INSERT INTO locale
25222         (locale_id, locale_code, locale_descrip,
25223          locale_lang_file,
25224          locale_dateformat,
25225          locale_currformat,
25226          locale_qtyformat,
25227          locale_comments,
25228          locale_qtyperformat,
25229          locale_salespriceformat,
25230          locale_extpriceformat,
25231          locale_timeformat,
25232          locale_timestampformat,
25233          local_costformat,
25234          locale_costformat,
25235          locale_purchpriceformat,
25236          locale_uomratioformat,
25237          locale_intervalformat,
25238          locale_lang_id,
25239          locale_country_id,
25240          locale_error_color,
25241          locale_warning_color,
25242          locale_emphasis_color,
25243          locale_altemphasis_color,
25244          locale_expired_color,
25245          locale_future_color,
25246          locale_curr_scale,
25247          locale_salesprice_scale,
25248          locale_purchprice_scale,
25249          locale_extprice_scale,
25250          locale_cost_scale,
25251          locale_qty_scale,
25252          locale_qtyper_scale,
25253          locale_uomratio_scale)
25254   SELECT _localeid, locale_code || '-COPY', '',
25255          locale_lang_file,
25256          locale_dateformat,
25257          locale_currformat,
25258          locale_qtyformat,
25259          locale_comments,
25260          locale_qtyperformat,
25261          locale_salespriceformat,
25262          locale_extpriceformat,
25263          locale_timeformat,
25264          locale_timestampformat,
25265          local_costformat,
25266          locale_costformat,
25267          locale_purchpriceformat,
25268          locale_uomratioformat,
25269          locale_intervalformat,
25270          locale_lang_id,
25271          locale_country_id,
25272          locale_error_color,
25273          locale_warning_color,
25274          locale_emphasis_color,
25275          locale_altemphasis_color,
25276          locale_expired_color,
25277          locale_future_color,
25278          locale_curr_scale,
25279          locale_salesprice_scale,
25280          locale_purchprice_scale,
25281          locale_extprice_scale,
25282          locale_cost_scale,
25283          locale_qty_scale,
25284          locale_qtyper_scale,
25285          locale_uomratio_scale
25286     FROM locale
25287    WHERE(locale_id=pLocaleid);
25288
25289   RETURN _localeid;
25290
25291 END;
25292 $_$;
25293
25294
25295 ALTER FUNCTION public.copylocale(integer) OWNER TO admin;
25296
25297 --
25298 -- TOC entry 1247 (class 1255 OID 146565809)
25299 -- Dependencies: 4536 8
25300 -- Name: copypo(integer, integer, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
25301 --
25302
25303 CREATE FUNCTION copypo(integer, integer, date, boolean) RETURNS integer
25304     LANGUAGE plpgsql
25305     AS $_$
25306 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25307 -- See www.xtuple.com/CPAL for the full text of the software license.
25308 DECLARE
25309   pSrcid                ALIAS FOR $1;
25310   pVendid               ALIAS FOR $2;
25311   pOrderdate            ALIAS FOR $3;
25312   pRecheckVendinfo      ALIAS FOR $4;
25313
25314   _tgtid                INTEGER;
25315   _orderdate            DATE;
25316   _head                 RECORD;
25317   _itemsrc              RECORD;
25318   _lineitem             RECORD;
25319   _qty                  NUMERIC;
25320   _unitprice            NUMERIC;
25321   _uomratio             NUMERIC;
25322   _vend_restrictpurch   BOOLEAN;
25323
25324 BEGIN
25325   SELECT * INTO _head FROM pohead WHERE pohead_id = pSrcid;
25326   IF (NOT FOUND) THEN
25327     RETURN -1;
25328   END IF;
25329   IF (_head.pohead_vend_id != pVendid) THEN
25330     RETURN -2;          -- not supported now but should be in the future
25331   END IF;               -- when enabled, set pRecheckVendinfo if vendors don't match
25332
25333   IF (pOrderdate IS NULL) THEN
25334     _orderdate := CURRENT_DATE;
25335   ELSE
25336     _orderdate := pOrderdate;
25337   END IF;
25338
25339   INSERT INTO pohead (pohead_status, pohead_number,
25340                       pohead_orderdate, pohead_vend_id,
25341                       pohead_fob, pohead_shipvia,
25342                       pohead_freight, pohead_printed,
25343                       pohead_terms_id, pohead_warehous_id,
25344                       pohead_vendaddr_id, pohead_agent_username,
25345                       pohead_curr_id, pohead_saved,
25346                       pohead_taxtype_id, pohead_taxzone_id,
25347                       pohead_dropship, pohead_vend_cntct_id,
25348                       pohead_vend_cntct_honorific, pohead_vend_cntct_first_name,
25349                       pohead_vend_cntct_middle, pohead_vend_cntct_last_name,
25350                       pohead_vend_cntct_suffix, pohead_vend_cntct_phone,
25351                       pohead_vend_cntct_title, pohead_vend_cntct_fax,
25352                       pohead_vend_cntct_email, pohead_vendaddress1,
25353                       pohead_vendaddress2, pohead_vendaddress3,
25354                       pohead_vendcity, pohead_vendstate,
25355                       pohead_vendzipcode, pohead_vendcountry,
25356                       pohead_shipto_cntct_id,
25357                       pohead_shipto_cntct_honorific, pohead_shipto_cntct_first_name,
25358                       pohead_shipto_cntct_middle, pohead_shipto_cntct_last_name,
25359                       pohead_shipto_cntct_suffix, pohead_shipto_cntct_phone,
25360                       pohead_shipto_cntct_title, pohead_shipto_cntct_fax,
25361                       pohead_shipto_cntct_email, pohead_shiptoaddress_id,
25362                       pohead_shiptoaddress1,
25363                       pohead_shiptoaddress2, pohead_shiptoaddress3,
25364                       pohead_shiptocity, pohead_shiptostate,
25365                       pohead_shiptozipcode, pohead_shiptocountry
25366               ) VALUES (
25367                       'U', fetchPoNumber(),
25368                       _orderdate, _head.pohead_vend_id,
25369                       _head.pohead_fob, _head.pohead_shipvia,
25370                       _head.pohead_freight, false,
25371                       _head.pohead_terms_id, _head.pohead_warehous_id,
25372                       _head.pohead_vendaddr_id, _head.pohead_agent_username,
25373                       _head.pohead_curr_id, true,
25374                       _head.pohead_taxtype_id, _head.pohead_taxzone_id,
25375                       false, _head.pohead_vend_cntct_id,
25376                       _head.pohead_vend_cntct_honorific, _head.pohead_vend_cntct_first_name,
25377                       _head.pohead_vend_cntct_middle, _head.pohead_vend_cntct_last_name,
25378                       _head.pohead_vend_cntct_suffix, _head.pohead_vend_cntct_phone,
25379                       _head.pohead_vend_cntct_title, _head.pohead_vend_cntct_fax,
25380                       _head.pohead_vend_cntct_email, _head.pohead_vendaddress1,
25381                       _head.pohead_vendaddress2, _head.pohead_vendaddress3,
25382                       _head.pohead_vendcity, _head.pohead_vendstate,
25383                       _head.pohead_vendzipcode, _head.pohead_vendcountry,
25384                       _head.pohead_shipto_cntct_id,
25385                       _head.pohead_shipto_cntct_honorific, _head.pohead_shipto_cntct_first_name,
25386                       _head.pohead_shipto_cntct_middle, _head.pohead_shipto_cntct_last_name,
25387                       _head.pohead_shipto_cntct_suffix, _head.pohead_shipto_cntct_phone,
25388                       _head.pohead_shipto_cntct_title, _head.pohead_shipto_cntct_fax,
25389                       _head.pohead_shipto_cntct_email, _head.pohead_shiptoaddress_id,
25390                       _head.pohead_shiptoaddress1,
25391                       _head.pohead_shiptoaddress2, _head.pohead_shiptoaddress3,
25392                       _head.pohead_shiptocity, _head.pohead_shiptostate,
25393                       _head.pohead_shiptozipcode, _head.pohead_shiptocountry);
25394
25395   _tgtid := CURRVAL('pohead_pohead_id_seq');
25396
25397   IF (pRecheckVendinfo) THEN
25398     SELECT vend_restrictpurch INTO _vend_restrictpurch
25399       FROM vendinfo WHERE (vend_id = pVendid);
25400
25401     FOR _lineitem IN SELECT *
25402                   FROM poitem 
25403                   WHERE (poitem_pohead_id = pSrcid) LOOP
25404
25405       SELECT * INTO _itemsrc
25406       FROM itemsrc, itemsite
25407       WHERE (itemsrc_active
25408         AND  (itemsrc_id = _lineitem.poitem_itemsrc_id)
25409         AND  (itemsite_id = _lineitem.poitem_itemsite_id));
25410       IF (NOT FOUND AND _vend_restrictpurch) THEN
25411         RETURN -3;
25412       END IF;
25413
25414       -- handle changes to the uom ratio and consequent qty changes
25415       _uomratio := COALESCE(_itemsrc.itemsrc_invvendoruomratio, _lineitem.poitem_invvenduomratio);
25416       IF (_itemsrc.itemsrc_invvendoruomratio IS NULL
25417           OR _itemsrc.itemsrc_invvendoruomratio != _lineitem.poitem_invvenduomratio) THEN
25418         _qty := _lineitem.poitem_qty_ordered;
25419
25420       ELSE
25421         _qty := _lineitem.poitem_qty_ordered * _lineitem.poitem_invvenduomratio /
25422                                                _itemsrc.itemsrc_invvendoruomratio;
25423         IF (_itemsrc.itemsrc_minordqty IS NOT NULL) THEN
25424           IF (_qty < _itemsrc.itemsrc_minordqty) THEN
25425             _qty := _itemsrc.itemsrc_minordqty;
25426           ELSIF (_itemsrc.itemsrc_multordqty > 0
25427                    AND _qty % _itemsrc.itemsrc_multordqty > 0) THEN
25428             _qty = _qty % _itemsrc.itemsrc_multordqty + _itemsrc.itemsrc_multordqty;
25429           END IF;
25430         END IF;
25431       END IF;
25432
25433       IF (_itemsrc.itemsrc_id IS NULL) THEN
25434         _unitprice = _lineitem.poitem_unitprice;
25435       ELSE
25436         SELECT itemsrcPrice(_itemsrc.itemsrc_id, _head.pohead_warehous_id, _head.pohead_dropship,
25437                             _lineitem.poitem_qty_ordered, _head.pohead_curr_id, CURRENT_DATE) INTO _unitprice;
25438         IF (_unitprice IS NULL) THEN
25439           RETURN -4;
25440         END IF;
25441       END IF;
25442
25443       INSERT INTO poitem (poitem_status, poitem_pohead_id, poitem_linenumber,
25444                           poitem_duedate,
25445                           poitem_itemsite_id,
25446                           poitem_vend_item_descrip,
25447                           poitem_vend_uom,
25448                           poitem_invvenduomratio,
25449                           poitem_qty_ordered, poitem_unitprice,
25450                           poitem_vend_item_number,
25451                           poitem_comments, poitem_expcat_id,
25452                           poitem_itemsrc_id,
25453                           poitem_freight,
25454                           poitem_stdcost,
25455                           poitem_manuf_name,
25456                           poitem_manuf_item_number,
25457                           poitem_manuf_item_descrip,
25458                           poitem_taxtype_id
25459                     ) VALUES (
25460                           'U', _tgtid, _lineitem.poitem_linenumber,
25461                           _orderdate + COALESCE(_itemsrc.itemsrc_leadtime, 0),
25462                           _lineitem.poitem_itemsite_id,
25463                           COALESCE(_itemsrc.itemsrc_vend_item_descrip,
25464                                    _lineitem.poitem_vend_item_descrip),
25465                           COALESCE(_itemsrc.itemsrc_vend_uom, _lineitem.poitem_vend_uom),
25466                           COALESCE(_itemsrc.itemsrc_invvendoruomratio,
25467                                    _lineitem.poitem_invvenduomratio),
25468                           _qty, _unitprice,
25469                           COALESCE(_itemsrc.itemsrc_vend_item_number,
25470                                    _lineitem.poitem_vend_item_number),
25471                           _lineitem.poitem_comments, _lineitem.poitem_expcat_id,
25472                           COALESCE(_itemsrc.itemsrc_id, -1),
25473                           _lineitem.poitem_freight,
25474                           stdcost(_itemsrc.itemsite_item_id),
25475                           COALESCE(_itemsrc.itemsrc_manuf_name,
25476                                    _lineitem.poitem_manuf_name),
25477                           COALESCE(_itemsrc.itemsrc_manuf_item_number,
25478                                    _lineitem.poitem_manuf_item_number),
25479                           COALESCE(_itemsrc.itemsrc_manuf_item_descrip,
25480                                    _lineitem.poitem_manuf_item_descrip),
25481                           _lineitem.poitem_taxtype_id);
25482
25483     END LOOP;
25484   ELSE
25485     INSERT INTO poitem (poitem_status, poitem_pohead_id, poitem_linenumber,
25486                         poitem_duedate, poitem_itemsite_id,
25487                         poitem_vend_item_descrip, poitem_vend_uom,
25488                         poitem_invvenduomratio, poitem_qty_ordered,
25489                         poitem_unitprice,
25490                         poitem_vend_item_number, poitem_comments,
25491                         poitem_expcat_id, poitem_itemsrc_id, poitem_freight,
25492                         poitem_stdcost, poitem_manuf_name, 
25493                         poitem_manuf_item_number, poitem_manuf_item_descrip,
25494                         poitem_taxtype_id
25495                 ) SELECT 'U', _tgtid, poitem_linenumber,
25496                         _orderdate + COALESCE(itemsrc_leadtime, 0), poitem_itemsite_id,
25497                         poitem_vend_item_descrip, poitem_vend_uom,
25498                         poitem_invvenduomratio, poitem_qty_ordered,
25499                         poitem_unitprice,
25500                         poitem_vend_item_number, poitem_comments,
25501                         poitem_expcat_id, poitem_itemsrc_id, poitem_freight,
25502                         stdcost(itemsite_item_id), poitem_manuf_name,
25503                         poitem_manuf_item_number, poitem_manuf_item_descrip,
25504                         poitem_taxtype_id
25505                   FROM poitem
25506                     LEFT OUTER JOIN itemsrc ON (itemsrc_id=poitem_itemsrc_id)
25507                     LEFT OUTER JOIN itemsite ON (itemsite_id=poitem_itemsite_id)
25508                   WHERE (poitem_pohead_id = pSrcid);
25509   END IF;
25510
25511   -- Todo: recalculate tax?
25512
25513   RETURN _tgtid;
25514
25515 END;
25516 $_$;
25517
25518
25519 ALTER FUNCTION public.copypo(integer, integer, date, boolean) OWNER TO admin;
25520
25521 --
25522 -- TOC entry 1262 (class 1255 OID 146565811)
25523 -- Dependencies: 4536 8
25524 -- Name: copypricingschedule(integer); Type: FUNCTION; Schema: public; Owner: admin
25525 --
25526
25527 CREATE FUNCTION copypricingschedule(pipsheadid integer) RETURNS integer
25528     LANGUAGE plpgsql
25529     AS $$
25530 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25531 -- See www.xtuple.com/CPAL for the full text of the software license.
25532 DECLARE
25533   _ipsheadid INTEGER;
25534   _ipsitemid INTEGER;
25535   _ipsfreightid INTEGER;
25536   _x RECORD;
25537
25538 BEGIN
25539
25540   _ipsheadid := nextval('ipshead_ipshead_id_seq');
25541   INSERT INTO ipshead 
25542   ( ipshead_id, ipshead_name, ipshead_descrip,
25543     ipshead_effective, ipshead_expires, 
25544     ipshead_curr_id, ipshead_updated ) 
25545   SELECT _ipsheadid, orig.ipshead_name || (SELECT CAST((COUNT(cnt.ipshead_id)+1) AS text)
25546                                             FROM ipshead cnt
25547                                             WHERE (SUBSTRING(cnt.ipshead_name FROM 0 FOR char_length(orig.ipshead_name)+1) = orig.ipshead_name)),
25548          orig.ipshead_descrip, orig.ipshead_effective, orig.ipshead_expires, 
25549          orig.ipshead_curr_id, CURRENT_DATE
25550   FROM ipshead orig
25551   WHERE (orig.ipshead_id=pIpsheadId);
25552
25553   FOR _x IN
25554     SELECT ipsitem_id FROM ipsiteminfo WHERE (ipsitem_ipshead_id=pIpsheadid)
25555   LOOP 
25556       INSERT INTO ipsiteminfo 
25557           (ipsitem_ipshead_id, ipsitem_item_id, ipsitem_prodcat_id,
25558            ipsitem_qtybreak, ipsitem_price,
25559            ipsitem_qty_uom_id, ipsitem_price_uom_id,
25560            ipsitem_discntprcnt, ipsitem_fixedamtdiscount,
25561            ipsitem_type, ipsitem_warehous_id) 
25562       SELECT _ipsheadid, ipsitem_item_id, ipsitem_prodcat_id,
25563            ipsitem_qtybreak, ipsitem_price,
25564            ipsitem_qty_uom_id, ipsitem_price_uom_id,
25565            ipsitem_discntprcnt, ipsitem_fixedamtdiscount,
25566            ipsitem_type, ipsitem_warehous_id
25567       FROM ipsiteminfo 
25568       WHERE (ipsitem_id=_x.ipsitem_id)
25569       RETURNING ipsitem_id INTO _ipsitemid; 
25570
25571       INSERT INTO ipsitemchar
25572         ( ipsitemchar_ipsitem_id, ipsitemchar_char_id,
25573           ipsitemchar_value, ipsitemchar_price)
25574       SELECT  _ipsitemid, ipsitemchar_char_id,
25575           ipsitemchar_value, ipsitemchar_price
25576       FROM ipsitemchar
25577       WHERE (ipsitemchar_ipsitem_id=_x.ipsitem_id);
25578   END LOOP;
25579
25580   FOR _x IN
25581     SELECT ipsfreight_id FROM ipsfreight WHERE (ipsfreight_ipshead_id=pIpsheadid)
25582   LOOP 
25583       _ipsfreightid := nextval('ipsfreight_ipsfreight_id_seq');
25584       INSERT INTO ipsfreight
25585           (ipsfreight_id, ipsfreight_ipshead_id, 
25586            ipsfreight_qtybreak, ipsfreight_price,
25587            ipsfreight_type, ipsfreight_warehous_id,
25588            ipsfreight_shipzone_id,ipsfreight_freightclass_id,
25589            ipsfreight_shipvia) 
25590       SELECT _ipsfreightid, _ipsheadid, ipsfreight_qtybreak, 
25591            ipsfreight_price,ipsfreight_type, 
25592            ipsfreight_warehous_id,ipsfreight_shipzone_id,
25593            ipsfreight_freightclass_id,ipsfreight_shipvia
25594       FROM ipsfreight
25595       WHERE (ipsfreight_id=_x.ipsfreight_id); 
25596
25597   END LOOP;
25598
25599   RETURN _ipsheadid;
25600
25601 END;
25602 $$;
25603
25604
25605 ALTER FUNCTION public.copypricingschedule(pipsheadid integer) OWNER TO admin;
25606
25607 --
25608 -- TOC entry 1263 (class 1255 OID 146565812)
25609 -- Dependencies: 4536 8
25610 -- Name: copyprj(integer, date); Type: FUNCTION; Schema: public; Owner: admin
25611 --
25612
25613 CREATE FUNCTION copyprj(integer, date) RETURNS integer
25614     LANGUAGE plpgsql
25615     AS $_$
25616 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25617 -- See www.xtuple.com/CPAL for the full text of the software license.
25618 DECLARE
25619   pparentid   ALIAS FOR $1;
25620   _counter    INTEGER;
25621   _duedate    DATE := COALESCE($2, CURRENT_DATE);
25622   _alarmid    INTEGER;
25623   _i          INTEGER;
25624   _newnumber  TEXT;
25625   _p          RECORD;
25626   _prjid      INTEGER;
25627   _testnumber TEXT;
25628
25629 BEGIN
25630   RAISE DEBUG 'copyPrj(%, %) entered', pparentid, _duedate;
25631
25632   SELECT * INTO _p
25633   FROM prj
25634   WHERE (prj_id=pparentid);
25635
25636   -- new number = old number up to but not including -, followed by _duedate
25637   -- e.g. REPAIR-FRIDGE becomes REPAIR-2010-05-15
25638   --  but REPAIR_FRIDGE becomes REPAIR_FRIDGE-2010-05-15
25639   IF (_p.prj_recurring_prj_id IS NULL) THEN
25640     _newnumber := _p.prj_number;
25641   ELSE
25642     _newnumber := SUBSTRING(_p.prj_number FROM '[^-]*');
25643     IF (_newnumber IS NULL) THEN
25644       _newnumber := _p.prj_number;
25645     END IF;
25646   END IF;
25647   _newnumber := _newnumber || '-' || to_char(_duedate, 'YYYY-MM-DD');
25648   
25649   RAISE DEBUG 'copyPrj checking if _newnumber % exists', _newnumber;
25650   SELECT MAX(prj_number) INTO _testnumber
25651     FROM prj
25652    WHERE (prj_number ~ ('^' || _newnumber));
25653   IF (_testnumber = _newnumber) THEN
25654     _newnumber := _newnumber || '-001';
25655   ELSIF (_testnumber IS NOT NULL) THEN
25656     _counter := CAST(SUBSTRING(_testnumber FROM '...$') AS INTEGER);
25657     _counter := _counter + 1;
25658     _newnumber := REGEXP_REPLACE(_testnumber, '...$', to_char(_counter, 'FM009'));
25659   END IF;
25660   RAISE DEBUG 'copyPrj _newnumber is now %', _newnumber;
25661
25662   INSERT INTO prj(
25663             prj_number,     prj_name,           prj_descrip,
25664             prj_status,     prj_so,             prj_wo,
25665             prj_po,         prj_owner_username,
25666             prj_due_date,   prj_username,       prj_recurring_prj_id
25667   ) SELECT  _newnumber,     _p.prj_name,        _p.prj_descrip,
25668             'P',            _p.prj_so,          _p.prj_wo,
25669             _p.prj_po,      _p.prj_owner_username,
25670             _duedate,       _p.prj_username,    _p. prj_recurring_prj_id
25671       FROM prj
25672      WHERE (prj_id=pparentid)
25673   RETURNING prj_id INTO _prjid;
25674
25675   IF (_prjid IS NULL) THEN
25676     RETURN -1;
25677   END IF;
25678
25679   SELECT saveAlarm(NULL, NULL, _duedate,
25680                    CAST(alarm_time - DATE_TRUNC('day',alarm_time) AS TIME),
25681                    alarm_time_offset,
25682                    alarm_time_qualifier,
25683                    alarm_event_recipient  IS NOT NULL, alarm_event_recipient,
25684                    alarm_email_recipient  IS NOT NULL, alarm_email_recipient,
25685                    alarm_sysmsg_recipient IS NOT NULL, alarm_sysmsg_recipient,
25686                    'J', _prjid, 'CHANGEONE')
25687     INTO _alarmid
25688     FROM alarm
25689    WHERE ((alarm_source='J')
25690       AND (alarm_source_id=pparentid));
25691
25692    IF (_alarmid < 0) THEN
25693      RETURN _alarmid;
25694    END IF;
25695
25696   RETURN _prjid;
25697 END;
25698 $_$;
25699
25700
25701 ALTER FUNCTION public.copyprj(integer, date) OWNER TO admin;
25702
25703 --
25704 -- TOC entry 1264 (class 1255 OID 146565813)
25705 -- Dependencies: 4536 8
25706 -- Name: copyproject(integer, text, text, date); Type: FUNCTION; Schema: public; Owner: admin
25707 --
25708
25709 CREATE FUNCTION copyproject(integer, text, text, date) RETURNS integer
25710     LANGUAGE plpgsql
25711     AS $_$
25712 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25713 -- See www.xtuple.com/CPAL for the full text of the software license.
25714 DECLARE
25715   pPrjId ALIAS FOR $1;
25716   pPrjNumber ALIAS FOR $2;
25717   pPrjName ALIAS FOR $3;
25718   pDueDate ALIAS FOR $4;
25719   _prjid INTEGER;
25720   _offset INTEGER;
25721
25722 BEGIN
25723
25724   IF (COALESCE(pPrjNumber, '') = '') THEN
25725     RETURN -1;
25726   END IF;
25727
25728   IF (COALESCE(pPrjName, '') = '') THEN
25729     RETURN -1;
25730   END IF;
25731
25732   IF (EXISTS(SELECT prj_id FROM prj WHERE UPPER(prj_number)=UPPER(pPrjNumber))) THEN
25733     RETURN -2;
25734   END IF;
25735
25736   IF (NOT EXISTS(SELECT prj_id FROM prj WHERE prj_id=pPrjId)) THEN
25737     RETURN -3;
25738   END IF;
25739
25740   IF (pDueDate IS NULL) THEN
25741     RETURN -4;
25742   END IF;
25743
25744   SELECT (pDueDate - prj_due_date) INTO _offset
25745    FROM prj
25746    WHERE (prj_id=pPrjId);
25747
25748   SELECT NEXTVAL('prj_prj_id_seq') INTO _prjid;
25749
25750   INSERT INTO prj
25751   ( prj_id, prj_number, prj_name, 
25752     prj_descrip, prj_status,
25753     prj_so, prj_wo, prj_po,
25754     prj_owner_username, prj_start_date,
25755     prj_due_date, prj_assigned_date, prj_completed_date,
25756     prj_username, prj_recurring_prj_id,
25757     prj_crmacct_id, prj_cntct_id )
25758   SELECT _prjid, UPPER(pPrjNumber), pPrjName,
25759          prj_descrip, 'P',
25760          prj_so, prj_wo, prj_po,
25761          prj_owner_username, NULL,
25762          (prj_due_date + COALESCE(_offset, 0)),
25763          CASE WHEN (prj_username IS NULL) THEN NULL ELSE CURRENT_DATE END, NULL,
25764          prj_username, prj_recurring_prj_id,
25765          prj_crmacct_id, prj_cntct_id
25766   FROM prj
25767   WHERE (prj_id=pPrjId);
25768
25769   INSERT INTO prjtask
25770   ( prjtask_number, prjtask_name, prjtask_descrip,
25771     prjtask_prj_id, prjtask_anyuser, prjtask_status,
25772     prjtask_hours_budget, prjtask_hours_actual,
25773     prjtask_exp_budget, prjtask_exp_actual,
25774     prjtask_owner_username, prjtask_start_date,
25775     prjtask_due_date, prjtask_assigned_date,
25776     prjtask_completed_date, prjtask_username )
25777   SELECT prjtask_number, prjtask_name, prjtask_descrip,
25778          _prjid, prjtask_anyuser, 'P',
25779          prjtask_hours_budget, 0.0,
25780          prjtask_exp_budget, 0.0,
25781          prjtask_owner_username, NULL,
25782          (prjtask_due_date + COALESCE(_offset, 0)),
25783          CASE WHEN (prjtask_username IS NULL) THEN NULL ELSE CURRENT_DATE END,
25784          NULL, prjtask_username
25785   FROM prjtask
25786   WHERE (prjtask_prj_id=pPrjId);
25787
25788   INSERT INTO docass
25789   ( docass_source_id, docass_source_type,
25790     docass_target_id, docass_target_type,
25791     docass_purpose )
25792   SELECT _prjid, docass_source_type,
25793          docass_target_id, docass_target_type,
25794          docass_purpose
25795   FROM docass
25796   WHERE ((docass_source_id=pPrjId)
25797     AND  (docass_source_type='J'));
25798
25799   RETURN _prjid;
25800
25801 END;
25802 $_$;
25803
25804
25805 ALTER FUNCTION public.copyproject(integer, text, text, date) OWNER TO admin;
25806
25807 --
25808 -- TOC entry 1265 (class 1255 OID 146565814)
25809 -- Dependencies: 4536 8
25810 -- Name: copyquote(integer, date); Type: FUNCTION; Schema: public; Owner: admin
25811 --
25812
25813 CREATE FUNCTION copyquote(integer, date) RETURNS integer
25814     LANGUAGE plpgsql
25815     AS $_$
25816 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25817 -- See www.xtuple.com/CPAL for the full text of the software license.
25818 DECLARE
25819   pQuheadid ALIAS FOR $1;
25820   pSchedDate ALIAS FOR $2;
25821   _quheadid INTEGER;
25822   _qunumber TEXT;
25823
25824 BEGIN
25825
25826   SELECT NEXTVAL('quhead_quhead_id_seq') INTO _quheadid;
25827   IF (fetchMetricText('QUNumberGeneration') = 'S') THEN
25828     SELECT fetchSoNumber() INTO _qunumber;
25829   ELSE
25830     SELECT fetchQuNumber() INTO _qunumber;
25831   END IF;
25832
25833   INSERT INTO quhead
25834   ( quhead_id, quhead_number, quhead_cust_id, quhead_prj_id,
25835     quhead_quotedate, quhead_packdate, quhead_fob,
25836     quhead_warehous_id, quhead_terms_id, quhead_salesrep_id,
25837     quhead_custponumber, quhead_shipvia,
25838     quhead_shipto_id, quhead_shiptoname, quhead_shiptoaddress1, quhead_shiptoaddress2, quhead_shiptoaddress3,
25839     quhead_shiptocity, quhead_shiptostate, quhead_shiptozipcode, quhead_shiptophone, quhead_shiptocountry,
25840     quhead_billtoname, quhead_billtoaddress1, quhead_billtoaddress2, quhead_billtoaddress3,
25841     quhead_billtocity, quhead_billtostate, quhead_billtozip,
25842     quhead_misc_accnt_id, quhead_misc_descrip, quhead_misc, quhead_freight, quhead_commission,
25843     quhead_ordercomments, quhead_shipcomments,
25844     quhead_imported, quhead_curr_id, quhead_taxzone_id, quhead_taxtype_id, quhead_ophead_id, quhead_status,
25845     quhead_shipto_cntct_id, quhead_shipto_cntct_honorific, quhead_shipto_cntct_first_name, quhead_shipto_cntct_middle,
25846     quhead_shipto_cntct_last_name, quhead_shipto_cntct_suffix, quhead_shipto_cntct_phone, quhead_shipto_cntct_title,
25847     quhead_shipto_cntct_fax, quhead_shipto_cntct_email, quhead_billto_cntct_id, quhead_billto_cntct_honorific,
25848     quhead_billto_cntct_first_name, quhead_billto_cntct_middle, quhead_billto_cntct_last_name, quhead_billto_cntct_suffix,
25849     quhead_billto_cntct_phone, quhead_billto_cntct_title, quhead_billto_cntct_fax, quhead_billto_cntct_email )
25850   SELECT _quheadid, _qunumber, quhead_cust_id, quhead_prj_id,
25851          CURRENT_DATE, COALESCE(pSchedDate, quhead_packdate), quhead_fob,
25852          quhead_warehous_id, quhead_terms_id, quhead_salesrep_id,
25853          quhead_custponumber, quhead_shipvia,
25854          quhead_shipto_id, quhead_shiptoname, quhead_shiptoaddress1, quhead_shiptoaddress2, quhead_shiptoaddress3,
25855          quhead_shiptocity, quhead_shiptostate, quhead_shiptozipcode, quhead_shiptophone, quhead_shiptocountry,
25856          quhead_billtoname, quhead_billtoaddress1, quhead_billtoaddress2, quhead_billtoaddress3,
25857          quhead_billtocity, quhead_billtostate, quhead_billtozip,
25858          quhead_misc_accnt_id, quhead_misc_descrip, quhead_misc, quhead_freight, quhead_commission,
25859          quhead_ordercomments, quhead_shipcomments,
25860          FALSE, quhead_curr_id, quhead_taxzone_id, quhead_taxtype_id, quhead_ophead_id, 'O',
25861          quhead_shipto_cntct_id, quhead_shipto_cntct_honorific, quhead_shipto_cntct_first_name, quhead_shipto_cntct_middle,
25862          quhead_shipto_cntct_last_name, quhead_shipto_cntct_suffix, quhead_shipto_cntct_phone, quhead_shipto_cntct_title,
25863          quhead_shipto_cntct_fax, quhead_shipto_cntct_email, quhead_billto_cntct_id, quhead_billto_cntct_honorific,
25864          quhead_billto_cntct_first_name, quhead_billto_cntct_middle, quhead_billto_cntct_last_name, quhead_billto_cntct_suffix,
25865          quhead_billto_cntct_phone, quhead_billto_cntct_title, quhead_billto_cntct_fax, quhead_billto_cntct_email
25866   FROM quhead
25867   WHERE (quhead_id=pQuheadid);
25868
25869   INSERT INTO quitem
25870   ( quitem_quhead_id, quitem_linenumber, quitem_itemsite_id,
25871     quitem_scheddate, quitem_promdate, quitem_qtyord,
25872     quitem_price, quitem_custprice, quitem_unitcost,
25873     quitem_qty_uom_id, quitem_price_uom_id,
25874     quitem_qty_invuomratio, quitem_price_invuomratio,
25875     quitem_memo, quitem_custpn, quitem_imported, quitem_taxtype_id,
25876     quitem_createorder, quitem_order_warehous_id, quitem_item_id, quitem_prcost,
25877     quitem_dropship, quitem_itemsrc_id, quitem_pricemode )
25878   SELECT _quheadid, quitem_linenumber, quitem_itemsite_id,
25879          COALESCE(pSchedDate, quitem_scheddate),
25880          quitem_promdate,
25881          quitem_qtyord,
25882          quitem_price, quitem_custprice, stdCost(itemsite_item_id),
25883          quitem_qty_uom_id, quitem_price_uom_id,
25884          quitem_qty_invuomratio, quitem_price_invuomratio,
25885          quitem_memo, quitem_custpn, FALSE, quitem_taxtype_id,
25886          quitem_createorder, quitem_order_warehous_id, quitem_item_id, quitem_prcost,
25887          quitem_dropship, quitem_itemsrc_id, quitem_pricemode
25888   FROM quitem, itemsite
25889   WHERE ( (quitem_itemsite_id=itemsite_id)
25890    AND (quitem_quhead_id=pQuheadid));
25891
25892   INSERT INTO charass
25893         (charass_target_type, charass_target_id,
25894          charass_char_id, charass_value)
25895   SELECT charass_target_type, b.quitem_id,
25896          charass_char_id, charass_value
25897     FROM quitem a, charass, quitem b
25898    WHERE ((charass_target_type='SI')
25899      AND  (charass_target_id=a.quitem_id)
25900      AND  (a.quitem_quhead_id=pQuheadid)
25901      AND  (b.quitem_quhead_id=_quheadid)
25902      AND  (a.quitem_linenumber=b.quitem_linenumber)
25903      );
25904
25905   RETURN _quheadid;
25906
25907 END;
25908 $_$;
25909
25910
25911 ALTER FUNCTION public.copyquote(integer, date) OWNER TO admin;
25912
25913 --
25914 -- TOC entry 1266 (class 1255 OID 146565815)
25915 -- Dependencies: 4536 8
25916 -- Name: copyso(integer, date); Type: FUNCTION; Schema: public; Owner: admin
25917 --
25918
25919 CREATE FUNCTION copyso(psoheadid integer, pscheddate date) RETURNS integer
25920     LANGUAGE plpgsql
25921     AS $$
25922 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
25923 -- See www.xtuple.com/CPAL for the full text of the software license.
25924 DECLARE
25925   _soheadid INTEGER;
25926   _soitemid INTEGER;
25927   _soitem RECORD;
25928
25929 BEGIN
25930
25931   SELECT NEXTVAL('cohead_cohead_id_seq') INTO _soheadid;
25932
25933   INSERT INTO cohead
25934   ( cohead_id,
25935     cohead_number,
25936     cohead_cust_id,
25937     cohead_custponumber,
25938     cohead_type,
25939     cohead_orderdate,
25940     cohead_warehous_id,
25941     cohead_shipto_id,
25942     cohead_shiptoname,
25943     cohead_shiptoaddress1,
25944     cohead_shiptoaddress2,
25945     cohead_shiptoaddress3,
25946     cohead_shiptoaddress4,
25947     cohead_shiptoaddress5,
25948     cohead_salesrep_id,
25949     cohead_terms_id,
25950     cohead_fob,
25951     cohead_shipvia,
25952     cohead_shiptocity,
25953     cohead_shiptostate,
25954     cohead_shiptozipcode,
25955     cohead_freight,
25956     cohead_misc,
25957     cohead_imported,
25958     cohead_ordercomments,
25959     cohead_shipcomments,
25960     cohead_shiptophone,
25961     cohead_shipchrg_id,
25962     cohead_shipform_id,
25963     cohead_billtoname,
25964     cohead_billtoaddress1,
25965     cohead_billtoaddress2,
25966     cohead_billtoaddress3,
25967     cohead_billtocity,
25968     cohead_billtostate,
25969     cohead_billtozipcode,
25970     cohead_misc_accnt_id,
25971     cohead_misc_descrip,
25972     cohead_commission,
25973     cohead_miscdate,
25974     cohead_holdtype,
25975     cohead_packdate,
25976     cohead_prj_id,
25977     cohead_wasquote,
25978     cohead_lastupdated,
25979     cohead_shipcomplete,
25980     cohead_created,
25981     cohead_creator,
25982     cohead_quote_number,
25983     cohead_billtocountry,
25984     cohead_shiptocountry,
25985     cohead_curr_id,
25986     cohead_calcfreight,
25987     cohead_shipto_cntct_id,
25988     cohead_shipto_cntct_honorific,
25989     cohead_shipto_cntct_first_name,
25990     cohead_shipto_cntct_middle,
25991     cohead_shipto_cntct_last_name,
25992     cohead_shipto_cntct_suffix,
25993     cohead_shipto_cntct_phone,
25994     cohead_shipto_cntct_title,
25995     cohead_shipto_cntct_fax,
25996     cohead_shipto_cntct_email,
25997     cohead_billto_cntct_id,
25998     cohead_billto_cntct_honorific,
25999     cohead_billto_cntct_first_name,
26000     cohead_billto_cntct_middle,
26001     cohead_billto_cntct_last_name,
26002     cohead_billto_cntct_suffix,
26003     cohead_billto_cntct_phone,
26004     cohead_billto_cntct_title,
26005     cohead_billto_cntct_fax,
26006     cohead_billto_cntct_email,
26007     cohead_taxzone_id,
26008     cohead_taxtype_id,
26009     cohead_ophead_id,
26010     cohead_status,
26011     cohead_saletype_id,
26012     cohead_shipzone_id )
26013   SELECT
26014     _soheadid,
26015     fetchSoNumber(),
26016     cohead_cust_id,
26017     cohead_custponumber,
26018     cohead_type,
26019     CURRENT_DATE,
26020     cohead_warehous_id,
26021     cohead_shipto_id,
26022     cohead_shiptoname,
26023     cohead_shiptoaddress1,
26024     cohead_shiptoaddress2,
26025     cohead_shiptoaddress3,
26026     cohead_shiptoaddress4,
26027     cohead_shiptoaddress5,
26028     cohead_salesrep_id,
26029     cohead_terms_id,
26030     cohead_fob,
26031     cohead_shipvia,
26032     cohead_shiptocity,
26033     cohead_shiptostate,
26034     cohead_shiptozipcode,
26035     cohead_freight,
26036     cohead_misc,
26037     FALSE,
26038     cohead_ordercomments,
26039     cohead_shipcomments,
26040     cohead_shiptophone,
26041     cohead_shipchrg_id,
26042     cohead_shipform_id,
26043     cohead_billtoname,
26044     cohead_billtoaddress1,
26045     cohead_billtoaddress2,
26046     cohead_billtoaddress3,
26047     cohead_billtocity,
26048     cohead_billtostate,
26049     cohead_billtozipcode,
26050     cohead_misc_accnt_id,
26051     cohead_misc_descrip,
26052     cohead_commission,
26053     cohead_miscdate,
26054     cohead_holdtype,
26055     COALESCE(pSchedDate, cohead_packdate),
26056     cohead_prj_id,
26057     FALSE,
26058     cohead_lastupdated,
26059     cohead_shipcomplete,
26060     NULL,
26061     getEffectiveXtUser(),
26062     NULL,
26063     cohead_billtocountry,
26064     cohead_shiptocountry,
26065     cohead_curr_id,
26066     cohead_calcfreight,
26067     cohead_shipto_cntct_id,
26068     cohead_shipto_cntct_honorific,
26069     cohead_shipto_cntct_first_name,
26070     cohead_shipto_cntct_middle,
26071     cohead_shipto_cntct_last_name,
26072     cohead_shipto_cntct_suffix,
26073     cohead_shipto_cntct_phone,
26074     cohead_shipto_cntct_title,
26075     cohead_shipto_cntct_fax,
26076     cohead_shipto_cntct_email,
26077     cohead_billto_cntct_id,
26078     cohead_billto_cntct_honorific,
26079     cohead_billto_cntct_first_name,
26080     cohead_billto_cntct_middle,
26081     cohead_billto_cntct_last_name,
26082     cohead_billto_cntct_suffix,
26083     cohead_billto_cntct_phone,
26084     cohead_billto_cntct_title,
26085     cohead_billto_cntct_fax,
26086     cohead_billto_cntct_email,
26087     cohead_taxzone_id,
26088     cohead_taxtype_id,
26089     cohead_ophead_id,
26090     cohead_status,
26091     cohead_saletype_id,
26092     cohead_shipzone_id
26093   FROM cohead
26094   WHERE (cohead_id=pSoheadid);
26095
26096   FOR _soitem IN
26097     SELECT *
26098     FROM coitem JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
26099     WHERE ( (coitem_cohead_id=pSoheadid)
26100       AND   (coitem_status <> 'X')
26101       AND   (coitem_subnumber = 0) ) LOOP
26102
26103     SELECT NEXTVAL('coitem_coitem_id_seq') INTO _soitemid;
26104
26105     -- insert characteristics first so they can be copied to associated supply order
26106     INSERT INTO charass
26107           (charass_target_type, charass_target_id,
26108            charass_char_id, charass_value)
26109     SELECT charass_target_type, _soitemid,
26110            charass_char_id, charass_value
26111       FROM charass
26112      WHERE ((charass_target_type='SI')
26113        AND  (charass_target_id=_soitem.coitem_id));
26114
26115     INSERT INTO coitem
26116     ( coitem_id,
26117       coitem_cohead_id,
26118       coitem_linenumber,
26119       coitem_itemsite_id,
26120       coitem_status,
26121       coitem_scheddate,
26122       coitem_promdate,
26123       coitem_qtyord,
26124       coitem_unitcost,
26125       coitem_price,
26126       coitem_custprice,
26127       coitem_qtyshipped,
26128       coitem_order_id,
26129       coitem_memo,
26130       coitem_imported,
26131       coitem_qtyreturned,
26132       coitem_closedate,
26133       coitem_custpn,
26134       coitem_order_type,
26135       coitem_close_username,
26136 --      coitem_lastupdated,
26137       coitem_substitute_item_id,
26138       coitem_created,
26139       coitem_creator,
26140       coitem_prcost,
26141       coitem_qty_uom_id,
26142       coitem_qty_invuomratio,
26143       coitem_price_uom_id,
26144       coitem_price_invuomratio,
26145       coitem_warranty,
26146       coitem_cos_accnt_id,
26147       coitem_qtyreserved,
26148       coitem_subnumber,
26149       coitem_firm,
26150       coitem_taxtype_id )
26151     VALUES
26152     ( _soitemid,
26153       _soheadid,
26154       _soitem.coitem_linenumber,
26155       _soitem.coitem_itemsite_id,
26156       'O',
26157       COALESCE(pSchedDate, _soitem.coitem_scheddate),
26158       _soitem.coitem_promdate,
26159       _soitem.coitem_qtyord,
26160       stdCost(_soitem.itemsite_item_id),
26161       _soitem.coitem_price,
26162       _soitem.coitem_custprice,
26163       0.0,
26164       -1,
26165       _soitem.coitem_memo,
26166       FALSE,
26167       0.0,
26168       NULL,
26169       _soitem.coitem_custpn,
26170       _soitem.coitem_order_type,
26171       NULL,
26172 --      NULL,
26173       _soitem.coitem_substitute_item_id,
26174       NULL,
26175       getEffectiveXtUser(),
26176       _soitem.coitem_prcost,
26177       _soitem.coitem_qty_uom_id,
26178       _soitem.coitem_qty_invuomratio,
26179       _soitem.coitem_price_uom_id,
26180       _soitem.coitem_price_invuomratio,
26181       _soitem.coitem_warranty,
26182       _soitem.coitem_cos_accnt_id,
26183       0.0,
26184       _soitem.coitem_subnumber,
26185       _soitem.coitem_firm,
26186       _soitem.coitem_taxtype_id );
26187
26188   END LOOP;
26189
26190   RETURN _soheadid;
26191
26192 END;
26193 $$;
26194
26195
26196 ALTER FUNCTION public.copyso(psoheadid integer, pscheddate date) OWNER TO admin;
26197
26198 --
26199 -- TOC entry 1268 (class 1255 OID 146565816)
26200 -- Dependencies: 4536 8
26201 -- Name: copytodoitem(integer, date, integer); Type: FUNCTION; Schema: public; Owner: admin
26202 --
26203
26204 CREATE FUNCTION copytodoitem(integer, date, integer) RETURNS integer
26205     LANGUAGE plpgsql
26206     AS $_$
26207 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26208 -- See www.xtuple.com/CPAL for the full text of the software license.
26209 DECLARE
26210   pparentid   ALIAS FOR $1;
26211   _duedate    DATE := COALESCE($2, CURRENT_DATE);
26212   pincdtid    ALIAS FOR $3;
26213   _alarmid    INTEGER;
26214   _todoitemid INTEGER;
26215
26216 BEGIN
26217   INSERT INTO todoitem(
26218             todoitem_name,      todoitem_description,
26219             todoitem_incdt_id,
26220             todoitem_creator_username,                  todoitem_status,
26221             todoitem_active,    todoitem_due_date,
26222             todoitem_assigned_date,
26223             todoitem_seq,       todoitem_notes,         todoitem_crmacct_id,
26224             todoitem_ophead_id, todoitem_owner_username,todoitem_priority_id,
26225             todoitem_username,  todoitem_recurring_todoitem_id
26226   ) SELECT  todoitem_name,      todoitem_description,
26227             CASE WHEN pincdtid IS NULL THEN todoitem_incdt_id ELSE pincdtid END,
26228             getEffectiveXtUser(),                               'N',
26229             TRUE,               _duedate,
26230             CASE WHEN (todoitem_username IS NOT NULL) THEN CURRENT_DATE
26231                  ELSE NULL
26232             END,
26233             todoitem_seq,       todoitem_notes,         todoitem_crmacct_id,
26234             todoitem_ophead_id, todoitem_owner_username,todoitem_priority_id,
26235             todoitem_username,  todoitem_recurring_todoitem_id
26236       FROM todoitem
26237      WHERE (todoitem_id=pparentid)
26238   RETURNING todoitem_id INTO _todoitemid;
26239
26240   IF (_todoitemid IS NULL) THEN
26241     RETURN -10;
26242   END IF;
26243
26244   SELECT saveAlarm(NULL, NULL, _duedate,
26245                    CAST(alarm_time - DATE_TRUNC('day',alarm_time) AS TIME),
26246                    alarm_time_offset,
26247                    alarm_time_qualifier,
26248                    (alarm_event_recipient IS NOT NULL), alarm_event_recipient,
26249                    (alarm_email_recipient IS NOT NULL AND fetchMetricBool('EnableBatchManager')), alarm_email_recipient,
26250                    (alarm_sysmsg_recipient IS NOT NULL), alarm_sysmsg_recipient,
26251                    'TODO', _todoitemid, 'CHANGEONE')
26252     INTO _alarmid
26253     FROM alarm
26254    WHERE ((alarm_source='TODO')
26255       AND (alarm_source_id=pparentid));
26256
26257    IF (_alarmid < 0) THEN
26258      RETURN _alarmid;
26259    END IF;
26260
26261   RETURN _todoitemid;
26262 END;
26263 $_$;
26264
26265
26266 ALTER FUNCTION public.copytodoitem(integer, date, integer) OWNER TO admin;
26267
26268 --
26269 -- TOC entry 1269 (class 1255 OID 146565817)
26270 -- Dependencies: 4536 8
26271 -- Name: copyvoucher(integer, date); Type: FUNCTION; Schema: public; Owner: admin
26272 --
26273
26274 CREATE FUNCTION copyvoucher(integer, date) RETURNS integer
26275     LANGUAGE plpgsql
26276     AS $_$
26277 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26278 -- See www.xtuple.com/CPAL for the full text of the software license.
26279 DECLARE
26280   pVoheadid ALIAS FOR $1;
26281   _voheadid INTEGER;
26282   _vonumber TEXT;
26283   _vodate DATE := COALESCE($2, CURRENT_DATE);
26284   _i RECORD;
26285   _l RECORD;
26286   _vodistid INTEGER;
26287
26288 BEGIN
26289   SELECT *
26290     INTO _i
26291     FROM vohead
26292    WHERE(vohead_id=pVoheadid);
26293   IF(NOT FOUND) THEN
26294     RETURN -1;
26295   END IF;
26296
26297   _vonumber := fetchVoNumber();
26298   _voheadid := nextval('vohead_vohead_id_seq');
26299
26300   INSERT INTO vohead
26301         (vohead_id,
26302          vohead_number, vohead_pohead_id,
26303          vohead_posted, vohead_duedate,
26304          vohead_invcnumber, vohead_amount,
26305          vohead_docdate, vohead_1099,
26306          vohead_distdate, vohead_reference,
26307          vohead_terms_id, vohead_vend_id,
26308          vohead_curr_id, vohead_adjtaxtype_id,
26309          vohead_freighttaxtype_id, vohead_gldistdate,
26310          vohead_misc, vohead_taxzone_id,
26311          vohead_taxtype_id, vohead_notes,
26312          vohead_recurring_vohead_id )
26313   VALUES(_voheadid,
26314          _vonumber, _i.vohead_pohead_id,
26315          false, determineDueDate(_i.vohead_terms_id, _vodate),
26316          _i.vohead_invcnumber, _i.vohead_amount,
26317          _vodate, _i.vohead_1099,
26318          _vodate, _i.vohead_reference,
26319          _i.vohead_terms_id, _i.vohead_vend_id,
26320          _i.vohead_curr_id, _i.vohead_adjtaxtype_id,
26321          _i.vohead_freighttaxtype_id, _vodate,
26322          _i.vohead_misc, _i.vohead_taxzone_id,
26323          _i.vohead_taxtype_id, _i.vohead_notes,
26324          _i.vohead_recurring_vohead_id);
26325
26326   FOR _l IN SELECT *
26327             FROM vodist
26328             WHERE (vodist_vohead_id=pVoheadid) LOOP
26329     SELECT NEXTVAL('vodist_vodist_id_seq') INTO _vodistid;
26330
26331     INSERT INTO vodist
26332         (vodist_id, vodist_poitem_id,
26333          vodist_vohead_id, vodist_costelem_id,
26334          vodist_accnt_id, vodist_amount,
26335          vodist_qty, vodist_expcat_id,
26336          vodist_tax_id, vodist_discountable,
26337          vodist_notes)
26338     VALUES
26339         (_vodistid, _l.vodist_poitem_id,
26340          _voheadid, _l.vodist_costelem_id,
26341          _l.vodist_accnt_id, _l.vodist_amount,
26342          _l.vodist_qty, _l.vodist_expcat_id,
26343          _l.vodist_tax_id, _l.vodist_discountable,
26344          _l.vodist_notes);
26345
26346   END LOOP;
26347
26348   RETURN _voheadid;
26349 END;
26350 $_$;
26351
26352
26353 ALTER FUNCTION public.copyvoucher(integer, date) OWNER TO admin;
26354
26355 --
26356 -- TOC entry 1270 (class 1255 OID 146565818)
26357 -- Dependencies: 4536 8
26358 -- Name: correctporeceipt(integer, numeric, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
26359 --
26360
26361 CREATE FUNCTION correctporeceipt(integer, numeric, numeric, integer) RETURNS integer
26362     LANGUAGE plpgsql
26363     AS $_$
26364 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26365 -- See www.xtuple.com/CPAL for the full text of the software license.
26366 DECLARE
26367   pPorecvid ALIAS FOR $1;
26368   pQty ALIAS FOR $2;
26369   pFreight ALIAS FOR $3;
26370   pItemlocSeries ALIAS FOR $4;
26371
26372 BEGIN
26373   RETURN correctReceipt('PO', $1, $2, $3, $4, NULL, NULL);
26374 END;
26375 $_$;
26376
26377
26378 ALTER FUNCTION public.correctporeceipt(integer, numeric, numeric, integer) OWNER TO admin;
26379
26380 --
26381 -- TOC entry 1271 (class 1255 OID 146565819)
26382 -- Dependencies: 4536 8
26383 -- Name: correctporeceipt(integer, numeric, numeric, integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
26384 --
26385
26386 CREATE FUNCTION correctporeceipt(integer, numeric, numeric, integer, integer, date) RETURNS integer
26387     LANGUAGE plpgsql
26388     AS $_$
26389 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26390 -- See www.xtuple.com/CPAL for the full text of the software license.
26391 BEGIN
26392   RETURN correctReceipt('PO', $1, $2, $3, $4, $5, $6);
26393 END;
26394 $_$;
26395
26396
26397 ALTER FUNCTION public.correctporeceipt(integer, numeric, numeric, integer, integer, date) OWNER TO admin;
26398
26399 --
26400 -- TOC entry 1272 (class 1255 OID 146565820)
26401 -- Dependencies: 4536 8
26402 -- Name: correctproduction(integer, numeric, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
26403 --
26404
26405 CREATE FUNCTION correctproduction(integer, numeric, boolean, boolean) RETURNS integer
26406     LANGUAGE plpgsql
26407     AS $_$
26408 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26409 -- See www.xtuple.com/CPAL for the full text of the software license.
26410 BEGIN
26411   RAISE NOTICE 'correctProduction(INTEGER, NUMERIC, BOOLEAN, BOOLEAN) has been deprecated. Use corrrectProduction(INTEGER, NUMERIC, BOOLEAN, INTEGER) or a package-specific version instead.';
26412   RETURN  correctProduction($1, $2, $3, 0, now());
26413 END;
26414 $_$;
26415
26416
26417 ALTER FUNCTION public.correctproduction(integer, numeric, boolean, boolean) OWNER TO admin;
26418
26419 --
26420 -- TOC entry 1273 (class 1255 OID 146565821)
26421 -- Dependencies: 4536 8
26422 -- Name: correctproduction(integer, numeric, boolean, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
26423 --
26424
26425 CREATE FUNCTION correctproduction(integer, numeric, boolean, boolean, integer) RETURNS integer
26426     LANGUAGE plpgsql
26427     AS $_$
26428 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26429 -- See www.xtuple.com/CPAL for the full text of the software license.
26430 BEGIN
26431   RAISE NOTICE 'correctProduction(INTEGER, NUMERIC, BOOLEAN, BOOLEAN, INTEGER) has been deprecated. Use corrrectProduction(INTEGER, NUMERIC, BOOLEAN, INTEGER) or a package-specific version instead.';
26432   RETURN correctProduction($1, $2, $3, $5, now());
26433 END;
26434 $_$;
26435
26436
26437 ALTER FUNCTION public.correctproduction(integer, numeric, boolean, boolean, integer) OWNER TO admin;
26438
26439 --
26440 -- TOC entry 1274 (class 1255 OID 146565822)
26441 -- Dependencies: 4536 8
26442 -- Name: correctproduction(integer, numeric, boolean, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
26443 --
26444
26445 CREATE FUNCTION correctproduction(integer, numeric, boolean, integer, timestamp with time zone) RETURNS integer
26446     LANGUAGE plpgsql
26447     AS $_$
26448 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26449 -- See www.xtuple.com/CPAL for the full text of the software license.
26450 DECLARE
26451   pWoid          ALIAS FOR $1;
26452   pQty           ALIAS FOR $2;
26453   pBackflush     ALIAS FOR $3;
26454   pItemlocSeries ALIAS FOR $4;
26455   pGlDistTS      ALIAS FOR $5;
26456 BEGIN
26457   RETURN correctProduction($1, $2, $3, $4, $5, NULL);
26458 END;
26459 $_$;
26460
26461
26462 ALTER FUNCTION public.correctproduction(integer, numeric, boolean, integer, timestamp with time zone) OWNER TO admin;
26463
26464 --
26465 -- TOC entry 1275 (class 1255 OID 146565823)
26466 -- Dependencies: 4536 8
26467 -- Name: correctproduction(integer, numeric, boolean, integer, timestamp with time zone, integer); Type: FUNCTION; Schema: public; Owner: admin
26468 --
26469
26470 CREATE FUNCTION correctproduction(integer, numeric, boolean, integer, timestamp with time zone, integer) RETURNS integer
26471     LANGUAGE plpgsql
26472     AS $_$
26473 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26474 -- See www.xtuple.com/CPAL for the full text of the software license.
26475 DECLARE
26476   pWoid          ALIAS FOR $1;
26477   pQty           ALIAS FOR $2;
26478   pBackflush     ALIAS FOR $3;
26479   pItemlocSeries ALIAS FOR $4;
26480   pGlDistTS      ALIAS FOR $5;
26481   pInvhistId     ALIAS FOR $6;
26482   _invhistid        INTEGER;
26483   _itemlocSeries    INTEGER;
26484   _r                RECORD;
26485   _parentWIPAccntid INTEGER;
26486   _parentQty        NUMERIC;
26487   _qty              NUMERIC;
26488   _wipPost          NUMERIC;
26489   _sense            TEXT;
26490   _status           TEXT;
26491   _type             TEXT;
26492   _qtyfxd           NUMERIC := 0;
26493
26494 BEGIN
26495
26496   -- Qty is positive for Assembly W/O
26497   -- Qty is negative for Disassembly W/O
26498   IF (pQty = 0) THEN
26499     RETURN pItemlocseries;
26500   ELSIF (pQty > 0) THEN
26501     _sense := 'from';
26502   ELSE
26503     _sense := 'to';
26504   END IF;
26505
26506   SELECT item_type, roundQty(item_fractional, pQty), wo_status
26507     INTO _type, _parentQty, _status
26508     FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
26509             JOIN item ON (item_id=itemsite_item_id)
26510    WHERE (wo_id=pWoid);
26511   
26512   IF (_status != 'I') THEN
26513     RETURN -1;
26514   END IF;
26515
26516   IF (_type = 'J') THEN
26517     RETURN -2;
26518   END IF;
26519
26520   IF (pItemlocSeries = 0) THEN
26521     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
26522   ELSE
26523     _itemlocSeries := pItemlocSeries;
26524   END IF;
26525
26526   --  Calculate the WIP to correct 
26527   SELECT CASE WHEN (wo_cosmethod = 'D') THEN wo_postedvalue
26528               ELSE  round(((wo_postedvalue - wo_wipvalue) / wo_qtyrcv * _parentQty), 2)
26529          END INTO _wipPost
26530   FROM wo
26531   WHERE (wo_id=pWoid);
26532
26533   --  Post the inventory transaction
26534   SELECT postInvTrans( itemsite_id, 'RM', (_parentQty * -1.0),
26535                        'W/O', 'WO', formatwonumber(pWoid), '',
26536                        ('Correct Receive Inventory ' || item_number || ' ' || _sense || ' Manufacturing'),
26537                        costcat_asset_accnt_id, getPrjAccntId(wo_prj_id, costcat_wip_accnt_id), _itemlocSeries, pGlDistTS,
26538                        (_wipPost * -1.0), -- only used when cost is average
26539                        pInvhistId) INTO _invhistid
26540   FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
26541           JOIN item ON (item_id=itemsite_item_id)
26542           JOIN costcat ON (costcat_id=itemsite_costcat_id)
26543   WHERE (wo_id=pWoid);
26544
26545   --  Decrease this W/O's qty. received and increase its WIP value
26546   UPDATE wo
26547   SET wo_qtyrcv = (wo_qtyrcv - _parentQty),
26548       wo_wipvalue = (wo_wipvalue + (CASE WHEN(itemsite_costmethod IN ('A','J'))
26549                                               THEN _wipPost
26550                                          WHEN(itemsite_costmethod='S')
26551                                               THEN stdcost(itemsite_item_id) * _parentQty
26552                                          ELSE 0.0 END))
26553   FROM itemsite
26554   WHERE ( (wo_itemsite_id=itemsite_id)
26555    AND (wo_id=pWoid) );
26556
26557   IF (pBackflush) THEN
26558     FOR _r IN SELECT item_id, item_fractional,
26559                       itemsite_id, itemsite_warehous_id,
26560                       itemsite_controlmethod, itemsite_loccntrl,
26561                       itemsite_costmethod, 
26562                       wo_qtyrcv, wo_prj_id,
26563                       womatl_id, womatl_qtyfxd, womatl_qtyper,
26564                       womatl_scrap, womatl_issuemethod, womatl_uom_id
26565                FROM wo JOIN womatl ON (womatl_wo_id=wo_id AND womatl_issuemethod='L')
26566                        JOIN itemsite ON (itemsite_id=womatl_itemsite_id)
26567                        JOIN item ON (item_id=itemsite_item_id)
26568                WHERE (wo_id=pWoid) LOOP
26569
26570       --  Cache the qty to be issued
26571       -- If going back to beginning, unissue fixed qty as well
26572       IF (_r.wo_qtyrcv - _parentQty > 0) THEN
26573         _qtyfxd := 0;
26574       ELSE
26575         _qtyfxd := _r.womatl_qtyfxd;
26576       END IF;
26577       
26578       _qty = roundQty(_r.item_fractional, (_qtyfxd + _parentQty * _r.womatl_qtyper) * (1 + _r.womatl_scrap));
26579
26580       IF (_qty > 0) THEN
26581         SELECT returnWoMaterial(_r.womatl_id, _qty, _itemlocSeries, pGlDistTS) INTO _itemlocSeries;
26582       END IF;
26583
26584     END LOOP;
26585
26586         --  BEGIN ROB Decrease this W/O's WIP value for custom costing
26587           UPDATE wo
26588           SET wo_wipvalue = (wo_wipvalue - (itemcost_stdcost * _parentQty)) 
26589         FROM costelem, itemcost, costcat, itemsite, item
26590         WHERE 
26591           ((wo_id=pWoid) AND
26592           (wo_itemsite_id=itemsite_id) AND
26593           (itemsite_item_id=item_id) AND
26594           (costelem_id = itemcost_costelem_id) AND
26595           (itemcost_item_id = itemsite_item_id) AND
26596           (itemsite_costcat_id = costcat_id) AND
26597           (costelem_exp_accnt_id) IS NOT NULL  AND 
26598           (costelem_sys = false));
26599
26600         --  ROB Distribute to G/L - create Cost Variance, debit WIP
26601           PERFORM insertGLTransaction( 'W/O', 'WO', formatwonumber(pWoid),
26602                                        ('Correct Post Other Cost ' || item_number || ' ' || _sense || ' Manufacturing'),
26603                                        getPrjAccntId(wo_prj_id, costelem_exp_accnt_id), 
26604                                        getPrjAccntId(wo_prj_id, costcat_wip_accnt_id), _invhistid,
26605                                        ((itemcost_stdcost * _parentQty)* -1),
26606                                        CURRENT_DATE )
26607         FROM wo, costelem, itemcost, costcat, itemsite, item
26608         WHERE 
26609           ((wo_id=pWoid) AND
26610           (wo_itemsite_id=itemsite_id) AND
26611           (itemsite_item_id=item_id) AND
26612           (costelem_id = itemcost_costelem_id) AND
26613           (itemcost_item_id = itemsite_item_id) AND
26614           (itemsite_costcat_id = costcat_id) AND
26615           (costelem_exp_accnt_id) IS NOT NULL  AND 
26616           (costelem_sys = false));
26617         --End ROB
26618
26619   END IF;
26620
26621   RETURN _itemlocSeries;
26622
26623 END;
26624 $_$;
26625
26626
26627 ALTER FUNCTION public.correctproduction(integer, numeric, boolean, integer, timestamp with time zone, integer) OWNER TO admin;
26628
26629 --
26630 -- TOC entry 1276 (class 1255 OID 146565825)
26631 -- Dependencies: 4536 8
26632 -- Name: correctreceipt(integer, numeric, numeric, integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
26633 --
26634
26635 CREATE FUNCTION correctreceipt(integer, numeric, numeric, integer, integer, date) RETURNS integer
26636     LANGUAGE plpgsql
26637     AS $_$
26638 BEGIN
26639   RETURN correctReceipt($1, $2, $3, $4, $5, $6, NULL);
26640 END;
26641 $_$;
26642
26643
26644 ALTER FUNCTION public.correctreceipt(integer, numeric, numeric, integer, integer, date) OWNER TO admin;
26645
26646 --
26647 -- TOC entry 1277 (class 1255 OID 146565826)
26648 -- Dependencies: 4536 8
26649 -- Name: correctreceipt(integer, numeric, numeric, integer, integer, date, numeric); Type: FUNCTION; Schema: public; Owner: admin
26650 --
26651
26652 CREATE FUNCTION correctreceipt(integer, numeric, numeric, integer, integer, date, numeric) RETURNS integer
26653     LANGUAGE plpgsql
26654     AS $_$
26655 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26656 -- See www.xtuple.com/CPAL for the full text of the software license.
26657 DECLARE
26658   precvid               ALIAS FOR $1;
26659   pQty                  ALIAS FOR $2;
26660   pFreight              ALIAS FOR $3;
26661   _itemlocSeries        INTEGER := COALESCE($4, 0);
26662   _currid               INTEGER := $5;
26663   pEffective            ALIAS FOR $6;
26664   pRecvCost             ALIAS FOR $7;
26665   _freight              NUMERIC;
26666   _qty                  NUMERIC;
26667   _invhistid            INTEGER;
26668   _o                    RECORD;
26669   _r                    RECORD;
26670   _recvcost             NUMERIC;
26671   _tmp        INTEGER;
26672   _pricevar             NUMERIC := 0.00;
26673   _journalNumber INTEGER := fetchJournalNumber('GL-MISC');
26674
26675 BEGIN
26676   SELECT recv_qty, recv_date::DATE AS recv_date, recv_freight_curr_id,
26677          recv_orderitem_id,
26678          round(currToCurr(recv_freight_curr_id,
26679                           COALESCE(_currid, recv_freight_curr_id),
26680          recv_freight, recv_date::DATE),2) AS recv_freight,
26681          recv_posted, recv_order_type,
26682          COALESCE(itemsite_id, -1) AS itemsiteid,
26683          itemsite_item_id, itemsite_costmethod, itemsite_controlmethod,
26684          (recv_splitfrom_id IS NOT NULL
26685          OR (SELECT (count(*) > 0) 
26686              FROM recv
26687              WHERE (recv_splitfrom_id=recv_id))) AS split INTO _r
26688   FROM recv LEFT OUTER JOIN itemsite ON (recv_itemsite_id=itemsite_id)
26689   WHERE (recv_id=precvid);
26690
26691   IF (NOT FOUND) THEN
26692     RETURN _itemlocSeries;
26693   END IF;
26694
26695   IF (NOT _r.recv_order_type IN ('PO', 'RA', 'TO')) THEN
26696     RETURN -11;
26697   END IF;
26698
26699   IF (_r.split) THEN
26700     RETURN -12;
26701   END IF;
26702
26703   SELECT currToBase(orderitem_unitcost_curr_id, orderitem_unitcost,
26704                     _r.recv_date::DATE) AS unitprice_base,
26705          orderhead_number, orderitem_linenumber,
26706          orderhead_curr_id AS freight_curr_id,
26707          orderitem_orderhead_type,
26708          orderitem_qty_invuomratio INTO _o
26709   FROM orderhead, orderitem
26710   WHERE ((orderhead_id=orderitem_orderhead_id)
26711     AND  (orderhead_type=orderitem_orderhead_type)
26712     AND  (orderitem_id=_r.recv_orderitem_id)
26713     AND  (orderitem_orderhead_type=_r.recv_order_type));
26714
26715   IF (NOT FOUND) THEN
26716     RETURN _itemlocSeries;
26717   END IF;
26718
26719   -- Default to _o.orderitem_unitcost if recv_purchcost is not supplied
26720   -- Note: this should never happen, a value is always supplied
26721   if (pRecvCost IS NULL) THEN
26722     _recvcost := _o.orderitem_unitcost;
26723   ELSE
26724     -- Note: if the receipt has already been posted, pRecvCost will always 
26725     --       equal the original recv_purchcost (cannot be modified in GUI)
26726     _recvcost := pRecvCost; 
26727   END IF;
26728
26729   IF (_r.recv_posted) THEN
26730     _qty := (pQty - _r.recv_qty);
26731     IF (_qty <> 0) THEN
26732       IF (_r.itemsiteid = -1) THEN
26733         PERFORM insertGLTransaction( _journalNumber,'S/R',
26734                                      _r.recv_order_type,
26735                                      _o.orderhead_number,
26736                                      'Receive Non-Inventory from ' || _r.recv_order_type,
26737                                      expcat_liability_accnt_id,
26738                                      getPrjAccntId(poitem_prj_id, expcat_exp_accnt_id),
26739                                      -1,
26740                                      ROUND(_o.unitprice_base * _qty, 2),
26741                                      pEffective )
26742         FROM poitem, expcat
26743         WHERE ((poitem_expcat_id=expcat_id)
26744           AND  (poitem_id=_r.recv_orderitem_id)
26745           AND  (_o.orderitem_orderhead_type='PO'));
26746
26747         UPDATE recv
26748         SET recv_qty=pQty,
26749             recv_value=(recv_value + ROUND(_o.unitprice_base * _qty, 2)),
26750             recv_date = pEffective
26751         WHERE (recv_id=precvid);
26752       ELSEIF (_r.itemsite_controlmethod = 'N') THEN
26753         PERFORM insertGLTransaction( _journalNumber,'S/R',
26754                                      _r.recv_order_type,
26755                                      _o.orderhead_number,
26756                                      'Receive Non-Controlled Inventory from ' || _r.recv_order_type,
26757                                      costcat_liability_accnt_id,
26758                                      getPrjAccntId(poitem_prj_id, costcat_exp_accnt_id),
26759                                      -1,
26760                                      ROUND(_o.unitprice_base * _qty, 2),
26761                                      pEffective )
26762         FROM poitem, itemsite, costcat
26763         WHERE ((poitem_itemsite_id=itemsite_id)
26764           AND  (itemsite_costcat_id=costcat_id)
26765           AND  (poitem_id=_r.recv_orderitem_id)
26766           AND  (_o.orderitem_orderhead_type='PO'));
26767
26768         UPDATE recv
26769         SET recv_qty=pQty,
26770             recv_value=(recv_value + ROUND(_o.unitprice_base * _qty, 2)),
26771             recv_date = pEffective
26772         WHERE (recv_id=precvid);
26773       ELSE
26774         IF (_itemlocSeries = 0 OR _itemlocSeries IS NULL) THEN
26775           _itemlocSeries := NEXTVAL('itemloc_series_seq');
26776         END IF;
26777
26778   SELECT postInvTrans( itemsite_id, 'RP',
26779                              (_qty * _o.orderitem_qty_invuomratio),
26780                              'S/R', _r.recv_order_type,
26781                              _o.orderhead_number::TEXT || '-' || _o.orderitem_linenumber::TEXT, '',
26782                              'Receive Inventory from ' || _r.recv_order_type,
26783                              costcat_asset_accnt_id,
26784                              costcat_liability_accnt_id,
26785                              _itemlocSeries, pEffective,
26786            ROUND(_recvcost * _qty, 2) -- alway passing since it is ignored if not average costed item
26787                            ) INTO _tmp
26788         FROM itemsite, costcat
26789         WHERE ((itemsite_costcat_id=costcat_id)
26790     AND  (itemsite_id=_r.itemsiteid) );
26791
26792         IF(_r.itemsite_costmethod='A') THEN
26793           UPDATE recv
26794              SET recv_qty=pQty,
26795                  recv_value=(recv_value + _recvcost * _qty * _o.orderitem_qty_invuomratio),
26796                  recv_date = pEffective
26797            WHERE(recv_id=precvid);
26798         ELSE
26799           UPDATE recv
26800              SET recv_qty=pQty,
26801                  recv_value=(recv_value + stdcost(_r.itemsite_item_id) * _qty * _o.orderitem_qty_invuomratio),
26802                  recv_date = pEffective
26803            WHERE(recv_id=precvid);
26804         END IF;
26805     END IF;
26806
26807       IF (_r.recv_order_type = 'PO') THEN
26808         UPDATE poitem
26809         SET poitem_qty_received=(poitem_qty_received + _qty)
26810         WHERE (poitem_id=_r.recv_orderitem_id);
26811       ELSIF (_r.recv_order_type = 'RA' AND fetchMetricBool('EnableReturnAuth')) THEN
26812         UPDATE raitem
26813         SET raitem_qtyreceived=(raitem_qtyreceived + _qty)
26814         WHERE (raitem_id=_r.recv_orderitem_id);
26815       ELSIF (_r.recv_order_type = 'TO' AND fetchMetricBool('MultiWhs')) THEN
26816         UPDATE toitem
26817         SET toitem_qty_received=(toitem_qty_received + _qty)
26818         WHERE (toitem_id=_r.recv_orderitem_id);
26819       END IF;
26820
26821     END IF;
26822
26823        IF (fetchMetricBool('RecordPPVonReceipt')) THEN -- If the 'Purchase Price Variance on Receipt' option is true
26824          _invhistid := _tmp;
26825          -- Find the difference in the purchase price value expected from the P/O and the value of the transaction
26826          SELECT (((currToBase(pohead_curr_id,
26827          COALESCE(recv_purchcost, poitem_unitprice),
26828          recv_date::DATE)) * _qty) - (invhist_value_after - invhist_value_before)) INTO _pricevar
26829          FROM invhist, recv, pohead, poitem
26830          WHERE ((recv_orderitem_id=poitem_id)
26831            AND  (poitem_pohead_id=pohead_id)
26832            AND  (recv_id=precvid)
26833            AND  (invhist_id = _invhistid));
26834
26835          -- If difference exists then
26836          IF (_pricevar <> 0.00) THEN
26837            -- Record an additional GL Transaction for the purchase price variance
26838            SELECT insertGLTransaction( _journalNumber,
26839                 'S/R', _r.recv_order_type, _o.orderhead_number,
26840                                        'Purchase price variance adjusted for P/O ' || _o.orderhead_number || ' for item ' || _o.orderitem_linenumber::TEXT,
26841                                        costcat_liability_accnt_id,
26842                                        getPrjAccntId(poitem_prj_id, costcat_purchprice_accnt_id), -1,
26843                                        _pricevar,
26844                                        pEffective, false ) INTO _tmp
26845            FROM itemsite, costcat, poitem, recv
26846            WHERE ((itemsite_costcat_id=costcat_id)
26847               AND (recv_id=precvid)
26848               AND (recv_orderitem_id=poitem_id)
26849               AND (itemsite_id=recv_itemsite_id) );
26850            IF (NOT FOUND) THEN
26851              RAISE EXCEPTION 'Could not insert G/L transaction: no cost category found for itemsite_id %',
26852              _r.itemsite_id;
26853            ELSIF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
26854              RETURN _tmp;
26855            ELSE
26856              -- Posting to trial balance is deferred to prevent locking
26857              INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
26858              VALUES ( _tmp, _itemlocSeries );
26859            END IF;
26860          END IF;
26861        END IF;
26862
26863     _freight := (pFreight - _r.recv_freight);
26864     IF (_freight <> 0) THEN
26865
26866       IF (_r.itemsiteid = -1) THEN
26867   PERFORM insertGLTransaction( _journalNumber,'S/R', _r.recv_order_type,
26868                                      _o.orderhead_number,
26869                                     'Receive Non-Inventory Freight from ' || _r.recv_order_type,
26870              expcat_liability_accnt_id, getPrjAccntId(poitem_prj_id, expcat_freight_accnt_id), -1,
26871                                       ROUND(currToBase(_currid, _freight,
26872                                                     pEffective), 2),
26873                                      pEffective )
26874         FROM poitem, expcat
26875         WHERE ((poitem_expcat_id=expcat_id)
26876           AND  (poitem_id=_r.recv_orderitem_id)
26877           AND  (_r.recv_order_type='PO'));
26878       ELSE
26879   PERFORM insertGLTransaction(_journalNumber,'S/R', _r.recv_order_type,
26880                                     _o.orderhead_number, 
26881                                     'Receive Non-Inventory Freight from ' ||
26882                                                             _r.recv_order_type,
26883                                    costcat_liability_accnt_id,
26884                                    costcat_freight_accnt_id, -1,
26885                                    round(currToBase(_currid, _freight,
26886                                                     pEffective), 2),
26887                                    pEffective )
26888         FROM itemsite, costcat
26889         WHERE ( (itemsite_costcat_id=costcat_id)
26890           AND   (itemsite_id=_r.itemsiteid) );
26891       END IF;
26892
26893       IF (_r.recv_order_type = 'PO') THEN
26894         UPDATE poitem
26895         SET poitem_freight_received=(poitem_freight_received +
26896                                    currToCurr(_currid, _o.freight_curr_id,
26897                                               _freight, pEffective))
26898         WHERE (poitem_id=_r.recv_orderitem_id);
26899
26900       -- raitem does not track freight
26901
26902       ELSEIF (_r.recv_order_type = 'TO' AND fetchMetricBool('MultiWhs')) THEN
26903         UPDATE toitem
26904         SET toitem_freight_received=(toitem_freight_received +
26905                                    currToCurr(_currid, _o.freight_curr_id,
26906                                               _freight, pEffective))
26907         WHERE (toitem_id=_r.recv_orderitem_id);
26908       END IF;
26909
26910       UPDATE recv
26911       SET recv_freight=currToCurr(_currid, recv_freight_curr_id, pFreight,
26912                                   pEffective),
26913           recv_date = pEffective
26914       WHERE (recv_id=precvid);
26915     END IF;
26916
26917   ELSE
26918
26919 -- Receipt not posted yet
26920     UPDATE recv SET recv_qty=pQty, recv_freight=pFreight, recv_purchcost=_recvcost WHERE recv_id=precvid;
26921   END IF;
26922
26923 RETURN _itemlocSeries;
26924
26925 END;
26926 $_$;
26927
26928
26929 ALTER FUNCTION public.correctreceipt(integer, numeric, numeric, integer, integer, date, numeric) OWNER TO admin;
26930
26931 --
26932 -- TOC entry 1278 (class 1255 OID 146565828)
26933 -- Dependencies: 4536 8
26934 -- Name: cosbycustomervalue(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
26935 --
26936
26937 CREATE FUNCTION cosbycustomervalue(integer, integer) RETURNS numeric
26938     LANGUAGE plpgsql
26939     AS $_$
26940 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26941 -- See www.xtuple.com/CPAL for the full text of the software license.
26942 DECLARE
26943   pCustid ALIAS FOR $1;
26944   pPeriodid ALIAS FOR $2;
26945   _value NUMERIC;
26946   _startDate DATE;
26947   _endDate DATE;
26948
26949 BEGIN
26950
26951   _startDate := findPeriodStart(pPeriodid);
26952   _endDate := findPeriodEnd(pPeriodid);
26953
26954 -- Returns value in base currency
26955 -- ToDo: is cohist_shipdate the right DATE to use?
26956   SELECT SUM(cohist_qtyshipped * currToBase(cohist_curr_id, cohist_unitcost, cohist_shipdate)) INTO _value
26957   FROM cohist
26958   WHERE ( (cohist_cust_id=pCustid)
26959    AND (cohist_invcdate BETWEEN _startDate AND _endDate) );
26960
26961   IF (_value IS NULL) THEN
26962     _value := 0;
26963   END IF;
26964
26965   RETURN _value;
26966
26967 END;
26968 $_$;
26969
26970
26971 ALTER FUNCTION public.cosbycustomervalue(integer, integer) OWNER TO admin;
26972
26973 --
26974 -- TOC entry 1279 (class 1255 OID 146565829)
26975 -- Dependencies: 4536 8
26976 -- Name: costsbycustomerbyitemsite(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
26977 --
26978
26979 CREATE FUNCTION costsbycustomerbyitemsite(integer, integer, integer) RETURNS numeric
26980     LANGUAGE plpgsql
26981     AS $_$
26982 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
26983 -- See www.xtuple.com/CPAL for the full text of the software license.
26984 DECLARE
26985   pCustid ALIAS FOR $1;
26986   pItemsiteid ALIAS FOR $2;
26987   pPeriodid ALIAS FOR $3;
26988   _value NUMERIC;
26989   _startDate DATE;
26990   _endDate DATE;
26991
26992 BEGIN
26993
26994   _startDate := findPeriodStart(pPeriodid);
26995   _endDate := findPeriodEnd(pPeriodid);
26996
26997 -- Returns value in base currency
26998 -- ToDo: is cohist_shipdate the right DATE to use?
26999   SELECT SUM(cohist_qtyshipped * currToBase(cohist_curr_id, cohist_unitcost, cohist_shipdate)) INTO _value
27000   FROM cohist
27001   WHERE ( (cohist_itemsite_id<>pItemsiteid)
27002    AND (cohist_cust_id=pCustid)
27003    AND (cohist_invcdate BETWEEN _startDate AND _endDate) );
27004
27005   IF (_value IS NULL) THEN
27006     _value := 0;
27007   END IF;
27008
27009   RETURN _value;
27010
27011 END;
27012 $_$;
27013
27014
27015 ALTER FUNCTION public.costsbycustomerbyitemsite(integer, integer, integer) OWNER TO admin;
27016
27017 --
27018 -- TOC entry 1281 (class 1255 OID 146565830)
27019 -- Dependencies: 4536 8
27020 -- Name: costsbycustomervalue(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
27021 --
27022
27023 CREATE FUNCTION costsbycustomervalue(integer, integer) RETURNS numeric
27024     LANGUAGE plpgsql
27025     AS $_$
27026 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27027 -- See www.xtuple.com/CPAL for the full text of the software license.
27028 DECLARE
27029   pCustid ALIAS FOR $1;
27030   pPeriodid ALIAS FOR $2;
27031   _value NUMERIC;
27032   _startDate DATE;
27033   _endDate DATE;
27034
27035 BEGIN
27036
27037   _startDate := findPeriodStart(pPeriodid);
27038   _endDate := findPeriodEnd(pPeriodid);
27039
27040 -- Returns value in base currency
27041 -- ToDo: is cohist_shipdate the right DATE to use?
27042   SELECT SUM(cohist_qtyshipped * currToBase(cohist_curr_id, cohist_unitcost, cohist_shipdate)) INTO _value
27043   FROM cohist
27044   WHERE ( (cohist_itemsite_id<>-1)
27045    AND (cohist_cust_id=pCustid)
27046    AND (cohist_invcdate BETWEEN _startDate AND _endDate) );
27047
27048   IF (_value IS NULL) THEN
27049     _value := 0;
27050   END IF;
27051
27052   RETURN _value;
27053
27054 END;
27055 $_$;
27056
27057
27058 ALTER FUNCTION public.costsbycustomervalue(integer, integer) OWNER TO admin;
27059
27060 --
27061 -- TOC entry 1282 (class 1255 OID 146565831)
27062 -- Dependencies: 4536 8
27063 -- Name: costsbycustomervalue(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
27064 --
27065
27066 CREATE FUNCTION costsbycustomervalue(integer, integer, integer) RETURNS numeric
27067     LANGUAGE plpgsql
27068     AS $_$
27069 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27070 -- See www.xtuple.com/CPAL for the full text of the software license.
27071 DECLARE
27072   pCustid ALIAS FOR $1;
27073   pPeriodid ALIAS FOR $2;
27074   pProdcatid ALIAS FOR $3;
27075   _value NUMERIC;
27076   _startDate DATE;
27077   _endDate DATE;
27078
27079 BEGIN
27080
27081   _startDate := findPeriodStart(pPeriodid);
27082   _endDate := findPeriodEnd(pPeriodid);
27083
27084 -- Returns value in base currency
27085 -- ToDo: is cohist_shipdate the right DATE to use?
27086   SELECT SUM(cohist_qtyshipped * currToBase(cohist_curr_id, cohist_unitcost, cohist_shipdate)) INTO _value
27087   FROM cohist, itemsite, item
27088   WHERE ( (cohist_cust_id=pCustid)
27089    AND (cohist_itemsite_id=itemsite_id)
27090    AND (itemsite_item_id=item_id)
27091    AND (item_prodcat_id=pProdcatid)
27092    AND (cohist_invcdate BETWEEN _startDate AND _endDate) );
27093
27094   IF (_value IS NULL) THEN
27095     _value := 0;
27096   END IF;
27097
27098   RETURN _value;
27099
27100 END;
27101 $_$;
27102
27103
27104 ALTER FUNCTION public.costsbycustomervalue(integer, integer, integer) OWNER TO admin;
27105
27106 --
27107 -- TOC entry 1283 (class 1255 OID 146565832)
27108 -- Dependencies: 4536 8
27109 -- Name: costsbycustomervalue(integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
27110 --
27111
27112 CREATE FUNCTION costsbycustomervalue(integer, integer, text) RETURNS numeric
27113     LANGUAGE plpgsql
27114     AS $_$
27115 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27116 -- See www.xtuple.com/CPAL for the full text of the software license.
27117 DECLARE
27118   pCustid ALIAS FOR $1;
27119   pPeriodid ALIAS FOR $2;
27120   pProdcat ALIAS FOR $3;
27121   _value NUMERIC;
27122   _startDate DATE;
27123   _endDate DATE;
27124
27125 BEGIN
27126
27127   _startDate := findPeriodStart(pPeriodid);
27128   _endDate := findPeriodEnd(pPeriodid);
27129
27130 -- Returns value in base currency
27131 -- ToDo: is cohist_shipdate the right date to use?
27132   SELECT SUM(cohist_qtyshipped * currToBase(cohist_curr_id, cohist_unitcost, cohist_shipdate)) INTO _value
27133   FROM cohist, itemsite, item, prodcat
27134   WHERE ( (cohist_cust_id=pCustid)
27135    AND (cohist_itemsite_id=itemsite_id)
27136    AND (itemsite_item_id=item_id)
27137    AND (item_prodcat_id=prodcat_id)
27138    AND (prodcat_code ~ pProdcat)
27139    AND (cohist_invcdate BETWEEN _startDate AND _endDate) );
27140
27141   IF (_value IS NULL) THEN
27142     _value := 0;
27143   END IF;
27144
27145   RETURN _value;
27146
27147 END;
27148 $_$;
27149
27150
27151 ALTER FUNCTION public.costsbycustomervalue(integer, integer, text) OWNER TO admin;
27152
27153 --
27154 -- TOC entry 1284 (class 1255 OID 146565833)
27155 -- Dependencies: 4536 8
27156 -- Name: createaccountingperiod(date, date); Type: FUNCTION; Schema: public; Owner: admin
27157 --
27158
27159 CREATE FUNCTION createaccountingperiod(date, date) RETURNS integer
27160     LANGUAGE plpgsql
27161     AS $_$
27162 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27163 -- See www.xtuple.com/CPAL for the full text of the software license.
27164 DECLARE
27165   pStartDate ALIAS FOR $1;
27166   pEndDate ALIAS FOR $2;
27167
27168 BEGIN
27169
27170   RETURN createAccountingPeriod(pStartDate, pEndDate, NULL, NULL);
27171
27172 END;
27173 $_$;
27174
27175
27176 ALTER FUNCTION public.createaccountingperiod(date, date) OWNER TO admin;
27177
27178 --
27179 -- TOC entry 1285 (class 1255 OID 146565834)
27180 -- Dependencies: 4536 8
27181 -- Name: createaccountingperiod(date, date, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
27182 --
27183
27184 CREATE FUNCTION createaccountingperiod(date, date, integer, integer) RETURNS integer
27185     LANGUAGE plpgsql
27186     AS $_$
27187 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27188 -- See www.xtuple.com/CPAL for the full text of the software license.
27189 DECLARE
27190   pStartDate ALIAS FOR $1;
27191   pEndDate ALIAS FOR $2;
27192   pYearPeriodId ALIAS FOR $3;
27193   pQuarter ALIAS FOR $4;
27194   _periodid INTEGER;
27195   _check INTEGER;
27196   _r RECORD;
27197   _initial BOOLEAN;
27198   _number INTEGER;
27199
27200 BEGIN
27201
27202 --  Make that the passed start date doesn't fall into any existing period
27203   SELECT period_id INTO _check
27204   FROM period
27205   WHERE (pStartDate BETWEEN period_start AND period_end);
27206   IF (FOUND) THEN
27207     RETURN -1;
27208   END IF;
27209
27210 --  Make that the passed end date doesn't fall into any existing period
27211   SELECT period_id INTO _check
27212   FROM period
27213   WHERE (pEndDate BETWEEN period_start AND period_end);
27214   IF (FOUND) THEN
27215     RETURN -2;
27216   END IF;
27217
27218 --  Make that the passed start and end dates don't enclose an existing period
27219   SELECT period_id INTO _check
27220   FROM period
27221   WHERE ( (period_start >= pStartDate)
27222    AND (period_end <= pEndDate) );
27223   IF (FOUND) THEN
27224     RETURN -3;
27225   END IF;
27226
27227 -- Make sure period is inside fiscal year
27228   SELECT yearperiod_id INTO _check
27229   FROM yearperiod
27230   WHERE ((yearperiod_id=pYearPeriodId)
27231   AND (pStartDate>=yearperiod_start)
27232   AND (pEndDate<=yearperiod_end));
27233   IF NOT (FOUND) THEN
27234     RETURN -4;
27235   END IF;
27236
27237 --  Determine if this is the initial accounting period
27238   SELECT CASE WHEN(count(*) > 0) THEN FALSE
27239               ELSE TRUE
27240          END INTO _initial
27241   FROM period;
27242
27243 -- Determine the next number
27244   SELECT COALESCE(MAX(period_number),0) + 1 INTO _number
27245   FROM period
27246   WHERE (period_yearperiod_id=pYearPeriodId);
27247
27248 --  Create the new accounting period
27249   SELECT NEXTVAL('period_period_id_seq') INTO _periodid;
27250   INSERT INTO period
27251   ( period_id, period_start, period_end, period_closed, period_freeze, 
27252     period_initial, period_number, period_yearperiod_id, period_quarter )
27253   VALUES
27254   ( _periodid, pStartDate, pEndDate, FALSE, FALSE, _initial, _number, pYearPeriodId, pQuarter );
27255
27256 --  Post any unposted G/L Transactions into the new period
27257   FOR _r IN SELECT DISTINCT gltrans_sequence
27258             FROM gltrans
27259             WHERE ( (NOT gltrans_posted)
27260              AND (gltrans_date BETWEEN pStartDate AND pEndDate) ) LOOP
27261     PERFORM postIntoTrialBalance(_r.gltrans_sequence);
27262   END LOOP;
27263
27264   RETURN _periodid;
27265
27266 END;
27267 $_$;
27268
27269
27270 ALTER FUNCTION public.createaccountingperiod(date, date, integer, integer) OWNER TO admin;
27271
27272 --
27273 -- TOC entry 1286 (class 1255 OID 146565835)
27274 -- Dependencies: 4536 8
27275 -- Name: createaccountingyearperiod(date, date); Type: FUNCTION; Schema: public; Owner: admin
27276 --
27277
27278 CREATE FUNCTION createaccountingyearperiod(date, date) RETURNS integer
27279     LANGUAGE plpgsql
27280     AS $_$
27281 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27282 -- See www.xtuple.com/CPAL for the full text of the software license.
27283 DECLARE
27284   pStartDate ALIAS FOR $1;
27285   pEndDate ALIAS FOR $2;
27286   _yearperiodid INTEGER;
27287   _check INTEGER;
27288   _checkBool BOOLEAN;
27289   _r RECORD;
27290   _initial BOOLEAN;
27291
27292 BEGIN
27293
27294 --  Make that the passed start date doesn't fall into any existing yearperiod
27295   SELECT yearperiod_id INTO _check
27296   FROM yearperiod
27297   WHERE (pStartDate BETWEEN yearperiod_start AND yearperiod_end);
27298   IF (FOUND) THEN
27299     RETURN -1;
27300   END IF;
27301
27302 --  Make that the passed end date doesn't fall into any existing yearperiod
27303   SELECT yearperiod_id INTO _check
27304   FROM yearperiod
27305   WHERE (pEndDate BETWEEN yearperiod_start AND yearperiod_end);
27306   IF (FOUND) THEN
27307     RETURN -2;
27308   END IF;
27309
27310 --  Make that the passed start and end dates don't enclose an existing yearperiod
27311   SELECT yearperiod_id INTO _check
27312   FROM yearperiod
27313   WHERE ( (yearperiod_start >= pStartDate)
27314    AND (yearperiod_end <= pEndDate) );
27315   IF (FOUND) THEN
27316     RETURN -3;
27317   END IF;
27318
27319 --  Make sure that the passed start is prior to the end date
27320   SELECT (pStartDate > pEndDate) INTO _checkBool;
27321   IF (_checkBool) THEN
27322     RETURN -5;
27323   END IF;
27324
27325 --  Determine if this is the initial accounting yearperiod
27326   SELECT CASE WHEN(count(*) > 0) THEN FALSE
27327               ELSE TRUE
27328          END INTO _initial
27329   FROM yearperiod;
27330
27331 --  Create the new accounting yearperiod
27332   SELECT NEXTVAL('yearperiod_yearperiod_id_seq') INTO _yearperiodid;
27333   INSERT INTO yearperiod
27334   ( yearperiod_id, yearperiod_start, yearperiod_end, yearperiod_closed )
27335   VALUES
27336   ( _yearperiodid, pStartDate, pEndDate, FALSE );
27337
27338   RETURN _yearperiodid;
27339
27340 END;
27341 $_$;
27342
27343
27344 ALTER FUNCTION public.createaccountingyearperiod(date, date) OWNER TO admin;
27345
27346 --
27347 -- TOC entry 1287 (class 1255 OID 146565836)
27348 -- Dependencies: 4536 8
27349 -- Name: createapchecks(integer, date); Type: FUNCTION; Schema: public; Owner: admin
27350 --
27351
27352 CREATE FUNCTION createapchecks(integer, date) RETURNS integer
27353     LANGUAGE plpgsql
27354     AS $_$
27355 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27356 -- See www.xtuple.com/CPAL for the full text of the software license.
27357 BEGIN
27358   RAISE NOTICE 'createAPChecks() is deprecated - use createChecks() instead';
27359   RETURN createChecks($1, $2);
27360 END;
27361 $_$;
27362
27363
27364 ALTER FUNCTION public.createapchecks(integer, date) OWNER TO admin;
27365
27366 --
27367 -- TOC entry 1288 (class 1255 OID 146565837)
27368 -- Dependencies: 4536 8
27369 -- Name: createapcreditmemo(integer, text, text, date, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
27370 --
27371
27372 CREATE FUNCTION createapcreditmemo(integer, text, text, date, numeric, text) RETURNS integer
27373     LANGUAGE plpgsql
27374     AS $_$
27375 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27376 -- See www.xtuple.com/CPAL for the full text of the software license.
27377 DECLARE
27378   pVendid ALIAS FOR $1;
27379   pDocNumber ALIAS FOR $2;
27380   pPoNumber ALIAS FOR $3;
27381   pDocDate ALIAS FOR $4;
27382   pAmount ALIAS FOR $5;
27383   pNotes ALIAS FOR $6;
27384   _result INTEGER;
27385
27386 BEGIN
27387
27388   SELECT createAPCreditMemo( pVendid, fetchJournalNumber('AP-MISC'),
27389                              pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, -1, pDocDate, -1, baseCurrId() ) INTO _result;
27390
27391   RETURN _result;
27392
27393 END;
27394 $_$;
27395
27396
27397 ALTER FUNCTION public.createapcreditmemo(integer, text, text, date, numeric, text) OWNER TO admin;
27398
27399 --
27400 -- TOC entry 1280 (class 1255 OID 146565838)
27401 -- Dependencies: 4536 8
27402 -- Name: createapcreditmemo(integer, integer, text, text, date, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
27403 --
27404
27405 CREATE FUNCTION createapcreditmemo(integer, integer, text, text, date, numeric, text) RETURNS integer
27406     LANGUAGE plpgsql
27407     AS $_$
27408 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27409 -- See www.xtuple.com/CPAL for the full text of the software license.
27410 DECLARE
27411   pVendid ALIAS FOR $1;
27412   pJournalNumber ALIAS FOR $2;
27413   pDocNumber ALIAS FOR $3;
27414   pPoNumber ALIAS FOR $4;
27415   pDocDate ALIAS FOR $5;
27416   pAmount ALIAS FOR $6;
27417   pNotes ALIAS FOR $7;
27418
27419 BEGIN
27420   RETURN createAPCreditMemo(pVendid, pJournalNumber, pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, -1, pDocDate, -1, baseCurrId() );
27421 END;
27422 $_$;
27423
27424
27425 ALTER FUNCTION public.createapcreditmemo(integer, integer, text, text, date, numeric, text) OWNER TO admin;
27426
27427 --
27428 -- TOC entry 1163 (class 1255 OID 146565839)
27429 -- Dependencies: 4536 8
27430 -- Name: createapcreditmemo(integer, text, text, date, numeric, text, integer); Type: FUNCTION; Schema: public; Owner: admin
27431 --
27432
27433 CREATE FUNCTION createapcreditmemo(integer, text, text, date, numeric, text, integer) RETURNS integer
27434     LANGUAGE plpgsql
27435     AS $_$
27436 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27437 -- See www.xtuple.com/CPAL for the full text of the software license.
27438 DECLARE
27439   pVendid ALIAS FOR $1;
27440   pDocNumber ALIAS FOR $2;
27441   pPoNumber ALIAS FOR $3;
27442   pDocDate ALIAS FOR $4;
27443   pAmount ALIAS FOR $5;
27444   pNotes ALIAS FOR $6;
27445   pAccntid ALIAS FOR $7;
27446   _result INTEGER;
27447
27448 BEGIN
27449
27450   SELECT createAPCreditMemo( pVendid, fetchJournalNumber('AP-MISC'),
27451                              pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDocDate, -1, baseCurrId() ) INTO _result;
27452
27453   RETURN _result;
27454
27455 END;
27456 $_$;
27457
27458
27459 ALTER FUNCTION public.createapcreditmemo(integer, text, text, date, numeric, text, integer) OWNER TO admin;
27460
27461 --
27462 -- TOC entry 1289 (class 1255 OID 146565840)
27463 -- Dependencies: 4536 8
27464 -- Name: createapcreditmemo(integer, integer, text, text, date, numeric, text, integer); Type: FUNCTION; Schema: public; Owner: admin
27465 --
27466
27467 CREATE FUNCTION createapcreditmemo(integer, integer, text, text, date, numeric, text, integer) RETURNS integer
27468     LANGUAGE plpgsql
27469     AS $_$
27470 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27471 -- See www.xtuple.com/CPAL for the full text of the software license.
27472 DECLARE
27473   pVendid ALIAS FOR $1;
27474   pJournalNumber ALIAS FOR $2;
27475   pDocNumber ALIAS FOR $3;
27476   pPoNumber ALIAS FOR $4;
27477   pDocDate ALIAS FOR $5;
27478   pAmount ALIAS FOR $6;
27479   pNotes ALIAS FOR $7;
27480   pAccntid ALIAS FOR $8;
27481 BEGIN
27482   RETURN createAPCreditMemo( pVendid, pJournalNumber,
27483                              pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDocDate, -1, baseCurrId() );
27484 END;
27485 $_$;
27486
27487
27488 ALTER FUNCTION public.createapcreditmemo(integer, integer, text, text, date, numeric, text, integer) OWNER TO admin;
27489
27490 --
27491 -- TOC entry 1290 (class 1255 OID 146565841)
27492 -- Dependencies: 4536 8
27493 -- Name: createapcreditmemo(integer, text, text, date, numeric, text, integer, date, integer); Type: FUNCTION; Schema: public; Owner: admin
27494 --
27495
27496 CREATE FUNCTION createapcreditmemo(integer, text, text, date, numeric, text, integer, date, integer) RETURNS integer
27497     LANGUAGE plpgsql
27498     AS $_$
27499 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27500 -- See www.xtuple.com/CPAL for the full text of the software license.
27501 DECLARE
27502   pVendid ALIAS FOR $1;
27503   pDocNumber ALIAS FOR $2;
27504   pPoNumber ALIAS FOR $3;
27505   pDocDate ALIAS FOR $4;
27506   pAmount ALIAS FOR $5;
27507   pNotes ALIAS FOR $6;
27508   pAccntid ALIAS FOR $7;
27509   pDueDate ALIAS FOR $8;
27510   pTermsid ALIAS FOR $9;
27511   _result INTEGER;
27512
27513 BEGIN
27514
27515   SELECT createAPCreditMemo( pVendid, fetchJournalNumber('AP-MISC'),
27516                              pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDueDate, pTermsid, baseCurrId() ) INTO _result;
27517
27518   RETURN _result;
27519
27520 END;
27521 $_$;
27522
27523
27524 ALTER FUNCTION public.createapcreditmemo(integer, text, text, date, numeric, text, integer, date, integer) OWNER TO admin;
27525
27526 --
27527 -- TOC entry 1291 (class 1255 OID 146565842)
27528 -- Dependencies: 4536 8
27529 -- Name: createapcreditmemo(integer, integer, text, text, date, numeric, text, integer, date, integer); Type: FUNCTION; Schema: public; Owner: admin
27530 --
27531
27532 CREATE FUNCTION createapcreditmemo(integer, integer, text, text, date, numeric, text, integer, date, integer) RETURNS integer
27533     LANGUAGE plpgsql
27534     AS $_$
27535 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27536 -- See www.xtuple.com/CPAL for the full text of the software license.
27537 DECLARE
27538   pVendid ALIAS FOR $1;
27539   pJournalNumber ALIAS FOR $2;
27540   pDocNumber ALIAS FOR $3;
27541   pPoNumber ALIAS FOR $4;
27542   pDocDate ALIAS FOR $5;
27543   pAmount ALIAS FOR $6;
27544   pNotes ALIAS FOR $7;
27545   pAccntid ALIAS FOR $8;
27546   pDueDate ALIAS FOR $9;
27547   pTermsid ALIAS FOR $10;
27548 BEGIN
27549   RETURN createAPCreditMemo( pVendid, pJournalNumber, pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDueDate, pTermsid, baseCurrId() );
27550 END;
27551 $_$;
27552
27553
27554 ALTER FUNCTION public.createapcreditmemo(integer, integer, text, text, date, numeric, text, integer, date, integer) OWNER TO admin;
27555
27556 --
27557 -- TOC entry 1292 (class 1255 OID 146565843)
27558 -- Dependencies: 4536 8
27559 -- Name: createapcreditmemo(integer, integer, text, text, date, numeric, text, integer, date, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
27560 --
27561
27562 CREATE FUNCTION createapcreditmemo(integer, integer, text, text, date, numeric, text, integer, date, integer, integer) RETURNS integer
27563     LANGUAGE plpgsql
27564     AS $_$
27565 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27566 -- See www.xtuple.com/CPAL for the full text of the software license.
27567 DECLARE
27568   pVendid ALIAS FOR $1;
27569   pJournalNumber ALIAS FOR $2;
27570   pDocNumber ALIAS FOR $3;
27571   pPoNumber ALIAS FOR $4;
27572   pDocDate ALIAS FOR $5;
27573   pAmount ALIAS FOR $6;
27574   pNotes ALIAS FOR $7;
27575   pAccntid ALIAS FOR $8;
27576   pDueDate ALIAS FOR $9;
27577   pTermsid ALIAS FOR $10;
27578   pCurrId ALIAS FOR $11;
27579 BEGIN
27580   RETURN createAPCreditMemo( NULL, pVendid, pJournalNumber, pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDueDate, pTermsid, pCurrId );
27581 END;
27582 $_$;
27583
27584
27585 ALTER FUNCTION public.createapcreditmemo(integer, integer, text, text, date, numeric, text, integer, date, integer, integer) OWNER TO admin;
27586
27587 --
27588 -- TOC entry 1293 (class 1255 OID 146565844)
27589 -- Dependencies: 4536 8
27590 -- Name: createapcreditmemo(integer, integer, integer, text, text, date, numeric, text, integer, date, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
27591 --
27592
27593 CREATE FUNCTION createapcreditmemo(integer, integer, integer, text, text, date, numeric, text, integer, date, integer, integer) RETURNS integer
27594     LANGUAGE plpgsql
27595     AS $_$
27596 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27597 -- See www.xtuple.com/CPAL for the full text of the software license.
27598 DECLARE
27599   pId ALIAS FOR $1;
27600   pVendid ALIAS FOR $2;
27601   pJournalNumber ALIAS FOR $3;
27602   pDocNumber ALIAS FOR $4;
27603   pPoNumber ALIAS FOR $5;
27604   pDocDate ALIAS FOR $6;
27605   pAmount ALIAS FOR $7;
27606   pNotes ALIAS FOR $8;
27607   pAccntid ALIAS FOR $9;
27608   pDueDate ALIAS FOR $10;
27609   pTermsid ALIAS FOR $11;
27610   pCurrId ALIAS FOR $12;
27611   _vendName TEXT;
27612   _apAccntid INTEGER;
27613   _prepaidAccntid INTEGER;
27614   _accntid INTEGER;
27615   _glSequence INTEGER;
27616   _journalNumber INTEGER;
27617   _apopenid INTEGER;
27618   _baseAmount NUMERIC;
27619   _taxBaseValue NUMERIC;
27620   _test INTEGER;
27621
27622 BEGIN
27623
27624   _apopenid := pId;
27625
27626   SELECT findAPAccount(pVendid) INTO _apAccntid;
27627   SELECT findAPPrepaidAccount(pVendid) INTO _prepaidAccntid;
27628
27629   SELECT vend_name INTO _vendName
27630   FROM vendinfo
27631   WHERE (vend_id=pVendid);
27632   
27633   _accntid := pAccntid;
27634
27635   PERFORM accnt_id
27636      FROM accnt
27637     WHERE (accnt_id=_accntid);
27638   IF (FOUND) THEN
27639     _prepaidAccntid := _accntid;
27640   ELSE
27641     _accntid := -1;
27642   END IF;
27643
27644   IF(pJournalNumber IS NULL) THEN
27645     SELECT fetchJournalNumber('AP-MISC') INTO _journalNumber;
27646   ELSE
27647     _journalNumber := pJournalNumber;
27648   END IF;
27649
27650   SELECT fetchGLSequence() INTO _glSequence;
27651
27652   IF (_apopenid IS NOT NULL) THEN
27653     UPDATE apopen SET
27654       apopen_username=getEffectiveXtUser(), apopen_journalnumber=_journalNumber,
27655       apopen_vend_id=pVendid, apopen_docnumber=pDocNumber,
27656       apopen_doctype='C', apopen_ponumber=pPoNumber,
27657       apopen_docdate=pDocDate, apopen_duedate=pDueDate,
27658       apopen_distdate=pDocDate, apopen_terms_id=pTermsid,
27659       apopen_amount=pAmount, apopen_paid=0,
27660       apopen_open=(pAmount <> 0), apopen_notes=pNotes,
27661       apopen_accnt_id=_accntid, apopen_curr_id=pCurrId,
27662       apopen_closedate=CASE WHEN (pAmount = 0) THEN pDocdate END
27663     WHERE apopen_id = _apopenid;
27664   ELSE
27665     SELECT NEXTVAL('apopen_apopen_id_seq') INTO _apopenid;
27666     INSERT INTO apopen
27667     ( apopen_id, apopen_username, apopen_journalnumber,
27668       apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_ponumber,
27669       apopen_docdate, apopen_duedate, apopen_distdate, apopen_terms_id,
27670       apopen_amount, apopen_paid, apopen_open, apopen_notes, apopen_accnt_id, apopen_curr_id,
27671       apopen_closedate )
27672     VALUES
27673     ( _apopenid, getEffectiveXtUser(), _journalNumber,
27674       pVendid, pDocNumber, 'C', pPoNumber,
27675       pDocDate, pDueDate, pDocDate, pTermsid,
27676       pAmount, 0, (pAmount <> 0), pNotes, _accntid, pCurrId,
27677       CASE WHEN (pAmount = 0) THEN pDocDate END );
27678   END IF;
27679
27680   _baseAmount := round(currToBase(pCurrId, pAmount, pDocDate), 2);
27681
27682   -- Debit the A/P account for the full amount
27683   SELECT insertIntoGLSeries ( _glSequence, 'A/P', 'CM',
27684                               pDocNumber, _apAccntid,
27685                               (_baseAmount * -1),
27686                               pDocDate, (_vendName || ' ' || pNotes) ) INTO _test;
27687
27688   -- Credit the Tax account for the tax amount
27689   _taxBaseValue := addTaxToGLSeries(_glSequence,
27690                                       'A/P', 'CM', pDocNumber,
27691                                       pCurrId, pDocDate, pDocDate,
27692                                       'apopentax', _apopenid,
27693                                       _vendName);
27694
27695   UPDATE apopentax SET taxhist_journalnumber = _journalNumber
27696   WHERE taxhist_parent_id=_apopenid;
27697
27698   -- Credit the Prepaid account for the basis amount
27699   SELECT insertIntoGLSeries ( _glSequence, 'A/P', 'CM',
27700                               pDocNumber, _prepaidAccntid,
27701                               (_baseAmount - _taxBaseValue),
27702                               pDocDate, (_vendName || ' ' || pNotes) ) INTO _test;
27703
27704   --  Commit the GLSeries;
27705   SELECT postGLSeries(_glSequence, _journalNumber) INTO _test;
27706   IF (_test < 0) THEN
27707     DELETE FROM apopen WHERE (apopen_id=_apopenid);
27708     PERFORM deleteGLSeries(_glSequence);
27709     RAISE EXCEPTION 'postGLSeries commit failed with %', _test;
27710   END IF;
27711
27712   RETURN pJournalNumber;
27713
27714 END;
27715 $_$;
27716
27717
27718 ALTER FUNCTION public.createapcreditmemo(integer, integer, integer, text, text, date, numeric, text, integer, date, integer, integer) OWNER TO admin;
27719
27720 --
27721 -- TOC entry 1294 (class 1255 OID 146565845)
27722 -- Dependencies: 4536 8
27723 -- Name: createapcreditmemoapplication(integer, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
27724 --
27725
27726 CREATE FUNCTION createapcreditmemoapplication(psourceapopenid integer, ptargetapopenid integer, pamount numeric, pcurrid integer) RETURNS integer
27727     LANGUAGE plpgsql
27728     AS $$
27729 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27730 -- See www.xtuple.com/CPAL for the full text of the software license.
27731 DECLARE
27732   _apCreditApplyId      INTEGER;
27733
27734 BEGIN
27735   IF (pAmount > (SELECT ROUND(currToCurr(apopen_curr_id, pCurrId, (apopen_amount - apopen_paid), apopen_docdate), 2)
27736                  FROM apopen
27737                  WHERE (apopen_id=pTargetApopenId))) THEN
27738     RETURN -1;
27739   END IF;
27740
27741   IF (pAmount > (SELECT ROUND((apopen_amount - apopen_paid) - 
27742                        COALESCE(SUM(currToCurr(apcreditapply_curr_id,
27743                                                 apopen_curr_id, 
27744                                                 apcreditapply_amount, 
27745                                                 apopen_docdate)), 0), 2)
27746              FROM apopen LEFT OUTER JOIN apcreditapply 
27747                ON ((apcreditapply_source_apopen_id=apopen_id) 
27748               AND (apcreditapply_target_apopen_id<>pTargetApopenId)) 
27749              WHERE (apopen_id=pSourceApopenId) 
27750              GROUP BY apopen_amount, apopen_paid)) THEN
27751       RETURN -2;
27752     END IF;
27753
27754   SELECT apcreditapply_id INTO _apCreditApplyId
27755     FROM apcreditapply
27756    WHERE ((apcreditapply_source_apopen_id=pSourceApopenId)
27757      AND  (apcreditapply_target_apopen_id=pTargetApopenId));
27758
27759   IF (FOUND) THEN
27760     UPDATE apcreditapply SET apcreditapply_amount=pAmount,
27761                              apcreditapply_curr_id=pCurrId
27762     WHERE (apcreditapply_id=_apCreditApplyId);
27763   ELSE
27764     INSERT INTO apcreditapply (
27765       apcreditapply_source_apopen_id,
27766       apcreditapply_target_apopen_id,
27767       apcreditapply_amount, apcreditapply_curr_id
27768     ) VALUES (
27769       pSourceApopenId,
27770       pTargetApopenId,
27771       pAmount, pCurrId)
27772     RETURNING apcreditapply_id INTO _apCreditApplyId;
27773   END IF;
27774
27775   RETURN _apCreditApplyId;
27776
27777 END;
27778 $$;
27779
27780
27781 ALTER FUNCTION public.createapcreditmemoapplication(psourceapopenid integer, ptargetapopenid integer, pamount numeric, pcurrid integer) OWNER TO admin;
27782
27783 --
27784 -- TOC entry 1295 (class 1255 OID 146565846)
27785 -- Dependencies: 4536 8
27786 -- Name: createapdebitmemo(integer, text, text, date, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
27787 --
27788
27789 CREATE FUNCTION createapdebitmemo(integer, text, text, date, numeric, text) RETURNS integer
27790     LANGUAGE plpgsql
27791     AS $_$
27792 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27793 -- See www.xtuple.com/CPAL for the full text of the software license.
27794 DECLARE
27795   pVendid ALIAS FOR $1;
27796   pDocNumber ALIAS FOR $2;
27797   pPoNumber ALIAS FOR $3;
27798   pDocDate ALIAS FOR $4;
27799   pAmount ALIAS FOR $5;
27800   pNotes ALIAS FOR $6;
27801   _result INTEGER;
27802
27803 BEGIN
27804
27805   SELECT createAPDebitMemo( pVendid, fetchJournalNumber('AP-MISC'),
27806                             pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, -1, pDocDate, -1, baseCurrId() ) INTO _result;
27807
27808   RETURN _result;
27809
27810 END;
27811 $_$;
27812
27813
27814 ALTER FUNCTION public.createapdebitmemo(integer, text, text, date, numeric, text) OWNER TO admin;
27815
27816 --
27817 -- TOC entry 1296 (class 1255 OID 146565847)
27818 -- Dependencies: 4536 8
27819 -- Name: createapdebitmemo(integer, integer, text, text, date, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
27820 --
27821
27822 CREATE FUNCTION createapdebitmemo(integer, integer, text, text, date, numeric, text) RETURNS integer
27823     LANGUAGE plpgsql
27824     AS $_$
27825 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27826 -- See www.xtuple.com/CPAL for the full text of the software license.
27827 DECLARE
27828   pVendid ALIAS FOR $1;
27829   pJournalNumber ALIAS FOR $2;
27830   pDocNumber ALIAS FOR $3;
27831   pPoNumber ALIAS FOR $4;
27832   pDocDate ALIAS FOR $5;
27833   pAmount ALIAS FOR $6;
27834   pNotes ALIAS FOR $7;
27835
27836 BEGIN
27837
27838   RETURN createAPDebitMemo(pVendid, pJournalNumber, pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, -1, pDocDate, -1, baseCurrId() );
27839
27840 END;
27841 $_$;
27842
27843
27844 ALTER FUNCTION public.createapdebitmemo(integer, integer, text, text, date, numeric, text) OWNER TO admin;
27845
27846 --
27847 -- TOC entry 1297 (class 1255 OID 146565848)
27848 -- Dependencies: 4536 8
27849 -- Name: createapdebitmemo(integer, text, text, date, numeric, text, integer); Type: FUNCTION; Schema: public; Owner: admin
27850 --
27851
27852 CREATE FUNCTION createapdebitmemo(integer, text, text, date, numeric, text, integer) RETURNS integer
27853     LANGUAGE plpgsql
27854     AS $_$
27855 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27856 -- See www.xtuple.com/CPAL for the full text of the software license.
27857 DECLARE
27858   pVendid ALIAS FOR $1;
27859   pDocNumber ALIAS FOR $2;
27860   pPoNumber ALIAS FOR $3;
27861   pDocDate ALIAS FOR $4;
27862   pAmount ALIAS FOR $5;
27863   pNotes ALIAS FOR $6;
27864   pAccntid ALIAS FOR $7;
27865   _result INTEGER;
27866
27867 BEGIN
27868
27869   SELECT createAPDebitMemo( pVendid, fetchJournalNumber('AP-MISC'),
27870                             pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDocDate, -1, baseCurrId() ) INTO _result;
27871
27872   RETURN _result;
27873
27874 END;
27875 $_$;
27876
27877
27878 ALTER FUNCTION public.createapdebitmemo(integer, text, text, date, numeric, text, integer) OWNER TO admin;
27879
27880 --
27881 -- TOC entry 1298 (class 1255 OID 146565849)
27882 -- Dependencies: 4536 8
27883 -- Name: createapdebitmemo(integer, integer, text, text, date, numeric, text, integer); Type: FUNCTION; Schema: public; Owner: admin
27884 --
27885
27886 CREATE FUNCTION createapdebitmemo(integer, integer, text, text, date, numeric, text, integer) RETURNS integer
27887     LANGUAGE plpgsql
27888     AS $_$
27889 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27890 -- See www.xtuple.com/CPAL for the full text of the software license.
27891 DECLARE
27892   pVendid ALIAS FOR $1;
27893   pJournalNumber ALIAS FOR $2;
27894   pDocNumber ALIAS FOR $3;
27895   pPoNumber ALIAS FOR $4;
27896   pDocDate ALIAS FOR $5;
27897   pAmount ALIAS FOR $6;
27898   pNotes ALIAS FOR $7;
27899   pAccntid ALIAS FOR $8;
27900 BEGIN
27901   RETURN createAPDebitMemo( pVendid, pJournalNumber,
27902                             pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDocDate, -1, baseCurrId() );
27903 END;
27904 $_$;
27905
27906
27907 ALTER FUNCTION public.createapdebitmemo(integer, integer, text, text, date, numeric, text, integer) OWNER TO admin;
27908
27909 --
27910 -- TOC entry 1299 (class 1255 OID 146565850)
27911 -- Dependencies: 4536 8
27912 -- Name: createapdebitmemo(integer, text, text, date, numeric, text, integer, date, integer); Type: FUNCTION; Schema: public; Owner: admin
27913 --
27914
27915 CREATE FUNCTION createapdebitmemo(integer, text, text, date, numeric, text, integer, date, integer) RETURNS integer
27916     LANGUAGE plpgsql
27917     AS $_$
27918 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27919 -- See www.xtuple.com/CPAL for the full text of the software license.
27920 DECLARE
27921   pVendid ALIAS FOR $1;
27922   pDocNumber ALIAS FOR $2;
27923   pPoNumber ALIAS FOR $3;
27924   pDocDate ALIAS FOR $4;
27925   pAmount ALIAS FOR $5;
27926   pNotes ALIAS FOR $6;
27927   pAccntid ALIAS FOR $7;
27928   pDueDate ALIAS FOR $8;
27929   pTermsid ALIAS FOR $9;
27930   _result INTEGER;
27931
27932 BEGIN
27933
27934   SELECT createAPDebitMemo( pVendid, fetchJournalNumber('AP-MISC'),
27935                             pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDueDate, pTermsid, baseCurrId() ) INTO _result;
27936
27937   RETURN _result;
27938
27939 END;
27940 $_$;
27941
27942
27943 ALTER FUNCTION public.createapdebitmemo(integer, text, text, date, numeric, text, integer, date, integer) OWNER TO admin;
27944
27945 --
27946 -- TOC entry 1300 (class 1255 OID 146565851)
27947 -- Dependencies: 4536 8
27948 -- Name: createapdebitmemo(integer, integer, text, text, date, numeric, text, integer, date, integer); Type: FUNCTION; Schema: public; Owner: admin
27949 --
27950
27951 CREATE FUNCTION createapdebitmemo(integer, integer, text, text, date, numeric, text, integer, date, integer) RETURNS integer
27952     LANGUAGE plpgsql
27953     AS $_$
27954 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27955 -- See www.xtuple.com/CPAL for the full text of the software license.
27956 DECLARE
27957   pVendid ALIAS FOR $1;
27958   pJournalNumber ALIAS FOR $2;
27959   pDocNumber ALIAS FOR $3;
27960   pPoNumber ALIAS FOR $4;
27961   pDocDate ALIAS FOR $5;
27962   pAmount ALIAS FOR $6;
27963   pNotes ALIAS FOR $7;
27964   pAccntid ALIAS FOR $8;
27965   pDueDate ALIAS FOR $9;
27966   pTermsid ALIAS FOR $10;
27967
27968 BEGIN
27969   RETURN createAPDebitMemo(pVendid, pJournalNumber, pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDueDate, pTermsid, baseCurrId() );
27970 END;
27971 $_$;
27972
27973
27974 ALTER FUNCTION public.createapdebitmemo(integer, integer, text, text, date, numeric, text, integer, date, integer) OWNER TO admin;
27975
27976 --
27977 -- TOC entry 1301 (class 1255 OID 146565852)
27978 -- Dependencies: 4536 8
27979 -- Name: createapdebitmemo(integer, integer, text, text, date, numeric, text, integer, date, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
27980 --
27981
27982 CREATE FUNCTION createapdebitmemo(integer, integer, text, text, date, numeric, text, integer, date, integer, integer) RETURNS integer
27983     LANGUAGE plpgsql
27984     AS $_$
27985 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
27986 -- See www.xtuple.com/CPAL for the full text of the software license.
27987 DECLARE
27988   pVendid ALIAS FOR $1;
27989   pJournalNumber ALIAS FOR $2;
27990   pDocNumber ALIAS FOR $3;
27991   pPoNumber ALIAS FOR $4;
27992   pDocDate ALIAS FOR $5;
27993   pAmount ALIAS FOR $6;
27994   pNotes ALIAS FOR $7;
27995   pAccntid ALIAS FOR $8;
27996   pDueDate ALIAS FOR $9;
27997   pTermsid ALIAS FOR $10;
27998   pCurrId ALIAS FOR $11;
27999
28000 BEGIN
28001   RETURN createAPDebitMemo(NULL, pVendid, pJournalNumber, pDocNumber, pPoNumber, pDocDate, pAmount, pNotes, pAccntid, pDueDate, pTermsid, pCurrId );
28002 END;
28003 $_$;
28004
28005
28006 ALTER FUNCTION public.createapdebitmemo(integer, integer, text, text, date, numeric, text, integer, date, integer, integer) OWNER TO admin;
28007
28008 --
28009 -- TOC entry 1302 (class 1255 OID 146565853)
28010 -- Dependencies: 4536 8
28011 -- Name: createapdebitmemo(integer, integer, integer, text, text, date, numeric, text, integer, date, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
28012 --
28013
28014 CREATE FUNCTION createapdebitmemo(integer, integer, integer, text, text, date, numeric, text, integer, date, integer, integer) RETURNS integer
28015     LANGUAGE plpgsql
28016     AS $_$
28017 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28018 -- See www.xtuple.com/CPAL for the full text of the software license.
28019 DECLARE
28020   pId ALIAS FOR $1;
28021   pVendid ALIAS FOR $2;
28022   pJournalNumber ALIAS FOR $3;
28023   pDocNumber ALIAS FOR $4;
28024   pPoNumber ALIAS FOR $5;
28025   pDocDate ALIAS FOR $6;
28026   pAmount ALIAS FOR $7;
28027   pNotes ALIAS FOR $8;
28028   pAccntid ALIAS FOR $9;
28029   pDueDate ALIAS FOR $10;
28030   pTermsid ALIAS FOR $11;
28031   pCurrId ALIAS FOR $12;
28032   _vendName TEXT;
28033   _apAccntid INTEGER;
28034   _prepaidAccntid INTEGER;
28035   _accntid INTEGER;
28036   _glSequence INTEGER;
28037   _journalNumber INTEGER;
28038   _apopenid INTEGER;
28039   _baseAmount NUMERIC;
28040   _taxBaseValue NUMERIC;
28041   _test INTEGER;
28042
28043 BEGIN
28044
28045   _apopenid := pId;
28046
28047   SELECT findAPAccount(pVendid) INTO _apAccntid;
28048   SELECT findAPPrepaidAccount(pVendid) INTO _prepaidAccntid;
28049
28050   SELECT vend_name INTO _vendName
28051   FROM vendinfo
28052   WHERE (vend_id=pVendid);
28053
28054   _accntid := pAccntid;
28055
28056   PERFORM accnt_id
28057      FROM accnt
28058     WHERE (accnt_id=_accntid);
28059   IF (FOUND) THEN
28060     _prepaidAccntid := _accntid;
28061   ELSE
28062     _accntid := -1;
28063   END IF;
28064
28065   IF(pJournalNumber IS NULL) THEN
28066     SELECT fetchJournalNumber('AP-MISC') INTO _journalNumber;
28067   ELSE
28068     _journalNumber := pJournalNumber;
28069   END IF;
28070
28071   SELECT fetchGLSequence() INTO _glSequence;
28072
28073   IF (_apopenid IS NOT NULL) THEN
28074     UPDATE apopen SET
28075       apopen_username=getEffectiveXtUser(), apopen_journalnumber=_journalNumber,
28076       apopen_vend_id=pVendid, apopen_docnumber=pDocNumber,
28077       apopen_doctype='D', apopen_ponumber=pPoNumber,
28078       apopen_docdate=pDocDate, apopen_duedate=pDueDate,
28079       apopen_distdate=pDocDate, apopen_terms_id=pTermsid,
28080       apopen_amount=pAmount, apopen_paid=0,
28081       apopen_open=(pAmount <> 0), apopen_notes=pNotes,
28082       apopen_accnt_id=_accntid, apopen_curr_id=pCurrId,
28083       apopen_closedate=CASE WHEN (pAmount = 0) THEN pDocdate END
28084     WHERE apopen_id = _apopenid;
28085   ELSE
28086     SELECT NEXTVAL('apopen_apopen_id_seq') INTO _apopenid;
28087     INSERT INTO apopen
28088     ( apopen_id, apopen_username, apopen_journalnumber,
28089       apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_ponumber,
28090       apopen_docdate, apopen_duedate, apopen_distdate, apopen_terms_id,
28091       apopen_amount, apopen_paid, apopen_discountable_amount, apopen_open, apopen_notes, apopen_accnt_id, apopen_curr_id,
28092       apopen_closedate )
28093     VALUES
28094     ( _apopenid, getEffectiveXtUser(), _journalNumber,
28095       pVendid, pDocNumber, 'D', pPoNumber,
28096       pDocDate, pDueDate, pDocDate, pTermsid,
28097       pAmount, 0, 0, (pAmount <> 0), pNotes, _accntid, pCurrId,
28098       CASE WHEN (pAmount = 0) THEN pDocDate END );
28099   END IF;
28100
28101   _baseAmount := round(currToBase(pCurrId, pAmount, pDocDate), 2);
28102
28103   -- Credit the A/P account for the full amount
28104   SELECT insertIntoGLSeries ( _glSequence, 'A/P', 'DM',
28105                               pDocNumber, _apAccntid,
28106                               _baseAmount,
28107                               pDocDate, (_vendName || ' ' || pNotes) ) INTO _test;
28108
28109   -- Debit the Tax account for the tax amount
28110   _taxBaseValue := addTaxToGLSeries(_glSequence,
28111                                       'A/P', 'DM', pDocNumber,
28112                                       pCurrId, pDocDate, pDocDate,
28113                                       'apopentax', _apopenid,
28114                                       _vendName);
28115
28116   UPDATE apopentax SET taxhist_journalnumber = _journalNumber
28117   WHERE taxhist_parent_id=_apopenid;
28118
28119   -- Debit the Prepaid account for the basis amount
28120   -- Note, the taxBaseValue is negative so it is added
28121   SELECT insertIntoGLSeries ( _glSequence, 'A/P', 'DM',
28122                               pDocNumber, _prepaidAccntid,
28123                               (_baseAmount + _taxBaseValue) * -1,
28124                               pDocDate, (_vendName || ' ' || pNotes) ) INTO _test;
28125
28126   --  Commit the GLSeries;
28127   SELECT postGLSeries(_glSequence, _journalNumber) INTO _test;
28128   IF (_test < 0) THEN
28129     DELETE FROM apopen WHERE (apopen_id=_apopenid);
28130     PERFORM deleteGLSeries(_glSequence);
28131     RAISE EXCEPTION 'postGLSeries commit failed with %', _test;
28132   END IF;
28133
28134   RETURN _apopenid;
28135
28136 END;
28137 $_$;
28138
28139
28140 ALTER FUNCTION public.createapdebitmemo(integer, integer, integer, text, text, date, numeric, text, integer, date, integer, integer) OWNER TO admin;
28141
28142 --
28143 -- TOC entry 1303 (class 1255 OID 146565854)
28144 -- Dependencies: 4536 8
28145 -- Name: createapdiscount(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
28146 --
28147
28148 CREATE FUNCTION createapdiscount(integer, numeric) RETURNS integer
28149     LANGUAGE plpgsql
28150     AS $_$
28151 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28152 -- See www.xtuple.com/CPAL for the full text of the software license.
28153 DECLARE
28154   pApopenid ALIAS FOR $1;
28155   pAmount ALIAS FOR $2;
28156   _result INTEGER;
28157   
28158 BEGIN
28159
28160   SELECT createAPDiscount(pApopenid, fetchJournalNumber('AP-MISC'), pAmount) INTO _result;
28161
28162   RETURN _result;
28163
28164 END;
28165 $_$;
28166
28167
28168 ALTER FUNCTION public.createapdiscount(integer, numeric) OWNER TO admin;
28169
28170 --
28171 -- TOC entry 1304 (class 1255 OID 146565855)
28172 -- Dependencies: 4536 8
28173 -- Name: createapdiscount(integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
28174 --
28175
28176 CREATE FUNCTION createapdiscount(integer, integer, numeric) RETURNS integer
28177     LANGUAGE plpgsql
28178     AS $_$
28179 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28180 -- See www.xtuple.com/CPAL for the full text of the software license.
28181 DECLARE
28182   pApopenid ALIAS FOR $1;
28183   pJournalNumber ALIAS FOR $2;
28184   pAmount ALIAS FOR $3;
28185   _ap RECORD;
28186   _sequence INTEGER;
28187   _apopenid INTEGER;
28188   _apcreditapplyid INTEGER;
28189   _result INTEGER;
28190   _crAccnt INTEGER;
28191   _dbAccnt INTEGER;
28192   _reference    TEXT;
28193   _discountDateAmt NUMERIC;
28194
28195 BEGIN
28196
28197   SELECT NEXTVAL('apopen_apopen_id_seq') INTO _apopenid;
28198
28199   SELECT * INTO _ap
28200   FROM apopen
28201   WHERE (apopen_id = pApopenid);
28202   IF (NOT FOUND) THEN
28203     RETURN -1;
28204   END IF;
28205
28206   _crAccnt := findAPDiscountAccount(_ap.apopen_vend_id);
28207   _dbAccnt := findAPAccount(_ap.apopen_vend_id);
28208   _reference := ('Discount for ' || _ap.apopen_doctype || ' ' || _ap.apopen_docnumber);
28209
28210   SELECT fetchGLSequence() INTO _sequence;
28211
28212   _discountDateAmt = round(pAmount / _ap.apopen_curr_rate, 2);
28213   PERFORM insertIntoGLSeries( _sequence, 'A/P', 'DS', _ap.apopen_docnumber,
28214                               _dbAccnt,
28215                               _discountDateAmt * -1,
28216                               CURRENT_DATE,
28217                               _reference);
28218   PERFORM insertIntoGLSeries( _sequence, 'A/P', 'DS', _ap.apopen_docnumber,
28219                               _crAccnt,
28220                               _discountDateAmt,
28221                               CURRENT_DATE,
28222                               _reference);
28223
28224   PERFORM postGLSeries(_sequence, pJournalNumber);
28225
28226   INSERT INTO apopen
28227   ( apopen_id, apopen_username, apopen_journalnumber,
28228     apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_ponumber,
28229     apopen_docdate, apopen_duedate, apopen_distdate, apopen_terms_id, apopen_curr_id,
28230     apopen_amount, apopen_paid, apopen_open, apopen_notes, apopen_discount, apopen_curr_rate )
28231   SELECT _apopenid, getEffectiveXtUser(), pJournalNumber,
28232          apopen_vend_id, apopen_docnumber, 'C', apopen_ponumber,
28233          CURRENT_DATE, CURRENT_DATE, CURRENT_DATE, -1, apopen_curr_id,
28234          pAmount, 0, TRUE, _reference, TRUE, apopen_curr_rate
28235     FROM apopen
28236    WHERE (apopen_id=pApopenid);
28237
28238   SELECT apcreditapply_id INTO _apcreditapplyid
28239     FROM apcreditapply
28240    WHERE ( (apcreditapply_source_apopen_id=_apopenid)
28241      AND   (apcreditapply_target_apopen_id=pApopenid) );
28242   IF (FOUND) THEN
28243     UPDATE apcreditapply
28244        SET apcreditapply_amount=pAmount
28245      WHERE (apcreditapply_id=_apcreditapplyid);
28246   ELSE
28247     SELECT nextval('apcreditapply_apcreditapply_id_seq') INTO _apcreditapplyid;
28248     INSERT INTO apcreditapply
28249            ( apcreditapply_id, apcreditapply_source_apopen_id,
28250              apcreditapply_target_apopen_id, apcreditapply_amount,
28251              apcreditapply_curr_id )
28252     VALUES ( _apcreditapplyid, _apopenid, pApopenid, pAmount, _ap.apopen_curr_id );
28253   END IF;
28254
28255   SELECT postAPCreditMemoApplication(_apopenid) INTO _result;
28256
28257   IF (_result < 0) THEN
28258     RETURN _result;
28259   END IF;
28260
28261   RETURN pJournalNumber;
28262
28263 END;
28264 $_$;
28265
28266
28267 ALTER FUNCTION public.createapdiscount(integer, integer, numeric) OWNER TO admin;
28268
28269 --
28270 -- TOC entry 1306 (class 1255 OID 146565856)
28271 -- Dependencies: 4536 8
28272 -- Name: createarcashdeposit(integer, text, text, date, numeric, text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
28273 --
28274
28275 CREATE FUNCTION createarcashdeposit(integer, text, text, date, numeric, text, integer, integer) RETURNS integer
28276     LANGUAGE plpgsql
28277     AS $_$
28278 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28279 -- See www.xtuple.com/CPAL for the full text of the software license.
28280 DECLARE
28281   pCustid ALIAS FOR $1;
28282   pDocNumber ALIAS FOR $2;
28283   pOrderNumber ALIAS FOR $3;
28284   pDocDate ALIAS FOR $4;
28285   pAmount ALIAS FOR $5;
28286   pNotes ALIAS FOR $6;
28287   pJournalNumber ALIAS FOR $7;
28288   pCurrId ALIAS FOR $8;
28289   _prepaidaccntid INTEGER;
28290   _deferredaccntid INTEGER;
28291   _glSequence INTEGER;
28292   _aropenid INTEGER;
28293
28294 BEGIN
28295
28296   IF (pAmount <= 0) THEN
28297     RETURN 0;
28298   END IF;
28299
28300   _prepaidaccntid := findPrepaidAccount(pCustid);
28301   IF (_prepaidaccntid = -1) THEN
28302     RAISE EXCEPTION 'There was an error creating the Customer Deposit GL Transactions. No Prepaid Account is assigned.';
28303   END IF;
28304
28305   _deferredaccntid := findDeferredAccount(pCustid);
28306   IF (_deferredaccntid = -1) THEN
28307     RAISE EXCEPTION 'There was an error creating the Customer Deposit GL Transactions. No Deferred Account is assigned.';
28308   END IF;
28309
28310   SELECT NEXTVAL('aropen_aropen_id_seq') INTO _aropenid;
28311
28312   SELECT insertGLTransaction( pJournalNumber, 'A/R', 'CD',
28313                               pDocNumber, pNotes, _deferredaccntid, _prepaidaccntid,
28314                               _aropenid,
28315                               round(currToBase(pCurrId, pAmount, pDocDate), 2),
28316                               pDocDate) INTO _glSequence;
28317
28318   INSERT INTO aropen
28319   ( aropen_id, aropen_username, aropen_journalnumber,
28320     aropen_cust_id, aropen_docnumber, aropen_doctype, aropen_ordernumber,
28321     aropen_docdate, aropen_duedate, aropen_distdate, aropen_terms_id, aropen_salesrep_id,
28322     aropen_amount, aropen_paid, aropen_commission_due, aropen_commission_paid,
28323     aropen_applyto, aropen_ponumber, aropen_cobmisc_id,
28324     aropen_open, aropen_notes, aropen_rsncode_id,
28325     aropen_salescat_id, aropen_accnt_id, aropen_curr_id )
28326   VALUES
28327   ( _aropenid, getEffectiveXtUser(), pJournalNumber,
28328     pCustid, pDocNumber, 'R', pOrderNumber,
28329     pDocDate, pDocDate, pDocDate, -1, NULL,
28330     round(pAmount, 2), 0, 0.0, FALSE,
28331     '', '', -1,
28332     TRUE, pNotes, -1,
28333     -1, -1, pCurrId );
28334
28335   RETURN _aropenid;
28336
28337 END;
28338 $_$;
28339
28340
28341 ALTER FUNCTION public.createarcashdeposit(integer, text, text, date, numeric, text, integer, integer) OWNER TO admin;
28342
28343 --
28344 -- TOC entry 1307 (class 1255 OID 146565857)
28345 -- Dependencies: 907 4536 8
28346 -- Name: createarcreditmemo(integer, integer, text, text, date, numeric, text, integer, integer, integer, date, integer, integer, numeric, integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
28347 --
28348
28349 CREATE FUNCTION createarcreditmemo(pid integer, pcustid integer, pdocnumber text, pordernumber text, pdocdate date, pamount numeric, pnotes text, prsncodeid integer, psalescatid integer, paccntid integer, pduedate date, ptermsid integer, psalesrepid integer, pcommissiondue numeric DEFAULT 0, pjournalnumber integer DEFAULT NULL::integer, pcurrid integer DEFAULT basecurrid(), paraccntid integer DEFAULT NULL::integer, pcoccpayid integer DEFAULT NULL::integer) RETURNS integer
28350     LANGUAGE plpgsql
28351     AS $$
28352 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28353 -- See www.xtuple.com/CPAL for the full text of the software license.
28354 DECLARE
28355   _accntid        INTEGER;
28356   _arAccntid      INTEGER;
28357   _aropenid       INTEGER;
28358   _cohistid       INTEGER;
28359   _custName       TEXT;
28360   _duedate        DATE    := COALESCE(pDueDate, pDocDate);
28361   _glSequence     INTEGER;
28362   _journalNumber  INTEGER;
28363   _prepaidAccntid INTEGER;
28364   _salescatid     INTEGER;
28365   _taxBaseValue   NUMERIC;
28366   _test           INTEGER;
28367   _tmp            INTEGER;
28368
28369 BEGIN
28370
28371   _aropenid := pId;
28372
28373   IF (pAmount <= 0) THEN
28374     RETURN 0;
28375   END IF;
28376
28377   _arAccntid := COALESCE(pARAccntid, findARAccount(pCustid));
28378   _prepaidAccntid := findPrepaidAccount(pCustid);
28379
28380   _accntid := pAccntid;
28381   _salescatid := pSalescatid;
28382
28383   SELECT cust_name INTO _custName
28384   FROM custinfo
28385   WHERE (cust_id=pCustid);
28386
28387   IF EXISTS(SELECT 1 FROM accnt WHERE (accnt_id=_accntid)) THEN
28388     _prepaidAccntid := _accntid;
28389   ELSE
28390     _accntid := -1;
28391   END IF;
28392
28393   SELECT accnt_id INTO _tmp
28394     FROM salescat, accnt
28395    WHERE ((salescat_prepaid_accnt_id=accnt_id)
28396      AND  (salescat_id=_salescatid));
28397   IF (FOUND) THEN
28398     _accntid := -1;
28399     _prepaidAccntid := _tmp;
28400   ELSE
28401     _salescatid = -1;
28402   END IF;
28403
28404   IF(pJournalNumber IS NULL) THEN
28405     SELECT fetchJournalNumber('AR-MISC') INTO _journalNumber;
28406   ELSE
28407     _journalNumber := pJournalNumber;
28408   END IF;
28409
28410   _glSequence := fetchGLSequence();
28411
28412   -- CreatelUpdate aropen for full amount
28413   IF (_aropenid IS NOT NULL) THEN
28414     UPDATE aropen SET
28415       aropen_username=getEffectiveXtUser(), aropen_journalnumber=_journalNumber,
28416       aropen_cust_id=pCustid, aropen_docnumber=pDocNumber, aropen_doctype='C',
28417       aropen_ordernumber=pOrderNumber,aropen_docdate=pDocDate, aropen_duedate=_duedate,
28418       aropen_distdate=pDocDate, aropen_terms_id=pTermsid,
28419       aropen_salesrep_id=pSalesrepid, aropen_amount=round(pAmount, 2), aropen_paid=0,
28420       aropen_commission_due=pCommissiondue, aropen_commission_paid=FALSE,
28421       aropen_applyto='', aropen_ponumber='', aropen_cobmisc_id=-1,
28422       aropen_open=TRUE, aropen_notes=pNotes, aropen_rsncode_id=pRsncodeid,
28423       aropen_salescat_id=_salescatid, aropen_accnt_id=_accntid, aropen_curr_id=pCurrId
28424     WHERE aropen_id = pId;
28425   ELSE
28426     SELECT NEXTVAL('aropen_aropen_id_seq') INTO _aropenid;
28427     INSERT INTO aropen
28428     ( aropen_id, aropen_username, aropen_journalnumber,
28429       aropen_cust_id, aropen_docnumber, aropen_doctype, aropen_ordernumber,
28430       aropen_docdate, aropen_duedate, aropen_distdate, aropen_terms_id, aropen_salesrep_id,
28431       aropen_amount, aropen_paid, aropen_commission_due, aropen_commission_paid,
28432       aropen_applyto, aropen_ponumber, aropen_cobmisc_id,
28433       aropen_open, aropen_notes, aropen_rsncode_id,
28434       aropen_salescat_id, aropen_accnt_id, aropen_curr_id )
28435     VALUES
28436     ( _aropenid, getEffectiveXtUser(), _journalNumber,
28437       pCustid, pDocNumber, 'C', pOrderNumber,
28438       pDocDate, _duedate, pDocDate, pTermsid, pSalesrepid,
28439       round(pAmount, 2), 0, pCommissiondue, FALSE,
28440       '', '', -1,
28441       TRUE, pNotes, pRsncodeid,
28442       _salescatid, _accntid, pCurrId );
28443   END IF;
28444
28445   -- Credit the A/R account for the full amount
28446   SELECT insertIntoGLSeries ( _glSequence, 'A/R', 'CM',
28447                               pDocNumber, _arAccntid,
28448                               round(currToBase(pCurrId, pAmount, pDocDate), 2),
28449                               pDocDate, (_custName || ' ' || pNotes)) INTO _test;
28450
28451   -- Debit the Tax account for the tax amount
28452   _taxBaseValue := addTaxToGLSeries(_glSequence,
28453                                       'A/R', 'CM', pDocNumber,
28454                                       pCurrId, pDocDate, pDocDate,
28455                                       'aropentax', _aropenid,
28456                                       (_custName || ' ' || pNotes));
28457
28458   UPDATE aropentax SET taxhist_journalnumber = _journalNumber
28459   WHERE taxhist_parent_id=_aropenid;
28460
28461   -- Debit the Prepaid account for the basis amount
28462   -- Note, _taxBaseValue is negative so it is added to pAmount
28463   SELECT insertIntoGLSeries ( _glSequence, 'A/R', 'CM',
28464                               pDocNumber, _prepaidAccntid,
28465                               round(currToBase(pCurrId, pAmount * -1, pDocDate) + _taxBaseValue * -1, 2),
28466                               pDocDate, (_custName || ' ' || pNotes)) INTO _test;
28467
28468   --  Commit the GLSeries;
28469   SELECT postGLSeries(_glSequence, _journalNumber) INTO _test;
28470   IF (_test < 0) THEN
28471     DELETE FROM aropen WHERE (aropen_id=_aropenid);
28472     PERFORM deleteGLSeries(_glSequence);
28473     RAISE EXCEPTION 'postGLSeries commit failed with %', _test;
28474   END IF;
28475
28476   --  Record Sales History
28477   INSERT INTO cohist
28478   ( cohist_cust_id,
28479    cohist_itemsite_id, cohist_shipto_id,
28480     cohist_misc_type, cohist_misc_descrip,
28481     cohist_shipdate, cohist_shipvia,
28482     cohist_ordernumber, cohist_ponumber, cohist_orderdate,
28483     cohist_doctype, cohist_invcnumber, cohist_invcdate,
28484     cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
28485     cohist_salesrep_id,
28486     cohist_commission, cohist_commissionpaid,
28487     cohist_curr_id, cohist_sequence, cohist_cohead_ccpay_id)
28488   VALUES
28489   (CASE WHEN pCustid < 0 THEN NULL ELSE pCustid END,
28490    -1, -1,
28491     'M', 'A/R Misc Credit Memo',
28492     pDocDate, '',
28493     pOrderNumber, '', pDocDate,
28494     'C', pDocNumber, pDocDate,
28495     1, (pAmount + _taxBaseValue) * -1, 0, -- taxBaseValue is negative, so we add
28496     CASE WHEN pSalesrepid < 0 THEN NULL ELSE pSalesrepid END,
28497     (pCommissiondue * -1.0), FALSE,
28498     pCurrId, _glSequence, pCoCcpayId)
28499   RETURNING cohist_id INTO _cohistid;
28500
28501   INSERT INTO cohisttax
28502   ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
28503     taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
28504     taxhist_percent, taxhist_amount, taxhist_tax,
28505     taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
28506     taxhist_journalnumber )
28507   SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
28508          taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
28509          taxhist_percent, taxhist_amount, taxhist_tax,
28510          taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
28511          taxhist_journalnumber
28512   FROM aropentax
28513   WHERE (taxhist_parent_id=_aropenid);
28514
28515   RETURN _aropenid;
28516
28517 END;
28518 $$;
28519
28520
28521 ALTER FUNCTION public.createarcreditmemo(pid integer, pcustid integer, pdocnumber text, pordernumber text, pdocdate date, pamount numeric, pnotes text, prsncodeid integer, psalescatid integer, paccntid integer, pduedate date, ptermsid integer, psalesrepid integer, pcommissiondue numeric, pjournalnumber integer, pcurrid integer, paraccntid integer, pcoccpayid integer) OWNER TO admin;
28522
28523 --
28524 -- TOC entry 1308 (class 1255 OID 146565859)
28525 -- Dependencies: 4536 8
28526 -- Name: createardebitmemo(integer, integer, integer, text, text, date, numeric, text, integer, integer, integer, date, integer, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
28527 --
28528
28529 CREATE FUNCTION createardebitmemo(integer, integer, integer, text, text, date, numeric, text, integer, integer, integer, date, integer, integer, numeric, integer) RETURNS integer
28530     LANGUAGE plpgsql
28531     AS $_$
28532 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28533 -- See www.xtuple.com/CPAL for the full text of the software license.
28534 DECLARE
28535   pId                   ALIAS FOR $1;
28536   pCustid               ALIAS FOR $2;
28537   pJournalNumber        ALIAS FOR $3;
28538   pDocNumber            ALIAS FOR $4;
28539   pOrderNumber          ALIAS FOR $5;
28540   pDocDate              ALIAS FOR $6;
28541   pAmount               ALIAS FOR $7;
28542   pNotes                ALIAS FOR $8;
28543   pRsncodeid            ALIAS FOR $9;
28544   pSalescatid           ALIAS FOR $10;
28545   pAccntid              ALIAS FOR $11;
28546   pDueDate              ALIAS FOR $12;
28547   pTermsid              ALIAS FOR $13;
28548   pSalesrepid           ALIAS FOR $14;
28549   pCommissiondue        ALIAS FOR $15;
28550   pCurrId               ALIAS FOR $16;
28551   _custName TEXT;
28552   _journalNumber INTEGER;
28553   _arAccntid INTEGER;
28554   _prepaidAccntid INTEGER;
28555   _salescatid INTEGER;
28556   _accntid INTEGER;
28557   _glSequence INTEGER;
28558   _aropenid INTEGER;
28559   _cohistid INTEGER;
28560   _tmp INTEGER;
28561   _test INTEGER;
28562   _taxBaseValue NUMERIC;
28563
28564 BEGIN
28565   _aropenid=pId;
28566   
28567   IF (pAmount <= 0) THEN
28568     RETURN 0;
28569   END IF;
28570
28571   SELECT findARAccount(pCustid) INTO _arAccntid;
28572   SELECT findPrepaidAccount(pCustid) INTO _prepaidAccntid;
28573
28574   _accntid := pAccntid;
28575   _salescatid := pSalescatid;
28576
28577   SELECT cust_name INTO _custName
28578   FROM custinfo
28579   WHERE (cust_id=pCustid);
28580   
28581   PERFORM accnt_id
28582      FROM accnt
28583     WHERE (accnt_id=_accntid);
28584   IF (FOUND) THEN
28585     _prepaidAccntid := _accntid;
28586   ELSE
28587     _accntid := -1;
28588   END IF;
28589
28590   SELECT accnt_id INTO _tmp
28591     FROM salescat, accnt
28592    WHERE ((salescat_prepaid_accnt_id=accnt_id)
28593      AND  (salescat_id=_salescatid));
28594   IF (FOUND) THEN
28595     _accntid := -1;
28596     _prepaidAccntid := _tmp;
28597   ELSE
28598     _salescatid = -1;
28599   END IF;
28600
28601   IF (pJournalNumber IS NULL) THEN
28602     _journalNumber := fetchJournalNumber('AR-MISC');
28603   ELSE
28604     _journalNumber := pJournalNumber;
28605   END IF;
28606
28607   SELECT fetchGLSequence() INTO _glSequence;
28608
28609   -- CreatelUpdate aropen for full amount
28610   IF (_aropenid IS NOT NULL) THEN
28611     UPDATE aropen SET
28612       aropen_username=getEffectiveXtUser(), aropen_journalnumber=_journalNumber,
28613       aropen_cust_id=pCustid, aropen_docnumber=pDocNumber, aropen_doctype='D', 
28614       aropen_ordernumber=pOrderNumber,aropen_docdate=pDocDate, aropen_duedate=pDueDate, 
28615       aropen_distdate=pDocDate, aropen_terms_id=pTermsid, 
28616       aropen_salesrep_id=pSalesrepid, aropen_amount=round(pAmount, 2), aropen_paid=0, 
28617       aropen_commission_due=pCommissiondue, aropen_commission_paid=FALSE,
28618       aropen_applyto='', aropen_ponumber='', aropen_cobmisc_id=-1,
28619       aropen_open=TRUE, aropen_notes=pNotes, aropen_rsncode_id=pRsncodeid,
28620       aropen_salescat_id=_salescatid, aropen_accnt_id=_accntid, aropen_curr_id=pCurrId
28621     WHERE aropen_id = pId;
28622   ELSE
28623     SELECT NEXTVAL('aropen_aropen_id_seq') INTO _aropenid;
28624     INSERT INTO aropen
28625     ( aropen_id, aropen_username, aropen_journalnumber,
28626       aropen_cust_id, aropen_docnumber, aropen_doctype, aropen_ordernumber,
28627       aropen_docdate, aropen_duedate, aropen_distdate, aropen_terms_id, aropen_salesrep_id,
28628       aropen_amount, aropen_paid, aropen_commission_due, aropen_commission_paid,
28629       aropen_applyto, aropen_ponumber, aropen_cobmisc_id,
28630       aropen_open, aropen_notes, aropen_rsncode_id,
28631       aropen_salescat_id, aropen_accnt_id, aropen_curr_id )
28632     VALUES
28633     ( _aropenid, getEffectiveXtUser(), _journalNumber,
28634       pCustid, pDocNumber, 'D', pOrderNumber,
28635       pDocDate, pDueDate, pDocDate, pTermsid, pSalesrepid,
28636       round(pAmount, 2), 0, pCommissiondue, FALSE,
28637       '', '', -1,
28638       TRUE, pNotes, pRsncodeid,
28639       _salescatid, _accntid, pCurrId );
28640   END IF;
28641
28642   -- Debit the A/R account for the full amount
28643   SELECT insertIntoGLSeries ( _glSequence, 'A/R', 'DM',
28644                               pDocNumber, _arAccntid,
28645                               round(currToBase(pCurrId, pAmount, pDocDate) * -1, 2),
28646                               pDocDate, (_custName || ' ' || pNotes)) INTO _test;
28647
28648   -- Credit the Tax account for the tax amount
28649   _taxBaseValue := addTaxToGLSeries(_glSequence,
28650                                       'A/R', 'DM', pDocNumber,
28651                                       pCurrId, pDocDate, pDocDate,
28652                                       'aropentax', _aropenid,
28653                                       (_custName || ' ' || pNotes));
28654
28655   UPDATE aropentax SET taxhist_journalnumber = _journalNumber
28656   WHERE taxhist_parent_id=_aropenid;
28657
28658   -- Credit the Prepaid account for the basis amount
28659   SELECT insertIntoGLSeries ( _glSequence, 'A/R', 'DM',
28660                               pDocNumber, _prepaidAccntid,
28661                               round(currToBase(pCurrId, (pAmount), pDocDate), 2) - _taxBaseValue,
28662                               pDocDate, (_custName || ' ' || pNotes)) INTO _test;
28663
28664   --  Commit the GLSeries;
28665   SELECT postGLSeries(_glSequence, _journalNumber) INTO _test;
28666   IF (_test < 0) THEN
28667     DELETE FROM aropen WHERE (aropen_id=_aropenid);
28668     PERFORM deleteGLSeries(_glSequence);
28669     RAISE EXCEPTION 'postGLSeries commit failed with %', _test;
28670   END IF;
28671
28672   --  Record Sales History
28673   SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
28674   INSERT INTO cohist
28675   ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
28676     cohist_misc_type, cohist_misc_descrip,
28677     cohist_shipdate, cohist_shipvia,
28678     cohist_ordernumber, cohist_ponumber, cohist_orderdate,
28679     cohist_doctype, cohist_invcnumber, cohist_invcdate,
28680     cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
28681     cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
28682     cohist_curr_id, cohist_sequence )
28683   VALUES
28684   ( _cohistid, pCustid, -1, -1,
28685     'M', 'A/R Misc Debit Memo',
28686     pDocDate, '',
28687     '', '', pDocDate,
28688     'D', pDocNumber, pDocDate,
28689     1, (pAmount - _taxBaseValue), 0,
28690     pSalesrepid, pCommissiondue, FALSE,
28691     pCurrId, _glSequence );
28692   INSERT INTO cohisttax
28693   ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
28694     taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
28695     taxhist_percent, taxhist_amount, taxhist_tax,
28696     taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
28697     taxhist_journalnumber )
28698   SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
28699          taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
28700          taxhist_percent, taxhist_amount, taxhist_tax,
28701          taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
28702          taxhist_journalnumber
28703   FROM aropentax
28704   WHERE (taxhist_parent_id=_aropenid);
28705
28706   RETURN _aropenid;
28707
28708 END;
28709 $_$;
28710
28711
28712 ALTER FUNCTION public.createardebitmemo(integer, integer, integer, text, text, date, numeric, text, integer, integer, integer, date, integer, integer, numeric, integer) OWNER TO admin;
28713
28714 --
28715 -- TOC entry 1309 (class 1255 OID 146565861)
28716 -- Dependencies: 4536 8
28717 -- Name: createbillingheader(integer); Type: FUNCTION; Schema: public; Owner: admin
28718 --
28719
28720 CREATE FUNCTION createbillingheader(integer) RETURNS integer
28721     LANGUAGE plpgsql
28722     AS $_$
28723 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28724 -- See www.xtuple.com/CPAL for the full text of the software license.
28725 DECLARE
28726   pSoheadid             ALIAS FOR $1;
28727   _cobmiscid            INTEGER;
28728   _cohead               cohead%ROWTYPE;
28729   _miscApplied          NUMERIC := 0.0;
28730   _freight              NUMERIC;
28731   _freighttypeid        INTEGER;
28732   _invcDate             DATE;
28733   _schedDate            DATE;
28734   _shipDate             DATE;
28735   _shipVia              TEXT;
28736   _tax                  NUMERIC;
28737
28738 BEGIN
28739
28740   --  Fetch cohead
28741   SELECT * INTO _cohead
28742   FROM cohead
28743   WHERE (cohead_id=pSoheadid);
28744
28745   --  Check for an existing cobmisc
28746   SELECT cobmisc_id INTO _cobmiscid
28747   FROM cobmisc
28748   WHERE ( (NOT cobmisc_posted)
28749    AND (cobmisc_cohead_id=pSoheadid) );
28750
28751   IF (FOUND) THEN
28752   --  Find a Shipping-Entered freight charge
28753     SELECT SUM(currToCurr(shiphead_freight_curr_id, _cohead.cohead_curr_id,
28754                           shiphead_freight, CURRENT_DATE)) INTO _freight
28755     FROM (
28756     SELECT shiphead_id, shiphead_freight_curr_id, shiphead_freight
28757     FROM shiphead JOIN shipitem ON (shipitem_shiphead_id=shiphead_id AND NOT shipitem_invoiced)
28758     WHERE ((shiphead_order_type='SO')
28759       AND  (shiphead_order_id=pSoheadid))
28760     GROUP BY shiphead_id, shiphead_freight_curr_id, shiphead_freight) AS data;
28761
28762     IF (_freight IS NOT NULL) THEN
28763       UPDATE cobmisc SET cobmisc_freight = _freight
28764       WHERE (cobmisc_id=_cobmiscid);
28765     END IF;
28766
28767     RETURN _cobmiscid;
28768   END IF;
28769
28770   --  Find misc charges that have already been applied for the S/O
28771   SELECT COALESCE(SUM(cobmisc_misc), 0.0) INTO _miscApplied
28772   FROM cobmisc
28773   WHERE (cobmisc_cohead_id=pSoheadid);
28774
28775   SELECT NEXTVAL('cobmisc_cobmisc_id_seq') INTO _cobmiscid;
28776
28777   --  Check for a valid shipdate
28778   SELECT MIN(shiphead_shipdate) INTO _shipDate
28779   FROM shiphead, shipitem
28780   WHERE ( (shipitem_shiphead_id=shiphead_id)
28781    AND (NOT shipitem_invoiced)
28782    AND (shiphead_shipped)
28783    AND (shiphead_order_type='SO')
28784    AND (shiphead_order_id=pSoheadid) );
28785
28786   --  Schema shouldn't allow, but we'll try for now
28787   IF (_shipDate IS NULL) THEN
28788     SELECT MAX(shipitem_shipdate) INTO _shipDate
28789     FROM shipitem, shiphead
28790     WHERE ( (shipitem_shiphead_id=shiphead_id)
28791      AND (shiphead_order_type='SO')
28792      AND (shiphead_order_id=pSoheadid) );
28793
28794     --  How about a transaction date
28795     IF (_shipDate IS NULL) THEN
28796       SELECT COALESCE(MAX(shipitem_transdate), CURRENT_DATE) INTO _shipDate
28797       FROM shipitem, shiphead
28798       WHERE ((shipitem_shiphead_id=shiphead_id)
28799         AND  (shiphead_order_type='SO')
28800         AND  (shiphead_order_id=pSoheadid) );
28801     END IF;
28802   END IF;
28803
28804   --  Get the earliest schedule date for this order.
28805   SELECT MIN(coitem_scheddate) INTO _schedDate
28806     FROM coitem
28807    WHERE ((coitem_status <> 'X') AND (coitem_cohead_id=pSoheadid));
28808
28809   IF (_schedDate IS NULL) THEN
28810     _schedDate := _shipDate;
28811   END IF;
28812
28813   --  Find a Shipping-Entered freight charge
28814   SELECT SUM(currToCurr(shiphead_freight_curr_id, _cohead.cohead_curr_id,
28815                         shiphead_freight, CURRENT_DATE)), shiphead_shipvia
28816          INTO _freight, _shipVia
28817   FROM (
28818   SELECT shiphead_id, shiphead_freight_curr_id, shiphead_freight, shiphead_shipvia
28819   FROM shiphead JOIN shipitem ON (shipitem_shiphead_id=shiphead_id AND NOT shipitem_invoiced)
28820   WHERE ((shiphead_order_type='SO')
28821     AND  (shiphead_order_id=pSoheadid))
28822   GROUP BY shiphead_id, shiphead_freight_curr_id, shiphead_freight, shiphead_shipvia) AS data
28823   GROUP BY shiphead_shipvia;
28824
28825   --  Nope, use the cohead freight charge
28826   IF (_freight IS NULL) THEN
28827     _freight       := _cohead.cohead_freight;
28828   END IF;
28829
28830   --  Finally, look for a Shipping-Entered Ship Via
28831   SELECT shiphead_shipvia INTO _shipVia
28832   FROM shiphead, shipitem
28833   WHERE ( (shipitem_shiphead_id=shiphead_id)
28834    AND (NOT shipitem_invoiced)
28835    AND (shiphead_order_type='SO')
28836    AND (shiphead_order_id=pSoheadid) )
28837   LIMIT 1;
28838   IF (NOT FOUND) THEN
28839     _shipVia := _cohead.cohead_shipvia;
28840   END IF;
28841
28842   --Determine any tax
28843
28844   SELECT 
28845   getFreightTaxTypeId() INTO _freighttypeid;
28846   SELECT SUM(COALESCE(taxdetail_tax, 0.00)) INTO _tax
28847   FROM calculatetaxdetail(_cohead.cohead_taxzone_id, _freighttypeid, _cohead.cohead_orderdate,_cohead.cohead_curr_id, _freight);
28848
28849   --  Determine if we are using the _shipDate or _schedDate or current_date for the _invcDate
28850   IF( fetchMetricText('InvoiceDateSource')='scheddate') THEN
28851     _invcDate := _schedDate;
28852   ELSIF( fetchMetricText('InvoiceDateSource')='shipdate') THEN
28853     _invcDate := _shipDate;
28854   ELSE
28855     _invcDate := current_date;
28856   END IF;
28857
28858    INSERT INTO cobmisc (
28859         cobmisc_id, cobmisc_cohead_id, cobmisc_shipvia, cobmisc_freight, cobmisc_misc, cobmisc_payment 
28860         ,cobmisc_notes,cobmisc_shipdate ,cobmisc_invcdate,cobmisc_posted ,cobmisc_misc_accnt_id 
28861         ,cobmisc_misc_descrip,cobmisc_closeorder,cobmisc_curr_id
28862         ,cobmisc_taxtype_id,cobmisc_taxzone_id
28863         )
28864         SELECT
28865         _cobmiscid,_cohead.cohead_id,_shipVia,_freight,
28866         CASE WHEN (_cohead.cohead_misc - _miscApplied = 0.0) THEN 0.0
28867              ELSE (_cohead.cohead_misc - _miscApplied) END,0,
28868         _cohead.cohead_ordercomments,_shipDate,_invcDate,FALSE,_cohead.cohead_misc_accnt_id,
28869         _cohead.cohead_misc_descrip,NOT(cust_backorder),_cohead.cohead_curr_id,
28870         _cohead.cohead_taxtype_id,_cohead.cohead_taxzone_id
28871         FROM custinfo
28872         WHERE (cust_id=_cohead.cohead_cust_id);
28873
28874   RETURN _cobmiscid;
28875
28876 END;
28877 $_$;
28878
28879
28880 ALTER FUNCTION public.createbillingheader(integer) OWNER TO admin;
28881
28882 --
28883 -- TOC entry 1310 (class 1255 OID 146565863)
28884 -- Dependencies: 4536 8
28885 -- Name: createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
28886 --
28887
28888 CREATE FUNCTION createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text) RETURNS integer
28889     LANGUAGE plpgsql
28890     AS $_$
28891 DECLARE
28892   pBomitemid ALIAS FOR $1;
28893   pParentItemid ALIAS FOR $2;
28894   pComponentItemid ALIAS FOR $3;
28895   pSeqNumber ALIAS FOR $4;
28896   pIssueMethod ALIAS FOR $5;
28897   pUomId ALIAS FOR $6;
28898   pQtyPer ALIAS FOR $7;
28899   pScrap ALIAS FOR $8;
28900   pEffective ALIAS FOR $9;
28901   pExpires ALIAS FOR $10;
28902   pCreateWo ALIAS FOR $11;
28903   pBOOItemseqid ALIAS FOR $12;
28904   pSchedAtWooper ALIAS FOR $13;
28905   pECN ALIAS FOR $14;
28906   pSubType ALIAS FOR $15;
28907   pRevisionid ALIAS FOR $16;
28908   pCharId ALIAS FOR $17;
28909   pCharVal ALIAS FOR $18;
28910   _bomworksetid INTEGER;
28911   _temp INTEGER;
28912   _bomitemid INTEGER;
28913
28914 BEGIN
28915
28916   SELECT createBOMItem( pBomitemid, pParentItemid, pComponentItemid,
28917                         pSeqNumber, pIssueMethod,
28918                         pUomId, pQtyPer, pScrap,
28919                         pEffective, pExpires,
28920                         pCreateWo, pBOOItemseqid, pSchedAtWooper, pECN, pSubType, pRevisionid, pCharId, pCharVal, NULL, NULL ) INTO _bomitemid;
28921
28922   RETURN _bomitemid;
28923   
28924 END;
28925 $_$;
28926
28927
28928 ALTER FUNCTION public.createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text) OWNER TO admin;
28929
28930 --
28931 -- TOC entry 1312 (class 1255 OID 146565865)
28932 -- Dependencies: 4536 8
28933 -- Name: createbomitem(integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
28934 --
28935
28936 CREATE FUNCTION createbomitem(integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) RETURNS integer
28937     LANGUAGE plpgsql
28938     AS $_$
28939 DECLARE
28940   pBomitemid ALIAS FOR $1;
28941   pParentItemid ALIAS FOR $2;
28942   pComponentItemid ALIAS FOR $3;
28943   pIssueMethod ALIAS FOR $4;
28944   pUomId ALIAS FOR $5;
28945   pQtyPer ALIAS FOR $6;
28946   pScrap ALIAS FOR $7;
28947   pEffective ALIAS FOR $8;
28948   pExpires ALIAS FOR $9;
28949   pCreateWo ALIAS FOR $10;
28950   pBOOItemseqid ALIAS FOR $11;
28951   pSchedAtWooper ALIAS FOR $12;
28952   pECN ALIAS FOR $13;
28953   pSubType ALIAS FOR $14;
28954   pRevisionid ALIAS FOR $15;
28955   pCharId ALIAS FOR $16;
28956   pCharVal ALIAS FOR $17;
28957   pNotes ALIAS FOR $18;
28958   pRef ALIAS FOR $19;
28959   _seqNumber INTEGER;
28960   _bomitemid INTEGER;
28961
28962 BEGIN
28963
28964 --  Grab the next Sequence Number, if any
28965   SELECT MAX(bomitem_seqnumber) INTO _seqNumber
28966   FROM bomitem(pParentItemid,pRevisionid);
28967
28968   IF (_seqNumber IS NOT NULL) THEN
28969    _seqNumber := (_seqNumber + 10);
28970   ELSE
28971    _seqNumber := 10;
28972   END IF;
28973
28974   SELECT createBOMItem( pBomitemid, pParentItemid, pComponentItemid,
28975                         _seqNumber, pIssueMethod,
28976                         pUomId, pQtyPer, pScrap,
28977                         pEffective, pExpires,
28978                         pCreateWo, pBOOItemseqid, pSchedAtWooper, pECN, pSubType, pRevisionid, pCharId, pCharVal, pNotes, pRef ) INTO _bomitemid;
28979
28980   RETURN _bomitemid;
28981
28982 END;
28983 $_$;
28984
28985
28986 ALTER FUNCTION public.createbomitem(integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) OWNER TO admin;
28987
28988 --
28989 -- TOC entry 1315 (class 1255 OID 146565867)
28990 -- Dependencies: 4536 8
28991 -- Name: createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
28992 --
28993
28994 CREATE FUNCTION createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text) RETURNS integer
28995     LANGUAGE plpgsql
28996     AS $_$
28997 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
28998 -- See www.xtuple.com/CPAL for the full text of the software license.
28999 DECLARE
29000   pBomitemid ALIAS FOR $1;
29001   pParentItemid ALIAS FOR $2;
29002   pComponentItemid ALIAS FOR $3;
29003   pSeqNumber ALIAS FOR $4;
29004   pIssueMethod ALIAS FOR $5;
29005   pUomId ALIAS FOR $6;
29006   pQtyFxd ALIAS FOR $7;
29007   pQtyPer ALIAS FOR $8;
29008   pScrap ALIAS FOR $9;
29009   pEffective ALIAS FOR $10;
29010   pExpires ALIAS FOR $11;
29011   pCreateWo ALIAS FOR $12;
29012   pBOOItemseqid ALIAS FOR $13;
29013   pSchedAtWooper ALIAS FOR $14;
29014   pECN ALIAS FOR $15;
29015   pSubType ALIAS FOR $16;
29016   pRevisionid ALIAS FOR $17;
29017   pCharId ALIAS FOR $18;
29018   pCharVal ALIAS FOR $19;
29019   _bomworksetid INTEGER;
29020   _temp INTEGER;
29021   _bomitemid INTEGER;
29022
29023 BEGIN
29024
29025   SELECT createBOMItem( pBomitemid, pParentItemid, pComponentItemid,
29026                         pSeqNumber, pIssueMethod,
29027                         pUomId, pQtyFxd, pQtyPer, pScrap,
29028                         pEffective, pExpires,
29029                         pCreateWo, pBOOItemseqid, pSchedAtWooper, pECN, pSubType, pRevisionid, pCharId, pCharVal, NULL, NULL ) INTO _bomitemid;
29030
29031   RETURN _bomitemid;
29032   
29033 END;
29034 $_$;
29035
29036
29037 ALTER FUNCTION public.createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text) OWNER TO admin;
29038
29039 --
29040 -- TOC entry 1311 (class 1255 OID 146565864)
29041 -- Dependencies: 4536 8
29042 -- Name: createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
29043 --
29044
29045 CREATE FUNCTION createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) RETURNS integer
29046     LANGUAGE plpgsql
29047     AS $_$
29048 DECLARE
29049   pBomitemid ALIAS FOR $1;
29050   pParentItemid ALIAS FOR $2;
29051   pComponentItemid ALIAS FOR $3;
29052   pSeqNumber ALIAS FOR $4;
29053   pIssueMethod ALIAS FOR $5;
29054   pUomId ALIAS FOR $6;
29055   pQtyPer ALIAS FOR $7;
29056   pScrap ALIAS FOR $8;
29057   pEffective ALIAS FOR $9;
29058   pExpires ALIAS FOR $10;
29059   pCreateWo ALIAS FOR $11;
29060   pBOOItemseqid ALIAS FOR $12;
29061   pSchedAtWooper ALIAS FOR $13;
29062   pECN ALIAS FOR $14;
29063   pSubType ALIAS FOR $15;
29064   pRevisionid ALIAS FOR $16;
29065   pCharId ALIAS FOR $17;
29066   pCharVal ALIAS FOR $18;
29067   pNotes ALIAS FOR $19;
29068   pRef ALIAS FOR $20;
29069   _bomworksetid INTEGER;
29070   _temp INTEGER;
29071
29072 BEGIN
29073
29074 --  Make sure that the parent and component are not the same
29075   IF (pParentItemid = pComponentItemid) THEN
29076     RETURN -1;
29077   END IF;
29078
29079 --  Make sure that the parent is not used in the component at some level
29080   IF ( SELECT (item_type IN ('M', 'F'))
29081        FROM item
29082        WHERE (item_id=pComponentItemid) ) THEN
29083     SELECT indentedWhereUsed(pParentItemid) INTO _bomworksetid;
29084     SELECT bomwork_id INTO _temp
29085     FROM bomwork
29086     WHERE ( (bomwork_set_id=_bomworksetid)
29087      AND (bomwork_item_id=pComponentItemid) )
29088     LIMIT 1;
29089     IF (FOUND) THEN
29090       PERFORM deleteBOMWorkset(_bomworksetid);
29091       RETURN -2;
29092     END IF;
29093   END IF;
29094
29095   PERFORM deleteBOMWorkset(_bomworksetid);
29096
29097 --  Create the BOM Item
29098   INSERT INTO bomitem
29099   ( bomitem_id, bomitem_parent_item_id, bomitem_item_id,
29100     bomitem_seqnumber, bomitem_issuemethod,
29101     bomitem_uom_id, bomitem_qtyper, bomitem_scrap,
29102     bomitem_effective, bomitem_expires,
29103     bomitem_createwo,
29104     bomitem_booitem_seq_id, bomitem_schedatwooper,
29105     bomitem_ecn, bomitem_subtype, bomitem_moddate, bomitem_rev_id,
29106     bomitem_char_id, bomitem_value, bomitem_notes, bomitem_ref )
29107   VALUES
29108   ( pBomitemid, pParentItemid, pComponentItemid,
29109     pSeqNumber, pIssueMethod,
29110     pUomId, pQtyPer, pScrap,
29111     pEffective, pExpires,
29112     pCreateWo,
29113     pBOOItemseqid, COALESCE(pSchedAtWooper, FALSE),
29114     pECN, pSubType, CURRENT_DATE, pRevisionid,
29115     pCharId,pCharVal,pNotes, pRef );
29116
29117   RETURN pBomitemid;
29118
29119 END;
29120 $_$;
29121
29122
29123 ALTER FUNCTION public.createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) OWNER TO admin;
29124
29125 --
29126 -- TOC entry 1316 (class 1255 OID 146565868)
29127 -- Dependencies: 4536 8
29128 -- Name: createbomitem(integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
29129 --
29130
29131 CREATE FUNCTION createbomitem(integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) RETURNS integer
29132     LANGUAGE plpgsql
29133     AS $_$
29134 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29135 -- See www.xtuple.com/CPAL for the full text of the software license.
29136 DECLARE
29137   pBomitemid ALIAS FOR $1;
29138   pParentItemid ALIAS FOR $2;
29139   pComponentItemid ALIAS FOR $3;
29140   pIssueMethod ALIAS FOR $4;
29141   pUomId ALIAS FOR $5;
29142   pQtyFxd ALIAS FOR $6;
29143   pQtyPer ALIAS FOR $7;
29144   pScrap ALIAS FOR $8;
29145   pEffective ALIAS FOR $9;
29146   pExpires ALIAS FOR $10;
29147   pCreateWo ALIAS FOR $11;
29148   pBOOItemseqid ALIAS FOR $12;
29149   pSchedAtWooper ALIAS FOR $13;
29150   pECN ALIAS FOR $14;
29151   pSubType ALIAS FOR $15;
29152   pRevisionid ALIAS FOR $16;
29153   pCharId ALIAS FOR $17;
29154   pCharVal ALIAS FOR $18;
29155   pNotes ALIAS FOR $19;
29156   pRef ALIAS FOR $20;
29157   _seqNumber INTEGER;
29158   _bomitemid INTEGER;
29159
29160 BEGIN
29161
29162 --  Grab the next Sequence Number, if any
29163   SELECT MAX(bomitem_seqnumber) INTO _seqNumber
29164   FROM bomitem(pParentItemid,pRevisionid);
29165
29166   IF (_seqNumber IS NOT NULL) THEN
29167    _seqNumber := (_seqNumber + 10);
29168   ELSE
29169    _seqNumber := 10;
29170   END IF;
29171
29172   SELECT createBOMItem( pBomitemid, pParentItemid, pComponentItemid,
29173                         _seqNumber, pIssueMethod,
29174                         pUomId, pQtyFxd, pQtyPer, pScrap,
29175                         pEffective, pExpires,
29176                         pCreateWo, pBOOItemseqid, pSchedAtWooper, pECN, pSubType, pRevisionid, pCharId, pCharVal, pNotes, pRef ) INTO _bomitemid;
29177
29178   RETURN _bomitemid;
29179
29180 END;
29181 $_$;
29182
29183
29184 ALTER FUNCTION public.createbomitem(integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) OWNER TO admin;
29185
29186 --
29187 -- TOC entry 1314 (class 1255 OID 146565866)
29188 -- Dependencies: 4536 8
29189 -- Name: createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
29190 --
29191
29192 CREATE FUNCTION createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) RETURNS integer
29193     LANGUAGE plpgsql
29194     AS $_$
29195 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29196 -- See www.xtuple.com/CPAL for the full text of the software license.
29197 DECLARE
29198   pBomitemid ALIAS FOR $1;
29199   pParentItemid ALIAS FOR $2;
29200   pComponentItemid ALIAS FOR $3;
29201   pSeqNumber ALIAS FOR $4;
29202   pIssueMethod ALIAS FOR $5;
29203   pUomId ALIAS FOR $6;
29204   pQtyFxd ALIAS FOR $7;
29205   pQtyPer ALIAS FOR $8;
29206   pScrap ALIAS FOR $9;
29207   pEffective ALIAS FOR $10;
29208   pExpires ALIAS FOR $11;
29209   pCreateWo ALIAS FOR $12;
29210   pBOOItemseqid ALIAS FOR $13;
29211   pSchedAtWooper ALIAS FOR $14;
29212   pECN ALIAS FOR $15;
29213   pSubType ALIAS FOR $16;
29214   pRevisionid ALIAS FOR $17;
29215   pCharId ALIAS FOR $18;
29216   pCharVal ALIAS FOR $19;
29217   pNotes ALIAS FOR $20;
29218   pRef ALIAS FOR $21;
29219   _bomworksetid INTEGER;
29220   _temp INTEGER;
29221
29222 BEGIN
29223
29224 --  Make sure that the parent and component are not the same
29225   IF (pParentItemid = pComponentItemid) THEN
29226     RETURN -1;
29227   END IF;
29228
29229 --  Make sure that the parent is not used in the component at some level
29230   SELECT indentedWhereUsed(pParentItemid) INTO _bomworksetid;
29231   SELECT bomwork_id INTO _temp
29232   FROM bomwork
29233   WHERE ( (bomwork_set_id=_bomworksetid)
29234    AND (bomwork_item_id=pComponentItemid) )
29235   LIMIT 1;
29236   IF (FOUND) THEN
29237     PERFORM deleteBOMWorkset(_bomworksetid);
29238     RETURN -2;
29239   END IF;
29240
29241   PERFORM deleteBOMWorkset(_bomworksetid);
29242
29243 --  Create the BOM Item
29244   INSERT INTO bomitem
29245   ( bomitem_id, bomitem_parent_item_id, bomitem_item_id,
29246     bomitem_seqnumber, bomitem_issuemethod,
29247     bomitem_uom_id, bomitem_qtyfxd, bomitem_qtyper, bomitem_scrap,
29248     bomitem_effective, bomitem_expires,
29249     bomitem_createwo,
29250     bomitem_booitem_seq_id, bomitem_schedatwooper,
29251     bomitem_ecn, bomitem_subtype, bomitem_moddate, bomitem_rev_id,
29252     bomitem_char_id, bomitem_value, bomitem_notes, bomitem_ref )
29253   VALUES
29254   ( pBomitemid, pParentItemid, pComponentItemid,
29255     pSeqNumber, pIssueMethod,
29256     pUomId, pQtyFxd, pQtyPer, pScrap,
29257     pEffective, pExpires,
29258     pCreateWo,
29259     pBOOItemseqid, COALESCE(pSchedAtWooper, FALSE),
29260     pECN, pSubType, CURRENT_DATE, pRevisionid,
29261     pCharId,pCharVal,pNotes, pRef );
29262
29263   RETURN pBomitemid;
29264
29265 END;
29266 $_$;
29267
29268
29269 ALTER FUNCTION public.createbomitem(integer, integer, integer, integer, character, integer, numeric, numeric, numeric, date, date, boolean, integer, boolean, text, character, integer, integer, text, text, text) OWNER TO admin;
29270
29271 --
29272 -- TOC entry 1317 (class 1255 OID 146565869)
29273 -- Dependencies: 4536 8
29274 -- Name: createcheck(integer, text, integer, date, numeric, integer, integer, integer, text, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
29275 --
29276
29277 CREATE FUNCTION createcheck(integer, text, integer, date, numeric, integer, integer, integer, text, text, boolean) RETURNS integer
29278     LANGUAGE plpgsql
29279     AS $_$
29280 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29281 -- See www.xtuple.com/CPAL for the full text of the software license.
29282 DECLARE
29283   pBankaccntid          ALIAS FOR  $1;
29284   pRecipType            ALIAS FOR  $2;
29285   pRecipId              ALIAS FOR  $3;
29286   pCheckDate            ALIAS FOR  $4;
29287   pAmount               ALIAS FOR  $5;
29288   pCurrid               ALIAS FOR  $6;
29289   pExpcatid             ALIAS FOR  $7;
29290   _journalNumber        INTEGER := $8;
29291   pFor                  ALIAS FOR  $9;
29292   pNotes                ALIAS FOR $10;
29293   pMisc                 ALIAS FOR $11;
29294   _checkid INTEGER;
29295 BEGIN
29296
29297   SELECT createCheck(pBankaccntid,pRecipType,pRecipId,pCheckDate,pAmount,pCurrid,pExpcatid,_journalNumber,pFor,pNotes,pMisc,NULL) INTO _checkid;
29298   RETURN _checkid;
29299
29300 END;
29301 $_$;
29302
29303
29304 ALTER FUNCTION public.createcheck(integer, text, integer, date, numeric, integer, integer, integer, text, text, boolean) OWNER TO admin;
29305
29306 --
29307 -- TOC entry 1318 (class 1255 OID 146565870)
29308 -- Dependencies: 4536 8
29309 -- Name: createcheck(integer, text, integer, date, numeric, integer, integer, integer, text, text, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
29310 --
29311
29312 CREATE FUNCTION createcheck(integer, text, integer, date, numeric, integer, integer, integer, text, text, boolean, integer) RETURNS integer
29313     LANGUAGE plpgsql
29314     AS $_$
29315 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29316 -- See www.xtuple.com/CPAL for the full text of the software license.
29317 DECLARE
29318   pBankaccntid          ALIAS FOR  $1;
29319   pRecipType            ALIAS FOR  $2;
29320   pRecipId              ALIAS FOR  $3;
29321   pCheckDate            ALIAS FOR  $4;
29322   pAmount               ALIAS FOR  $5;
29323   pCurrid               ALIAS FOR  $6;
29324   pExpcatid             ALIAS FOR  $7;
29325   _journalNumber        INTEGER := $8;
29326   pFor                  ALIAS FOR  $9;
29327   pNotes                ALIAS FOR $10;
29328   pMisc                 ALIAS FOR $11;
29329   pAropenid             ALIAS FOR $12;
29330   _checkid              INTEGER;
29331   _check_curr_rate      NUMERIC;
29332   _bankaccnt_currid     INTEGER;
29333
29334 BEGIN
29335   SELECT bankaccnt_curr_id,currRate(bankaccnt_curr_id,pCheckDate) INTO _bankaccnt_currid, _check_curr_rate
29336   FROM bankaccnt
29337   WHERE bankaccnt_id = pBankaccntid;
29338   IF (NOT FOUND) THEN
29339     RETURN -1;
29340   END IF;
29341
29342   IF (pRecipType NOT IN ('C', 'T', 'V')) THEN
29343     RETURN -2;
29344   END IF;
29345
29346   IF (pCheckDate IS NULL) THEN
29347     RETURN -3;
29348   END IF;
29349
29350   IF (pAmount <= 0) THEN
29351     RETURN -4;
29352   END IF;
29353
29354   IF (pCurrid IS NULL
29355       OR NOT EXISTS(SELECT * FROM curr_symbol WHERE (curr_id=pCurrid))) THEN
29356     RETURN -5;
29357   END IF;
29358
29359   IF (pExpcatid IS NOT NULL
29360       AND NOT EXISTS(SELECT * FROM expcat WHERE (expcat_id=pExpcatid))) THEN
29361     RETURN -6;
29362   END IF;
29363
29364 -- Do not assign Journal Number until check is posted
29365 --  if (_journalNumber IS NULL) THEN
29366 --    _journalNumber := fetchJournalNumber('AP-CK');
29367 --  END IF;
29368
29369   _checkid := NEXTVAL('checkhead_checkhead_id_seq');
29370
29371   INSERT INTO checkhead
29372   ( checkhead_id,               checkhead_recip_type,   checkhead_recip_id,
29373     checkhead_bankaccnt_id,     checkhead_number,
29374     checkhead_amount,
29375     checkhead_checkdate,        checkhead_misc,         checkhead_expcat_id,
29376     checkhead_journalnumber,    checkhead_for,          checkhead_notes,
29377     checkhead_curr_id )
29378   VALUES
29379   ( _checkid,                   pRecipType,             pRecipId,
29380     pBankaccntid,               -1, --fetchNextCheckNumber(pBankaccntid),
29381     currToCurr(pCurrid, _bankaccnt_currid, pAmount, pCheckDate),
29382     pCheckDate,                 COALESCE(pMisc, FALSE), pExpcatid,
29383     _journalNumber,             pFor,                   pNotes,
29384     _bankaccnt_currid );
29385
29386   IF (pAropenid IS NOT NULL AND fetchmetricbool('EnableReturnAuth')) THEN
29387     INSERT INTO checkitem (checkitem_checkhead_id,checkitem_amount,checkitem_discount,checkitem_ponumber,
29388                            checkitem_aropen_id,checkitem_docdate,checkitem_curr_id,checkitem_cmnumber,
29389                            checkitem_ranumber, checkitem_curr_rate)
29390     SELECT _checkid, currToCurr(checkhead_curr_id, aropen_curr_id, pAmount, checkhead_checkdate),
29391       0,cmhead_custponumber,pAropenid,aropen_docdate,aropen_curr_id,cmhead_number,rahead_number,
29392       1 / (_check_curr_rate / aropen_curr_rate)
29393     FROM checkhead, aropen
29394       LEFT OUTER JOIN cmhead ON (aropen_docnumber=cmhead_number)
29395       LEFT OUTER JOIN rahead ON (cmhead_rahead_id=rahead_id)
29396     WHERE ((aropen_id=pAropenid)
29397      AND (checkhead_id=_checkid));
29398   ELSIF (pAropenid IS NOT NULL) THEN
29399     INSERT INTO checkitem (checkitem_checkhead_id,checkitem_amount,checkitem_discount,checkitem_ponumber,
29400                            checkitem_aropen_id,checkitem_docdate,checkitem_curr_id,checkitem_cmnumber,
29401                            checkitem_ranumber, checkitem_curr_rate)
29402     SELECT _checkid,currToCurr(checkhead_curr_id, aropen_curr_id, pAmount, checkhead_checkdate),
29403       0,cmhead_custponumber,pAropenid,aropen_docdate,aropen_curr_id,cmhead_number,NULL,
29404       1 / (_check_curr_rate / aropen_curr_rate)
29405     FROM checkhead, aropen
29406       LEFT OUTER JOIN cmhead ON (aropen_docnumber=cmhead_number)
29407     WHERE ((aropen_id=pAropenid)
29408      AND (checkhead_id=_checkid));
29409   END IF;
29410   
29411
29412   RETURN _checkid;
29413
29414 END;
29415 $_$;
29416
29417
29418 ALTER FUNCTION public.createcheck(integer, text, integer, date, numeric, integer, integer, integer, text, text, boolean, integer) OWNER TO admin;
29419
29420 --
29421 -- TOC entry 1320 (class 1255 OID 146565871)
29422 -- Dependencies: 4536 8
29423 -- Name: createchecks(integer, date); Type: FUNCTION; Schema: public; Owner: admin
29424 --
29425
29426 CREATE FUNCTION createchecks(pbankaccntid integer, pcheckdate date) RETURNS integer
29427     LANGUAGE plpgsql
29428     AS $_$
29429 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29430 -- See www.xtuple.com/CPAL for the full text of the software license.
29431 DECLARE
29432   _v RECORD;
29433   _r RECORD;
29434   _c RECORD;
29435   _checkid              INTEGER;
29436   _counter              INTEGER := 0;
29437   _check_curr_id        INTEGER;
29438   _check_curr_rate      NUMERIC;
29439
29440 BEGIN
29441
29442   SELECT bankaccnt_curr_id, currRate(bankaccnt_curr_id, pCheckDate) 
29443     INTO _check_curr_id, _check_curr_rate
29444     FROM bankaccnt
29445     WHERE ( bankaccnt_id = pBankaccntid );
29446   FOR _v IN SELECT DISTINCT vend_id, vend_number, vend_name
29447               FROM apselect
29448               JOIN apopen   ON (apselect_apopen_id=apopen_id)
29449               JOIN vendinfo ON (apopen_vend_id=vend_id)
29450             WHERE ((apselect_bankaccnt_id=pBankaccntid)
29451                AND (apselect_date <= pCheckDate)) LOOP
29452
29453     -- if we owe this vendor anything (we might not) then create a check
29454     -- allow $0 checks
29455     IF ((SELECT SUM(CASE apopen_doctype WHEN 'C' THEN (apselect_amount * -1.0)
29456                                         ELSE apselect_amount END * _check_curr_rate / apopen_curr_rate)          
29457          FROM apselect JOIN apopen ON (apopen_id=apselect_apopen_id)
29458          WHERE ((apopen_vend_id=_v.vend_id)
29459            AND  (apselect_bankaccnt_id=pBankaccntid)) ) >= 0) THEN
29460       -- 0.01 is a temporary amount; we''ll update the check amount later
29461       _checkid := createCheck(pBankaccntid,     'V',    _v.vend_id,
29462                               pCheckDate,               0.01,   _check_curr_id,
29463                               NULL,             NULL, '',       '',     FALSE);
29464
29465       FOR _r IN SELECT apopen_id, apselect_id,
29466                        apopen_docnumber, apopen_invcnumber, apopen_ponumber,
29467                        apopen_docdate, apselect_curr_id,
29468                        apselect_amount, apselect_discount
29469                 FROM apselect, apopen
29470                 WHERE ( (apselect_apopen_id=apopen_id)
29471                  AND (apopen_vend_id=_v.vend_id)
29472                  AND (apselect_bankaccnt_id=pBankaccntid) ) LOOP
29473         INSERT INTO checkitem
29474         ( checkitem_checkhead_id, checkitem_apopen_id,
29475           checkitem_vouchernumber, checkitem_invcnumber, checkitem_ponumber,
29476           checkitem_amount, checkitem_discount, checkitem_docdate,
29477           checkitem_curr_id, checkitem_curr_rate )
29478         VALUES
29479         ( _checkid, _r.apopen_id,
29480           _r.apopen_docnumber, _r.apopen_invcnumber, _r.apopen_ponumber,
29481           _r.apselect_amount, _r.apselect_discount, _r.apopen_docdate,
29482           _r.apselect_curr_id, 
29483           1 / (_check_curr_rate / currRate(_r.apselect_curr_id, pCheckdate))  );
29484
29485         DELETE FROM apselect
29486         WHERE (apselect_id=_r.apselect_id);
29487
29488       END LOOP;
29489
29490       -- one check can pay for purchases on multiple dates in multiple currencies
29491       UPDATE checkhead
29492       SET checkhead_amount = (SELECT SUM(CASE WHEN (apopen_doctype='C') THEN checkitem_amount / checkitem_curr_rate * -1.0
29493                                               ELSE checkitem_amount / checkitem_curr_rate END)
29494                               FROM checkitem LEFT OUTER JOIN apopen ON (apopen_id=checkitem_apopen_id)
29495                               WHERE (checkitem_checkhead_id=checkhead_id))
29496       WHERE (checkhead_id=_checkid);
29497
29498       _counter := (_counter + 1);
29499     END IF;
29500
29501   END LOOP;
29502
29503   RETURN _counter;
29504
29505 END;
29506 $_$;
29507
29508
29509 ALTER FUNCTION public.createchecks(pbankaccntid integer, pcheckdate date) OWNER TO admin;
29510
29511 --
29512 -- TOC entry 1321 (class 1255 OID 146565872)
29513 -- Dependencies: 4536 8
29514 -- Name: createcounttag(integer, text, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
29515 --
29516
29517 CREATE FUNCTION createcounttag(integer, text, boolean, boolean) RETURNS integer
29518     LANGUAGE plpgsql
29519     AS $_$
29520 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29521 -- See www.xtuple.com/CPAL for the full text of the software license.
29522 DECLARE
29523   pItemsiteid ALIAS FOR $1;
29524   pComments ALIAS FOR $2;
29525   pPriority ALIAS FOR $3;
29526   pFreeze ALIAS FOR $4;
29527 BEGIN
29528   RETURN createCountTag(pItemsiteid, pComments, pPriority, pFreeze, NULL);
29529 END;
29530 $_$;
29531
29532
29533 ALTER FUNCTION public.createcounttag(integer, text, boolean, boolean) OWNER TO admin;
29534
29535 --
29536 -- TOC entry 1322 (class 1255 OID 146565873)
29537 -- Dependencies: 4536 8
29538 -- Name: createcounttag(integer, text, boolean, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
29539 --
29540
29541 CREATE FUNCTION createcounttag(integer, text, boolean, boolean, integer) RETURNS integer
29542     LANGUAGE plpgsql
29543     AS $_$
29544
29545 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29546 -- See www.xtuple.com/CPAL for the full text of the software license.
29547 DECLARE
29548   pItemsiteid ALIAS FOR $1;
29549   pComments ALIAS FOR $2;
29550   pPriority ALIAS FOR $3;
29551   pFreeze ALIAS FOR $4;
29552   pLocationid ALIAS FOR $5;
29553   _invcntid INTEGER;
29554   _whs          RECORD;
29555   _type CHARACTER;
29556   _controlmethod        CHARACTER;
29557
29558 BEGIN
29559
29560   SELECT item_type, itemsite_controlmethod INTO _type, _controlmethod
29561     FROM itemsite, item
29562    WHERE ((itemsite_item_id=item_id)
29563      AND  (itemsite_id=pItemsiteid));
29564
29565   IF (NOT FOUND OR _type IN ('F', 'R', 'L','J') OR _controlmethod = 'N') THEN
29566     RETURN 0; -- We simply do not do these item types.
29567   END IF;
29568
29569   -- Test for existing tags
29570    IF (pLocationid IS NULL) THEN
29571        SELECT invcnt_id INTO _invcntid
29572        FROM invcnt
29573        WHERE ((NOT invcnt_posted)
29574        AND (invcnt_location_id IS NULL)
29575        AND (invcnt_itemsite_id=pItemsiteid));
29576   
29577   ELSE
29578
29579     SELECT invcnt_id INTO _invcntid
29580      FROM invcnt
29581      WHERE ((NOT invcnt_posted)
29582      AND (invcnt_itemsite_id=pItemsiteid)
29583      AND (invcnt_location_id=pLocationid));
29584   END IF;
29585
29586   IF (NOT FOUND) THEN
29587     SELECT NEXTVAL('invcnt_invcnt_id_seq') INTO _invcntid;
29588
29589     SELECT whsinfo.* INTO _whs
29590       FROM whsinfo, itemsite
29591      WHERE ((warehous_id=itemsite_warehous_id)
29592        AND  (itemsite_id=pItemsiteid));
29593
29594     INSERT INTO invcnt (
29595       invcnt_id, invcnt_itemsite_id, invcnt_tagdate,
29596       invcnt_tagnumber,
29597       invcnt_tag_username, invcnt_posted,
29598       invcnt_priority, invcnt_comments, invcnt_location_id
29599     ) VALUES (
29600       _invcntid, pItemsiteid, CURRENT_TIMESTAMP,
29601       (_whs.warehous_counttag_prefix || _whs.warehous_counttag_number::TEXT),
29602       getEffectiveXtUser(), FALSE,
29603       pPriority, pComments, pLocationid
29604     );
29605
29606     UPDATE whsinfo
29607     SET warehous_counttag_number=(warehous_counttag_number + 1)
29608     WHERE (warehous_id=_whs.warehous_id);
29609
29610     IF (pFreeze) THEN
29611       UPDATE itemsite
29612       SET itemsite_freeze=TRUE
29613       WHERE (itemsite_id=pItemsiteid);
29614     END IF;
29615
29616   END IF;
29617
29618   RETURN _invcntid;
29619 END;
29620 $_$;
29621
29622
29623 ALTER FUNCTION public.createcounttag(integer, text, boolean, boolean, integer) OWNER TO admin;
29624
29625 --
29626 -- TOC entry 1323 (class 1255 OID 146565874)
29627 -- Dependencies: 4536 8
29628 -- Name: createcustomer(integer); Type: FUNCTION; Schema: public; Owner: admin
29629 --
29630
29631 CREATE FUNCTION createcustomer(integer) RETURNS integer
29632     LANGUAGE plpgsql
29633     AS $_$
29634   DECLARE
29635     pcrmacctId  ALIAS FOR $1;
29636     _custId     INTEGER := 0;
29637   BEGIN
29638     IF (pcrmacctId < 0 OR pcrmacctId IS NULL) THEN
29639       RETURN -1;
29640     END IF;
29641
29642     SELECT crmacct_cust_id INTO _custId
29643     FROM crmacct WHERE crmacct_id = pcrmacctId;
29644
29645     IF (_custId IS NOT NULL AND _custId <= 0) THEN
29646       RETURN -2;
29647     END IF;
29648
29649     INSERT INTO _customer (active, customer_number, customer_name)
29650       SELECT crmacct_active, crmacct_number, crmacct_name
29651       FROM crmacct
29652       WHERE crmacct_id = pcrmacctId;
29653     _custId := CURRVAL('cust_cust_id_seq');
29654
29655     UPDATE crmacct SET crmacct_prospect_id = NULL, crmacct_cust_id = _custId
29656     WHERE crmacct_id = pcrmacctId;
29657
29658     RETURN _custId;
29659   END;
29660 $_$;
29661
29662
29663 ALTER FUNCTION public.createcustomer(integer) OWNER TO admin;
29664
29665 --
29666 -- TOC entry 1324 (class 1255 OID 146565875)
29667 -- Dependencies: 4536 8
29668 -- Name: createcyclecountsbywarehouse(integer, integer, text, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
29669 --
29670
29671 CREATE FUNCTION createcyclecountsbywarehouse(integer, integer, text, boolean, boolean) RETURNS integer
29672     LANGUAGE plpgsql
29673     AS $_$
29674 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29675 -- See www.xtuple.com/CPAL for the full text of the software license.
29676 DECLARE
29677   pWarehousid ALIAS FOR $1;
29678   pMaxNumber ALIAS FOR $2;
29679   pComments ALIAS FOR $3;
29680   pPriority ALIAS FOR $4;
29681   pFreeze ALIAS FOR $5;
29682
29683 BEGIN
29684   RETURN createCycleCountsByWarehouse(pWarehousid, pMaxNumber, pComments, pPriority, pFreeze, NULL, FALSE);
29685 END;
29686 $_$;
29687
29688
29689 ALTER FUNCTION public.createcyclecountsbywarehouse(integer, integer, text, boolean, boolean) OWNER TO admin;
29690
29691 --
29692 -- TOC entry 1325 (class 1255 OID 146565876)
29693 -- Dependencies: 4536 8
29694 -- Name: createcyclecountsbywarehouse(integer, integer, integer, text, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
29695 --
29696
29697 CREATE FUNCTION createcyclecountsbywarehouse(integer, integer, integer, text, boolean, boolean) RETURNS integer
29698     LANGUAGE plpgsql
29699     AS $_$
29700 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29701 -- See www.xtuple.com/CPAL for the full text of the software license.
29702 DECLARE
29703   pWarehousid ALIAS FOR $1;
29704   pClasscodeid ALIAS FOR $2;
29705   pMaxNumber ALIAS FOR $3;
29706   pComments ALIAS FOR $4;
29707   pPriority ALIAS FOR $5;
29708   pFreeze ALIAS FOR $6;
29709 BEGIN
29710   RETURN createCycleCountsByWarehouseByClassCode(pWarehousid, pClasscodeid, pMaxNumber, pComments, pPriority, pFreeze, NULL, FALSE);
29711 END;
29712 $_$;
29713
29714
29715 ALTER FUNCTION public.createcyclecountsbywarehouse(integer, integer, integer, text, boolean, boolean) OWNER TO admin;
29716
29717 --
29718 -- TOC entry 1326 (class 1255 OID 146565877)
29719 -- Dependencies: 4536 8
29720 -- Name: createcyclecountsbywarehouse(integer, text, integer, text, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
29721 --
29722
29723 CREATE FUNCTION createcyclecountsbywarehouse(integer, text, integer, text, boolean, boolean) RETURNS integer
29724     LANGUAGE plpgsql
29725     AS $_$
29726 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29727 -- See www.xtuple.com/CPAL for the full text of the software license.
29728 DECLARE
29729   pWarehousid ALIAS FOR $1;
29730   pClasscodePattern ALIAS FOR $2;
29731   pMaxNumber ALIAS FOR $3;
29732   pComments ALIAS FOR $4;
29733   pPriority ALIAS FOR $5;
29734   pFreeze ALIAS FOR $6;
29735 BEGIN
29736   RETURN createCycleCountsByWarehouseByClassCode(pWarehousid, pClasscodePattern, pMaxNumber, pComments, pPriority, pFreeze, NULL, FALSE);
29737 END;
29738 $_$;
29739
29740
29741 ALTER FUNCTION public.createcyclecountsbywarehouse(integer, text, integer, text, boolean, boolean) OWNER TO admin;
29742
29743 --
29744 -- TOC entry 1327 (class 1255 OID 146565878)
29745 -- Dependencies: 4536 8
29746 -- Name: createcyclecountsbywarehouse(integer, integer, text, boolean, boolean, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
29747 --
29748
29749 CREATE FUNCTION createcyclecountsbywarehouse(integer, integer, text, boolean, boolean, integer, boolean) RETURNS integer
29750     LANGUAGE plpgsql
29751     AS $_$
29752 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29753 -- See www.xtuple.com/CPAL for the full text of the software license.
29754 DECLARE
29755   pWarehousid ALIAS FOR $1;
29756   pMaxNumber ALIAS FOR $2;
29757   pComments ALIAS FOR $3;
29758   pPriority ALIAS FOR $4;
29759   pFreeze ALIAS FOR $5;
29760   pLocationid ALIAS FOR $6;
29761   pIgnoreZeroBalance ALIAS FOR $7;
29762   _itemsites RECORD;
29763   _returnVal    INTEGER;
29764   
29765 BEGIN
29766
29767 IF (pLocationid IS NULL) THEN
29768   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, itemsite_qtyonhand
29769                     FROM itemsite, item
29770                     WHERE ( (itemsite_active)
29771                      AND (itemsite_item_id=item_id)
29772                      AND (itemsite_cyclecountfreq > 0)
29773                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
29774                      AND (itemsite_id NOT IN ( SELECT invcnt_itemsite_id
29775                                                FROM invcnt, itemsite
29776                                                WHERE ( (invcnt_itemsite_id=itemsite_id)
29777                                                 AND (itemsite_warehous_id=pWarehousid)
29778                                                 AND (invcnt_location_id IS NULL)
29779                                                 AND (NOT invcnt_posted) ) ) )
29780                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
29781                      AND ((pLocationid IS NULL) OR (validLocation(pLocationid, itemsite_id)))
29782                      AND (itemsite_warehous_id=pWarehousid) )
29783                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass, item_number
29784
29785 LIMIT pMaxNumber LOOP
29786     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
29787                                     pPriority, pFreeze, pLocationid);
29788     IF (_returnVal < 0) THEN
29789       RETURN _returnVal;
29790     END IF;
29791   END LOOP;            
29792
29793 ELSE
29794   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, SUM(itemloc_qty)
29795                     FROM itemsite, itemloc
29796                     WHERE ( (itemsite_active)
29797                      AND (itemsite_cyclecountfreq > 0)
29798                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
29799                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
29800                      AND (pLocationid = itemloc_location_id)
29801                      AND (itemloc_itemsite_id = itemsite_id)
29802                      AND (itemsite_warehous_id=pWarehousid) )
29803                     GROUP BY itemsite_id, itemsite_warehous_id,
29804                              itemsite_datelastcount, itemsite_cyclecountfreq,
29805                              itemsite_abcclass
29806                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass
29807
29808 LIMIT pMaxNumber LOOP
29809     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
29810                                     pPriority, pFreeze, pLocationid);
29811     IF (_returnVal < 0) THEN
29812       RETURN _returnVal;
29813     END IF;
29814   END LOOP;  
29815                    
29816 END IF;
29817
29818   RETURN 0;
29819 END;
29820 $_$;
29821
29822
29823 ALTER FUNCTION public.createcyclecountsbywarehouse(integer, integer, text, boolean, boolean, integer, boolean) OWNER TO admin;
29824
29825 --
29826 -- TOC entry 1313 (class 1255 OID 146565879)
29827 -- Dependencies: 4536 8
29828 -- Name: createcyclecountsbywarehousebyclasscode(integer, integer, integer, text, boolean, boolean, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
29829 --
29830
29831 CREATE FUNCTION createcyclecountsbywarehousebyclasscode(integer, integer, integer, text, boolean, boolean, integer, boolean) RETURNS integer
29832     LANGUAGE plpgsql
29833     AS $_$
29834 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29835 -- See www.xtuple.com/CPAL for the full text of the software license.
29836 DECLARE
29837   pWarehousid ALIAS FOR $1;
29838   pClasscodeid ALIAS FOR $2;
29839   pMaxNumber ALIAS FOR $3;
29840   pComments ALIAS FOR $4;
29841   pPriority ALIAS FOR $5;
29842   pFreeze ALIAS FOR $6;
29843   pLocationid ALIAS FOR $7;
29844   pIgnoreZeroBalance ALIAS FOR $8;
29845   _itemsites RECORD;
29846   _returnVal    INTEGER;
29847   
29848 BEGIN
29849
29850 IF (pLocationid IS NULL) THEN
29851   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, itemsite_qtyonhand
29852                     FROM itemsite, item
29853                     WHERE ( (itemsite_active)
29854                      AND (itemsite_item_id=item_id)
29855                      AND (itemsite_cyclecountfreq > 0)
29856                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
29857                      AND (itemsite_id NOT IN ( SELECT invcnt_itemsite_id
29858                                                FROM invcnt, itemsite
29859                                                WHERE ( (invcnt_itemsite_id=itemsite_id)
29860                                                 AND (itemsite_warehous_id=pWarehousid)
29861                                                 AND (invcnt_location_id IS NULL)
29862                                                 AND (NOT invcnt_posted) ) ) )
29863                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
29864                      AND ((pLocationid IS NULL) OR (validLocation(pLocationid, itemsite_id)))
29865                      AND (itemsite_warehous_id=pWarehousid)
29866                      AND (item_classcode_id=pClasscodeid) )
29867                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass, item_number
29868                     LIMIT pMaxNumber LOOP
29869     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
29870                                     pPriority, pFreeze, pLocationid);
29871     IF (_returnVal < 0) THEN
29872       RETURN _returnVal;
29873     END IF;
29874   END LOOP;
29875
29876 ELSE
29877   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, SUM(itemloc_qty)
29878                     FROM itemsite, item, itemloc
29879                     WHERE ( (itemsite_active)
29880                      AND (itemsite_item_id=item_id)
29881                      AND (itemsite_cyclecountfreq > 0)
29882                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
29883                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
29884                      AND (pLocationid = itemloc_location_id)
29885                      AND (itemloc_itemsite_id = itemsite_id)
29886                      AND (itemsite_warehous_id=pWarehousid) 
29887                      AND (item_classcode_id=pClasscodeid) )
29888                     GROUP BY itemsite_id, itemsite_warehous_id,
29889                              itemsite_datelastcount, itemsite_cyclecountfreq,
29890                              itemsite_abcclass
29891                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass
29892                     LIMIT pMaxNumber LOOP
29893     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
29894                                     pPriority, pFreeze, pLocationid);
29895     IF (_returnVal < 0) THEN
29896       RETURN _returnVal;
29897     END IF;
29898   END LOOP;
29899
29900 END IF;
29901
29902   RETURN 0;
29903 END;
29904 $_$;
29905
29906
29907 ALTER FUNCTION public.createcyclecountsbywarehousebyclasscode(integer, integer, integer, text, boolean, boolean, integer, boolean) OWNER TO admin;
29908
29909 --
29910 -- TOC entry 1319 (class 1255 OID 146565880)
29911 -- Dependencies: 4536 8
29912 -- Name: createcyclecountsbywarehousebyclasscode(integer, text, integer, text, boolean, boolean, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
29913 --
29914
29915 CREATE FUNCTION createcyclecountsbywarehousebyclasscode(integer, text, integer, text, boolean, boolean, integer, boolean) RETURNS integer
29916     LANGUAGE plpgsql
29917     AS $_$
29918 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
29919 -- See www.xtuple.com/CPAL for the full text of the software license.
29920 DECLARE
29921   pWarehousid ALIAS FOR $1;
29922   pClasscodePattern ALIAS FOR $2;
29923   pMaxNumber ALIAS FOR $3;
29924   pComments ALIAS FOR $4;
29925   pPriority ALIAS FOR $5;
29926   pFreeze ALIAS FOR $6;
29927   pLocationid ALIAS FOR $7;
29928   pIgnoreZeroBalance ALIAS FOR $8;
29929   _itemsites RECORD;
29930   _returnVal    INTEGER;
29931   
29932 BEGIN
29933
29934 IF (pLocationid IS NULL) THEN
29935   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, itemsite_qtyonhand
29936                     FROM itemsite, item, classcode
29937                     WHERE ( (itemsite_active)
29938                      AND (itemsite_item_id=item_id)
29939                      AND (item_classcode_id=classcode_id)
29940                      AND (itemsite_cyclecountfreq > 0)
29941                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
29942                      AND (itemsite_id NOT IN ( SELECT invcnt_itemsite_id
29943                                                FROM invcnt, itemsite
29944                                                WHERE ( (invcnt_itemsite_id=itemsite_id)
29945                                                 AND (itemsite_warehous_id=pWarehousid)
29946                                                 AND (invcnt_location_id IS NULL)
29947                                                 AND (NOT invcnt_posted) ) ) )
29948                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
29949                      AND ((pLocationid IS NULL) OR (validLocation(pLocationid, itemsite_id)))
29950                      AND (itemsite_warehous_id=pWarehousid)
29951                      AND (classcode_code ~ pClasscodePattern) )
29952                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass, item_number
29953                     LIMIT pMaxNumber LOOP
29954     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
29955                                     pPriority, pFreeze, pLocationid);
29956     IF (_returnVal < 0) THEN
29957       RETURN _returnVal;
29958     END IF;
29959   END LOOP;
29960
29961 ELSE
29962   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, SUM(itemloc_qty)
29963                     FROM itemsite, item, classcode, itemloc
29964                     WHERE ( (itemsite_active)
29965                      AND (itemsite_item_id=item_id)
29966                      AND (item_classcode_id=classcode_id)
29967                      AND (itemsite_cyclecountfreq > 0)
29968                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
29969                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
29970                      AND (pLocationid = itemloc_location_id)
29971                      AND (itemloc_itemsite_id = itemsite_id)
29972                      AND (itemsite_warehous_id=pWarehousid)
29973                      AND (classcode_code ~ pClasscodePattern) )
29974                     GROUP BY itemsite_id, itemsite_warehous_id,
29975                              itemsite_datelastcount, itemsite_cyclecountfreq,
29976                              itemsite_abcclass
29977                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass
29978                     LIMIT pMaxNumber LOOP
29979     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
29980                                     pPriority, pFreeze, pLocationid);
29981     IF (_returnVal < 0) THEN
29982       RETURN _returnVal;
29983     END IF;
29984   END LOOP;
29985
29986 END IF;
29987
29988   RETURN 0;
29989 END;
29990 $_$;
29991
29992
29993 ALTER FUNCTION public.createcyclecountsbywarehousebyclasscode(integer, text, integer, text, boolean, boolean, integer, boolean) OWNER TO admin;
29994
29995 --
29996 -- TOC entry 1329 (class 1255 OID 146565881)
29997 -- Dependencies: 4536 8
29998 -- Name: createcyclecountsbywarehousebyplannercode(integer, text, integer, text, boolean, boolean, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
29999 --
30000
30001 CREATE FUNCTION createcyclecountsbywarehousebyplannercode(integer, text, integer, text, boolean, boolean, integer, boolean) RETURNS integer
30002     LANGUAGE plpgsql
30003     AS $_$
30004 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30005 -- See www.xtuple.com/CPAL for the full text of the software license.
30006 DECLARE
30007   pWarehousid ALIAS FOR $1;
30008   pPlancodePattern ALIAS FOR $2;
30009   pMaxNumber ALIAS FOR $3;
30010   pComments ALIAS FOR $4;
30011   pPriority ALIAS FOR $5;
30012   pFreeze ALIAS FOR $6;
30013   pLocationid ALIAS FOR $7;
30014   pIgnoreZeroBalance ALIAS FOR $8;
30015   _itemsites RECORD;
30016   _returnVal    INTEGER;
30017   
30018 BEGIN
30019
30020 IF (pLocationid IS NULL) THEN
30021   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, itemsite_qtyonhand
30022                     FROM itemsite, item, plancode
30023                     WHERE ( (itemsite_active)
30024                      AND (itemsite_item_id=item_id)
30025                      AND (itemsite_plancode_id=plancode_id)
30026                      AND (itemsite_cyclecountfreq > 0)
30027                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
30028                      AND (itemsite_id NOT IN ( SELECT invcnt_itemsite_id
30029                                                FROM invcnt, itemsite
30030                                                WHERE ( (invcnt_itemsite_id=itemsite_id)
30031                                                 AND (itemsite_warehous_id=pWarehousid)
30032                                                 AND (invcnt_location_id IS NULL)
30033                                                 AND (NOT invcnt_posted) ) ) )
30034                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
30035                      AND ((pLocationid IS NULL) OR (validLocation(pLocationid, itemsite_id)))
30036                      AND (itemsite_warehous_id=pWarehousid)
30037                      AND (plancode_code ~ pPlancodePattern) )
30038                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass, item_number
30039                     LIMIT pMaxNumber LOOP
30040     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
30041                                     pPriority, pFreeze, pLocationid);
30042     IF (_returnVal < 0) THEN
30043       RETURN _returnVal;
30044     END IF;
30045   END LOOP;
30046
30047 ELSE
30048   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, SUM(itemloc_qty)
30049                     FROM itemsite, plancode, itemloc
30050                     WHERE ( (itemsite_active)
30051                      AND (itemsite_plancode_id=plancode_id)
30052                      AND (itemsite_cyclecountfreq > 0)
30053                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
30054                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
30055                      AND (pLocationid = itemloc_location_id)
30056                      AND (itemloc_itemsite_id = itemsite_id)
30057                      AND (itemsite_warehous_id=pWarehousid)
30058                      AND (plancode_code ~ pPlancodePattern) )
30059                     GROUP BY itemsite_id, itemsite_warehous_id,
30060                              itemsite_datelastcount, itemsite_cyclecountfreq,
30061                              itemsite_abcclass
30062                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass
30063                     LIMIT pMaxNumber LOOP
30064     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
30065                                     pPriority, pFreeze, pLocationid);
30066     IF (_returnVal < 0) THEN
30067       RETURN _returnVal;
30068     END IF;
30069   END LOOP;
30070
30071 END IF;
30072
30073   RETURN 0;
30074 END;
30075 $_$;
30076
30077
30078 ALTER FUNCTION public.createcyclecountsbywarehousebyplannercode(integer, text, integer, text, boolean, boolean, integer, boolean) OWNER TO admin;
30079
30080 --
30081 -- TOC entry 1330 (class 1255 OID 146565882)
30082 -- Dependencies: 4536 8
30083 -- Name: createcyclecountsbywarehousebyplannercode(integer, integer, integer, text, boolean, boolean, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
30084 --
30085
30086 CREATE FUNCTION createcyclecountsbywarehousebyplannercode(integer, integer, integer, text, boolean, boolean, integer, boolean) RETURNS integer
30087     LANGUAGE plpgsql
30088     AS $_$
30089 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30090 -- See www.xtuple.com/CPAL for the full text of the software license.
30091 DECLARE
30092   pWarehousid ALIAS FOR $1;
30093   pPlancodeid ALIAS FOR $2;
30094   pMaxNumber ALIAS FOR $3;
30095   pComments ALIAS FOR $4;
30096   pPriority ALIAS FOR $5;
30097   pFreeze ALIAS FOR $6;
30098   pLocationid ALIAS FOR $7;
30099   pIgnoreZeroBalance ALIAS FOR $8;
30100   _itemsites RECORD;
30101   _returnVal    INTEGER;
30102   
30103 BEGIN
30104
30105 IF (pLocationid IS NULL) THEN
30106   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, itemsite_qtyonhand
30107                     FROM itemsite, item
30108                     WHERE ( (itemsite_active)
30109                      AND (itemsite_item_id=item_id)
30110                      AND (itemsite_cyclecountfreq > 0)
30111                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
30112                      AND (itemsite_id NOT IN ( SELECT invcnt_itemsite_id
30113                                                FROM invcnt, itemsite
30114                                                WHERE ( (invcnt_itemsite_id=itemsite_id)
30115                                                 AND (itemsite_warehous_id=pWarehousid)
30116                                                 AND (invcnt_location_id IS NULL)
30117                                                 AND (NOT invcnt_posted) ) ) )
30118                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
30119                      AND ((pLocationid IS NULL) OR (validLocation(pLocationid, itemsite_id)))
30120                      AND (itemsite_warehous_id=pWarehousid)
30121                      AND (itemsite_plancode_id=pPlancodeid) )
30122                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass, item_number
30123                     LIMIT pMaxNumber LOOP
30124     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
30125                                     pPriority, pFreeze, pLocationid);
30126     IF (_returnVal < 0) THEN
30127       RETURN _returnVal;
30128     END IF;
30129   END LOOP;
30130
30131 ELSE
30132   FOR _itemsites IN SELECT itemsite_id, itemsite_warehous_id, SUM(itemloc_qty)
30133                     FROM itemsite, itemloc
30134                     WHERE ( (itemsite_active)
30135                      AND (itemsite_cyclecountfreq > 0)
30136                      AND ((COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq) < CURRENT_DATE)
30137                      AND ((NOT pIgnoreZeroBalance) OR (itemsite_qtyonhand <> 0))
30138                      AND (itemloc_itemsite_id = itemsite_id)
30139                      AND (itemsite_warehous_id=pWarehousid)
30140                      AND (pLocationid = itemloc_location_id)
30141                      AND (itemsite_plancode_id=pPlancodeid) )
30142                     GROUP BY itemsite_id, itemsite_warehous_id,
30143                              itemsite_datelastcount, itemsite_cyclecountfreq,
30144                              itemsite_abcclass
30145                     ORDER BY (COALESCE(itemsite_datelastcount, startOfTime()) + itemsite_cyclecountfreq), itemsite_abcclass
30146                     LIMIT pMaxNumber LOOP
30147     _returnVal := createCountTag(_itemsites.itemsite_id, pComments,
30148                                     pPriority, pFreeze, pLocationid);
30149     IF (_returnVal < 0) THEN
30150       RETURN _returnVal;
30151     END IF;
30152   END LOOP;
30153
30154 END IF;
30155
30156   RETURN 0;
30157 END;
30158 $_$;
30159
30160
30161 ALTER FUNCTION public.createcyclecountsbywarehousebyplannercode(integer, integer, integer, text, boolean, boolean, integer, boolean) OWNER TO admin;
30162
30163 --
30164 -- TOC entry 1331 (class 1255 OID 146565883)
30165 -- Dependencies: 4536 8
30166 -- Name: createfile(text, text, bytea); Type: FUNCTION; Schema: public; Owner: admin
30167 --
30168
30169 CREATE FUNCTION createfile(text, text, bytea) RETURNS integer
30170     LANGUAGE plpgsql
30171     AS $_$
30172 declare
30173   pTitle ALIAS FOR $1;
30174   pDescription ALIAS FOR $2;
30175   pStream ALIAS FOR $3;
30176   _id integer;
30177 begin
30178   _id := nextval('file_file_id_seq');
30179   insert into file (file_id, file_title, file_descrip, file_stream) values (_id, pTitle, pDescription, pStream);
30180   return _id;
30181 end;
30182 $_$;
30183
30184
30185 ALTER FUNCTION public.createfile(text, text, bytea) OWNER TO admin;
30186
30187 --
30188 -- TOC entry 1332 (class 1255 OID 146565884)
30189 -- Dependencies: 4536 8
30190 -- Name: createinvoice(integer); Type: FUNCTION; Schema: public; Owner: admin
30191 --
30192
30193 CREATE FUNCTION createinvoice(integer) RETURNS integer
30194     LANGUAGE plpgsql
30195     AS $_$
30196 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30197 -- See www.xtuple.com/CPAL for the full text of the software license.
30198 DECLARE
30199   pCobmiscid ALIAS FOR $1;
30200   _invcheadid INTEGER;
30201   _invcitemid INTEGER;
30202   _qtyToInvoice NUMERIC;
30203   _r            RECORD;
30204   _s            RECORD;
30205   _lastlinenumber INTEGER := 1;
30206   
30207 BEGIN
30208
30209   IF ( ( SELECT cobmisc_posted
30210          FROM cobmisc
30211          WHERE (cobmisc_id=pCobmiscid) ) ) THEN
30212     RETURN -1;
30213   END IF;
30214
30215   SELECT NEXTVAL('invchead_invchead_id_seq') INTO _invcheadid;
30216
30217 --  Give this selection a number if it has not been assigned one
30218   UPDATE cobmisc
30219   SET cobmisc_invcnumber=fetchInvcNumber()
30220   WHERE ( (cobmisc_invcnumber IS NULL)
30221    AND (cobmisc_id=pCobmiscid) );
30222
30223 --  Create the Invoice header
30224   INSERT INTO invchead
30225   ( 
30226         invchead_id,invchead_cust_id,invchead_shipto_id,invchead_ordernumber,invchead_orderdate,
30227         invchead_posted,invchead_printed,invchead_invcnumber,invchead_invcdate,invchead_shipdate,
30228         invchead_ponumber,invchead_shipvia,invchead_fob,invchead_billto_name,invchead_billto_address1,
30229         invchead_billto_address2,invchead_billto_address3,invchead_billto_city,invchead_billto_state,invchead_billto_zipcode,
30230         invchead_billto_phone,invchead_billto_country,invchead_shipto_name,invchead_shipto_address1,invchead_shipto_address2,
30231         invchead_shipto_address3,invchead_shipto_city,invchead_shipto_state,invchead_shipto_zipcode,invchead_shipto_phone,
30232         invchead_shipto_country,invchead_salesrep_id,invchead_commission,invchead_terms_id,invchead_freight,
30233         invchead_misc_amount,invchead_misc_descrip,invchead_misc_accnt_id,invchead_payment,
30234         invchead_paymentref,invchead_notes,invchead_prj_id,invchead_curr_id,
30235         invchead_taxzone_id, invchead_shipchrg_id,
30236         invchead_saletype_id, invchead_shipzone_id
30237    )
30238   SELECT 
30239         _invcheadid,cohead_cust_id,cohead_shipto_id,cohead_number,cohead_orderdate,
30240         FALSE,FALSE,cobmisc_invcnumber,cobmisc_invcdate,cobmisc_shipdate,
30241         cohead_custponumber,cobmisc_shipvia,cohead_fob,cohead_billtoname,cohead_billtoaddress1,
30242         cohead_billtoaddress2,cohead_billtoaddress3,cohead_billtocity,cohead_billtostate,cohead_billtozipcode,
30243         cntct_phone AS cust_phone,cohead_billtocountry,cohead_shiptoname,cohead_shiptoaddress1,cohead_shiptoaddress2,
30244         cohead_shiptoaddress3,cohead_shiptocity,cohead_shiptostate,cohead_shiptozipcode,cohead_shipto_cntct_phone,
30245         cohead_shiptocountry,cohead_salesrep_id,COALESCE(cohead_commission,0),cohead_terms_id,cobmisc_freight,
30246         COALESCE(cobmisc_misc, 0.00),cobmisc_misc_descrip,cobmisc_misc_accnt_id,cobmisc_payment,
30247         cobmisc_paymentref,cobmisc_notes,cohead_prj_id,cobmisc_curr_id,
30248         cobmisc_taxzone_id, cohead_shipchrg_id,
30249         cohead_saletype_id, cohead_shipzone_id
30250     FROM cobmisc, cohead, custinfo
30251     LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
30252   WHERE ( (cobmisc_cohead_id=cohead_id)
30253    AND (cohead_cust_id=cust_id)
30254    AND (cobmisc_id=pCobmiscid) );
30255
30256         INSERT INTO invcheadtax(taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id, taxhist_basis, 
30257                         taxhist_basis_tax_id, taxhist_sequence, taxhist_percent, taxhist_amount, taxhist_tax, taxhist_docdate)
30258         SELECT _invcheadid,taxhist_taxtype_id, taxhist_tax_id, taxhist_basis, 
30259                         taxhist_basis_tax_id, taxhist_sequence, taxhist_percent, taxhist_amount, taxhist_tax, taxhist_docdate
30260         FROM cobmisctax 
30261         WHERE taxhist_parent_id = pCobmiscid 
30262         AND taxhist_taxtype_id = getadjustmenttaxtypeid();
30263
30264 --  Create the Invoice Characteristic Assignments
30265     INSERT INTO charass
30266           (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default, charass_price)
30267     SELECT 'INV', _invcheadid, charass_char_id, charass_value, charass_default, charass_price
30268       FROM cobmisc JOIN cohead ON (cohead_id=cobmisc_cohead_id)
30269                    JOIN charass ON ((charass_target_type='SO') AND (charass_target_id=cohead_id))
30270                    JOIN char ON (char_id=charass_char_id AND char_invoices)
30271     WHERE (cobmisc_id=pCobmiscid);
30272
30273 --  Create the Invoice items
30274   FOR _r IN SELECT coitem_id, coitem_linenumber, coitem_subnumber, coitem_custpn,
30275                    coitem_qtyord, cobill_qty,
30276                    coitem_qty_uom_id, coitem_qty_invuomratio,
30277                    coitem_custprice, coitem_price,
30278                    coitem_price_uom_id, coitem_price_invuomratio,
30279                    coitem_memo, coitem_rev_accnt_id,
30280                    itemsite_item_id, itemsite_warehous_id,
30281                    cobill_taxtype_id,
30282                    formatSoItemNumber(coitem_id) AS ordnumber
30283             FROM coitem, cobill, itemsite
30284             WHERE ( (cobill_coitem_id=coitem_id)
30285              AND (coitem_itemsite_id=itemsite_id)
30286              AND (cobill_cobmisc_id=pCobmiscid) )
30287             ORDER BY coitem_linenumber, coitem_subnumber LOOP
30288
30289     SELECT NEXTVAL('invcitem_invcitem_id_seq') INTO _invcitemid;
30290     INSERT INTO invcitem
30291     ( invcitem_id, invcitem_invchead_id,
30292       invcitem_linenumber, invcitem_item_id, invcitem_warehous_id,
30293       invcitem_custpn, invcitem_number, invcitem_descrip,
30294       invcitem_ordered, invcitem_billed,
30295       invcitem_qty_uom_id, invcitem_qty_invuomratio,
30296       invcitem_custprice, invcitem_price,
30297       invcitem_price_uom_id, invcitem_price_invuomratio,
30298       invcitem_notes, invcitem_taxtype_id,
30299       invcitem_coitem_id, invcitem_rev_accnt_id )
30300     VALUES
30301     ( _invcitemid, _invcheadid,
30302       _lastlinenumber,
30303       _r.itemsite_item_id, _r.itemsite_warehous_id,
30304       _r.coitem_custpn, '', '',
30305       _r.coitem_qtyord, _r.cobill_qty,
30306       _r.coitem_qty_uom_id, _r.coitem_qty_invuomratio,
30307       _r.coitem_custprice, _r.coitem_price,
30308       _r.coitem_price_uom_id, _r.coitem_price_invuomratio,
30309       _r.coitem_memo, _r.cobill_taxtype_id,
30310       _r.coitem_id, _r.coitem_rev_accnt_id );
30311
30312 --  Find and mark any Lot/Serial invdetail records associated with this bill
30313     UPDATE invdetail SET invdetail_invcitem_id = _invcitemid
30314      WHERE (invdetail_id IN (SELECT invdetail_id
30315                                FROM invhist JOIN invdetail ON (invdetail_invhist_id=invhist_id)
30316                               WHERE ( (invhist_ordnumber = _r.ordnumber)
30317                                 AND   (invhist_ordtype = 'SO')
30318                                 AND   (invhist_transtype = 'SH')
30319                                 AND   (invdetail_invcitem_id IS NULL) ) ));
30320
30321 --  Mark any shipped, uninvoiced shipitems for the current coitem as invoiced
30322     _qtyToInvoice :=  _r.cobill_qty;
30323     FOR _s IN SELECT shipitem.*, shipitem_qty = _r.cobill_qty AS matched
30324               FROM shipitem, shiphead
30325               WHERE ((shipitem_shiphead_id=shiphead_id)
30326                 AND  (shipitem_orderitem_id=_r.coitem_id)
30327                 AND  (shiphead_shipped)
30328                 AND  (shiphead_order_type='SO')
30329                 AND  (NOT shipitem_invoiced))
30330               ORDER BY matched DESC, shipitem_qty DESC FOR UPDATE LOOP
30331       IF (_qtyToInvoice >= _s.shipitem_qty) THEN
30332         UPDATE shipitem
30333         SET shipitem_invoiced=TRUE, shipitem_invcitem_id=_invcitemid
30334         WHERE (shipitem_id=_s.shipitem_id);
30335         _qtyToInvoice := _qtyToInvoice - _s.shipitem_qty;
30336       END IF;
30337       IF (_qtyToInvoice <= 0) THEN
30338         EXIT;
30339       END IF;
30340     END LOOP;
30341
30342     UPDATE cobill SET cobill_invcnum=cobmisc_invcnumber,
30343                       cobill_invcitem_id=invcitem_id
30344     FROM invcitem, coitem, cobmisc
30345     WHERE ((invcitem_linenumber=_lastlinenumber)
30346       AND  (coitem_id=cobill_coitem_id)
30347       AND  (cobmisc_id=cobill_cobmisc_id)
30348       AND  (cobill_cobmisc_id=pCobmiscid)
30349       AND  (invcitem_invchead_id=_invcheadid));
30350     
30351     _lastlinenumber := _lastlinenumber + 1;
30352
30353   END LOOP;
30354
30355 --  Close all requested coitem's
30356   IF ( ( SELECT cobmisc_closeorder
30357          FROM cobmisc
30358          WHERE (cobmisc_id=pCobmiscid) ) ) THEN
30359     UPDATE coitem
30360     SET coitem_status='C'
30361     FROM cobmisc
30362     WHERE ( (coitem_status NOT IN ('C', 'X'))
30363      AND (coitem_cohead_id=cobmisc_cohead_id)
30364      AND (cobmisc_id=pCobmiscid) );
30365   ELSE
30366     UPDATE coitem
30367     SET coitem_status='C'
30368     FROM cobill
30369     WHERE ( (cobill_coitem_id=coitem_id)
30370      AND (coitem_status <> 'X')
30371      AND (cobill_toclose)
30372      AND (cobill_cobmisc_id=pCobmiscid) );
30373   END IF;
30374
30375 --  Mark the cobmisc as posted
30376   UPDATE cobmisc
30377   SET cobmisc_posted=TRUE, cobmisc_invchead_id=_invcheadid
30378   WHERE (cobmisc_id=pCobmiscid);
30379
30380 --  All done
30381   RETURN _invcheadid;
30382
30383 END;
30384 $_$;
30385
30386
30387 ALTER FUNCTION public.createinvoice(integer) OWNER TO admin;
30388
30389 --
30390 -- TOC entry 1333 (class 1255 OID 146565886)
30391 -- Dependencies: 4536 8
30392 -- Name: createinvoiceconsolidated(integer); Type: FUNCTION; Schema: public; Owner: admin
30393 --
30394
30395 CREATE FUNCTION createinvoiceconsolidated(integer) RETURNS integer
30396     LANGUAGE plpgsql
30397     AS $_$
30398 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30399 -- See www.xtuple.com/CPAL for the full text of the software license.
30400 DECLARE
30401   pCustid ALIAS FOR $1;
30402   _invcheadid INTEGER;
30403   _invcitemid INTEGER;
30404   _qtyToInvoice NUMERIC;
30405   _r            RECORD;
30406   _s            RECORD;
30407   _c            RECORD;
30408   _i            RECORD;
30409   _count      INTEGER;
30410   _invcnumber INTEGER;
30411   _lastlinenumber INTEGER;
30412
30413 BEGIN
30414   _count := 0;
30415
30416   FOR _c IN SELECT min(cobmisc_id) AS cobmisc_id, count(*) AS cnt,
30417 -- there are the key values for consolidation
30418                    cohead_billtoname, cohead_billtoaddress1,
30419                    cohead_billtoaddress2, cohead_billtoaddress3,
30420                    cohead_billtocity, cohead_billtostate,
30421                    cohead_billtozipcode, cntct_phone AS cust_phone,
30422                    cohead_billtocountry,
30423                    cohead_salesrep_id, cohead_commission,
30424                    cohead_terms_id,
30425                    cobmisc_misc_accnt_id,
30426                    cohead_prj_id, cobmisc_curr_id,
30427                    cobmisc_taxzone_id,
30428                    cohead_shipchrg_id,
30429                    cohead_saletype_id,
30430                    cohead_shipzone_id,
30431                    
30432                 -- the following are consolidated values to use in creating the header
30433                    MIN(cohead_number) AS cohead_number,
30434                    MIN(cohead_orderdate) AS cohead_orderdate,
30435                    MIN(cobmisc_invcdate) AS cobmisc_invcdate,
30436                    MIN(cobmisc_shipdate) AS cobmisc_shipdate,
30437                    SUM(cobmisc_freight) AS cobmisc_freight,
30438                    SUM(cobmisc_misc) AS cobmisc_misc,
30439                    SUM(cobmisc_payment) AS cobmisc_payment
30440                    
30441               FROM cobmisc
30442               JOIN cohead   ON (cobmisc_cohead_id=cohead_id)
30443               JOIN custinfo ON (cohead_cust_id=cust_id)
30444               LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
30445              WHERE(NOT cobmisc_posted
30446                AND (cohead_cust_id=pCustid)
30447                )
30448           GROUP BY cohead_billtoname, cohead_billtoaddress1,
30449                    cohead_billtoaddress2, cohead_billtoaddress3,
30450                    cohead_billtocity, cohead_billtostate,
30451                    cohead_billtozipcode, cust_phone,
30452                    cohead_billtocountry,
30453                    cohead_salesrep_id, cohead_commission,
30454                    cohead_terms_id,
30455                    cobmisc_misc_accnt_id,
30456                    cohead_prj_id, cobmisc_curr_id,
30457                    cobmisc_taxzone_id,
30458                    cohead_shipchrg_id,
30459                    cohead_saletype_id,
30460                    cohead_shipzone_id
30461                 LOOP
30462
30463     IF(_c.cnt = 1) THEN
30464       PERFORM createInvoice(_c.cobmisc_id);
30465       _count := (_count + 1);
30466     ELSE
30467       SELECT NEXTVAL('invchead_invchead_id_seq'), fetchInvcNumber() INTO _invcheadid, _invcnumber;
30468   
30469   --  Create the Invoice header
30470       INSERT INTO invchead
30471       ( invchead_id, invchead_cust_id, invchead_shipto_id,
30472         invchead_ordernumber, invchead_orderdate,
30473         invchead_posted, invchead_printed,
30474         invchead_invcnumber, invchead_invcdate, invchead_shipdate,
30475         invchead_ponumber, invchead_shipvia, invchead_fob,
30476         invchead_billto_name, invchead_billto_address1,
30477         invchead_billto_address2, invchead_billto_address3,
30478         invchead_billto_city, invchead_billto_state,
30479         invchead_billto_zipcode, invchead_billto_phone,
30480         invchead_billto_country,
30481         invchead_shipto_name, invchead_shipto_address1,
30482         invchead_shipto_address2, invchead_shipto_address3,
30483         invchead_shipto_city, invchead_shipto_state,
30484         invchead_shipto_zipcode, invchead_shipto_phone,
30485         invchead_shipto_country,
30486         invchead_salesrep_id, invchead_commission,
30487         invchead_terms_id,
30488         invchead_freight,
30489         invchead_misc_amount, invchead_misc_descrip, invchead_misc_accnt_id,
30490         invchead_payment, invchead_paymentref,
30491         invchead_notes, invchead_prj_id, invchead_curr_id,
30492         invchead_taxzone_id,
30493         invchead_shipchrg_id,
30494         invchead_saletype_id, invchead_shipzone_id )
30495       VALUES(_invcheadid,
30496              pCustid, -1,
30497              NULL, _c.cohead_orderdate,
30498              FALSE, FALSE,
30499              _invcnumber, _c.cobmisc_invcdate, _c.cobmisc_shipdate,
30500              'MULTIPLE', '', '',
30501              _c.cohead_billtoname, _c.cohead_billtoaddress1,
30502              _c.cohead_billtoaddress2, _c.cohead_billtoaddress3,
30503              _c.cohead_billtocity, _c.cohead_billtostate,
30504              _c.cohead_billtozipcode, _c.cust_phone,
30505              _c.cohead_billtocountry,
30506              '', '', '', '', '', '', '', '', '',
30507              _c.cohead_salesrep_id, COALESCE(_c.cohead_commission, 0),
30508              _c.cohead_terms_id,
30509              _c.cobmisc_freight,
30510              _c.cobmisc_misc, CASE WHEN(_c.cobmisc_misc <> 0) THEN 'Multiple' ELSE '' END,
30511              _c.cobmisc_misc_accnt_id,
30512              _c.cobmisc_payment, '',
30513              'Multiple Sales Order # Invoice', _c.cohead_prj_id, _c.cobmisc_curr_id,
30514              _c.cobmisc_taxzone_id,
30515              _c.cohead_shipchrg_id,
30516              _c.cohead_saletype_id, _c.cohead_shipzone_id
30517              );
30518  
30519     _lastlinenumber := 1;
30520     FOR _i IN SELECT cobmisc_id
30521                 FROM cobmisc
30522                 JOIN cohead   ON (cobmisc_cohead_id=cohead_id)
30523                 JOIN custinfo ON (cohead_cust_id=cust_id)
30524                 LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
30525                WHERE(NOT cobmisc_posted
30526                  AND (cohead_cust_id=pCustid)
30527                  AND (COALESCE(cohead_billtoname,'')         = COALESCE(_c.cohead_billtoname,''))
30528                  AND (COALESCE(cohead_billtoaddress1,'')     = COALESCE(_c.cohead_billtoaddress1,''))
30529                  AND (COALESCE(cohead_billtoaddress2,'')     = COALESCE(_c.cohead_billtoaddress2,''))
30530                  AND (COALESCE(cohead_billtoaddress3,'')     = COALESCE(_c.cohead_billtoaddress3,''))
30531                  AND (COALESCE(cohead_billtocity,'')         = COALESCE(_c.cohead_billtocity,''))
30532                  AND (COALESCE(cohead_billtostate,'')        = COALESCE(_c.cohead_billtostate,''))
30533                  AND (COALESCE(cohead_billtozipcode,'')      = COALESCE(_c.cohead_billtozipcode,''))
30534                  AND (COALESCE(cntct_phone,'')               = COALESCE(_c.cust_phone,''))
30535                  AND (COALESCE(cohead_billtocountry,'')      = COALESCE(_c.cohead_billtocountry,''))
30536                  AND (COALESCE(cohead_salesrep_id, 0)        = COALESCE(_c.cohead_salesrep_id, 0))
30537                  AND (COALESCE(cohead_commission, 0)         = COALESCE(_c.cohead_commission, 0))
30538                  AND (COALESCE(cohead_terms_id, 0)           = COALESCE(_c.cohead_terms_id, 0))
30539                  AND (COALESCE(cobmisc_misc_accnt_id, 0)     = COALESCE(_c.cobmisc_misc_accnt_id, 0))
30540                  AND (COALESCE(cohead_prj_id, 0)             = COALESCE(_c.cohead_prj_id, 0))
30541                  AND (COALESCE(cobmisc_curr_id, 0)           = COALESCE(_c.cobmisc_curr_id, 0))
30542                  AND (COALESCE(cobmisc_taxzone_id, 0)        = COALESCE(_c.cobmisc_taxzone_id, 0))
30543                  AND (COALESCE(cohead_saletype_id, 0)        = COALESCE(_c.cohead_saletype_id, 0))
30544                  AND (COALESCE(cohead_shipzone_id, 0)        = COALESCE(_c.cohead_shipzone_id, 0))
30545                 ) LOOP
30546
30547     --  Create the Invoice Head tax
30548         INSERT INTO invcheadtax(taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id, taxhist_basis, 
30549                                 taxhist_basis_tax_id, taxhist_sequence, taxhist_percent, taxhist_amount, taxhist_tax, taxhist_docdate)
30550         SELECT _invcheadid,taxhist_taxtype_id, taxhist_tax_id, taxhist_basis, 
30551                taxhist_basis_tax_id, taxhist_sequence, taxhist_percent, taxhist_amount, taxhist_tax, taxhist_docdate
30552         FROM cobmisctax 
30553         WHERE taxhist_parent_id = _i.cobmisc_id
30554           AND taxhist_taxtype_id = getadjustmenttaxtypeid();
30555
30556     --  Give this selection a number if it has not been assigned one
30557         UPDATE cobmisc
30558            SET cobmisc_invcnumber=_invcnumber
30559          WHERE(cobmisc_id=_i.cobmisc_id);
30560       
30561     --  Create the Invoice items
30562         FOR _r IN SELECT coitem_id, coitem_linenumber, coitem_subnumber, coitem_custpn,
30563                          coitem_qtyord, cobill_qty,
30564                          coitem_qty_uom_id, coitem_qty_invuomratio,
30565                          coitem_custprice, coitem_price,
30566                          coitem_price_uom_id, coitem_price_invuomratio,
30567                          coitem_memo,
30568                          itemsite_item_id, itemsite_warehous_id,
30569                          cobill_taxtype_id
30570                     FROM cohead, coitem, cobill, itemsite
30571                    WHERE((cobill_coitem_id=coitem_id)
30572                      AND (cohead_id=coitem_cohead_id)
30573                      AND (coitem_itemsite_id=itemsite_id)
30574                      AND (cobill_cobmisc_id=_i.cobmisc_id) ) 
30575                    ORDER BY cohead_number, coitem_linenumber, coitem_subnumber LOOP
30576       
30577           SELECT NEXTVAL('invcitem_invcitem_id_seq') INTO _invcitemid;
30578           INSERT INTO invcitem
30579           ( invcitem_id, invcitem_invchead_id,
30580             invcitem_linenumber, invcitem_item_id, invcitem_warehous_id,
30581             invcitem_custpn, invcitem_number, invcitem_descrip,
30582             invcitem_ordered, invcitem_billed,
30583             invcitem_qty_uom_id, invcitem_qty_invuomratio,
30584             invcitem_custprice, invcitem_price,
30585             invcitem_price_uom_id, invcitem_price_invuomratio,
30586             invcitem_notes,
30587             invcitem_taxtype_id,
30588             invcitem_coitem_id )
30589           VALUES
30590           ( _invcitemid, _invcheadid,
30591             _lastlinenumber,
30592             _r.itemsite_item_id, _r.itemsite_warehous_id,
30593             _r.coitem_custpn, '', '',
30594             _r.coitem_qtyord, _r.cobill_qty,
30595             _r.coitem_qty_uom_id, _r.coitem_qty_invuomratio,
30596             _r.coitem_custprice, _r.coitem_price,
30597             _r.coitem_price_uom_id, _r.coitem_price_invuomratio,
30598             _r.coitem_memo,
30599             _r.cobill_taxtype_id,
30600             _r.coitem_id );
30601           
30602       --  Find and mark any Lot/Serial invdetail records associated with this bill
30603           UPDATE invdetail SET invdetail_invcitem_id = _invcitemid
30604            WHERE (invdetail_id IN (SELECT invdetail_id
30605                                      FROM coitem, cohead, invhist, invdetail
30606                                     WHERE ((coitem_cohead_id=cohead_id)
30607                                       AND  (invdetail_invhist_id=invhist_id)
30608                                       AND  (invhist_ordnumber = text(cohead_number||'-'||formatSoLineNumber(coitem_id)))
30609                                       AND  (invdetail_invcitem_id IS NULL)
30610                                       AND  (coitem_id=_r.coitem_id)) ) );
30611       
30612       --  Mark any shipped, uninvoiced shipitems for the current coitem as invoiced
30613           _qtyToInvoice :=  _r.cobill_qty;
30614           FOR _s IN SELECT shipitem.*, shipitem_qty = _r.cobill_qty AS matched
30615                     FROM shipitem, shiphead
30616                     WHERE ((shipitem_shiphead_id=shiphead_id)
30617                       AND  (shipitem_orderitem_id=_r.coitem_id)
30618                       AND  (shiphead_shipped)
30619                       AND  (shiphead_order_type='SO')
30620                       AND  (NOT shipitem_invoiced))
30621                     ORDER BY matched DESC, shipitem_qty DESC FOR UPDATE LOOP
30622             IF (_qtyToInvoice >= _s.shipitem_qty) THEN
30623               UPDATE shipitem
30624               SET shipitem_invoiced=TRUE, shipitem_invcitem_id=_invcitemid
30625               WHERE (shipitem_id=_s.shipitem_id);
30626               _qtyToInvoice := _qtyToInvoice - _s.shipitem_qty;
30627             END IF;
30628             IF (_qtyToInvoice <= 0) THEN
30629               EXIT;
30630             END IF;
30631           END LOOP;
30632
30633           UPDATE cobill SET cobill_invcnum=cobmisc_invcnumber,
30634                           cobill_invcitem_id=invcitem_id
30635           FROM invcitem, coitem, cobmisc
30636           WHERE ((invcitem_linenumber=_lastlinenumber )
30637             AND  (coitem_id=cobill_coitem_id)
30638             AND  (cobmisc_id=cobill_cobmisc_id)
30639             AND  (cobill_cobmisc_id=_i.cobmisc_id)
30640             AND  (invcitem_invchead_id=_invcheadid));
30641
30642
30643           _lastlinenumber := _lastlinenumber + 1;
30644           
30645         END LOOP;
30646   
30647       --  Close all requested coitem's
30648         IF ( ( SELECT cobmisc_closeorder
30649                FROM cobmisc
30650                WHERE (cobmisc_id=_i.cobmisc_id) ) ) THEN
30651           UPDATE coitem
30652           SET coitem_status='C'
30653           FROM cobmisc
30654           WHERE ( (coitem_status NOT IN ('C', 'X'))
30655            AND (coitem_cohead_id=cobmisc_cohead_id)
30656            AND (cobmisc_id=_i.cobmisc_id) );
30657         ELSE
30658           UPDATE coitem
30659           SET coitem_status='C'
30660           FROM cobill
30661           WHERE ( (cobill_coitem_id=coitem_id)
30662            AND (coitem_status <> 'X')
30663            AND (cobill_toclose)
30664            AND (cobill_cobmisc_id=_i.cobmisc_id) );
30665         END IF;
30666       
30667       --  Mark the cobmisc as posted
30668         UPDATE cobmisc
30669         SET cobmisc_posted=TRUE, cobmisc_invchead_id=_invcheadid
30670         WHERE (cobmisc_id=_i.cobmisc_id);
30671     
30672       --  All done
30673         _count := (_count + 1);
30674       END LOOP;
30675     END IF;
30676   END LOOP;
30677   RETURN _count;
30678 END;
30679 $_$;
30680
30681
30682 ALTER FUNCTION public.createinvoiceconsolidated(integer) OWNER TO admin;
30683
30684 --
30685 -- TOC entry 1334 (class 1255 OID 146565888)
30686 -- Dependencies: 4536 8
30687 -- Name: createinvoices(); Type: FUNCTION; Schema: public; Owner: admin
30688 --
30689
30690 CREATE FUNCTION createinvoices() RETURNS integer
30691     LANGUAGE plpgsql
30692     AS $$
30693 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30694 -- See www.xtuple.com/CPAL for the full text of the software license.
30695 DECLARE
30696   _counter INTEGER;
30697   _cobmisc RECORD;
30698
30699 BEGIN
30700
30701   _counter := 0;
30702
30703   FOR _cobmisc IN SELECT cobmisc_id
30704                   FROM cobmisc
30705                   WHERE (NOT cobmisc_posted) LOOP
30706
30707     PERFORM createinvoice(_cobmisc.cobmisc_id);
30708     _counter := (_counter + 1);
30709
30710   END LOOP;
30711
30712   RETURN _counter;
30713 END;
30714 $$;
30715
30716
30717 ALTER FUNCTION public.createinvoices() OWNER TO admin;
30718
30719 --
30720 -- TOC entry 1335 (class 1255 OID 146565889)
30721 -- Dependencies: 4536 8
30722 -- Name: createinvoices(integer); Type: FUNCTION; Schema: public; Owner: admin
30723 --
30724
30725 CREATE FUNCTION createinvoices(integer) RETURNS integer
30726     LANGUAGE plpgsql
30727     AS $_$
30728 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30729 -- See www.xtuple.com/CPAL for the full text of the software license.
30730 BEGIN
30731   RETURN createinvoices($1, false);
30732 END;
30733 $_$;
30734
30735
30736 ALTER FUNCTION public.createinvoices(integer) OWNER TO admin;
30737
30738 --
30739 -- TOC entry 1336 (class 1255 OID 146565890)
30740 -- Dependencies: 4536 8
30741 -- Name: createinvoices(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
30742 --
30743
30744 CREATE FUNCTION createinvoices(integer, boolean) RETURNS integer
30745     LANGUAGE plpgsql
30746     AS $_$
30747 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30748 -- See www.xtuple.com/CPAL for the full text of the software license.
30749 DECLARE
30750   pCustTypeId ALIAS FOR $1;
30751   pConsolidate ALIAS FOR $2;
30752   _counter INTEGER;
30753   _tcounter INTEGER;
30754   _cobmisc RECORD;
30755
30756 BEGIN
30757
30758   _counter := 0;
30759
30760   IF (pConsolidate) THEN
30761     FOR _cobmisc IN SELECT DISTINCT cust_id
30762                       FROM cobmisc, cohead, custinfo
30763                      WHERE((NOT cobmisc_posted)
30764                        AND (cohead_id=cobmisc_cohead_id)
30765                        AND (cust_id=cohead_cust_id)
30766                        AND (cust_custtype_id=pCustTypeId)) LOOP
30767
30768       SELECT createinvoiceConsolidated(_cobmisc.cust_id)
30769         INTO _tcounter;
30770       _counter := (_counter + _tcounter);
30771     END LOOP;
30772   ELSE
30773     FOR _cobmisc IN SELECT cobmisc_id
30774                       FROM cobmisc, cohead, custinfo
30775                      WHERE((NOT cobmisc_posted)
30776                        AND (cohead_id=cobmisc_cohead_id)
30777                        AND (cust_id=cohead_cust_id)
30778                        AND (cust_custtype_id=pCustTypeId)) LOOP
30779   
30780       PERFORM createinvoice(_cobmisc.cobmisc_id);
30781       _counter := (_counter + 1);
30782
30783     END LOOP;
30784   END IF;
30785
30786   RETURN _counter;
30787 END;
30788 $_$;
30789
30790
30791 ALTER FUNCTION public.createinvoices(integer, boolean) OWNER TO admin;
30792
30793 --
30794 -- TOC entry 1337 (class 1255 OID 146565891)
30795 -- Dependencies: 4536 8
30796 -- Name: createmiscapcheck(integer, integer, date, numeric, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
30797 --
30798
30799 CREATE FUNCTION createmiscapcheck(integer, integer, date, numeric, integer, text, text) RETURNS integer
30800     LANGUAGE plpgsql
30801     AS $_$
30802 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30803 -- See www.xtuple.com/CPAL for the full text of the software license.
30804 BEGIN
30805   RAISE NOTICE 'createMiscAPCheck() is deprecated - use createCheck() instead';
30806   RETURN createCheck($1, 'V', $2, $3, $4, baseCurrId(), $5, NULL, $6, $7, FALSE);
30807 END;
30808 $_$;
30809
30810
30811 ALTER FUNCTION public.createmiscapcheck(integer, integer, date, numeric, integer, text, text) OWNER TO admin;
30812
30813 --
30814 -- TOC entry 1338 (class 1255 OID 146565892)
30815 -- Dependencies: 4536 8
30816 -- Name: createmiscapcheck(integer, integer, date, numeric, integer, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
30817 --
30818
30819 CREATE FUNCTION createmiscapcheck(integer, integer, date, numeric, integer, integer, text, text) RETURNS integer
30820     LANGUAGE plpgsql
30821     AS $_$
30822 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30823 -- See www.xtuple.com/CPAL for the full text of the software license.
30824 BEGIN
30825   RAISE NOTICE 'createMiscAPCheck() is deprecated - use createCheck() instead';
30826   RETURN createCheck($1, 'V', $2, $3, pAmount, $5, $6, NULL, $7, $8, FALSE);
30827 END;
30828 $_$;
30829
30830
30831 ALTER FUNCTION public.createmiscapcheck(integer, integer, date, numeric, integer, integer, text, text) OWNER TO admin;
30832
30833 --
30834 -- TOC entry 1339 (class 1255 OID 146565893)
30835 -- Dependencies: 4536 8
30836 -- Name: createpkgschema(text, text); Type: FUNCTION; Schema: public; Owner: admin
30837 --
30838
30839 CREATE FUNCTION createpkgschema(text, text) RETURNS integer
30840     LANGUAGE plpgsql
30841     AS $_$
30842 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30843 -- See www.xtuple.com/CPAL for the full text of the software license.
30844 DECLARE
30845   pname         ALIAS FOR $1;
30846   pcomment      ALIAS FOR $2;
30847   _createtable  TEXT;
30848   _debug        BOOL    := true;
30849   _namespaceoid INTEGER := -1;
30850   _tabs         TEXT[] := ARRAY['cmd',  'cmdarg', 'image',  'metasql',
30851                                 'priv', 'report', 'script', 'uiform'] ;
30852   _pkgtab       TEXT;
30853
30854 BEGIN
30855   IF (LENGTH(COALESCE(pname, '')) <= 0) THEN
30856     RAISE EXCEPTION 'Cannot create a schema for this package without a name.';
30857   END IF;
30858
30859   SELECT oid INTO _namespaceoid
30860   FROM pg_namespace
30861   WHERE (LOWER(nspname)=LOWER(pname));
30862   IF (NOT FOUND) THEN
30863     EXECUTE 'CREATE SCHEMA ' || LOWER(pname);
30864     EXECUTE 'GRANT ALL ON SCHEMA ' || LOWER(pname) || ' TO GROUP xtrole;';
30865
30866     SELECT oid INTO _namespaceoid
30867     FROM pg_namespace
30868     WHERE (LOWER(nspname)=LOWER(pname));
30869   END IF;
30870
30871   FOR i IN ARRAY_LOWER(_tabs,1)..ARRAY_UPPER(_tabs,1) LOOP
30872     _pkgtab := pname || '.pkg' || _tabs[i];
30873
30874     IF NOT EXISTS(SELECT oid
30875                   FROM pg_class
30876                   WHERE ((relname=_pkgtab)
30877                      AND (relnamespace=_namespaceoid))) THEN
30878       _createtable := 'CREATE TABLE ' || _pkgtab || ' () INHERITS (' || _tabs[i] || ');';
30879       IF (_debug) THEN RAISE NOTICE '%', _createtable; END IF;
30880       EXECUTE _createtable;
30881
30882       EXECUTE 'ALTER TABLE ' || _pkgtab ||
30883               ' ALTER ' || _tabs[i] || '_id SET NOT NULL,' ||
30884               ' ADD PRIMARY KEY (' || _tabs[i] || '_id),' ||
30885               ' ALTER ' || _tabs[i] || '_id SET DEFAULT NEXTVAL(''' ||
30886               _tabs[i] || '_' || _tabs[i] || '_id_seq'');';
30887
30888       EXECUTE 'REVOKE ALL ON ' || _pkgtab || ' FROM PUBLIC;';
30889       EXECUTE 'GRANT  ALL ON ' || _pkgtab || ' TO GROUP xtrole;';
30890
30891       IF (_tabs[i] = 'cmdarg') THEN
30892         EXECUTE 'ALTER TABLE ' || _pkgtab ||
30893                 ' ADD FOREIGN KEY (cmdarg_cmd_id) REFERENCES ' ||
30894                 pname || '.pkgcmd(cmd_id);';
30895       END IF;
30896
30897       EXECUTE 'SELECT dropIfExists(''TRIGGER'', ''pkg' ||
30898                                    _tabs[i] || 'beforetrigger'', ''' ||
30899                                    pname || ''');' ;
30900       EXECUTE 'CREATE TRIGGER pkg' || _tabs[i] || 'beforetrigger ' ||
30901               'BEFORE INSERT OR UPDATE OR DELETE ON ' || _pkgtab ||
30902               ' FOR EACH ROW EXECUTE PROCEDURE _pkg' || _tabs[i] || 'beforetrigger();';
30903
30904       EXECUTE 'SELECT dropIfExists(''TRIGGER'', ''pkg' ||
30905                                    _tabs[i] || 'altertrigger'', ''' ||
30906                                    pname || ''');' ;
30907       EXECUTE 'CREATE TRIGGER pkg' || _tabs[i] || 'altertrigger ' ||
30908               'BEFORE INSERT OR UPDATE OR DELETE ON ' || _pkgtab ||
30909               ' FOR EACH ROW EXECUTE PROCEDURE _pkg' || _tabs[i] || 'altertrigger();';
30910
30911       EXECUTE 'SELECT dropIfExists(''TRIGGER'', ''pkg' ||
30912                                    _tabs[i] || 'aftertrigger'', ''' ||
30913                                    pname || ''');' ;
30914       EXECUTE 'CREATE TRIGGER pkg' || _tabs[i] || 'aftertrigger ' ||
30915               'AFTER INSERT OR UPDATE OR DELETE ON ' || _pkgtab ||
30916               ' FOR EACH ROW EXECUTE PROCEDURE _pkg' || _tabs[i] || 'aftertrigger();';
30917
30918     END IF;
30919   END LOOP;
30920
30921   EXECUTE 'COMMENT ON SCHEMA ' || quote_ident(pname) || ' IS ' ||
30922            quote_literal(pcomment) || ';';
30923
30924   RETURN _namespaceoid;
30925 END;
30926 $_$;
30927
30928
30929 ALTER FUNCTION public.createpkgschema(text, text) OWNER TO admin;
30930
30931 --
30932 -- TOC entry 1341 (class 1255 OID 146565896)
30933 -- Dependencies: 4536 8
30934 -- Name: createpr(character, integer); Type: FUNCTION; Schema: public; Owner: admin
30935 --
30936
30937 CREATE FUNCTION createpr(character, integer) RETURNS integer
30938     LANGUAGE plpgsql
30939     AS $_$
30940 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30941 -- See www.xtuple.com/CPAL for the full text of the software license.
30942 DECLARE
30943   pParentType ALIAS FOR $1;
30944   pParentId ALIAS FOR $2;
30945   _orderNumber INTEGER;
30946   _prid INTEGER;
30947
30948 BEGIN
30949
30950   IF (pParentType = 'W') THEN
30951     SELECT wo_number INTO _orderNumber
30952     FROM wo, womatl
30953     WHERE ((womatl_wo_id=wo_id)
30954      AND (womatl_id=pParentId));
30955
30956   ELSIF (pParentType = 'S') THEN
30957     SELECT CAST(cohead_number AS INTEGER) INTO _orderNumber
30958     FROM cohead, coitem
30959     WHERE ((coitem_cohead_id=cohead_id)
30960      AND (coitem_id=pParentId));
30961
30962   ELSIF (pParentType = 'F') THEN
30963     SELECT fetchPrNumber() INTO _orderNumber;
30964
30965   ELSE
30966     RETURN -2;
30967   END IF;
30968
30969   IF (NOT FOUND) THEN
30970     RETURN -1;
30971   END IF;
30972
30973   SELECT createPr(_orderNumber, pParentType, pParentId) INTO _prid;
30974
30975   RETURN _prid;
30976
30977 END;
30978 $_$;
30979
30980
30981 ALTER FUNCTION public.createpr(character, integer) OWNER TO admin;
30982
30983 --
30984 -- TOC entry 1340 (class 1255 OID 146565895)
30985 -- Dependencies: 4536 8
30986 -- Name: createpr(integer, character, integer); Type: FUNCTION; Schema: public; Owner: admin
30987 --
30988
30989 CREATE FUNCTION createpr(integer, character, integer) RETURNS integer
30990     LANGUAGE plpgsql
30991     AS $_$
30992 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
30993 -- See www.xtuple.com/CPAL for the full text of the software license.
30994 DECLARE
30995   pOrderNumber ALIAS FOR $1;
30996   pParentType ALIAS FOR $2;
30997   pParentId ALIAS FOR $3;
30998   _parent RECORD;
30999   _prid INTEGER;
31000   _orderNumber INTEGER;
31001
31002 BEGIN
31003
31004   IF (pOrderNumber = -1) THEN
31005     SELECT fetchPrNumber() INTO _orderNumber;
31006   ELSE
31007     _orderNumber := pOrderNumber;
31008   END IF;
31009
31010   IF (pParentType = 'W') THEN
31011     SELECT womatl_itemsite_id AS itemsiteid,
31012            itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq) AS qty,
31013            womatl_duedate AS duedate, wo_prj_id AS prjid,
31014            womatl_notes AS notes INTO _parent
31015     FROM wo, womatl, itemsite
31016     WHERE ((womatl_wo_id=wo_id)
31017      AND (womatl_itemsite_id=itemsite_id)
31018      AND (womatl_id=pParentId));
31019
31020   ELSIF (pParentType = 'S') THEN
31021     SELECT coitem_itemsite_id AS itemsiteid,
31022            (coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) AS qty,
31023            coitem_scheddate AS duedate, cohead_prj_id AS prjid,
31024            coitem_memo AS notes INTO _parent
31025     FROM coitem, cohead
31026     WHERE ((cohead_id=coitem_cohead_id)
31027      AND (coitem_id=pParentId));
31028
31029   ELSIF (pParentType = 'F') THEN
31030     SELECT planord_itemsite_id AS itemsiteid,
31031            planord_qty AS qty,
31032            planord_duedate AS duedate, NULL::INTEGER AS prjid,
31033            planord_comments AS notes INTO _parent
31034     FROM planord
31035     WHERE (planord_id=pParentId);
31036
31037   ELSE
31038     RETURN -2;
31039   END IF;
31040
31041   IF (NOT FOUND) THEN
31042     RETURN -1;
31043   END IF;
31044
31045   SELECT NEXTVAL('pr_pr_id_seq') INTO _prid;
31046   INSERT INTO pr
31047   ( pr_id, pr_number, pr_subnumber, pr_status,
31048     pr_order_type, pr_order_id, pr_prj_id,
31049     pr_itemsite_id, pr_qtyreq,
31050     pr_duedate, pr_releasenote )
31051   VALUES
31052   ( _prid, _orderNumber, nextPrSubnumber(_orderNumber), 'O',
31053     pParentType, pParentId, _parent.prjid,
31054     _parent.itemsiteid, validateOrderQty(_parent.itemsiteid, _parent.qty, TRUE),
31055     _parent.duedate, _parent.notes );
31056
31057   RETURN _prid;
31058
31059 END;
31060 $_$;
31061
31062
31063 ALTER FUNCTION public.createpr(integer, character, integer) OWNER TO admin;
31064
31065 --
31066 -- TOC entry 1343 (class 1255 OID 146565898)
31067 -- Dependencies: 4536 8
31068 -- Name: createpr(integer, character, integer, text); Type: FUNCTION; Schema: public; Owner: admin
31069 --
31070
31071 CREATE FUNCTION createpr(integer, character, integer, text) RETURNS integer
31072     LANGUAGE plpgsql
31073     AS $_$
31074 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31075 -- See www.xtuple.com/CPAL for the full text of the software license.
31076 DECLARE
31077   pOrderNumber ALIAS FOR $1;
31078   pParentType ALIAS FOR $2;
31079   pParentId ALIAS FOR $3;
31080   pParentNotes ALIAS FOR $4;
31081   _parent RECORD;
31082   _prid INTEGER;
31083   _orderNumber INTEGER;
31084
31085 BEGIN
31086
31087   IF (pOrderNumber = -1) THEN
31088     SELECT fetchPrNumber() INTO _orderNumber;
31089   ELSE
31090     _orderNumber := pOrderNumber;
31091   END IF;
31092
31093   IF (pParentType = 'W') THEN
31094     SELECT womatl_itemsite_id AS itemsiteid,
31095            itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq) AS qty,
31096            womatl_duedate AS duedate, wo_prj_id AS prjid INTO _parent
31097     FROM wo, womatl, itemsite
31098     WHERE ((womatl_wo_id=wo_id)
31099      AND (womatl_itemsite_id=itemsite_id)
31100      AND (womatl_id=pParentId));
31101
31102   ELSIF (pParentType = 'S') THEN
31103     SELECT coitem_itemsite_id AS itemsiteid,
31104            (coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) AS qty,
31105            coitem_scheddate AS duedate, cohead_prj_id AS prjid INTO _parent
31106     FROM coitem, cohead
31107     WHERE ((cohead_id=coitem_cohead_id)
31108      AND (coitem_id=pParentId));
31109
31110   ELSIF (pParentType = 'F') THEN
31111     SELECT planord_itemsite_id AS itemsiteid,
31112            planord_qty AS qty,
31113            planord_duedate AS duedate, NULL::INTEGER AS prjid 
31114            INTO _parent
31115     FROM planord
31116     WHERE (planord_id=pParentId);
31117
31118   ELSE
31119     RETURN -2;
31120   END IF;
31121
31122   IF (NOT FOUND) THEN
31123     RETURN -1;
31124   END IF;
31125
31126   SELECT NEXTVAL('pr_pr_id_seq') INTO _prid;
31127   INSERT INTO pr
31128   ( pr_id, pr_number, pr_subnumber, pr_status,
31129     pr_order_type, pr_order_id, pr_prj_id,
31130     pr_itemsite_id, pr_qtyreq, pr_duedate, pr_releasenote )
31131   VALUES
31132   ( _prid, _orderNumber, nextPrSubnumber(_orderNumber), 'O',
31133     pParentType, pParentId, _parent.prjid,
31134     _parent.itemsiteid, validateOrderQty(_parent.itemsiteid, _parent.qty, TRUE),
31135     _parent.duedate, pParentNotes );
31136
31137   RETURN _prid;
31138
31139 END;
31140 $_$;
31141
31142
31143 ALTER FUNCTION public.createpr(integer, character, integer, text) OWNER TO admin;
31144
31145 --
31146 -- TOC entry 1328 (class 1255 OID 146565894)
31147 -- Dependencies: 4536 8
31148 -- Name: createpr(integer, integer, numeric, date, text); Type: FUNCTION; Schema: public; Owner: admin
31149 --
31150
31151 CREATE FUNCTION createpr(integer, integer, numeric, date, text) RETURNS integer
31152     LANGUAGE plpgsql
31153     AS $_$
31154 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31155 -- See www.xtuple.com/CPAL for the full text of the software license.
31156 DECLARE
31157   pOrderNumber ALIAS FOR $1;
31158   pItemsiteid ALIAS FOR $2;
31159   pQty ALIAS FOR $3;
31160   pDueDate ALIAS FOR $4;
31161   pNotes ALIAS FOR $5;
31162   _prid INTEGER;
31163
31164 BEGIN
31165
31166   SELECT NEXTVAL('pr_pr_id_seq') INTO _prid;
31167   INSERT INTO pr
31168   ( pr_id, pr_number, pr_subnumber, pr_status,
31169     pr_order_type, pr_order_id,
31170     pr_itemsite_id, pr_qtyreq, pr_duedate, pr_releasenote )
31171   VALUES
31172   ( _prid, pOrderNumber, nextPrSubnumber(pOrderNumber), 'O',
31173     'M', -1,
31174     pItemsiteid, pQty, pDuedate, pNotes);
31175
31176   RETURN _prid;
31177
31178 END;
31179 $_$;
31180
31181
31182 ALTER FUNCTION public.createpr(integer, integer, numeric, date, text) OWNER TO admin;
31183
31184 --
31185 -- TOC entry 1342 (class 1255 OID 146565897)
31186 -- Dependencies: 4536 8
31187 -- Name: createpr(integer, integer, numeric, date, text, character, integer); Type: FUNCTION; Schema: public; Owner: admin
31188 --
31189
31190 CREATE FUNCTION createpr(integer, integer, numeric, date, text, character, integer) RETURNS integer
31191     LANGUAGE plpgsql
31192     AS $_$
31193 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31194 -- See www.xtuple.com/CPAL for the full text of the software license.
31195 DECLARE
31196   pOrderNumber ALIAS FOR $1;
31197   pItemsiteid ALIAS FOR $2;
31198   pQty ALIAS FOR $3;
31199   pDueDate ALIAS FOR $4;
31200   pNotes ALIAS FOR $5;
31201   pOrderType ALIAS FOR $6;
31202   pOrderId ALIAS FOR $7;
31203   _prid INTEGER;
31204
31205 BEGIN
31206
31207   SELECT NEXTVAL('pr_pr_id_seq') INTO _prid;
31208   INSERT INTO pr
31209   ( pr_id, pr_number, pr_subnumber, pr_status,
31210     pr_order_type, pr_order_id,
31211     pr_itemsite_id, pr_qtyreq, pr_duedate, pr_releasenote )
31212   VALUES
31213   ( _prid, pOrderNumber, nextPrSubnumber(pOrderNumber), 'O',
31214     pOrderType, pOrderId,
31215     pItemsiteid, pQty, pDuedate, pNotes );
31216
31217   RETURN _prid;
31218
31219 END;
31220 $_$;
31221
31222
31223 ALTER FUNCTION public.createpr(integer, integer, numeric, date, text, character, integer) OWNER TO admin;
31224
31225 --
31226 -- TOC entry 1344 (class 1255 OID 146565899)
31227 -- Dependencies: 4536 8
31228 -- Name: createpriv(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
31229 --
31230
31231 CREATE FUNCTION createpriv(text, text, text) RETURNS integer
31232     LANGUAGE plpgsql
31233     AS $_$
31234 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31235 -- See www.xtuple.com/CPAL for the full text of the software license.
31236 DECLARE
31237   pModule ALIAS FOR $1;
31238   pName   ALIAS FOR $2;
31239   pDesc   ALIAS FOR $3;
31240   _id     INTEGER;
31241 BEGIN
31242
31243   SELECT priv_id
31244     INTO _id
31245     FROM priv
31246    WHERE(priv_name=pName);
31247
31248   IF (FOUND) THEN
31249     UPDATE priv
31250        SET priv_module=pModule,
31251            priv_descrip=pDesc
31252      WHERE(priv_id=_id);
31253   ELSE
31254     SELECT nextval('priv_priv_id_seq') INTO _id;
31255     INSERT INTO priv
31256           (priv_id, priv_module, priv_name, priv_descrip)
31257     VALUES(_id, pModule, pName, pDesc);
31258   END IF;
31259
31260   RETURN _id;
31261 END;
31262 $_$;
31263
31264
31265 ALTER FUNCTION public.createpriv(text, text, text) OWNER TO admin;
31266
31267 --
31268 -- TOC entry 1345 (class 1255 OID 146565900)
31269 -- Dependencies: 4536 8
31270 -- Name: createpurchasetosale(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
31271 --
31272
31273 CREATE FUNCTION createpurchasetosale(integer, integer, boolean) RETURNS integer
31274     LANGUAGE plpgsql
31275     AS $_$
31276 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31277 -- See www.xtuple.com/CPAL for the full text of the software license.
31278 DECLARE
31279   pCoitemId ALIAS FOR $1;
31280   pItemSourceId ALIAS FOR $2;
31281   pDropShip ALIAS FOR $3;
31282
31283 BEGIN
31284
31285   RETURN createPurchaseToSale(pCoitemId, pItemSourceId, pDropShip, NULL, NULL, NULL);
31286
31287 END;
31288 $_$;
31289
31290
31291 ALTER FUNCTION public.createpurchasetosale(integer, integer, boolean) OWNER TO admin;
31292
31293 --
31294 -- TOC entry 1346 (class 1255 OID 146565901)
31295 -- Dependencies: 4536 8
31296 -- Name: createpurchasetosale(integer, integer, boolean, numeric); Type: FUNCTION; Schema: public; Owner: admin
31297 --
31298
31299 CREATE FUNCTION createpurchasetosale(integer, integer, boolean, numeric) RETURNS integer
31300     LANGUAGE plpgsql
31301     AS $_$
31302 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31303 -- See www.xtuple.com/CPAL for the full text of the software license.
31304 DECLARE
31305   pCoitemId ALIAS FOR $1;
31306   pItemSourceId ALIAS FOR $2;
31307   pDropShip ALIAS FOR $3;
31308   pPrice ALIAS FOR $4;
31309
31310 BEGIN
31311
31312   RETURN createPurchaseToSale(pCoitemId, pItemSourceId, pDropShip, NULL, NULL, pPrice);
31313
31314 END;
31315 $_$;
31316
31317
31318 ALTER FUNCTION public.createpurchasetosale(integer, integer, boolean, numeric) OWNER TO admin;
31319
31320 --
31321 -- TOC entry 1347 (class 1255 OID 146565902)
31322 -- Dependencies: 4536 8
31323 -- Name: createpurchasetosale(integer, integer, boolean, numeric, date, numeric); Type: FUNCTION; Schema: public; Owner: admin
31324 --
31325
31326 CREATE FUNCTION createpurchasetosale(integer, integer, boolean, numeric, date, numeric) RETURNS integer
31327     LANGUAGE plpgsql
31328     AS $_$
31329 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31330 -- See www.xtuple.com/CPAL for the full text of the software license.
31331 DECLARE
31332   pCoitemId ALIAS FOR $1;
31333   pItemSourceId ALIAS FOR $2;
31334   pDropShip ALIAS FOR $3;
31335   pQty ALIAS FOR $4;
31336   pDueDate ALIAS FOR $5;
31337   pPrice ALIAS FOR $6;
31338
31339   _s RECORD;
31340   _w RECORD;
31341   _i RECORD;
31342   _shipto RECORD;
31343   _poheadid INTEGER := -1;
31344   _poitemid INTEGER := -1;
31345   _taxtypeid INTEGER := -1;
31346   _polinenumber INTEGER;
31347   _ponumber NUMERIC;
31348   _price NUMERIC;
31349   _temp INTEGER;
31350
31351 BEGIN
31352
31353   -- Check for existing poitem for this coitem
31354   SELECT poitem_id INTO _poitemid
31355   FROM poitem
31356   WHERE (poitem_order_id=pCoitemId)
31357     AND (poitem_order_type='S');
31358   IF (FOUND) THEN
31359     RETURN _poitemid;
31360   END IF;
31361
31362   SELECT *,
31363          COALESCE(roundQty(item_fractional, (coitem_qtyord * coitem_qty_invuomratio)), 0.0) AS orderqty
31364   INTO _s
31365   FROM coitem JOIN cohead ON (cohead_id = coitem_cohead_id)
31366               LEFT OUTER JOIN shiptoinfo ON (cohead_shipto_id = shipto_id)
31367               LEFT OUTER JOIN addr ON (shipto_addr_id = addr_id)
31368               LEFT OUTER JOIN cntct ON (shipto_cntct_id = cntct_id)
31369               LEFT OUTER JOIN itemsite ON (coitem_itemsite_id = itemsite_id)
31370               LEFT OUTER JOIN item ON (item_id = itemsite_item_id)
31371   WHERE (coitem_id = pCoitemId);
31372   IF (NOT FOUND) THEN
31373     RETURN -1;
31374   END IF;
31375
31376   SELECT * INTO _w
31377   FROM itemsite JOIN whsinfo ON (warehous_id = itemsite_warehous_id)
31378                 LEFT OUTER JOIN addr ON (warehous_addr_id = addr_id)
31379                 LEFT OUTER JOIN cntct ON (warehous_cntct_id = cntct_id)
31380   WHERE (itemsite_id = _s.itemsite_id);
31381
31382   SELECT * INTO _i
31383   FROM itemsrc JOIN vendinfo ON (itemsrc_vend_id = vend_id)
31384                LEFT OUTER JOIN cntct ON (vend_cntct1_id = cntct_id)
31385                LEFT OUTER JOIN addr ON (vend_addr_id = addr_id)
31386   WHERE (itemsrc_id = pItemSourceId);
31387   IF (NOT FOUND) THEN
31388     RETURN -2;
31389   END IF;
31390
31391   IF (pDropShip) THEN
31392     SELECT COALESCE(pohead_id, -1) INTO _temp
31393     FROM pohead
31394     WHERE ( (pohead_status = 'U')
31395       AND (pohead_vend_id = _i.itemsrc_vend_id)
31396       AND (pohead_shiptoname = COALESCE(_s.cohead_shiptoname, _s.shipto_name, ''))
31397       AND (pohead_shiptoaddress1 = COALESCE(_s.cohead_shiptoaddress1, _s.addr_line1, ''))
31398       AND (pohead_shiptoaddress2 = COALESCE(_s.cohead_shiptoaddress2, _s.addr_line2, ''))
31399       AND (pohead_shiptoaddress3 = COALESCE(_s.cohead_shiptoaddress3, _s.addr_line3, ''))
31400       AND (pohead_shiptocity = COALESCE(_s.cohead_shiptocity, _s.addr_city, ''))
31401       AND (pohead_shiptostate = COALESCE(_s.cohead_shiptostate, _s.addr_state, ''))
31402       AND (pohead_shiptozipcode = COALESCE(_s.cohead_shiptozipcode, _s.addr_postalcode, ''))
31403       AND (pohead_shiptocountry = COALESCE(_s.cohead_shiptocountry, _s.addr_country, '')) );
31404   ELSE
31405     SELECT COALESCE(pohead_id, -1) INTO _temp
31406     FROM pohead
31407     WHERE ( (pohead_status = 'U')
31408       AND (pohead_vend_id = _i.itemsrc_vend_id)
31409       AND (pohead_shiptoaddress1 = COALESCE(_w.addr_line1, ''))
31410       AND (pohead_shiptoaddress2 = COALESCE(_w.addr_line2, ''))
31411       AND (pohead_shiptoaddress3 = COALESCE(_w.addr_line3, ''))
31412       AND (pohead_shiptocity = COALESCE(_w.addr_city, ''))
31413       AND (pohead_shiptostate = COALESCE(_w.addr_state, ''))
31414       AND (pohead_shiptozipcode = COALESCE(_w.addr_postalcode, ''))
31415       AND (pohead_shiptocountry = COALESCE(_w.addr_country, '')) );
31416   END IF;
31417
31418   IF (FOUND) THEN
31419     _poheadid := _temp;
31420     UPDATE pohead
31421     SET pohead_dropship = pDropShip
31422     WHERE (pohead_id = _poheadid);
31423   ELSE
31424     SELECT NEXTVAL('pohead_pohead_id_seq') INTO _poheadid;
31425     SELECT fetchPoNumber() INTO _ponumber;
31426
31427     IF (pDropShip) THEN
31428       INSERT INTO pohead
31429         ( pohead_id, pohead_number, pohead_status, pohead_dropship,
31430           pohead_agent_username, pohead_vend_id, pohead_taxzone_id,
31431           pohead_orderdate, pohead_curr_id, pohead_cohead_id,
31432           pohead_warehous_id, pohead_shipvia,
31433           pohead_terms_id, pohead_shipto_cntct_id,
31434           pohead_shipto_cntct_honorific, pohead_shipto_cntct_first_name,
31435           pohead_shipto_cntct_middle, pohead_shipto_cntct_last_name,
31436           pohead_shipto_cntct_suffix, pohead_shipto_cntct_phone,
31437           pohead_shipto_cntct_title, pohead_shipto_cntct_fax, 
31438           pohead_shipto_cntct_email, pohead_shiptoaddress_id,
31439           pohead_shiptoname,
31440           pohead_shiptoaddress1,
31441           pohead_shiptoaddress2,
31442           pohead_shiptoaddress3,
31443           pohead_shiptocity, 
31444           pohead_shiptostate, pohead_shiptozipcode,
31445           pohead_shiptocountry, pohead_vend_cntct_id,
31446           pohead_vend_cntct_honorific, pohead_vend_cntct_first_name,
31447           pohead_vend_cntct_middle, pohead_vend_cntct_last_name,
31448           pohead_vend_cntct_suffix, pohead_vend_cntct_phone,
31449           pohead_vend_cntct_title, pohead_vend_cntct_fax,
31450           pohead_vend_cntct_email, pohead_vendaddress1,
31451           pohead_vendaddress2, pohead_vendaddress3,
31452           pohead_vendcity, pohead_vendstate,
31453           pohead_vendzipcode, pohead_vendcountry, pohead_comments )
31454       VALUES
31455         ( _poheadid, _ponumber, 'U', pDropShip,
31456           getEffectiveXtUser(), _i.itemsrc_vend_id, _i.vend_taxzone_id,
31457           CURRENT_DATE, COALESCE(_i.vend_curr_id, basecurrid()), _s.cohead_id,
31458           COALESCE(_s.cohead_warehous_id, -1), COALESCE(_i.vend_shipvia, TEXT('')),
31459           COALESCE(_i.vend_terms_id, -1), COALESCE(_s.cohead_shipto_cntct_id, _s.shipto_cntct_id),
31460           COALESCE(_s.cohead_shipto_cntct_honorific, _s.cntct_honorific), COALESCE(_s.cohead_shipto_cntct_first_name, _s.cntct_first_name),
31461           COALESCE(_s.cohead_shipto_cntct_middle, _s.cntct_middle), COALESCE(_s.cohead_shipto_cntct_last_name, _s.cntct_last_name),
31462           COALESCE(_s.cohead_shipto_cntct_suffix, _s.cntct_suffix), COALESCE(_s.cohead_shipto_cntct_phone, _s.cntct_phone),
31463           COALESCE(_s.cohead_shipto_cntct_title, _s.cntct_title), COALESCE(_s.cohead_shipto_cntct_fax, _s.cntct_fax),
31464           COALESCE(_s.cohead_shipto_cntct_email, _s.cntct_email), COALESCE(_s.shipto_addr_id, _s.addr_id),
31465           COALESCE(_s.cohead_shiptoname, _s.shipto_name, ''),
31466           COALESCE(_s.cohead_shiptoaddress1, _s.addr_line1, ''),
31467           COALESCE(_s.cohead_shiptoaddress2, _s.addr_line2, ''),
31468           COALESCE(_s.cohead_shiptoaddress3, _s.addr_line3, ''),
31469           COALESCE(_s.cohead_shiptocity, _s.addr_city, ''),
31470           COALESCE(_s.cohead_shiptostate, _s.addr_state, ''), COALESCE(_s.cohead_shiptozipcode, _s.addr_postalcode, ''),
31471           COALESCE(_s.cohead_shiptocountry, _s.addr_country, ''), _i.cntct_id,
31472           COALESCE(_i.cntct_honorific, TEXT('')), COALESCE(_i.cntct_first_name, TEXT('')),
31473           COALESCE(_i.cntct_middle, TEXT('')), COALESCE(_i.cntct_last_name, TEXT('')),
31474           COALESCE(_i.cntct_suffix, TEXT('')), COALESCE(_i.cntct_phone, TEXT('')),
31475           COALESCE(_i.cntct_title, TEXT('')), COALESCE(_i.cntct_fax, TEXT('')),
31476           COALESCE(_i.cntct_email, TEXT('')), COALESCE(_i.addr_line1, TEXT('')),
31477           COALESCE(_i.addr_line2, TEXT('')), COALESCE(_i.addr_line3, TEXT('')),
31478           COALESCE(_i.addr_city, TEXT('')), COALESCE(_i.addr_state, TEXT('')),
31479           COALESCE(_i.addr_postalcode, TEXT('')), COALESCE(_i.addr_country, TEXT('')), COALESCE(_s.cohead_shipcomments, TEXT('')) );
31480     ELSE
31481       INSERT INTO pohead
31482         ( pohead_id, pohead_number, pohead_status, pohead_dropship,
31483           pohead_agent_username, pohead_vend_id, pohead_taxzone_id,
31484           pohead_orderdate, pohead_curr_id, pohead_cohead_id,
31485           pohead_warehous_id, pohead_shipvia,
31486           pohead_terms_id, pohead_shipto_cntct_id,
31487           pohead_shipto_cntct_honorific, pohead_shipto_cntct_first_name,
31488           pohead_shipto_cntct_middle, pohead_shipto_cntct_last_name,
31489           pohead_shipto_cntct_suffix, pohead_shipto_cntct_phone,
31490           pohead_shipto_cntct_title, pohead_shipto_cntct_fax, 
31491           pohead_shipto_cntct_email, pohead_shiptoaddress_id,
31492           pohead_shiptoaddress1,
31493           pohead_shiptoaddress2,
31494           pohead_shiptoaddress3,
31495           pohead_shiptocity, 
31496           pohead_shiptostate, pohead_shiptozipcode,
31497           pohead_shiptocountry, pohead_vend_cntct_id,
31498           pohead_vend_cntct_honorific, pohead_vend_cntct_first_name,
31499           pohead_vend_cntct_middle, pohead_vend_cntct_last_name,
31500           pohead_vend_cntct_suffix, pohead_vend_cntct_phone,
31501           pohead_vend_cntct_title, pohead_vend_cntct_fax,
31502           pohead_vend_cntct_email, pohead_vendaddress1,
31503           pohead_vendaddress2, pohead_vendaddress3,
31504           pohead_vendcity, pohead_vendstate,
31505           pohead_vendzipcode, pohead_vendcountry )
31506       VALUES
31507         ( _poheadid, _ponumber, 'U', pDropShip,
31508           getEffectiveXtUser(), _i.itemsrc_vend_id, _i.vend_taxzone_id,
31509           CURRENT_DATE, COALESCE(_i.vend_curr_id, basecurrid()), _s.cohead_id,
31510           COALESCE(_s.cohead_warehous_id, -1), COALESCE(_i.vend_shipvia, TEXT('')),
31511           COALESCE(_i.vend_terms_id, -1), _w.cntct_id,
31512           _w.cntct_honorific, _w.cntct_first_name,
31513           _w.cntct_middle, _w.cntct_last_name,
31514           _w.cntct_suffix, _w.cntct_phone,
31515           _w.cntct_title, _w.cntct_fax,
31516           _w.cntct_email, _w.addr_id,
31517           COALESCE(_w.addr_line1, ''),
31518           COALESCE(_w.addr_line2, ''),
31519           COALESCE(_w.addr_line3, ''),
31520           COALESCE(_w.addr_city, ''),
31521           COALESCE(_w.addr_state, ''), COALESCE(_w.addr_postalcode, ''),
31522           COALESCE(_w.addr_country, ''), _i.cntct_id,
31523           COALESCE(_i.cntct_honorific, TEXT('')), COALESCE(_i.cntct_first_name, TEXT('')),
31524           COALESCE(_i.cntct_middle, TEXT('')), COALESCE(_i.cntct_last_name, TEXT('')),
31525           COALESCE(_i.cntct_suffix, TEXT('')), COALESCE(_i.cntct_phone, TEXT('')),
31526           COALESCE(_i.cntct_title, TEXT('')), COALESCE(_i.cntct_fax, TEXT('')),
31527           COALESCE(_i.cntct_email, TEXT('')), COALESCE(_i.addr_line1, TEXT('')),
31528           COALESCE(_i.addr_line2, TEXT('')), COALESCE(_i.addr_line3, TEXT('')),
31529           COALESCE(_i.addr_city, TEXT('')), COALESCE(_i.addr_state, TEXT('')),
31530           COALESCE(_i.addr_postalcode, TEXT('')), COALESCE(_i.addr_country, TEXT('')) );
31531     END IF;
31532   END IF;
31533
31534   SELECT NEXTVAL('poitem_poitem_id_seq') INTO _poitemid;
31535
31536   SELECT (COALESCE(MAX(poitem_linenumber), 0) + 1) INTO _polinenumber
31537   FROM poitem
31538   WHERE (poitem_pohead_id = _poheadid);
31539
31540   SELECT COALESCE(itemtax_taxtype_id, -1) INTO _taxtypeid
31541   FROM itemtax
31542   WHERE (itemtax_item_id = _i.itemsrc_item_id);
31543
31544   IF (pPrice IS NULL) THEN
31545     SELECT itemsrcPrice(pItemSourceId,
31546                         COALESCE(_s.cohead_warehous_id, -1),
31547                         pDropShip,
31548                         (COALESCE(pQty, _s.orderqty) / COALESCE(_i.itemsrc_invvendoruomratio, 1.00)),
31549                         COALESCE(_i.vend_curr_id, baseCurrId()),
31550                         CURRENT_DATE) INTO _price;
31551   ELSE
31552     _price := pPrice;
31553   END IF;
31554   raise notice '_price=%', _price;
31555
31556   IF (pDropShip) THEN
31557     INSERT INTO poitem
31558       ( poitem_id, poitem_status, poitem_pohead_id, poitem_linenumber, 
31559         poitem_duedate, poitem_itemsite_id,
31560         poitem_vend_item_descrip, poitem_vend_uom,
31561         poitem_invvenduomratio, poitem_qty_ordered, 
31562         poitem_unitprice, poitem_vend_item_number, 
31563         poitem_itemsrc_id, poitem_order_id, poitem_order_type, poitem_prj_id, poitem_stdcost, 
31564         poitem_manuf_name, poitem_manuf_item_number, 
31565         poitem_manuf_item_descrip, poitem_taxtype_id, poitem_comments )
31566     VALUES
31567       ( _poitemid, 'U', _poheadid, _polinenumber,
31568         COALESCE(pDueDate, _s.coitem_scheddate), _s.coitem_itemsite_id,
31569         COALESCE(_i.itemsrc_vend_item_descrip, TEXT('')), COALESCE(_i.itemsrc_vend_uom, TEXT('')),
31570         COALESCE(_i.itemsrc_invvendoruomratio, 1.00), (COALESCE(pQty, _s.orderqty) / COALESCE(_i.itemsrc_invvendoruomratio, 1.00)),
31571         _price, COALESCE(_i.itemsrc_vend_item_number, TEXT('')),
31572         pItemSourceId, pCoitemId, 'S', _s.cohead_prj_id, stdcost(_i.itemsrc_item_id),
31573         COALESCE(_i.itemsrc_manuf_name, TEXT('')), COALESCE(_i.itemsrc_manuf_item_number, TEXT('')),
31574         COALESCE(_i.itemsrc_manuf_item_descrip, TEXT('')), _taxtypeid,
31575         COALESCE(_s.coitem_memo, TEXT('')));
31576   ELSE
31577     INSERT INTO poitem
31578       ( poitem_id, poitem_status, poitem_pohead_id, poitem_linenumber, 
31579         poitem_duedate, poitem_itemsite_id,
31580         poitem_vend_item_descrip, poitem_vend_uom,
31581         poitem_invvenduomratio, poitem_qty_ordered, 
31582         poitem_unitprice, poitem_vend_item_number, 
31583         poitem_itemsrc_id, poitem_order_id, poitem_order_type, poitem_prj_id, poitem_stdcost, 
31584         poitem_manuf_name, poitem_manuf_item_number, 
31585         poitem_manuf_item_descrip, poitem_taxtype_id, poitem_comments )
31586     VALUES
31587       ( _poitemid, 'U', _poheadid, _polinenumber,
31588         COALESCE(pDueDate, _s.coitem_scheddate), _s.coitem_itemsite_id,
31589         COALESCE(_i.itemsrc_vend_item_descrip, TEXT('')), COALESCE(_i.itemsrc_vend_uom, TEXT('')),
31590         COALESCE(_i.itemsrc_invvendoruomratio, 1.00), (COALESCE(pQty, _s.orderqty) / COALESCE(_i.itemsrc_invvendoruomratio, 1.00)),
31591         _price, COALESCE(_i.itemsrc_vend_item_number, TEXT('')),
31592         pItemSourceId, pCoitemId, 'S', _s.cohead_prj_id, stdcost(_i.itemsrc_item_id),
31593         COALESCE(_i.itemsrc_manuf_name, TEXT('')), COALESCE(_i.itemsrc_manuf_item_number, TEXT('')),
31594         COALESCE(_i.itemsrc_manuf_item_descrip, TEXT('')), _taxtypeid,
31595         COALESCE(_s.coitem_memo, TEXT('')));
31596   END IF;
31597   -- Copy characteristics from the coitem to the poitem
31598   INSERT INTO charass
31599     ( charass_target_type, charass_target_id, charass_char_id,
31600       charass_value, charass_default, charass_price )
31601   SELECT 'PI', _poitemid, charass_char_id,
31602          charass_value, charass_default, charass_price
31603   FROM charass
31604   WHERE ( (charass_target_type='SI')
31605     AND   (charass_target_id=pCoitemId) );
31606
31607   UPDATE coitem
31608   SET coitem_order_type = 'P',
31609       coitem_order_id = _poitemid
31610   WHERE ( coitem_id = pCoitemId );
31611
31612   -- Generate the PoItemCreatedBySo event notice
31613   PERFORM postEvent('PoItemCreatedBySo', 'P', poitem_id,
31614                     itemsite_warehous_id,
31615                     (pohead_number || '-'|| poitem_linenumber || ': ' || item_number),
31616                     NULL, NULL, NULL, NULL)
31617   FROM poitem JOIN pohead ON (pohead_id=poitem_pohead_id)
31618               JOIN itemsite ON (itemsite_id=poitem_itemsite_id)
31619               JOIN item ON (item_id=itemsite_item_id)
31620   WHERE (poitem_id=_poitemid)
31621     AND (poitem_duedate <= (CURRENT_DATE + itemsite_eventfence));
31622
31623   RETURN _poitemid;
31624
31625 END;
31626 $_$;
31627
31628
31629 ALTER FUNCTION public.createpurchasetosale(integer, integer, boolean, numeric, date, numeric) OWNER TO admin;
31630
31631 --
31632 -- TOC entry 1348 (class 1255 OID 146565904)
31633 -- Dependencies: 4536 8
31634 -- Name: createrecurringinvoices(); Type: FUNCTION; Schema: public; Owner: admin
31635 --
31636
31637 CREATE FUNCTION createrecurringinvoices() RETURNS integer
31638     LANGUAGE plpgsql
31639     AS $$
31640 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31641 -- See www.xtuple.com/CPAL for the full text of the software license.
31642 BEGIN
31643   RAISE NOTICE 'createRecurringInvoices() has been deprecated; use createRecurringItems(NULL, ''I'') instead.';
31644
31645   RETURN createRecurringItems(NULL, 'I');
31646 END;
31647 $$;
31648
31649
31650 ALTER FUNCTION public.createrecurringinvoices() OWNER TO admin;
31651
31652 --
31653 -- TOC entry 1349 (class 1255 OID 146565905)
31654 -- Dependencies: 4536 8
31655 -- Name: createrecurringitems(integer, text); Type: FUNCTION; Schema: public; Owner: admin
31656 --
31657
31658 CREATE FUNCTION createrecurringitems(integer, text) RETURNS integer
31659     LANGUAGE plpgsql
31660     AS $_$
31661 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31662 -- See www.xtuple.com/CPAL for the full text of the software license.
31663 DECLARE
31664   pParentid  ALIAS FOR $1;      -- if NULL then all items with the given pType
31665   pType      TEXT := UPPER($2); -- if NULL then all types
31666                                 -- if both are null then all items of all types
31667   _copystmt  TEXT;
31668   _count     INTEGER := 0;
31669   _countstmt TEXT;
31670   _existcnt  INTEGER;
31671   _id        INTEGER;
31672   _interval  TEXT;
31673   _last      TIMESTAMP WITH TIME ZONE;
31674   _loopcount INTEGER := 1;
31675   _maxstmt   TEXT;
31676   _maxdate   TIMESTAMP WITH TIME ZONE := endOfTime();
31677   _result    INTEGER := 0;
31678   _next      TIMESTAMP WITH TIME ZONE;
31679   _r         RECORD;
31680   _rt        RECORD;
31681   _tmp       INTEGER;
31682
31683 BEGIN
31684   RAISE DEBUG 'createRecurringItems(%, %) entered', pParentid, pType;
31685
31686   FOR _r IN SELECT *
31687               FROM recur
31688              WHERE ((COALESCE(recur_end, endOfTime()) >= CURRENT_TIMESTAMP)
31689                 AND (pParentid IS NULL OR recur_parent_id=pParentid)
31690                 AND (pType IS NULL OR UPPER(recur_parent_type)=UPPER(pType))) LOOP
31691
31692     RAISE DEBUG 'createRecurringItems looking at recur %, %',
31693                 _r.recur_id, _r.recur_parent_type;
31694     _r.recur_max := COALESCE(_r.recur_max,
31695                              CAST(fetchMetricValue('RecurringInvoiceBuffer') AS INTEGER),
31696                              1);
31697     _interval := CASE _r.recur_period WHEN 'Y' THEN ' year'
31698                                       WHEN 'M' THEN ' month'
31699                                       WHEN 'W' THEN ' week'
31700                                       WHEN 'D' THEN ' day'
31701                                       WHEN 'H' THEN ' hour'
31702                                       WHEN 'm' THEN ' minute'
31703                                       ELSE NULL
31704                  END;
31705
31706     IF (_interval IS NULL OR COALESCE(_r.recur_freq, 0) <= 0) THEN
31707       RAISE EXCEPTION 'Unknown recurrence frequency % % ON % %',
31708                       _r.recur_freq,        _r.recur_period,
31709                       _r.recur_parent_type, _r.recur_parent_id;
31710     END IF;
31711
31712     SELECT * INTO _rt FROM recurtype WHERE (UPPER(recurtype_type)=UPPER(pType));
31713     GET DIAGNOSTICS _count = ROW_COUNT;
31714     IF (_count <= 0) THEN
31715       RETURN -10;
31716     END IF;
31717
31718     -- if the recurrence type has a max lookahead window, use it
31719     IF (_r.recur_parent_type = 'I') THEN
31720       _maxdate := CURRENT_TIMESTAMP + CAST(fetchMetricText('RecurringInvoiceBuffer') || ' days' AS INTERVAL);
31721     END IF;
31722     IF (_r.recur_parent_type = 'V') THEN
31723       _maxdate := CURRENT_TIMESTAMP + CAST(fetchMetricText('RecurringVoucherBuffer') || ' days' AS INTERVAL);
31724     END IF;
31725     IF (_maxdate > _r.recur_end) THEN   -- if recur_end is null, _maxdate is ok
31726       _maxdate = _r.recur_end;
31727     END IF;
31728
31729     -- build statements dynamically from the recurtype table because packages
31730     -- might also require recurring items. this way the algorithm is fixed
31731     -- and the details are data-driven
31732     _countstmt := 'SELECT COUNT(*) FROM [fulltable]' 
31733                || ' WHERE (($1=[table]_recurring_[table]_id)'
31734                || ' AND NOT([done]) '
31735                || ' AND ([limit]));';
31736     _countstmt := REPLACE(_countstmt, '[fulltable]', _rt.recurtype_table);
31737     _countstmt := REPLACE(_countstmt, '[table]',
31738                           REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
31739     _countstmt := REPLACE(_countstmt, '[done]',  _rt.recurtype_donecheck);
31740     _countstmt := REPLACE(_countstmt, '[limit]',
31741                           COALESCE(_rt.recurtype_limit, 'TRUE'));
31742
31743     _maxstmt := 'SELECT MAX([schedcol]) FROM [fulltable]'
31744                || ' WHERE (($1=[table]_recurring_[table]_id)'
31745                || '    AND ([limit]));';
31746     _maxstmt := REPLACE(_maxstmt, '[schedcol]', _rt.recurtype_schedcol);
31747     _maxstmt := REPLACE(_maxstmt, '[fulltable]',_rt.recurtype_table);
31748     _maxstmt := REPLACE(_maxstmt, '[table]',
31749                           REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
31750     _maxstmt := REPLACE(_maxstmt, '[limit]', COALESCE(_rt.recurtype_limit,
31751                                                      'TRUE'));
31752
31753     _copystmt := 'SELECT [copy]($1, [datetime] [more]);';
31754     _copystmt := REPLACE(_copystmt, '[copy]', _rt.recurtype_copyfunc);
31755     _copystmt := REPLACE(_copystmt, '[datetime]',
31756                          CASE WHEN UPPER(_rt.recurtype_copyargs[2])='DATE' THEN
31757                                     'CAST(''$2'' AS DATE)'
31758                               ELSE '''$2''' END);
31759     -- 8.4+:
31760     -- _copystmt := REPLACE(_copystmt, '[more]',
31761     --                      REPEAT(', NULL',
31762     --                             array_length(_rt.recurtype_copyargs) - 2));
31763     _tmp := CAST(REPLACE(REGEXP_REPLACE(array_dims(_rt.recurtype_copyargs),
31764                                         '.*:', ''), ']', '') AS INTEGER);
31765     _copystmt := REPLACE(_copystmt, '[more]', REPEAT(', NULL', _tmp - 2));
31766
31767     EXECUTE REPLACE(_countstmt, '$1', _r.recur_parent_id::TEXT) INTO _existcnt;
31768     EXECUTE REPLACE(_maxstmt,   '$1', _r.recur_parent_id::TEXT) INTO _last;
31769     RAISE DEBUG E'% got %, % got %', _countstmt, _existcnt, _maxstmt, _last;
31770
31771     _next := _last;
31772     _loopcount := 1;
31773     WHILE (_existcnt < _r.recur_max AND _next < _maxdate) LOOP
31774       _next := _last +
31775                CAST(_r.recur_freq * _loopcount || _interval AS INTERVAL);
31776       RAISE DEBUG 'createrecurringitems looping, existcnt = %, max = %, is % between % and %?',
31777                   _existcnt, _r.recur_max, _next, _r.recur_start, _r.recur_end;
31778
31779       IF (_next BETWEEN _r.recur_start AND _maxdate) THEN
31780         RAISE DEBUG 'createrecurringitems executing % with % and %',
31781                     _copystmt, _r.recur_parent_id, _next;
31782         -- 8.4+: EXECUTE _copystmt INTO _id USING _r.recur_parent_id, _next;
31783         EXECUTE REPLACE(REPLACE(_copystmt, '$1', _r.recur_parent_id::TEXT),
31784                                            '$2', _next::TEXT) INTO _id;
31785         RAISE DEBUG 'Copying for % returned %', _next, _id;
31786         _result   := _result   + 1;
31787         _existcnt := _existcnt + 1;
31788       END IF;
31789       _loopcount := _loopcount + 1;
31790     END LOOP;
31791   END LOOP;
31792
31793   RETURN _result;
31794 END;
31795 $_$;
31796
31797
31798 ALTER FUNCTION public.createrecurringitems(integer, text) OWNER TO admin;
31799
31800 --
31801 -- TOC entry 1350 (class 1255 OID 146565907)
31802 -- Dependencies: 4536 8
31803 -- Name: createtodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
31804 --
31805
31806 CREATE FUNCTION createtodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, text) RETURNS integer
31807     LANGUAGE plpgsql
31808     AS $_$  
31809 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31810 -- See www.xtuple.com/CPAL for the full text of the software license.
31811 BEGIN
31812   RETURN createTodoItem($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, NULL);
31813 END;
31814 $_$;
31815
31816
31817 ALTER FUNCTION public.createtodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, text) OWNER TO admin;
31818
31819 --
31820 -- TOC entry 1352 (class 1255 OID 146565908)
31821 -- Dependencies: 4536 8
31822 -- Name: createtodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
31823 --
31824
31825 CREATE FUNCTION createtodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, text, integer) RETURNS integer
31826     LANGUAGE plpgsql
31827     AS $_$
31828 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31829 -- See www.xtuple.com/CPAL for the full text of the software license.
31830 DECLARE
31831   ptodoid     ALIAS FOR  $1;
31832   pusername   ALIAS FOR  $2;
31833   pname       ALIAS FOR  $3;
31834   pdesc       ALIAS FOR  $4;
31835   pincdtid    ALIAS FOR  $5;
31836   pcrmacctid  ALIAS FOR  $6;
31837   pOpheadid   ALIAS FOR  $7;
31838   pstarted    ALIAS FOR  $8;
31839   pdue        ALIAS FOR  $9;
31840   pstatus     ALIAS FOR $10;
31841   passigned   ALIAS FOR $11;
31842   pcompleted  ALIAS FOR $12;
31843   ppriority   ALIAS FOR $13;
31844   pnotes      ALIAS FOR $14;
31845   powner      ALIAS FOR $15;
31846   pcntctid    ALIAS FOR $16;
31847
31848   _todoid     INTEGER;
31849   _priority   INTEGER         := ppriority;
31850   _status     CHARACTER(1)    := pstatus;
31851   _incdtid    INTEGER         := pincdtid;
31852   _crmacctid  INTEGER         := pcrmacctid;
31853   _opheadid   INTEGER         := pOpheadid;
31854   _assigned   DATE            := passigned;
31855   _result     INTEGER;
31856
31857 BEGIN
31858   IF (pusername IS NULL OR pusername = '') THEN
31859     RETURN -1;
31860   END IF;
31861
31862   IF (pname IS NULL OR pname = '') THEN
31863     RETURN -2;
31864   END IF;
31865
31866   IF (pdue IS NULL) THEN
31867     RETURN -3;
31868   END IF;
31869
31870   IF (pcompleted IS NOT NULL) THEN
31871     _status := 'C';
31872   ELSIF (pstatus IS NULL AND pstarted IS NOT NULL) THEN
31873     _status := 'I';
31874   ELSIF (pstatus IS NULL) THEN
31875     _status := 'N';
31876   END IF;
31877
31878   IF (_incdtid <= 0) THEN
31879     _incdtid := NULL;
31880   END IF;
31881
31882   IF (_crmacctid <= 0) THEN
31883     _crmacctid := NULL;
31884   END IF;
31885
31886   IF (_opheadid <= 0) THEN
31887     _opheadid := NULL;
31888   END IF;
31889
31890   IF (_priority <= 0) THEN
31891     _priority := NULL;
31892   END IF;
31893
31894   IF (_assigned IS NULL) THEN
31895     _assigned := CURRENT_DATE;
31896   END IF;
31897
31898   IF (ptodoid IS NULL) THEN
31899     SELECT NEXTVAL('todoitem_todoitem_id_seq') INTO _todoid;
31900   ELSE
31901     _todoid := ptodoid;
31902   END IF;
31903
31904   INSERT INTO todoitem ( todoitem_id, todoitem_username, todoitem_name,
31905                          todoitem_description, todoitem_incdt_id,
31906                          todoitem_creator_username, todoitem_status,
31907                          todoitem_active, todoitem_start_date,
31908                          todoitem_due_date, todoitem_assigned_date,
31909                          todoitem_completed_date, todoitem_priority_id,
31910                          todoitem_notes, todoitem_crmacct_id,
31911                          todoitem_ophead_id, todoitem_owner_username,
31912                          todoitem_cntct_id
31913               ) VALUES ( _todoid, pusername, pname,
31914                          pdesc, _incdtid,
31915                          getEffectiveXtUser(), _status,
31916                          TRUE, pstarted,
31917                          pdue, _assigned,
31918                          pcompleted, _priority, pnotes, _crmacctid, _opheadid, powner,
31919                          pcntctid );
31920
31921   RETURN _todoid;
31922 END;
31923 $_$;
31924
31925
31926 ALTER FUNCTION public.createtodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, text, integer) OWNER TO admin;
31927
31928 --
31929 -- TOC entry 1353 (class 1255 OID 146565909)
31930 -- Dependencies: 4536 8
31931 -- Name: createurl(text, text); Type: FUNCTION; Schema: public; Owner: admin
31932 --
31933
31934 CREATE FUNCTION createurl(text, text) RETURNS integer
31935     LANGUAGE plpgsql
31936     AS $_$
31937 declare
31938   pTitle ALIAS FOR $1;
31939   pUrl ALIAS FOR $2;
31940   _id integer;
31941 begin
31942   _id := nextval('urlinfo_url_id_seq');
31943   insert into urlinfo (url_id, url_title, url_url) values (_id, pTitle, pUrl);
31944   return _id;
31945 end;
31946 $_$;
31947
31948
31949 ALTER FUNCTION public.createurl(text, text) OWNER TO admin;
31950
31951 --
31952 -- TOC entry 1354 (class 1255 OID 146565910)
31953 -- Dependencies: 4536 8
31954 -- Name: createuser(text, boolean); Type: FUNCTION; Schema: public; Owner: admin
31955 --
31956
31957 CREATE FUNCTION createuser(pusername text, pcreateusers boolean) RETURNS integer
31958     LANGUAGE plpgsql
31959     AS $$
31960 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31961 -- See www.xtuple.com/CPAL for the full text of the software license.
31962 BEGIN
31963   IF (pCreateUsers) THEN
31964     EXECUTE 'CREATE USER "' || pUsername || '" CREATEROLE   IN GROUP xtrole;';
31965   ELSE
31966     EXECUTE 'CREATE USER "' || pUsername || '" NOCREATEROLE IN GROUP xtrole;';
31967   END IF;
31968   RETURN 1;
31969 END;
31970 $$;
31971
31972
31973 ALTER FUNCTION public.createuser(pusername text, pcreateusers boolean) OWNER TO admin;
31974
31975 --
31976 -- TOC entry 1356 (class 1255 OID 146565912)
31977 -- Dependencies: 4536 8
31978 -- Name: createwo(integer, integer, numeric, integer, date, text); Type: FUNCTION; Schema: public; Owner: admin
31979 --
31980
31981 CREATE FUNCTION createwo(integer, integer, numeric, integer, date, text) RETURNS integer
31982     LANGUAGE plpgsql
31983     AS $_$
31984 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
31985 -- See www.xtuple.com/CPAL for the full text of the software license.
31986 DECLARE
31987   pWoNumber ALIAS FOR $1;
31988   pItemsiteid ALIAS FOR $2;
31989   pQtyOrdered ALIAS FOR $3;
31990   pLeadTime ALIAS FOR $4;
31991   pDueDate ALIAS FOR $5;
31992   pProductionNotes ALIAS FOR $6;
31993
31994 BEGIN
31995   RETURN createWo( pWoNumber, pItemsiteid, 1, pQtyOrdered,
31996                    (pDueDate - pLeadTime), pDueDate,
31997                    pProductionNotes, NULL, NULL, -1 ); 
31998 END;
31999 $_$;
32000
32001
32002 ALTER FUNCTION public.createwo(integer, integer, numeric, integer, date, text) OWNER TO admin;
32003
32004 --
32005 -- TOC entry 1357 (class 1255 OID 146565913)
32006 -- Dependencies: 4536 8
32007 -- Name: createwo(integer, integer, numeric, date, date, text); Type: FUNCTION; Schema: public; Owner: admin
32008 --
32009
32010 CREATE FUNCTION createwo(integer, integer, numeric, date, date, text) RETURNS integer
32011     LANGUAGE plpgsql
32012     AS $_$
32013 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32014 -- See www.xtuple.com/CPAL for the full text of the software license.
32015 DECLARE
32016   pWoNumber ALIAS FOR $1;
32017   pItemsiteid ALIAS FOR $2;
32018   pQtyOrdered ALIAS FOR $3;
32019   pStartDate ALIAS FOR $4;
32020   pDueDate ALIAS FOR $5;
32021   pProductionNotes ALIAS FOR $6;
32022
32023 BEGIN
32024   RETURN createWo( pWoNumber, pItemsiteid, 1, pQtyOrdered,
32025                    pStartDate, pDueDate, pProductionNotes, NULL, NULL, -1);
32026 END;
32027 $_$;
32028
32029
32030 ALTER FUNCTION public.createwo(integer, integer, numeric, date, date, text) OWNER TO admin;
32031
32032 --
32033 -- TOC entry 1355 (class 1255 OID 146565911)
32034 -- Dependencies: 4536 8
32035 -- Name: createwo(integer, integer, numeric, integer, date, text, character, integer); Type: FUNCTION; Schema: public; Owner: admin
32036 --
32037
32038 CREATE FUNCTION createwo(integer, integer, numeric, integer, date, text, character, integer) RETURNS integer
32039     LANGUAGE plpgsql
32040     AS $_$
32041 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32042 -- See www.xtuple.com/CPAL for the full text of the software license.
32043 DECLARE
32044   pWoNumber ALIAS FOR $1;
32045   pItemsiteid ALIAS FOR $2;
32046   pQtyOrdered ALIAS FOR $3;
32047   pLeadTime ALIAS FOR $4;
32048   pDueDate ALIAS FOR $5;
32049   pProductionNotes ALIAS FOR $6;
32050   pParentType ALIAS FOR $7;
32051   pParentId ALIAS FOR $8;
32052
32053 BEGIN
32054   RETURN createWo( pWoNumber, pItemsiteid, 1, pQtyOrdered,
32055                    (pDueDate - pLeadTime), pDueDate,
32056                    pProductionNotes, pParentType, pParentId, -1 ); 
32057 END;
32058 $_$;
32059
32060
32061 ALTER FUNCTION public.createwo(integer, integer, numeric, integer, date, text, character, integer) OWNER TO admin;
32062
32063 --
32064 -- TOC entry 1358 (class 1255 OID 146565914)
32065 -- Dependencies: 4536 8
32066 -- Name: createwo(integer, integer, integer, numeric, integer, date, text, character, integer); Type: FUNCTION; Schema: public; Owner: admin
32067 --
32068
32069 CREATE FUNCTION createwo(integer, integer, integer, numeric, integer, date, text, character, integer) RETURNS integer
32070     LANGUAGE plpgsql
32071     AS $_$
32072 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32073 -- See www.xtuple.com/CPAL for the full text of the software license.
32074 DECLARE
32075   pWoNumber ALIAS FOR $1;
32076   pItemsiteid ALIAS FOR $2;
32077   pPriority ALIAS FOR $3;
32078   pQtyOrdered ALIAS FOR $4;
32079   pLeadTime ALIAS FOR $5;
32080   pDueDate ALIAS FOR $6;
32081   pProductionNotes ALIAS FOR $7;
32082   pParentType ALIAS FOR $8;
32083   pParentId ALIAS FOR $9;
32084
32085 BEGIN
32086   RETURN createWo(pWoNumber, pItemsiteid, pPriority, pQtyOrdered,
32087                   (pDueDate - pLeadTime), pDueDate, pProductionNotes,
32088                   pParentType, pParentId, -1);
32089 END;
32090 $_$;
32091
32092
32093 ALTER FUNCTION public.createwo(integer, integer, integer, numeric, integer, date, text, character, integer) OWNER TO admin;
32094
32095 --
32096 -- TOC entry 1359 (class 1255 OID 146565915)
32097 -- Dependencies: 4536 8
32098 -- Name: createwo(integer, integer, integer, numeric, integer, date, text, character, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
32099 --
32100
32101 CREATE FUNCTION createwo(integer, integer, integer, numeric, integer, date, text, character, integer, integer) RETURNS integer
32102     LANGUAGE plpgsql
32103     AS $_$
32104 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32105 -- See www.xtuple.com/CPAL for the full text of the software license.
32106 DECLARE
32107   pWoNumber ALIAS FOR $1;
32108   pItemsiteid ALIAS FOR $2;
32109   pPriority ALIAS FOR $3;
32110   pQtyOrdered ALIAS FOR $4;
32111   pLeadTime ALIAS FOR $5;
32112   pDueDate ALIAS FOR $6;
32113   pProductionNotes ALIAS FOR $7;
32114   pParentType ALIAS FOR $8;
32115   pParentId ALIAS FOR $9;
32116   pProjectId ALIAS FOR $10;
32117
32118 BEGIN
32119   RETURN createWo(pWoNumber, pItemsiteid, pPriority, pQtyOrdered,
32120                   (pDueDate - pLeadTime), pDueDate, pProductionNotes,
32121                   pParentType, pParentId, pProjectId);
32122 END;
32123 $_$;
32124
32125
32126 ALTER FUNCTION public.createwo(integer, integer, integer, numeric, integer, date, text, character, integer, integer) OWNER TO admin;
32127
32128 --
32129 -- TOC entry 1360 (class 1255 OID 146565916)
32130 -- Dependencies: 4536 8
32131 -- Name: createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
32132 --
32133
32134 CREATE FUNCTION createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer) RETURNS integer
32135     LANGUAGE plpgsql
32136     AS $_$
32137 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32138 -- See www.xtuple.com/CPAL for the full text of the software license.
32139 DECLARE
32140   pWoNumber ALIAS FOR $1;
32141   pItemsiteid ALIAS FOR $2;
32142   pPriority ALIAS FOR $3;
32143   pQtyOrdered ALIAS FOR $4;
32144   pStartDate ALIAS FOR $5;
32145   pDueDate ALIAS FOR $6;
32146   pProductionNotes ALIAS FOR $7;
32147   pParentType ALIAS FOR $8;
32148   pParentId ALIAS FOR $9;
32149   pProjectId ALIAS FOR $10;
32150   _woid INTEGER;
32151   _result INTEGER;
32152   _parentType char(1);
32153   _bomrevid INTEGER;
32154   _boorevid INTEGER;
32155
32156 BEGIN
32157
32158   SELECT getActiveRevId('BOM',itemsite_item_id) INTO _bomrevid
32159   FROM itemsite
32160   WHERE (itemsite_id=pItemsiteid);
32161
32162   SELECT getActiveRevId('BOO',itemsite_item_id) INTO _boorevid
32163   FROM itemsite
32164   WHERE (itemsite_id=pItemsiteid);
32165   
32166   RETURN createWo(pWoNumber, pItemsiteid, pPriority, pQtyOrdered,
32167                   pStartDate, pDueDate, pProductionNotes,
32168                   pParentType, pParentId, pProjectId, _bomrevid, _boorevid, NULL);
32169
32170 END;
32171 $_$;
32172
32173
32174 ALTER FUNCTION public.createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer) OWNER TO admin;
32175
32176 --
32177 -- TOC entry 1361 (class 1255 OID 146565917)
32178 -- Dependencies: 4536 8
32179 -- Name: createwo(integer, integer, integer, numeric, integer, date, text, character, integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
32180 --
32181
32182 CREATE FUNCTION createwo(integer, integer, integer, numeric, integer, date, text, character, integer, integer, integer, integer) RETURNS integer
32183     LANGUAGE plpgsql
32184     AS $_$
32185 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32186 -- See www.xtuple.com/CPAL for the full text of the software license.
32187 DECLARE
32188   pWoNumber ALIAS FOR $1;
32189   pItemsiteid ALIAS FOR $2;
32190   pPriority ALIAS FOR $3;
32191   pQtyOrdered ALIAS FOR $4;
32192   pLeadTime ALIAS FOR $5;
32193   pDueDate ALIAS FOR $6;
32194   pProductionNotes ALIAS FOR $7;
32195   pParentType ALIAS FOR $8;
32196   pParentId ALIAS FOR $9;
32197   pProjectId ALIAS FOR $10;
32198   pBomRevId ALIAS FOR $11;
32199   pBooRevId ALIAS FOR $12;
32200
32201 BEGIN
32202   RETURN createWo(pWoNumber, pItemsiteid, pPriority, pQtyOrdered,
32203                   (pDueDate - pLeadTime), pDueDate, pProductionNotes,
32204                   pParentType, pParentId, pProjectId, pBomRevId, pBooRevId, NULL);
32205 END;
32206 $_$;
32207
32208
32209 ALTER FUNCTION public.createwo(integer, integer, integer, numeric, integer, date, text, character, integer, integer, integer, integer) OWNER TO admin;
32210
32211 --
32212 -- TOC entry 1362 (class 1255 OID 146565918)
32213 -- Dependencies: 4536 8
32214 -- Name: createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
32215 --
32216
32217 CREATE FUNCTION createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer, integer, integer) RETURNS integer
32218     LANGUAGE plpgsql
32219     AS $_$
32220 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32221 -- See www.xtuple.com/CPAL for the full text of the software license.
32222 DECLARE
32223   pWoNumber ALIAS FOR $1;
32224   pItemsiteid ALIAS FOR $2;
32225   pPriority ALIAS FOR $3;
32226   pQtyOrdered ALIAS FOR $4;
32227   pStartDate ALIAS FOR $5;
32228   pDueDate ALIAS FOR $6;
32229   pProductionNotes ALIAS FOR $7;
32230   pParentType ALIAS FOR $8;
32231   pParentId ALIAS FOR $9;
32232   pProjectId ALIAS FOR $10;
32233   pBomRevId ALIAS FOR $11;
32234   pBooRevId ALIAS FOR $12;
32235 BEGIN
32236   RETURN createWo(pWoNumber, pItemsiteid, pPriority, pQtyOrdered,
32237                   pStartDate, pDueDate, pProductionNotes,
32238                   pParentType, pParentId, pProjectId, pBomRevId, pBooRevId, NULL);
32239 END;
32240 $_$;
32241
32242
32243 ALTER FUNCTION public.createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer, integer, integer) OWNER TO admin;
32244
32245 --
32246 -- TOC entry 1363 (class 1255 OID 146565919)
32247 -- Dependencies: 4536 8
32248 -- Name: createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer, integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
32249 --
32250
32251 CREATE FUNCTION createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer, integer, integer, text) RETURNS integer
32252     LANGUAGE plpgsql
32253     AS $_$
32254 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32255 -- See www.xtuple.com/CPAL for the full text of the software license.
32256 DECLARE
32257   pWoNumber ALIAS FOR $1;
32258   pItemsiteid ALIAS FOR $2;
32259   pPriority ALIAS FOR $3;
32260   pQtyOrdered ALIAS FOR $4;
32261   pStartDate ALIAS FOR $5;
32262   pDueDate ALIAS FOR $6;
32263   pProductionNotes ALIAS FOR $7;
32264   pParentType ALIAS FOR $8;
32265   pParentId ALIAS FOR $9;
32266   pProjectId ALIAS FOR $10;
32267   pBomRevId ALIAS FOR $11;
32268   pBooRevId ALIAS FOR $12;
32269   pCosMethod ALIAS FOR $13;
32270   _startDate DATE;
32271   _woid INTEGER;
32272   _result INTEGER;
32273   _parentType char(1);
32274   _parentId INTEGER;
32275   _cosmethod char(1);
32276   _itemsite RECORD;
32277   
32278 BEGIN
32279   
32280   _parentType := COALESCE(pParentType, ' ');
32281   _parentId   := COALESCE(pParentId, -1);
32282
32283   SELECT * INTO _itemsite FROM itemsite WHERE itemsite_id = pItemsiteid;
32284
32285 --  Check to make sure the itemsite specified is supplied at itemsite
32286   IF (NOT _itemsite.itemsite_wosupply) THEN
32287     RETURN -1;
32288   END IF;
32289
32290 --  Check to make sure if this is a job item that it is tied to a sales order
32291 --  Or if it is just an avarage costed item
32292   IF (pCosMethod IN ('D', 'P')) THEN
32293     _cosmethod := pCosMethod;
32294   ELSE
32295     IF (_itemsite.itemsite_costmethod = 'J') THEN
32296       IF (_parentType = ' ' OR _parentId = -1) THEN
32297         RAISE EXCEPTION 'Work Orders for Item Sites that are Job cost must have a parent order.';
32298       ELSE
32299         SELECT COALESCE(itemsite_cosdefault,fetchmetrictext('JobItemCosDefault'),'D') INTO _cosmethod FROM itemsite WHERE itemsite_id=pItemsiteid;
32300       END IF;
32301     ELSIF (_itemsite.itemsite_costmethod = 'A') THEN
32302       _cosmethod := COALESCE(_itemsite.itemsite_cosdefault,fetchmetrictext('JobItemCosDefault'),'D');
32303     END IF;
32304   END IF;
32305
32306 --  Check to see if the site calendar metric is set, and if so adjust the start date if necessary
32307   IF (fetchmetricbool('UseSiteCalendar')) THEN
32308     _startDate := calculatenextworkingdate(_itemsite.itemsite_warehous_id, pStartDate, 0);
32309     IF (_startDate != pStartDate) THEN
32310       _startDate := calculatenextworkingdate(_itemsite.itemsite_warehous_id, pDueDate, -_itemsite.itemsite_leadtime);
32311     END IF;
32312   ELSE
32313     _startDate := pStartDate;
32314   END IF;
32315   
32316 --  Grab the next wo_id
32317   SELECT NEXTVAL('wo_wo_id_seq') INTO _woid;
32318
32319 --  Create the W/O
32320   INSERT INTO wo
32321   ( wo_id, wo_number, wo_subnumber, wo_itemsite_id,
32322     wo_priority, wo_ordtype, wo_ordid,
32323     wo_status, wo_startdate, wo_duedate,
32324     wo_qtyord, wo_qtyrcv, wo_prodnotes, wo_prj_id,
32325     wo_bom_rev_id, wo_boo_rev_id, wo_cosmethod )
32326   SELECT _woid, pWoNumber, nextWoSubnumber(pWoNumber), itemsite_id,
32327          pPriority, _parentType, pParentId,
32328          'O', _startDate, pDueDate,
32329          roundQty(item_fractional, pQtyOrdered), 0, pProductionNotes, pProjectId, 
32330          pBomRevid, pBooRevid, _cosmethod
32331   FROM itemsite, item
32332   WHERE ((itemsite_item_id=item_id)
32333    AND (itemsite_id=pItemsiteid));
32334
32335 --  Explode the newly created W/O according to metrics
32336   IF ( ( SELECT (metric_value='t')
32337          FROM metric
32338          WHERE (metric_name='AutoExplodeWO') ) ) THEN
32339     SELECT explodeWo( _woid, ( SELECT (metric_value = 'M')
32340                                FROM metric
32341                                WHERE (metric_name='WOExplosionLevel') ) ) INTO _result;
32342   ELSE
32343     _result := _woid;
32344   END IF;
32345
32346   RETURN _result;
32347
32348 END;
32349 $_$;
32350
32351
32352 ALTER FUNCTION public.createwo(integer, integer, integer, numeric, date, date, text, character, integer, integer, integer, integer, text) OWNER TO admin;
32353
32354 --
32355 -- TOC entry 1364 (class 1255 OID 146565920)
32356 -- Dependencies: 4536 8
32357 -- Name: createwomaterial(integer, integer, character, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
32358 --
32359
32360 CREATE FUNCTION createwomaterial(integer, integer, character, numeric, numeric) RETURNS integer
32361     LANGUAGE plpgsql
32362     AS $_$
32363 DECLARE
32364   pWoid ALIAS FOR $1;
32365   pItemsiteid ALIAS FOR $2;
32366   pIssueMethod ALIAS FOR $3;
32367   pQtyPer ALIAS FOR $4;
32368   pScrap ALIAS FOR $5;
32369   _result INTEGER;
32370 BEGIN
32371   SELECT createWoMaterial(pWoid, pItemsiteid, pIssueMethod, item_inv_uom_id, pQtyPer, pScrap)
32372     INTO _result
32373     FROM itemsite JOIN item ON (itemsite_item_id=item_id)
32374    WHERE(itemsite_id=pItemsiteid);
32375   RETURN _result;
32376 END;
32377 $_$;
32378
32379
32380 ALTER FUNCTION public.createwomaterial(integer, integer, character, numeric, numeric) OWNER TO admin;
32381
32382 --
32383 -- TOC entry 1365 (class 1255 OID 146565921)
32384 -- Dependencies: 4536 8
32385 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
32386 --
32387
32388 CREATE FUNCTION createwomaterial(integer, integer, character, integer, numeric, numeric) RETURNS integer
32389     LANGUAGE plpgsql
32390     AS $_$
32391 DECLARE
32392   pWoid ALIAS FOR $1;
32393   pItemsiteid ALIAS FOR $2;
32394   pIssueMethod ALIAS FOR $3;
32395   pUomId ALIAS FOR $4;
32396   pQtyPer ALIAS FOR $5;
32397   pScrap ALIAS FOR $6;
32398   _womatlid INTEGER;
32399
32400 BEGIN
32401
32402   SELECT createWoMaterial(pWoid,pItemsiteid,pIssueMethod,pUomId,pQtyPer,pScrap,-1, NULL, NULL) INTO _womatlid;
32403
32404   RETURN _womatlid;
32405 END;
32406 $_$;
32407
32408
32409 ALTER FUNCTION public.createwomaterial(integer, integer, character, integer, numeric, numeric) OWNER TO admin;
32410
32411 --
32412 -- TOC entry 1368 (class 1255 OID 146565924)
32413 -- Dependencies: 4536 8
32414 -- Name: createwomaterial(integer, integer, character, numeric, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
32415 --
32416
32417 CREATE FUNCTION createwomaterial(integer, integer, character, numeric, numeric, numeric) RETURNS integer
32418     LANGUAGE plpgsql
32419     AS $_$
32420 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32421 -- See www.xtuple.com/CPAL for the full text of the software license.
32422 DECLARE
32423   pWoid ALIAS FOR $1;
32424   pItemsiteid ALIAS FOR $2;
32425   pIssueMethod ALIAS FOR $3;
32426   pQtyFxd ALIAS FOR $4;
32427   pQtyPer ALIAS FOR $5;
32428   pScrap ALIAS FOR $6;
32429   _result INTEGER;
32430 BEGIN
32431   SELECT createWoMaterial(pWoid, pItemsiteid, pIssueMethod, item_inv_uom_id, pQtyFxd, pQtyPer, pScrap)
32432     INTO _result
32433     FROM itemsite JOIN item ON (itemsite_item_id=item_id)
32434    WHERE(itemsite_id=pItemsiteid);
32435   RETURN _result;
32436 END;
32437 $_$;
32438
32439
32440 ALTER FUNCTION public.createwomaterial(integer, integer, character, numeric, numeric, numeric) OWNER TO admin;
32441
32442 --
32443 -- TOC entry 1366 (class 1255 OID 146565922)
32444 -- Dependencies: 4536 8
32445 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
32446 --
32447
32448 CREATE FUNCTION createwomaterial(integer, integer, character, integer, numeric, numeric, integer) RETURNS integer
32449     LANGUAGE plpgsql
32450     AS $_$
32451 DECLARE
32452   pWoid ALIAS FOR $1;
32453   pItemsiteid ALIAS FOR $2;
32454   pIssueMethod ALIAS FOR $3;
32455   pUomId ALIAS FOR $4;
32456   pQtyPer ALIAS FOR $5;
32457   pScrap ALIAS FOR $6;
32458   pBomitemId ALIAS FOR $7;
32459   _womatlid INTEGER;
32460
32461 BEGIN
32462
32463   _womatlid := (SELECT NEXTVAL('womatl_womatl_id_seq'));
32464
32465   INSERT INTO womatl
32466   ( womatl_id, womatl_wo_id, womatl_itemsite_id,
32467     womatl_issuemethod, womatl_uom_id, womatl_qtyper, womatl_scrap,
32468     womatl_qtyreq, womatl_qtyiss, womatl_qtywipscrap,
32469     womatl_wooper_id, womatl_bomitem_id, womatl_duedate )
32470   SELECT _womatlid, wo_id, pItemsiteid,
32471          pIssueMethod, pUomId, pQtyPer, pScrap,
32472          roundQty(item_fractional, (wo_qtyord * (pQtyPer * (1 + pScrap)))), 0, 0,
32473          -1, pBomitemId, wo_startdate
32474   FROM wo, itemsite, item
32475   WHERE ( (itemsite_item_id=item_id)
32476    AND (wo_id=pWoid)
32477    AND (itemsite_id=pItemsiteid) );
32478
32479   UPDATE wo
32480   SET wo_adhoc=TRUE
32481   WHERE (wo_id=pWoid);
32482
32483   UPDATE wo
32484   SET wo_status='E'
32485   WHERE ( (wo_status='O')
32486    AND (wo_id=pWoid) );
32487
32488   RETURN _womatlid;
32489 END;
32490 $_$;
32491
32492
32493 ALTER FUNCTION public.createwomaterial(integer, integer, character, integer, numeric, numeric, integer) OWNER TO admin;
32494
32495 --
32496 -- TOC entry 1369 (class 1255 OID 146565925)
32497 -- Dependencies: 4536 8
32498 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
32499 --
32500
32501 CREATE FUNCTION createwomaterial(integer, integer, character, integer, numeric, numeric, numeric) RETURNS integer
32502     LANGUAGE plpgsql
32503     AS $_$
32504 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32505 -- See www.xtuple.com/CPAL for the full text of the software license.
32506 DECLARE
32507   pWoid ALIAS FOR $1;
32508   pItemsiteid ALIAS FOR $2;
32509   pIssueMethod ALIAS FOR $3;
32510   pUomId ALIAS FOR $4;
32511   pQtyFxd ALIAS FOR $5;
32512   pQtyPer ALIAS FOR $6;
32513   pScrap ALIAS FOR $7;
32514   _womatlid INTEGER;
32515
32516 BEGIN
32517
32518   SELECT createWoMaterial(pWoid,pItemsiteid,pIssueMethod,pUomId,pQtyFxd,pQtyPer,pScrap,-1, NULL, NULL) INTO _womatlid;
32519
32520   RETURN _womatlid;
32521 END;
32522 $_$;
32523
32524
32525 ALTER FUNCTION public.createwomaterial(integer, integer, character, integer, numeric, numeric, numeric) OWNER TO admin;
32526
32527 --
32528 -- TOC entry 1367 (class 1255 OID 146565923)
32529 -- Dependencies: 4536 8
32530 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
32531 --
32532
32533 CREATE FUNCTION createwomaterial(integer, integer, character, integer, numeric, numeric, integer, text, text) RETURNS integer
32534     LANGUAGE plpgsql
32535     AS $_$
32536 DECLARE
32537   pWoid ALIAS FOR $1;
32538   pItemsiteid ALIAS FOR $2;
32539   pIssueMethod ALIAS FOR $3;
32540   pUomId ALIAS FOR $4;
32541   pQtyPer ALIAS FOR $5;
32542   pScrap ALIAS FOR $6;
32543   pBomitemId ALIAS FOR $7;
32544   pNotes ALIAS FOR $8;
32545   pRef ALIAS FOR $9;
32546   _womatlid INTEGER;
32547   _p RECORD;
32548
32549 BEGIN
32550
32551   _womatlid := (SELECT NEXTVAL('womatl_womatl_id_seq'));
32552
32553   INSERT INTO womatl
32554   ( womatl_id, womatl_wo_id, womatl_itemsite_id,
32555     womatl_issuemethod, womatl_uom_id, womatl_qtyper, womatl_scrap,
32556     womatl_qtyreq, womatl_qtyiss, womatl_qtywipscrap,
32557     womatl_wooper_id, womatl_bomitem_id, womatl_duedate, womatl_notes, womatl_ref )
32558   SELECT _womatlid, wo_id, pItemsiteid,
32559          pIssueMethod, pUomId, pQtyPer, pScrap,
32560          roundQty(item_fractional, (wo_qtyord * (pQtyPer * (1 + pScrap)))), 0, 0,
32561          -1, pBomitemId, wo_startdate, pNotes, pRef 
32562   FROM wo, itemsite, item
32563   WHERE ( (itemsite_item_id=item_id)
32564    AND (wo_id=pWoid)
32565    AND (itemsite_id=pItemsiteid) );
32566
32567 -- Handle all of the Phantom material requirements
32568   WHILE ( ( SELECT COUNT(*)
32569             FROM womatl, itemsite, item
32570             WHERE ( (womatl_itemsite_id=itemsite_id)
32571              AND (itemsite_item_id=item_id)
32572              AND (womatl_wo_id=pWoid)
32573              AND (item_type='F') ) ) > 0 ) LOOP
32574
32575     FOR _p IN SELECT wo_qtyord, wo_startdate, womatl_id, womatl_wooper_id
32576               FROM wo, womatl, itemsite, item
32577               WHERE ( (womatl_itemsite_id=itemsite_id)
32578                AND (itemsite_item_id=item_id)
32579                AND (item_type='F')
32580                AND (womatl_wo_id=wo_id)
32581                AND (wo_id=pWoid) ) LOOP
32582
32583       INSERT INTO womatl
32584       ( womatl_wo_id, womatl_itemsite_id, womatl_wooper_id,
32585         womatl_schedatwooper, womatl_duedate,
32586         womatl_uom_id, womatl_qtyper, womatl_scrap,
32587         womatl_qtyreq,
32588         womatl_qtyiss, womatl_qtywipscrap,
32589         womatl_lastissue, womatl_lastreturn,
32590         womatl_cost, womatl_picklist, womatl_createwo,
32591         womatl_issuemethod, womatl_notes, womatl_ref )
32592       SELECT pWoid, cs.itemsite_id, _p.womatl_wooper_id,
32593              womatl_schedatwooper, womatl_duedate,
32594              bomitem_uom_id, (bomitem_qtyper * womatl_qtyper), bomitem_scrap,
32595              roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id), (_p.wo_qtyord * bomitem_qtyper * womatl_qtyper * (1 + bomitem_scrap))),
32596              0, 0,
32597              startOfTime(), startOfTime(),
32598              0, ci.item_picklist, ( (ci.item_type='M') AND (bomitem_createwo) ),
32599              bomitem_issuemethod, bomitem_notes, bomitem_ref 
32600       FROM wo, womatl, bomitem, 
32601            itemsite AS cs, itemsite AS ps,
32602            item AS ci, item AS pi
32603       WHERE ( (womatl_itemsite_id=ps.itemsite_id)
32604        AND (womatl_wo_id=wo_id)
32605        AND (bomitem_parent_item_id=pi.item_id)
32606        AND (bomitem_item_id=ci.item_id)
32607        AND (ps.itemsite_warehous_id=cs.itemsite_warehous_id)
32608        AND (cs.itemsite_item_id=ci.item_id)
32609        AND (ps.itemsite_item_id=pi.item_id)
32610        AND (woEffectiveDate(_p.wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
32611        AND (womatl_id=_p.womatl_id));
32612
32613       DELETE FROM womatl
32614       WHERE (womatl_id=_p.womatl_id);
32615
32616     END LOOP;
32617   END LOOP;
32618
32619   UPDATE wo
32620   SET wo_adhoc=TRUE
32621   WHERE (wo_id=pWoid);
32622
32623   UPDATE wo
32624   SET wo_status='E'
32625   WHERE ( (wo_status='O')
32626    AND (wo_id=pWoid) );
32627
32628   RETURN _womatlid;
32629 END;
32630 $_$;
32631
32632
32633 ALTER FUNCTION public.createwomaterial(integer, integer, character, integer, numeric, numeric, integer, text, text) OWNER TO admin;
32634
32635 --
32636 -- TOC entry 1370 (class 1255 OID 146565926)
32637 -- Dependencies: 4536 8
32638 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric, numeric, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
32639 --
32640
32641 CREATE FUNCTION createwomaterial(integer, integer, character, integer, numeric, numeric, numeric, integer, text, text) RETURNS integer
32642     LANGUAGE plpgsql
32643     AS $_$
32644 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32645 -- See www.xtuple.com/CPAL for the full text of the software license.
32646 DECLARE
32647   pWoid ALIAS FOR $1;
32648   pItemsiteid ALIAS FOR $2;
32649   pIssueMethod ALIAS FOR $3;
32650   pUomId ALIAS FOR $4;
32651   pQtyFxd ALIAS FOR $5;
32652   pQtyPer ALIAS FOR $6;
32653   pScrap ALIAS FOR $7;
32654   pBomitemId ALIAS FOR $8;
32655   pNotes ALIAS FOR $9;
32656   pRef ALIAS FOR $10;
32657   _womatlid INTEGER;
32658
32659 BEGIN
32660
32661   SELECT createWoMaterial(pWoid,pItemsiteid,pIssueMethod,pUomId,pQtyFxd,pQtyPer,pScrap,pBomitemId,pNotes,pRef,NULL,NULL) INTO _womatlid;
32662
32663   RETURN _womatlid;
32664 END;
32665 $_$;
32666
32667
32668 ALTER FUNCTION public.createwomaterial(integer, integer, character, integer, numeric, numeric, numeric, integer, text, text) OWNER TO admin;
32669
32670 --
32671 -- TOC entry 1371 (class 1255 OID 146565927)
32672 -- Dependencies: 4536 8
32673 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric, numeric, integer, text, text, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
32674 --
32675
32676 CREATE FUNCTION createwomaterial(pwoid integer, pitemsiteid integer, pissuemethod character, puomid integer, pqtyfxd numeric, pqtyper numeric, pscrap numeric, pbomitemid integer, pnotes text, pref text, pwooperid integer, ppicklist boolean) RETURNS integer
32677     LANGUAGE plpgsql
32678     AS $$
32679 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32680 -- See www.xtuple.com/CPAL for the full text of the software license.
32681 DECLARE
32682   _womatlid INTEGER;
32683
32684 BEGIN
32685
32686   SELECT createWoMaterial(pWoid,
32687                           pItemsiteid,
32688                           pIssueMethod,
32689                           pUomId,
32690                           pQtyFxd,
32691                           pQtyPer,
32692                           pScrap,
32693                           pBomitemId,
32694                           pNotes,
32695                           pRef,
32696                           pWooperId,
32697                           pPickList,
32698                           0.0) INTO _womatlid;
32699
32700   RETURN _womatlid;
32701 END;
32702 $$;
32703
32704
32705 ALTER FUNCTION public.createwomaterial(pwoid integer, pitemsiteid integer, pissuemethod character, puomid integer, pqtyfxd numeric, pqtyper numeric, pscrap numeric, pbomitemid integer, pnotes text, pref text, pwooperid integer, ppicklist boolean) OWNER TO admin;
32706
32707 --
32708 -- TOC entry 1372 (class 1255 OID 146565928)
32709 -- Dependencies: 4536 8
32710 -- Name: createwomaterial(integer, integer, character, integer, numeric, numeric, numeric, integer, text, text, integer, boolean, numeric); Type: FUNCTION; Schema: public; Owner: admin
32711 --
32712
32713 CREATE FUNCTION createwomaterial(pwoid integer, pitemsiteid integer, pissuemethod character, puomid integer, pqtyfxd numeric, pqtyper numeric, pscrap numeric, pbomitemid integer, pnotes text, pref text, pwooperid integer, ppicklist boolean, pprice numeric) RETURNS integer
32714     LANGUAGE plpgsql
32715     AS $$
32716 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32717 -- See www.xtuple.com/CPAL for the full text of the software license.
32718 DECLARE
32719   _womatlid INTEGER;
32720   _p RECORD;
32721
32722 BEGIN
32723
32724   _womatlid := (SELECT NEXTVAL('womatl_womatl_id_seq'));
32725
32726   INSERT INTO womatl
32727   ( womatl_id, womatl_wo_id, womatl_itemsite_id,
32728     womatl_issuemethod, womatl_uom_id, womatl_qtyfxd,
32729     womatl_qtyper, womatl_scrap, womatl_qtyreq,
32730     womatl_qtyiss, womatl_qtywipscrap, womatl_wooper_id,
32731     womatl_bomitem_id, womatl_duedate, womatl_notes,
32732     womatl_ref, womatl_picklist, womatl_price )
32733   SELECT _womatlid, wo_id, pItemsiteid,
32734          pIssueMethod, pUomId, pQtyFxd,
32735          pQtyPer, pScrap, roundQty(item_fractional, (pQtyFxd + wo_qtyord * pQtyPer) * (1 + pScrap) ),
32736          0, 0, COALESCE(pWooperId, -1),
32737          pBomitemId, wo_startdate, pNotes,
32738          pRef, COALESCE(pPickList, item_picklist), pPrice 
32739   FROM wo, itemsite JOIN item ON (item_id=itemsite_item_id)
32740   WHERE ( (wo_id=pWoid)
32741    AND (itemsite_id=pItemsiteid) );
32742
32743 -- Handle all of the Phantom material requirements
32744   WHILE ( ( SELECT COUNT(*)
32745             FROM womatl, itemsite, item
32746             WHERE ( (womatl_itemsite_id=itemsite_id)
32747              AND (itemsite_item_id=item_id)
32748              AND (womatl_wo_id=pWoid)
32749              AND (item_type='F') ) ) > 0 ) LOOP
32750
32751     FOR _p IN SELECT wo_qtyord, wo_startdate, womatl_id, womatl_wooper_id
32752               FROM wo, womatl, itemsite, item
32753               WHERE ( (womatl_itemsite_id=itemsite_id)
32754                AND (itemsite_item_id=item_id)
32755                AND (item_type='F')
32756                AND (womatl_wo_id=wo_id)
32757                AND (wo_id=pWoid) ) LOOP
32758
32759       INSERT INTO womatl
32760       ( womatl_wo_id, womatl_itemsite_id, womatl_wooper_id,
32761         womatl_schedatwooper, womatl_duedate,
32762         womatl_uom_id, womatl_qtyfxd, womatl_qtyper, womatl_scrap,
32763         womatl_qtyreq,
32764         womatl_qtyiss, womatl_qtywipscrap,
32765         womatl_lastissue, womatl_lastreturn,
32766         womatl_cost, womatl_picklist, womatl_createwo,
32767         womatl_issuemethod, womatl_notes, womatl_ref )
32768       SELECT pWoid, cs.itemsite_id, _p.womatl_wooper_id,
32769              womatl_schedatwooper, womatl_duedate,
32770              bomitem_uom_id, bomitem_qtyfxd, (bomitem_qtyper * womatl_qtyper), bomitem_scrap,
32771              roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id), 
32772                      ((bomitem_qtyfxd + _p.wo_qtyord * bomitem_qtyper) * womatl_qtyper * (1 + bomitem_scrap))),
32773              0, 0,
32774              startOfTime(), startOfTime(),
32775              0, ci.item_picklist, ( (ci.item_type='M') AND (bomitem_createwo) ),
32776              bomitem_issuemethod, bomitem_notes, bomitem_ref 
32777       FROM wo, womatl, bomitem, 
32778            itemsite AS cs, itemsite AS ps,
32779            item AS ci, item AS pi
32780       WHERE ( (womatl_itemsite_id=ps.itemsite_id)
32781        AND (womatl_wo_id=wo_id)
32782        AND (bomitem_parent_item_id=pi.item_id)
32783        AND (bomitem_item_id=ci.item_id)
32784        AND (ps.itemsite_warehous_id=cs.itemsite_warehous_id)
32785        AND (cs.itemsite_item_id=ci.item_id)
32786        AND (ps.itemsite_item_id=pi.item_id)
32787        AND (woEffectiveDate(_p.wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
32788        AND (womatl_id=_p.womatl_id));
32789
32790       DELETE FROM womatl
32791       WHERE (womatl_id=_p.womatl_id);
32792
32793     END LOOP;
32794   END LOOP;
32795
32796   UPDATE wo
32797   SET wo_adhoc=TRUE
32798   WHERE (wo_id=pWoid);
32799
32800   UPDATE wo
32801   SET wo_status='E'
32802   WHERE ( (wo_status='O')
32803    AND (wo_id=pWoid) );
32804
32805   RETURN _womatlid;
32806 END;
32807 $$;
32808
32809
32810 ALTER FUNCTION public.createwomaterial(pwoid integer, pitemsiteid integer, pissuemethod character, puomid integer, pqtyfxd numeric, pqtyper numeric, pscrap numeric, pbomitemid integer, pnotes text, pref text, pwooperid integer, ppicklist boolean, pprice numeric) OWNER TO admin;
32811
32812 --
32813 -- TOC entry 1373 (class 1255 OID 146565929)
32814 -- Dependencies: 4536 8
32815 -- Name: creditmemototal(integer); Type: FUNCTION; Schema: public; Owner: admin
32816 --
32817
32818 CREATE FUNCTION creditmemototal(integer) RETURNS numeric
32819     LANGUAGE plpgsql
32820     AS $_$
32821 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
32822 -- See www.xtuple.com/CPAL for the full text of the software license.
32823 DECLARE
32824   pCreditmemoId ALIAS FOR $1;
32825   _result       NUMERIC;
32826
32827 BEGIN
32828
32829   -- TO DO:  Add in line item taxes
32830   SELECT COALESCE(cmhead_freight,0.0) + COALESCE(cmhead_misc,0.0) +
32831          ( SELECT COALESCE(ROUND(SUM((cmitem_qtycredit * cmitem_qty_invuomratio) * cmitem_unitprice / cmitem_price_invuomratio), 2), 0.0)
32832              FROM cmitem
32833             WHERE (cmitem_cmhead_id=cmhead_id)
32834            ) +
32835          (SELECT COALESCE(SUM(tax) * -1, 0) AS tax
32836            FROM ( SELECT ROUND(SUM(taxdetail_tax),2) AS tax
32837                   FROM tax
32838                   JOIN calculateTaxDetailSummary('CM', cmhead_id, 'T') ON (taxdetail_tax_id=tax_id)
32839                   GROUP BY tax_id) AS data)
32840            INTO _result
32841   FROM cmhead
32842   WHERE (cmhead_id=pCreditmemoId);
32843
32844   IF (NOT FOUND) THEN
32845     return 0;
32846   ELSE
32847     RETURN _result;
32848   END IF;
32849
32850 END;
32851 $_$;
32852
32853
32854 ALTER FUNCTION public.creditmemototal(integer) OWNER TO admin;
32855
32856 --
32857 -- TOC entry 205 (class 1259 OID 146565930)
32858 -- Dependencies: 5947 5948 5949 5950 5951 8
32859 -- Name: crmacct; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
32860 --
32861
32862 CREATE TABLE crmacct (
32863     crmacct_id integer NOT NULL,
32864     crmacct_number text NOT NULL,
32865     crmacct_name text,
32866     crmacct_active boolean DEFAULT true,
32867     crmacct_type character(1),
32868     crmacct_cust_id integer,
32869     crmacct_competitor_id integer,
32870     crmacct_partner_id integer,
32871     crmacct_prospect_id integer,
32872     crmacct_vend_id integer,
32873     crmacct_cntct_id_1 integer,
32874     crmacct_cntct_id_2 integer,
32875     crmacct_parent_id integer,
32876     crmacct_notes text,
32877     crmacct_taxauth_id integer,
32878     crmacct_owner_username text,
32879     crmacct_emp_id integer,
32880     crmacct_salesrep_id integer,
32881     crmacct_usr_username text,
32882     CONSTRAINT crmacct_crmacct_number_check CHECK ((crmacct_number <> ''::text)),
32883     CONSTRAINT crmacct_crmacct_type_check CHECK ((crmacct_type = ANY (ARRAY['I'::bpchar, 'O'::bpchar]))),
32884     CONSTRAINT crmacct_crmacct_usr_username_check CHECK ((btrim(crmacct_usr_username) <> ''::text)),
32885     CONSTRAINT crmacct_owner_username_check CHECK ((btrim(crmacct_owner_username) <> ''::text))
32886 );
32887
32888
32889 ALTER TABLE public.crmacct OWNER TO admin;
32890
32891 --
32892 -- TOC entry 8953 (class 0 OID 0)
32893 -- Dependencies: 205
32894 -- Name: TABLE crmacct; Type: COMMENT; Schema: public; Owner: admin
32895 --
32896
32897 COMMENT ON TABLE crmacct IS 'CRM Accounts are umbrella records that tie together people and organizations with whom we have business relationships.';
32898
32899
32900 --
32901 -- TOC entry 8954 (class 0 OID 0)
32902 -- Dependencies: 205
32903 -- Name: COLUMN crmacct.crmacct_id; Type: COMMENT; Schema: public; Owner: admin
32904 --
32905
32906 COMMENT ON COLUMN crmacct.crmacct_id IS 'Internal ID of this CRM Account.';
32907
32908
32909 --
32910 -- TOC entry 8955 (class 0 OID 0)
32911 -- Dependencies: 205
32912 -- Name: COLUMN crmacct.crmacct_number; Type: COMMENT; Schema: public; Owner: admin
32913 --
32914
32915 COMMENT ON COLUMN crmacct.crmacct_number IS 'Abbreviated human-readable identifier for this CRM Account.';
32916
32917
32918 --
32919 -- TOC entry 8956 (class 0 OID 0)
32920 -- Dependencies: 205
32921 -- Name: COLUMN crmacct.crmacct_name; Type: COMMENT; Schema: public; Owner: admin
32922 --
32923
32924 COMMENT ON COLUMN crmacct.crmacct_name IS 'Long name of this CRM Account.';
32925
32926
32927 --
32928 -- TOC entry 8957 (class 0 OID 0)
32929 -- Dependencies: 205
32930 -- Name: COLUMN crmacct.crmacct_active; Type: COMMENT; Schema: public; Owner: admin
32931 --
32932
32933 COMMENT ON COLUMN crmacct.crmacct_active IS 'This CRM Account is available for new activity.';
32934
32935
32936 --
32937 -- TOC entry 8958 (class 0 OID 0)
32938 -- Dependencies: 205
32939 -- Name: COLUMN crmacct.crmacct_type; Type: COMMENT; Schema: public; Owner: admin
32940 --
32941
32942 COMMENT ON COLUMN crmacct.crmacct_type IS 'This indicates whether the CRM Account represents an organization or an individual person.';
32943
32944
32945 --
32946 -- TOC entry 8959 (class 0 OID 0)
32947 -- Dependencies: 205
32948 -- Name: COLUMN crmacct.crmacct_cust_id; Type: COMMENT; Schema: public; Owner: admin
32949 --
32950
32951 COMMENT ON COLUMN crmacct.crmacct_cust_id IS 'If this is not null, this CRM Account is a Customer.';
32952
32953
32954 --
32955 -- TOC entry 8960 (class 0 OID 0)
32956 -- Dependencies: 205
32957 -- Name: COLUMN crmacct.crmacct_competitor_id; Type: COMMENT; Schema: public; Owner: admin
32958 --
32959
32960 COMMENT ON COLUMN crmacct.crmacct_competitor_id IS 'For now, > 0 indicates this CRM Account is a competitor. Eventually this may become a foreign key to a table of competitors.';
32961
32962
32963 --
32964 -- TOC entry 8961 (class 0 OID 0)
32965 -- Dependencies: 205
32966 -- Name: COLUMN crmacct.crmacct_partner_id; Type: COMMENT; Schema: public; Owner: admin
32967 --
32968
32969 COMMENT ON COLUMN crmacct.crmacct_partner_id IS 'For now, > 0 indicates this CRM Account is a partner. Eventually this may become a foreign key to a table of partners.';
32970
32971
32972 --
32973 -- TOC entry 8962 (class 0 OID 0)
32974 -- Dependencies: 205
32975 -- Name: COLUMN crmacct.crmacct_prospect_id; Type: COMMENT; Schema: public; Owner: admin
32976 --
32977
32978 COMMENT ON COLUMN crmacct.crmacct_prospect_id IS 'If this is not null, this CRM Account is a Prospect.';
32979
32980
32981 --
32982 -- TOC entry 8963 (class 0 OID 0)
32983 -- Dependencies: 205
32984 -- Name: COLUMN crmacct.crmacct_vend_id; Type: COMMENT; Schema: public; Owner: admin
32985 --
32986
32987 COMMENT ON COLUMN crmacct.crmacct_vend_id IS 'If this is not null, this CRM Account is a Vendor.';
32988
32989
32990 --
32991 -- TOC entry 8964 (class 0 OID 0)
32992 -- Dependencies: 205
32993 -- Name: COLUMN crmacct.crmacct_cntct_id_1; Type: COMMENT; Schema: public; Owner: admin
32994 --
32995
32996 COMMENT ON COLUMN crmacct.crmacct_cntct_id_1 IS 'The primary contact for the CRM Account.';
32997
32998
32999 --
33000 -- TOC entry 8965 (class 0 OID 0)
33001 -- Dependencies: 205
33002 -- Name: COLUMN crmacct.crmacct_cntct_id_2; Type: COMMENT; Schema: public; Owner: admin
33003 --
33004
33005 COMMENT ON COLUMN crmacct.crmacct_cntct_id_2 IS 'The secondary contact for the CRM Account.';
33006
33007
33008 --
33009 -- TOC entry 8966 (class 0 OID 0)
33010 -- Dependencies: 205
33011 -- Name: COLUMN crmacct.crmacct_parent_id; Type: COMMENT; Schema: public; Owner: admin
33012 --
33013
33014 COMMENT ON COLUMN crmacct.crmacct_parent_id IS 'The internal ID of an (optional) parent CRM Account. For example, if the current CRM Account is a subsidiary of another company, the crmacct_parent_id points to the CRM Account representing that parent company.';
33015
33016
33017 --
33018 -- TOC entry 8967 (class 0 OID 0)
33019 -- Dependencies: 205
33020 -- Name: COLUMN crmacct.crmacct_notes; Type: COMMENT; Schema: public; Owner: admin
33021 --
33022
33023 COMMENT ON COLUMN crmacct.crmacct_notes IS 'Free-form comments pertaining to the CRM Account.';
33024
33025
33026 --
33027 -- TOC entry 8968 (class 0 OID 0)
33028 -- Dependencies: 205
33029 -- Name: COLUMN crmacct.crmacct_taxauth_id; Type: COMMENT; Schema: public; Owner: admin
33030 --
33031
33032 COMMENT ON COLUMN crmacct.crmacct_taxauth_id IS 'If this is not null, this CRM Account is a Tax Authority.';
33033
33034
33035 --
33036 -- TOC entry 8969 (class 0 OID 0)
33037 -- Dependencies: 205
33038 -- Name: COLUMN crmacct.crmacct_owner_username; Type: COMMENT; Schema: public; Owner: admin
33039 --
33040
33041 COMMENT ON COLUMN crmacct.crmacct_owner_username IS 'The application User responsible for this CRM Account.';
33042
33043
33044 --
33045 -- TOC entry 8970 (class 0 OID 0)
33046 -- Dependencies: 205
33047 -- Name: COLUMN crmacct.crmacct_emp_id; Type: COMMENT; Schema: public; Owner: admin
33048 --
33049
33050 COMMENT ON COLUMN crmacct.crmacct_emp_id IS 'If this is not null, this CRM Account is an Employee.';
33051
33052
33053 --
33054 -- TOC entry 8971 (class 0 OID 0)
33055 -- Dependencies: 205
33056 -- Name: COLUMN crmacct.crmacct_salesrep_id; Type: COMMENT; Schema: public; Owner: admin
33057 --
33058
33059 COMMENT ON COLUMN crmacct.crmacct_salesrep_id IS 'If this is not null, this CRM Account is a Sales Rep.';
33060
33061
33062 --
33063 -- TOC entry 8972 (class 0 OID 0)
33064 -- Dependencies: 205
33065 -- Name: COLUMN crmacct.crmacct_usr_username; Type: COMMENT; Schema: public; Owner: admin
33066 --
33067
33068 COMMENT ON COLUMN crmacct.crmacct_usr_username IS 'If this is not null, this CRM Account is an application User.';
33069
33070
33071 --
33072 -- TOC entry 1374 (class 1255 OID 146565941)
33073 -- Dependencies: 2781 4536 8
33074 -- Name: crmacct(); Type: FUNCTION; Schema: public; Owner: admin
33075 --
33076
33077 CREATE FUNCTION crmacct() RETURNS SETOF crmacct
33078     LANGUAGE plpgsql
33079     AS $$
33080 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33081 -- See www.xtuple.com/CPAL for the full text of the software license.
33082 DECLARE
33083   _row crmacct%ROWTYPE;
33084   _priv TEXT;
33085   _grant BOOLEAN;
33086
33087 BEGIN
33088   -- This query will give us the most permissive privilege the user has been granted
33089   SELECT privilege, granted INTO _priv, _grant
33090   FROM privgranted 
33091   WHERE privilege IN ('MaintainAllCRMAccounts','ViewAllCRMAccounts','MaintainPersonalCRMAccounts','ViewPersonalCRMAccounts')
33092   ORDER BY granted DESC, sequence
33093   LIMIT 1;
33094
33095   -- If have an 'All' privilege return all results
33096   IF (_priv ~ 'All' AND _grant) THEN
33097     FOR _row IN 
33098       SELECT * FROM crmacct
33099     LOOP
33100       RETURN NEXT _row;
33101     END LOOP;
33102   -- Otherwise if have any other grant, must be personal privilege.
33103   ELSIF (_grant) THEN
33104     FOR _row IN 
33105       SELECT * FROM crmacct 
33106       WHERE crmacct_owner_username = getEffectiveXtUser()
33107     LOOP
33108       RETURN NEXT _row;
33109     END LOOP;
33110   END IF;
33111
33112   RETURN;
33113
33114 END;
33115 $$;
33116
33117
33118 ALTER FUNCTION public.crmacct() OWNER TO admin;
33119
33120 --
33121 -- TOC entry 8974 (class 0 OID 0)
33122 -- Dependencies: 1374
33123 -- Name: FUNCTION crmacct(); Type: COMMENT; Schema: public; Owner: admin
33124 --
33125
33126 COMMENT ON FUNCTION crmacct() IS 'A table function that returns CRM Account results according to privilege settings.';
33127
33128
33129 --
33130 -- TOC entry 1375 (class 1255 OID 146565942)
33131 -- Dependencies: 8
33132 -- Name: crypt(text, text); Type: FUNCTION; Schema: public; Owner: admin
33133 --
33134
33135 CREATE FUNCTION crypt(text, text) RETURNS text
33136     LANGUAGE c IMMUTABLE STRICT
33137     AS '$libdir/pgcrypto', 'pg_crypt';
33138
33139
33140 ALTER FUNCTION public.crypt(text, text) OWNER TO admin;
33141
33142 --
33143 -- TOC entry 1376 (class 1255 OID 146565943)
33144 -- Dependencies: 4536 8
33145 -- Name: currconcat(integer); Type: FUNCTION; Schema: public; Owner: admin
33146 --
33147
33148 CREATE FUNCTION currconcat(integer) RETURNS character varying
33149     LANGUAGE plpgsql
33150     AS $_$
33151 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
33152 -- See www.xtuple.com/CPAL for the full text of the software license.
33153 DECLARE
33154   id ALIAS FOR $1;
33155   returnVal   VARCHAR(15) := '';
33156 BEGIN
33157   SELECT currConcat(curr_abbr, curr_symbol) INTO returnVal
33158       FROM curr_symbol WHERE curr_id = id;
33159   RETURN returnVal;
33160 END;
33161 $_$;
33162
33163
33164 ALTER FUNCTION public.currconcat(integer) OWNER TO admin;
33165
33166 --
33167 -- TOC entry 1377 (class 1255 OID 146565944)
33168 -- Dependencies: 4536 8
33169 -- Name: currconcat(character varying, character varying); Type: FUNCTION; Schema: public; Owner: admin
33170 --
33171
33172 CREATE FUNCTION currconcat(character varying, character varying) RETURNS character varying
33173     LANGUAGE plpgsql
33174     AS $_$
33175 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
33176 -- See www.xtuple.com/CPAL for the full text of the software license.
33177 DECLARE
33178   curr_abbr   ALIAS FOR $1;
33179   curr_symbol ALIAS FOR $2;
33180   returnVal   VARCHAR(15) := '';
33181 BEGIN
33182   IF length(trim(curr_abbr)) > 0 AND length(trim(curr_symbol)) > 0 THEN
33183       returnVal := trim(curr_abbr) || ' - ' || trim(curr_symbol);
33184
33185   ELSIF length(trim(curr_abbr)) > 0 THEN
33186       returnVal := curr_abbr;
33187
33188   ELSIF length(trim(curr_symbol)) > 0 THEN
33189       returnVal := curr_symbol;
33190   END IF;
33191
33192   RETURN returnVal;
33193 END;
33194 $_$;
33195
33196
33197 ALTER FUNCTION public.currconcat(character varying, character varying) OWNER TO admin;
33198
33199 --
33200 -- TOC entry 1378 (class 1255 OID 146565945)
33201 -- Dependencies: 4536 8
33202 -- Name: currentapmemonumber(); Type: FUNCTION; Schema: public; Owner: admin
33203 --
33204
33205 CREATE FUNCTION currentapmemonumber() RETURNS integer
33206     LANGUAGE plpgsql
33207     AS $$
33208 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33209 -- See www.xtuple.com/CPAL for the full text of the software license.
33210 DECLARE
33211   _number INTEGER;
33212
33213 BEGIN
33214
33215   SELECT orderseq_number INTO _number
33216   FROM orderseq
33217   WHERE (orderseq_name='APMemoNumber');
33218   IF (NOT FOUND) THEN
33219     _number := 0;
33220   END IF;
33221
33222   RETURN _number;
33223
33224 END;
33225 $$;
33226
33227
33228 ALTER FUNCTION public.currentapmemonumber() OWNER TO admin;
33229
33230 --
33231 -- TOC entry 1351 (class 1255 OID 146565946)
33232 -- Dependencies: 4536 8
33233 -- Name: currentarmemonumber(); Type: FUNCTION; Schema: public; Owner: admin
33234 --
33235
33236 CREATE FUNCTION currentarmemonumber() RETURNS integer
33237     LANGUAGE plpgsql
33238     AS $$
33239 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33240 -- See www.xtuple.com/CPAL for the full text of the software license.
33241 DECLARE
33242   _number INTEGER;
33243
33244 BEGIN
33245
33246   SELECT orderseq_number INTO _number
33247   FROM orderseq
33248   WHERE (orderseq_name='ARMemoNumber');
33249   IF (NOT FOUND) THEN
33250     _number := 0;
33251   END IF;
33252
33253   RETURN _number;
33254
33255 END;
33256 $$;
33257
33258
33259 ALTER FUNCTION public.currentarmemonumber() OWNER TO admin;
33260
33261 --
33262 -- TOC entry 1172 (class 1255 OID 146565947)
33263 -- Dependencies: 4536 8
33264 -- Name: currentcashrcptnumber(); Type: FUNCTION; Schema: public; Owner: admin
33265 --
33266
33267 CREATE FUNCTION currentcashrcptnumber() RETURNS integer
33268     LANGUAGE plpgsql
33269     AS $$
33270 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33271 -- See www.xtuple.com/CPAL for the full text of the software license.
33272 DECLARE
33273   _number INTEGER;
33274
33275 BEGIN
33276
33277   SELECT orderseq_number INTO _number
33278   FROM orderseq
33279   WHERE (orderseq_name='CashRcptNumber');
33280   IF (NOT FOUND) THEN
33281     _number := 0;
33282   END IF;
33283
33284   RETURN _number;
33285
33286 END;
33287 $$;
33288
33289
33290 ALTER FUNCTION public.currentcashrcptnumber() OWNER TO admin;
33291
33292 --
33293 -- TOC entry 1267 (class 1255 OID 146565948)
33294 -- Dependencies: 4536 8
33295 -- Name: currentnumber(text); Type: FUNCTION; Schema: public; Owner: admin
33296 --
33297
33298 CREATE FUNCTION currentnumber(text) RETURNS integer
33299     LANGUAGE plpgsql
33300     AS $_$
33301 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33302 -- See www.xtuple.com/CPAL for the full text of the software license.
33303 DECLARE
33304   pName   ALIAS FOR $1;
33305   _number INTEGER;
33306
33307 BEGIN
33308   SELECT orderseq_number INTO _number
33309   FROM orderseq
33310   WHERE (orderseq_name=pName);
33311   IF (NOT FOUND) THEN
33312     _number := 0;
33313   END IF;
33314
33315   RETURN _number;
33316
33317 END;
33318 $_$;
33319
33320
33321 ALTER FUNCTION public.currentnumber(text) OWNER TO admin;
33322
33323 --
33324 -- TOC entry 1379 (class 1255 OID 146565949)
33325 -- Dependencies: 4536 8
33326 -- Name: currexchangecheckoverlap(); Type: FUNCTION; Schema: public; Owner: admin
33327 --
33328
33329 CREATE FUNCTION currexchangecheckoverlap() RETURNS trigger
33330     LANGUAGE plpgsql
33331     AS $$
33332 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33333 -- See www.xtuple.com/CPAL for the full text of the software license.
33334 DECLARE
33335     numberOfOverlaps INTEGER NOT NULL := 0;
33336     curr_string VARCHAR(16);
33337     new_id INTEGER;
33338 BEGIN
33339   new_id := NEW.curr_id;
33340   -- ensure that effective date <= expiration date
33341   IF NEW.curr_effective > NEW.curr_expires THEN
33342     RAISE EXCEPTION
33343       'Effective date % must be earlier than expiration date %',
33344       NEW.curr_effective, NEW.curr_expires;
33345   END IF;
33346
33347   -- ensure new exchange rate does not overlap in time with any others
33348   SELECT count(*) INTO numberOfOverlaps
33349     FROM curr_rate
33350     WHERE curr_id = NEW.curr_id
33351       AND curr_rate_id != NEW.curr_rate_id
33352       AND (
33353           (curr_effective BETWEEN
33354               NEW.curr_effective AND NEW.curr_expires OR
33355            curr_expires BETWEEN
33356               NEW.curr_effective AND NEW.curr_expires)
33357          OR (curr_effective <= NEW.curr_effective AND
33358              curr_expires   >= NEW.curr_expires)
33359       );
33360   IF numberOfOverlaps > 0 THEN
33361     SELECT currConcat(curr_symbol, curr_abbr)
33362       INTO curr_string
33363       FROM curr_symbol
33364       WHERE curr_id = new_id;
33365     RAISE EXCEPTION
33366       'The date range % to % overlaps with another date range.',
33367       NEW.curr_effective, NEW.curr_expires;
33368   END IF;
33369   RETURN NEW;
33370 END;
33371 $$;
33372
33373
33374 ALTER FUNCTION public.currexchangecheckoverlap() OWNER TO admin;
33375
33376 --
33377 -- TOC entry 1380 (class 1255 OID 146565950)
33378 -- Dependencies: 4536 8
33379 -- Name: currgain(integer, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
33380 --
33381
33382 CREATE FUNCTION currgain(integer, numeric, date, date) RETURNS numeric
33383     LANGUAGE plpgsql
33384     AS $_$
33385 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33386 -- See www.xtuple.com/CPAL for the full text of the software license.
33387 DECLARE
33388   pId ALIAS FOR $1;
33389   pValue ALIAS FOR $2;
33390   pStart ALIAS FOR $3;
33391   pEnd ALIAS FOR $4;
33392   _start DATE;
33393   _end DATE;
33394   _gain NUMERIC;
33395   _multiplier   INTEGER := 1;
33396
33397 BEGIN
33398   IF (pEnd = pStart OR pValue = 0) THEN
33399     RETURN 0;
33400   END IF;
33401
33402   IF (pStart > pEnd) THEN
33403     _start := pEnd;
33404     _end   := pStart;
33405     _multiplier := -1;
33406   ELSE
33407     _start := pStart;
33408     _end := pEnd;
33409   END IF;
33410
33411   _gain := currToBase(pId, pValue, _start) - currToBase(pId, pValue, _end);
33412   IF (_gain IS NULL) THEN
33413     RAISE EXCEPTION 'Missing exchange rate for curr_id % on % or %',
33414                     pId, _start, _end;
33415   END IF;
33416
33417   RETURN _gain * _multiplier;
33418 END;
33419 $_$;
33420
33421
33422 ALTER FUNCTION public.currgain(integer, numeric, date, date) OWNER TO admin;
33423
33424 --
33425 -- TOC entry 1381 (class 1255 OID 146565951)
33426 -- Dependencies: 4536 8
33427 -- Name: curronebase(); Type: FUNCTION; Schema: public; Owner: admin
33428 --
33429
33430 CREATE FUNCTION curronebase() RETURNS trigger
33431     LANGUAGE plpgsql
33432     AS $$
33433 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33434 -- See www.xtuple.com/CPAL for the full text of the software license.
33435 DECLARE
33436   baseCount INTEGER := 0;
33437 BEGIN
33438   IF NEW.curr_base = TRUE THEN
33439     SELECT count(*)
33440       INTO baseCount
33441       FROM curr_symbol
33442       WHERE curr_base = TRUE
33443         AND curr_id != NEW.curr_id;
33444     IF baseCount > 0 THEN
33445       RAISE EXCEPTION
33446           'Cannot make % - % the base currency because one is already defined.',
33447           NEW.curr_symbol, NEW.curr_abbr;
33448     ELSE
33449       SELECT count(*)
33450         INTO baseCount
33451         FROM curr_rate
33452         WHERE curr_id = NEW.curr_id;
33453       IF baseCount = 0 THEN
33454         -- put a row in the curr_rate table to avoid special-case
33455         -- code for converting base currency to base currency
33456         INSERT INTO curr_rate
33457           (curr_id, curr_rate, curr_effective, curr_expires) VALUES
33458           (NEW.curr_id, 1, startOfTime(), endOfTime());
33459       END IF;
33460     END IF;
33461   END IF;
33462   RETURN NEW;
33463 END;
33464 $$;
33465
33466
33467 ALTER FUNCTION public.curronebase() OWNER TO admin;
33468
33469 --
33470 -- TOC entry 1382 (class 1255 OID 146565952)
33471 -- Dependencies: 4536 8
33472 -- Name: currrate(integer, date); Type: FUNCTION; Schema: public; Owner: admin
33473 --
33474
33475 CREATE FUNCTION currrate(integer, date) RETURNS numeric
33476     LANGUAGE plpgsql STABLE
33477     AS $_$
33478 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33479 -- See www.xtuple.com/CPAL for the full text of the software license.
33480 BEGIN
33481   RETURN currRate($1, NULL, $2);
33482
33483 END;
33484 $_$;
33485
33486
33487 ALTER FUNCTION public.currrate(integer, date) OWNER TO admin;
33488
33489 --
33490 -- TOC entry 1383 (class 1255 OID 146565953)
33491 -- Dependencies: 4536 8
33492 -- Name: currrate(integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
33493 --
33494
33495 CREATE FUNCTION currrate(pfromcurr integer, ptocurr integer, pdate date) RETURNS numeric
33496     LANGUAGE plpgsql STABLE
33497     AS $$
33498 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33499 -- See www.xtuple.com/CPAL for the full text of the software license.
33500 DECLARE
33501   _fromRate NUMERIC := 1.0;
33502   _toRate NUMERIC := 1.0;
33503   _returnVal NUMERIC := 1.0;
33504 BEGIN
33505   IF pFromCurr = pToCurr THEN
33506     RETURN _returnVal;
33507   END IF;
33508
33509   IF (pFromCurr IS NOT NULL) THEN
33510     SELECT curr_rate INTO _fromRate
33511     FROM curr_rate
33512     WHERE ( (curr_id=pFromCurr)
33513     AND (pDate BETWEEN curr_effective AND curr_expires) );
33514
33515     IF ( NOT FOUND) THEN
33516       RAISE EXCEPTION 'Currency exchange rate for currency % not found on %', pFromCurr, formatDate(pDate);
33517     END IF;
33518   END IF;
33519
33520   IF (pToCurr IS NOT NULL) THEN
33521     SELECT curr_rate INTO _toRate
33522     FROM curr_rate
33523     WHERE ( (curr_id=pToCurr)
33524     AND (pDate BETWEEN curr_effective AND curr_expires) );
33525
33526     IF ( NOT FOUND) THEN
33527       RAISE EXCEPTION 'Currency exchange rate for currency % not found on %', pToCurr, formatDate(pDate);
33528     END IF;
33529   END IF;
33530
33531   _returnVal := _fromRate / _toRate;
33532
33533   RETURN _returnVal;
33534 END;
33535 $$;
33536
33537
33538 ALTER FUNCTION public.currrate(pfromcurr integer, ptocurr integer, pdate date) OWNER TO admin;
33539
33540 --
33541 -- TOC entry 1384 (class 1255 OID 146565954)
33542 -- Dependencies: 4536 8
33543 -- Name: currtobase(integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
33544 --
33545
33546 CREATE FUNCTION currtobase(integer, numeric, date) RETURNS numeric
33547     LANGUAGE plpgsql STABLE
33548     AS $_$
33549 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33550 -- See www.xtuple.com/CPAL for the full text of the software license.
33551 DECLARE
33552   pId     ALIAS FOR $1;
33553   pValue  ALIAS FOR $2;
33554   _date  DATE;
33555   _output NUMERIC;
33556 BEGIN
33557   _date := $3;
33558   IF _date IS NULL THEN
33559     _date := 'now';
33560   END IF;
33561
33562   IF pValue = 0 OR pValue IS NULL THEN
33563     _output := 0;
33564   ELSIF (baseCurrId() = pId) THEN
33565     _output := pValue;
33566   ELSE
33567     SELECT pValue / curr_rate
33568         INTO  _output
33569       FROM  curr_rate
33570      WHERE curr_id = pId
33571        AND _date BETWEEN curr_effective AND curr_expires;
33572     IF (_output IS NULL OR NOT FOUND) THEN
33573       RAISE EXCEPTION 'No exchange rate for % on %', pId, _date;
33574     END IF;
33575   END IF;
33576   RETURN _output;
33577 END;
33578 $_$;
33579
33580
33581 ALTER FUNCTION public.currtobase(integer, numeric, date) OWNER TO admin;
33582
33583 --
33584 -- TOC entry 1385 (class 1255 OID 146565955)
33585 -- Dependencies: 4536 8
33586 -- Name: currtocurr(integer, integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
33587 --
33588
33589 CREATE FUNCTION currtocurr(integer, integer, numeric, date) RETURNS numeric
33590     LANGUAGE plpgsql
33591     AS $_$
33592 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33593 -- See www.xtuple.com/CPAL for the full text of the software license.
33594 DECLARE
33595   pFromCurr ALIAS FOR $1;
33596   pToCurr ALIAS FOR $2;
33597   pValue   ALIAS FOR $3;
33598   pEffective ALIAS FOR $4;
33599   _convertedValue NUMERIC;
33600   _fromRate NUMERIC;
33601   _toRate NUMERIC;
33602 BEGIN
33603   IF pFromCurr = pToCurr THEN
33604     RETURN pValue;
33605   END IF;
33606
33607   IF pValue = 0 OR pValue IS NULL THEN
33608     RETURN 0;
33609   END IF;
33610
33611   SELECT curr_rate INTO _fromRate
33612   FROM curr_rate
33613   WHERE curr_id = pFromCurr
33614     AND pEffective BETWEEN curr_effective AND curr_expires;
33615
33616   IF (NOT FOUND) THEN
33617     RAISE EXCEPTION 'No exchange rate for % on %', pFromCurr, pEffective;
33618   END IF;
33619
33620   SELECT curr_rate INTO _toRate
33621   FROM curr_rate
33622   WHERE curr_id = pToCurr
33623     AND pEffective BETWEEN curr_effective AND curr_expires;
33624
33625   IF (NOT FOUND) THEN
33626     RAISE EXCEPTION 'No exchange rate for % on %', pToCurr, pEffective;
33627   END IF;
33628
33629   _convertedValue := pValue * _toRate / _fromRate;
33630
33631   RETURN _convertedValue;
33632 END;
33633 $_$;
33634
33635
33636 ALTER FUNCTION public.currtocurr(integer, integer, numeric, date) OWNER TO admin;
33637
33638 --
33639 -- TOC entry 1387 (class 1255 OID 146565956)
33640 -- Dependencies: 4536 8
33641 -- Name: currtolocal(integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
33642 --
33643
33644 CREATE FUNCTION currtolocal(integer, numeric, date) RETURNS numeric
33645     LANGUAGE plpgsql
33646     AS $_$
33647 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33648 -- See www.xtuple.com/CPAL for the full text of the software license.
33649 DECLARE
33650     pId     ALIAS FOR $1;
33651     pValue  ALIAS FOR $2;
33652     _date   DATE;
33653     _output NUMERIC;
33654 BEGIN
33655     _date := $3;
33656     IF _date IS NULL THEN
33657         _date := 'now';
33658     END IF;
33659
33660     IF pValue = 0 OR pValue IS NULL THEN
33661         _output := 0;
33662     ELSIF (baseCurrId() = pId) THEN
33663       _output := pValue;
33664     ELSE
33665         SELECT pValue * curr_rate
33666             INTO  _output
33667             FROM  curr_rate
33668             WHERE curr_id = pId
33669               AND _date BETWEEN curr_effective AND curr_expires;
33670         IF (_output IS NULL OR NOT FOUND) THEN
33671           RAISE EXCEPTION 'No exchange rate for % on %', pId, _date;
33672         END IF;
33673     END IF;
33674     RETURN _output;
33675 END;
33676 $_$;
33677
33678
33679 ALTER FUNCTION public.currtolocal(integer, numeric, date) OWNER TO admin;
33680
33681 --
33682 -- TOC entry 1388 (class 1255 OID 146565957)
33683 -- Dependencies: 8
33684 -- Name: custitem(integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
33685 --
33686
33687 CREATE FUNCTION custitem(cust_id integer, shipto_id integer DEFAULT (-1), asof date DEFAULT ('now'::text)::date) RETURNS SETOF integer
33688     LANGUAGE sql
33689     AS $_$
33690 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33691 -- See www.xtuple.com/CPAL for the full text of the software license.
33692
33693   -- Non Exclusive
33694   SELECT item_id
33695   FROM item 
33696   WHERE (NOT item_exclusive)
33697    AND (item_sold)
33698   UNION
33699   -- Exclusive, Shipto match
33700   SELECT item_id
33701   FROM item
33702     JOIN ipsiteminfo ON (ipsitem_item_id=item_id)
33703     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33704     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33705   WHERE (item_exclusive)
33706    AND (item_sold)
33707    AND ($2 != -1)
33708    AND (ipsass_shipto_id=$2)
33709    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33710   UNION
33711   SELECT item_id
33712   FROM item
33713     JOIN ipsiteminfo ON (ipsitem_prodcat_id=item_prodcat_id)
33714     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33715     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33716   WHERE (item_exclusive)
33717    AND (item_sold)
33718    AND ($2 != -1)
33719    AND (ipsass_shipto_id=$2)
33720    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33721   UNION
33722    -- Exclusive, Shipto pattern match
33723   SELECT item_id
33724   FROM item
33725     JOIN ipsiteminfo ON (ipsitem_item_id=item_id)
33726     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33727     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33728     JOIN shiptoinfo ON (shipto_num ~ ipsass_shipto_pattern)
33729   WHERE (item_exclusive)
33730    AND (item_sold)
33731    AND (COALESCE(length(ipsass_shipto_pattern), 0) > 0)
33732    AND (ipsass_cust_id=$1)
33733    AND ($2 != -1)
33734    AND (shipto_id=$2)
33735    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33736   UNION
33737   SELECT item_id
33738   FROM item
33739     JOIN ipsiteminfo ON (ipsitem_prodcat_id=item_prodcat_id)
33740     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33741     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33742     JOIN shiptoinfo ON (shipto_num ~ ipsass_shipto_pattern)
33743   WHERE (item_exclusive)
33744    AND (item_sold)
33745    AND (COALESCE(length(ipsass_shipto_pattern), 0) > 0)
33746    AND (ipsass_cust_id=$1)
33747    AND ($2 != -1)
33748    AND (shipto_id=$2)
33749    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33750   UNION
33751    -- Exclusive, Customer match
33752   SELECT item_id
33753   FROM item
33754     JOIN ipsiteminfo ON (ipsitem_item_id=item_id)
33755     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33756     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33757   WHERE (item_exclusive)
33758    AND (item_sold)
33759    AND (ipsass_cust_id=$1)
33760    AND (ipsass_shipto_id=-1)
33761    AND (ipsass_shipto_pattern='')
33762    AND (ipsass_custtype_id=-1)
33763    AND (ipsass_custtype_pattern='')
33764    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33765   UNION
33766   SELECT item_id
33767   FROM item
33768     JOIN ipsiteminfo ON (ipsitem_prodcat_id=item_prodcat_id)
33769     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33770     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33771   WHERE (item_exclusive)
33772    AND (item_sold)
33773    AND (ipsass_cust_id=$1)
33774    AND (ipsass_shipto_id=-1)
33775    AND (ipsass_shipto_pattern='')
33776    AND (ipsass_custtype_id=-1)
33777    AND (ipsass_custtype_pattern='')
33778    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33779   UNION
33780   -- Exclusive, Customer Type match
33781   SELECT item_id
33782   FROM item
33783     JOIN ipsiteminfo ON (ipsitem_item_id=item_id)
33784     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33785     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33786     JOIN custinfo ON (ipsass_custtype_id=cust_custtype_id)
33787   WHERE (item_exclusive)
33788    AND (item_sold)
33789    AND (cust_id=$1)
33790    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33791   UNION
33792   SELECT item_id
33793   FROM item
33794     JOIN ipsiteminfo ON (ipsitem_prodcat_id=item_prodcat_id)
33795     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33796     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33797     JOIN custinfo ON (ipsass_custtype_id=cust_custtype_id)
33798   WHERE (item_exclusive)
33799    AND (item_sold)
33800    AND (cust_id=$1)
33801    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33802   UNION
33803   -- Exclusive, Customer Type pattern match
33804   SELECT item_id
33805   FROM item
33806     JOIN ipsiteminfo ON (ipsitem_item_id=item_id)
33807     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33808     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33809     JOIN custtype ON (custtype_code ~ ipsass_custtype_pattern)
33810     JOIN custinfo ON (cust_custtype_id=custtype_id)
33811   WHERE (item_exclusive)
33812    AND (item_sold)
33813    AND (COALESCE(length(ipsass_custtype_pattern), 0) > 0)
33814    AND (cust_id=$1)
33815    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33816   UNION
33817   SELECT item_id
33818   FROM item
33819     JOIN ipsiteminfo ON (ipsitem_prodcat_id=item_prodcat_id)
33820     JOIN ipshead ON (ipshead_id=ipsitem_ipshead_id)
33821     JOIN ipsass ON (ipsass_ipshead_id=ipshead_id)
33822     JOIN custtype ON (custtype_code ~ ipsass_custtype_pattern)
33823     JOIN custinfo ON (cust_custtype_id=custtype_id)
33824   WHERE (item_exclusive)
33825    AND (item_sold)
33826    AND (COALESCE(length(ipsass_custtype_pattern), 0) > 0)
33827    AND (cust_id=$1)
33828    AND ($3 BETWEEN ipshead_effective AND (ipshead_expires - 1))
33829    
33830 $_$;
33831
33832
33833 ALTER FUNCTION public.custitem(cust_id integer, shipto_id integer, asof date) OWNER TO admin;
33834
33835 --
33836 -- TOC entry 1389 (class 1255 OID 146565958)
33837 -- Dependencies: 4536 8
33838 -- Name: customercanpurchase(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
33839 --
33840
33841 CREATE FUNCTION customercanpurchase(integer, integer) RETURNS boolean
33842     LANGUAGE plpgsql
33843     AS $_$
33844 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33845 -- See www.xtuple.com/CPAL for the full text of the software license.
33846 DECLARE
33847   pitemid ALIAS FOR $1;
33848   pCustid ALIAS FOR $2;
33849
33850 BEGIN
33851   RETURN customerCanPurchase(pitemid, pCustid, -1);
33852 END;
33853 $_$;
33854
33855
33856 ALTER FUNCTION public.customercanpurchase(integer, integer) OWNER TO admin;
33857
33858 --
33859 -- TOC entry 1390 (class 1255 OID 146565959)
33860 -- Dependencies: 4536 8
33861 -- Name: customercanpurchase(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
33862 --
33863
33864 CREATE FUNCTION customercanpurchase(integer, integer, integer) RETURNS boolean
33865     LANGUAGE plpgsql
33866     AS $_$
33867 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33868 -- See www.xtuple.com/CPAL for the full text of the software license.
33869 DECLARE
33870   pitemid ALIAS FOR $1;
33871   pCustid ALIAS FOR $2;
33872   pShiptoid AlIAS FOR $3;
33873   _id INTEGER;
33874   _item RECORD;
33875
33876 BEGIN
33877   RETURN customerCanPurchase(pitemid, pCustid, pShiptoid, CURRENT_DATE);
33878 END;
33879 $_$;
33880
33881
33882 ALTER FUNCTION public.customercanpurchase(integer, integer, integer) OWNER TO admin;
33883
33884 --
33885 -- TOC entry 1391 (class 1255 OID 146565960)
33886 -- Dependencies: 4536 8
33887 -- Name: customercanpurchase(integer, integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
33888 --
33889
33890 CREATE FUNCTION customercanpurchase(integer, integer, integer, date) RETURNS boolean
33891     LANGUAGE plpgsql
33892     AS $_$
33893 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
33894 -- See www.xtuple.com/CPAL for the full text of the software license.
33895 DECLARE
33896   pitemid ALIAS FOR $1;
33897   pCustid ALIAS FOR $2;
33898   pShiptoid AlIAS FOR $3;
33899   pAsOf ALIAS FOR $4;
33900   _id INTEGER;
33901   _item RECORD;
33902
33903 BEGIN
33904
33905   SELECT item_sold, item_exclusive
33906     INTO _item
33907     FROM item
33908    WHERE(item_id=pItemid);
33909
33910 --  Make sure that this is at least a sold Item
33911   IF (NOT _item.item_sold) THEN
33912     RETURN FALSE;
33913   END IF;
33914
33915 --  Everyone can purchase a non-exclusive item
33916   IF (NOT _item.item_exclusive) THEN
33917     RETURN TRUE;
33918   END IF;
33919
33920   IF(pShiptoid != -1) THEN
33921 --  Check for a shipto Assigned Price
33922     SELECT ipsitem_id INTO _id
33923       FROM ipsiteminfo, ipshead, ipsass
33924      WHERE((ipsitem_ipshead_id=ipshead_id)
33925        AND (ipsass_ipshead_id=ipshead_id)
33926        AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
33927        AND (ipsitem_item_id=pItemid)
33928        AND (ipsass_shipto_id != -1)
33929        AND (ipsass_shipto_id=pShiptoid))
33930      LIMIT 1;
33931     IF (FOUND) THEN
33932       RETURN TRUE;
33933     END IF;
33934     SELECT ipsitem_id INTO _id
33935       FROM ipsiteminfo, item, ipshead, ipsass
33936      WHERE((ipsitem_ipshead_id=ipshead_id)
33937        AND (ipsitem_prodcat_id = item_prodcat_id)
33938        AND (ipsass_ipshead_id=ipshead_id)
33939        AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
33940        AND (item_id=pItemid)
33941        AND (ipsass_shipto_id != -1)
33942        AND (ipsass_shipto_id=pShiptoid))
33943      LIMIT 1;
33944     IF (FOUND) THEN
33945       RETURN TRUE;
33946     END IF;
33947
33948 --  Check for a Shipto Pattern Assigned Price
33949     SELECT ipsitem_id INTO _id
33950       FROM ipsiteminfo, ipshead, ipsass, shiptoinfo
33951      WHERE((ipsitem_ipshead_id=ipshead_id)
33952        AND (ipsass_ipshead_id=ipshead_id)
33953        AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
33954        AND (COALESCE(length(ipsass_shipto_pattern), 0) > 0)
33955        AND (shipto_num ~ ipsass_shipto_pattern)
33956        AND (ipsass_cust_id=pCustid)
33957        AND (ipsitem_item_id=pItemid)
33958        AND (shipto_id=pShiptoid))
33959      LIMIT 1;
33960     IF (FOUND) THEN
33961       RETURN TRUE;
33962     END IF;
33963     SELECT ipsitem_id INTO _id
33964       FROM ipsiteminfo, item, ipshead, ipsass, shiptoinfo
33965      WHERE((ipsitem_ipshead_id=ipshead_id)
33966        AND (ipsitem_prodcat_id = item_prodcat_id)
33967        AND (ipsass_ipshead_id=ipshead_id)
33968        AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
33969        AND (COALESCE(length(ipsass_shipto_pattern), 0) > 0)
33970        AND (shipto_num ~ ipsass_shipto_pattern)
33971        AND (ipsass_cust_id=pCustid)
33972        AND (item_id=pItemid)
33973        AND (shipto_id=pShiptoid))
33974      LIMIT 1;
33975     IF (FOUND) THEN
33976       RETURN TRUE;
33977     END IF;
33978   END IF;
33979
33980 --  Check for a Customer Assigned Price
33981   SELECT ipsitem_id INTO _id
33982     FROM ipsiteminfo, ipshead, ipsass
33983    WHERE((ipsitem_ipshead_id=ipshead_id)
33984      AND (ipsass_ipshead_id=ipshead_id)
33985      AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
33986      AND (ipsitem_item_id=pItemid)
33987      AND (COALESCE(length(ipsass_shipto_pattern), 0) = 0)
33988      AND (ipsass_cust_id=pCustid))
33989    LIMIT 1;
33990   IF (FOUND) THEN
33991     RETURN TRUE;
33992   END IF;
33993   SELECT ipsitem_id INTO _id
33994     FROM ipsiteminfo, item, ipshead, ipsass
33995    WHERE((ipsitem_ipshead_id=ipshead_id)
33996      AND (ipsitem_prodcat_id = item_prodcat_id)
33997      AND (ipsass_ipshead_id=ipshead_id)
33998      AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
33999      AND (item_id=pItemid)
34000      AND (COALESCE(length(ipsass_shipto_pattern), 0) = 0)
34001      AND (ipsass_cust_id=pCustid))
34002    LIMIT 1;
34003   IF (FOUND) THEN
34004     RETURN TRUE;
34005   END IF;
34006
34007 --  Check for a Customer Type Assigned Price
34008   SELECT ipsitem_id INTO _id
34009     FROM ipsiteminfo, ipshead, ipsass, custinfo
34010    WHERE( (ipsitem_ipshead_id=ipshead_id)
34011      AND  (ipsass_ipshead_id=ipshead_id)
34012      AND  (ipsass_custtype_id != -1)
34013      AND  (cust_custtype_id = ipsass_custtype_id)
34014      AND  (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
34015      AND  (ipsitem_item_id=pItemid)
34016      AND  (cust_id=pCustid))
34017     LIMIT 1;
34018   IF (FOUND) THEN
34019     RETURN TRUE;
34020   END IF;
34021   SELECT ipsitem_id INTO _id
34022     FROM ipsiteminfo, item, ipshead, ipsass, custinfo
34023    WHERE( (ipsitem_ipshead_id=ipshead_id)
34024      AND  (ipsitem_prodcat_id = item_prodcat_id)
34025      AND  (ipsass_ipshead_id=ipshead_id)
34026      AND  (ipsass_custtype_id != -1)
34027      AND  (cust_custtype_id = ipsass_custtype_id)
34028      AND  (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
34029      AND  (item_id=pItemid)
34030      AND  (cust_id=pCustid))
34031     LIMIT 1;
34032   IF (FOUND) THEN
34033     RETURN TRUE;
34034   END IF;
34035
34036 --  Check for a Customer Type Pattern Assigned Price
34037   SELECT ipsitem_id INTO _id
34038     FROM ipsiteminfo, ipshead, ipsass, custtype, custinfo
34039    WHERE((ipsitem_ipshead_id=ipshead_id)
34040      AND (ipsass_ipshead_id=ipshead_id)
34041      AND (coalesce(length(ipsass_custtype_pattern), 0) > 0)
34042      AND (custtype_code ~ ipsass_custtype_pattern)
34043      AND (cust_custtype_id=custtype_id)
34044      AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
34045      AND (ipsitem_item_id=pItemid)
34046      AND (cust_id=pCustid))
34047    LIMIT 1;
34048   IF (FOUND) THEN
34049     RETURN TRUE;
34050   END IF;
34051   SELECT ipsitem_id INTO _id
34052     FROM ipsiteminfo, item, ipshead, ipsass, custtype, custinfo
34053    WHERE((ipsitem_ipshead_id=ipshead_id)
34054      AND (ipsitem_prodcat_id = item_prodcat_id)
34055      AND (ipsass_ipshead_id=ipshead_id)
34056      AND (coalesce(length(ipsass_custtype_pattern), 0) > 0)
34057      AND (custtype_code ~ ipsass_custtype_pattern)
34058      AND (cust_custtype_id=custtype_id)
34059      AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
34060      AND (item_id=pItemid)
34061      AND (cust_id=pCustid))
34062    LIMIT 1;
34063   IF (FOUND) THEN
34064     RETURN TRUE;
34065   END IF;
34066
34067 --  That's it, Sales don't count - yet
34068   RETURN FALSE;
34069
34070 END;
34071 $_$;
34072
34073
34074 ALTER FUNCTION public.customercanpurchase(integer, integer, integer, date) OWNER TO admin;
34075
34076 --
34077 -- TOC entry 1392 (class 1255 OID 146565961)
34078 -- Dependencies: 8
34079 -- Name: dearmor(text); Type: FUNCTION; Schema: public; Owner: admin
34080 --
34081
34082 CREATE FUNCTION dearmor(text) RETURNS bytea
34083     LANGUAGE c IMMUTABLE STRICT
34084     AS '$libdir/pgcrypto', 'pg_dearmor';
34085
34086
34087 ALTER FUNCTION public.dearmor(text) OWNER TO admin;
34088
34089 --
34090 -- TOC entry 1393 (class 1255 OID 146565962)
34091 -- Dependencies: 8
34092 -- Name: decrypt(bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
34093 --
34094
34095 CREATE FUNCTION decrypt(bytea, bytea, text) RETURNS bytea
34096     LANGUAGE c IMMUTABLE STRICT
34097     AS '$libdir/pgcrypto', 'pg_decrypt';
34098
34099
34100 ALTER FUNCTION public.decrypt(bytea, bytea, text) OWNER TO admin;
34101
34102 --
34103 -- TOC entry 1394 (class 1255 OID 146565963)
34104 -- Dependencies: 8
34105 -- Name: decrypt_iv(bytea, bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
34106 --
34107
34108 CREATE FUNCTION decrypt_iv(bytea, bytea, bytea, text) RETURNS bytea
34109     LANGUAGE c IMMUTABLE STRICT
34110     AS '$libdir/pgcrypto', 'pg_decrypt_iv';
34111
34112
34113 ALTER FUNCTION public.decrypt_iv(bytea, bytea, bytea, text) OWNER TO admin;
34114
34115 --
34116 -- TOC entry 1395 (class 1255 OID 146565964)
34117 -- Dependencies: 4536 8
34118 -- Name: defaultlocationname(integer); Type: FUNCTION; Schema: public; Owner: admin
34119 --
34120
34121 CREATE FUNCTION defaultlocationname(integer) RETURNS text
34122     LANGUAGE plpgsql
34123     AS $_$
34124 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34125 -- See www.xtuple.com/CPAL for the full text of the software license.
34126 DECLARE
34127   pItemsiteid ALIAS FOR $1;
34128   _p RECORD;
34129
34130 BEGIN
34131
34132   SELECT itemsite_location_id, itemsite_location INTO _p
34133   FROM itemsite
34134   WHERE (itemsite_id=pItemsiteid);
34135
34136   IF (NOT FOUND) THEN
34137     RETURN 'Error';
34138   ELSIF (_p.itemsite_location_id = -1) THEN
34139     RETURN _p.itemsite_location;
34140   ELSE
34141     RETURN formatLocationName(_p.itemsite_location_id);
34142   END IF;
34143
34144 END;
34145 $_$;
34146
34147
34148 ALTER FUNCTION public.defaultlocationname(integer) OWNER TO admin;
34149
34150 --
34151 -- TOC entry 1396 (class 1255 OID 146565965)
34152 -- Dependencies: 4536 8
34153 -- Name: deleteaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
34154 --
34155
34156 CREATE FUNCTION deleteaccount(integer) RETURNS integer
34157     LANGUAGE plpgsql
34158     AS $_$
34159 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34160 -- See www.xtuple.com/CPAL for the full text of the software license.
34161 DECLARE
34162   pAccntid ALIAS FOR $1;
34163   _check INTEGER;
34164
34165 BEGIN
34166
34167 --  Check to see if the passed accnt is used in a Cost Category
34168   SELECT costcat_id INTO _check
34169   FROM costcat
34170   WHERE ( (costcat_asset_accnt_id=pAccntid)
34171      OR   (costcat_liability_accnt_id=pAccntid)
34172      OR   (costcat_adjustment_accnt_id=pAccntid)
34173      OR   (costcat_purchprice_accnt_id=pAccntid)
34174      OR   (costcat_laboroverhead_accnt_id=pAccntid)
34175      OR   (costcat_scrap_accnt_id=pAccntid)
34176      OR   (costcat_invcost_accnt_id=pAccntid)
34177      OR   (costcat_wip_accnt_id=pAccntid)
34178      OR   (costcat_shipasset_accnt_id=pAccntid)
34179      OR   (costcat_mfgscrap_accnt_id=pAccntid)
34180      OR   (costcat_transform_accnt_id=pAccntid)
34181      OR   (costcat_freight_accnt_id=pAccntid) )
34182   LIMIT 1;
34183   IF (FOUND) THEN
34184     RETURN -1;
34185   END IF;
34186
34187 --  Check to see if the passed accnt is used in a Sales Account Assignment
34188   SELECT salesaccnt_id INTO _check
34189   FROM salesaccnt
34190   WHERE ( (salesaccnt_sales_accnt_id=pAccntid)
34191      OR   (salesaccnt_credit_accnt_id=pAccntid)
34192      OR   (salesaccnt_cos_accnt_id=pAccntid) )
34193   LIMIT 1;
34194   IF (FOUND) THEN
34195     RETURN -2;
34196   END IF;
34197
34198 --  Check to see if the passed accnt is used in a A/R Account Assignment
34199   SELECT araccnt_id INTO _check
34200   FROM araccnt
34201   WHERE ( (araccnt_freight_accnt_id=pAccntid)
34202      OR   (araccnt_ar_accnt_id=pAccntid)
34203      OR   (araccnt_prepaid_accnt_id=pAccntid) )
34204   LIMIT 1;
34205   IF (FOUND) THEN
34206     RETURN -3;
34207   END IF;
34208
34209 --  Check to see if the passed accnt is used in a Warehouse
34210   IF EXISTS (SELECT 1
34211                FROM whsinfo
34212               WHERE (warehous_default_accnt_id=pAccntid)) THEN
34213     RETURN -4;
34214   END IF;
34215
34216 --  Check to see if the passed accnt is used in a Bank Account
34217   SELECT bankaccnt_id INTO _check
34218   FROM bankaccnt
34219   WHERE (bankaccnt_accnt_id=pAccntid)
34220   LIMIT 1;
34221   IF (FOUND) THEN
34222     RETURN -5;
34223   END IF;
34224
34225 --  Check to see if the passed accnt is used in an Expense Category
34226   SELECT expcat_id INTO _check
34227   FROM expcat
34228   WHERE ( (expcat_exp_accnt_id=pAccntid)
34229      OR   (expcat_liability_accnt_id=pAccntid)
34230      OR   (expcat_purchprice_accnt_id=pAccntid)
34231      OR   (expcat_freight_accnt_id=pAccntid) )
34232   LIMIT 1;
34233   IF (FOUND) THEN
34234     RETURN -6;
34235   END IF;
34236
34237 --  Check to see if the passed accnt is used in a Tax Code
34238   SELECT tax_id INTO _check
34239   FROM tax
34240   WHERE (tax_sales_accnt_id=pAccntid)
34241   LIMIT 1;
34242   IF (FOUND) THEN
34243     RETURN -7;
34244   END IF;
34245
34246 --  Check to see if the passed accnt is used in a Standard Journal Item
34247   SELECT stdjrnlitem_id INTO _check
34248   FROM stdjrnlitem
34249   WHERE (stdjrnlitem_accnt_id=pAccntid)
34250   LIMIT 1;
34251   IF (FOUND) THEN
34252     RETURN -8;
34253   END IF;
34254
34255 --  Check to see if the passed accnt is used in a A/P Account Assignment
34256   SELECT apaccnt_ap_accnt_id INTO _check
34257   FROM apaccnt
34258   WHERE ( (apaccnt_ap_accnt_id=pAccntid)
34259      OR   (apaccnt_prepaid_accnt_id=pAccntid)
34260      OR   (apaccnt_discount_accnt_id=pAccntid) )
34261   LIMIT 1;
34262   IF (FOUND) THEN
34263     RETURN -9;
34264   END IF;
34265
34266 --  Check to see if the passed accnt is used in an A/R Open Item record
34267   SELECT aropen_accnt_id INTO _check
34268     FROM aropen
34269    WHERE (aropen_accnt_id=pAccntid)
34270    LIMIT 1;
34271   IF (FOUND) THEN
34272     RETURN -11;
34273   END IF;
34274
34275 --  Check to see if the passed accnt has been used in the G/L
34276   SELECT gltrans_accnt_id INTO _check
34277   FROM gltrans
34278   WHERE (gltrans_accnt_id=pAccntid)
34279   LIMIT 1;
34280   IF (FOUND) THEN
34281     RETURN -99;
34282   END IF;
34283
34284   SELECT glseries_accnt_id INTO _check
34285   FROM glseries
34286   WHERE (glseries_accnt_id=pAccntid)
34287   LIMIT 1;
34288   IF (FOUND) THEN
34289     RETURN -99;
34290   END IF;
34291
34292   SELECT trialbal_accnt_id INTO _check
34293   FROM trialbal
34294   WHERE (trialbal_accnt_id=pAccntid)
34295     AND (trialbal_beginning != 0 OR trialbal_ending != 0)
34296   LIMIT 1;
34297   IF (FOUND) THEN
34298     RETURN -99;
34299   END IF;
34300
34301   SELECT cashrcptmisc_accnt_id INTO _check
34302   FROM cashrcptmisc
34303   WHERE (cashrcptmisc_accnt_id=pAccntid)
34304   LIMIT 1;
34305   IF (FOUND) THEN
34306     RETURN -99;
34307   END IF;
34308
34309 --  Delete any non-critical use
34310   DELETE FROM flitem
34311   WHERE (flitem_accnt_id=pAccntid);
34312
34313   -- only possible because of trialbal error-check above
34314   DELETE FROM trialbal
34315   WHERE (trialbal_accnt_id=pAccntid)
34316     AND (trialbal_beginning=0)
34317     AND (trialbal_ending=0);
34318
34319 --  Delete the Account
34320   DELETE FROM accnt
34321   WHERE (accnt_id=pAccntid);
34322
34323   RETURN 0;
34324
34325 END;
34326 $_$;
34327
34328
34329 ALTER FUNCTION public.deleteaccount(integer) OWNER TO admin;
34330
34331 --
34332 -- TOC entry 1398 (class 1255 OID 146565966)
34333 -- Dependencies: 4536 8
34334 -- Name: deleteaccountingperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
34335 --
34336
34337 CREATE FUNCTION deleteaccountingperiod(integer) RETURNS integer
34338     LANGUAGE plpgsql
34339     AS $_$
34340 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34341 -- See www.xtuple.com/CPAL for the full text of the software license.
34342 DECLARE
34343   pPeriodid ALIAS FOR $1;
34344   _check RECORD;
34345
34346 BEGIN
34347
34348 --  Check to make sure that the passed period is not closed
34349   IF ( ( SELECT period_closed
34350          FROM period
34351          WHERE (period_id=pPeriodid) ) ) THEN
34352     RETURN -1;
34353   END IF;
34354
34355 --  Check to make sure that there are not any posted G/L Transactions
34356 --  in the period.
34357   SELECT gltrans_id INTO _check
34358   FROM gltrans, period
34359   WHERE ( (gltrans_date BETWEEN period_start AND period_end)
34360    AND (gltrans_posted)
34361    AND (period_id=pPeriodid) )
34362   LIMIT 1;
34363   IF (FOUND) THEN
34364     RETURN -4;
34365   END IF;
34366
34367   SELECT b.period_id INTO _check
34368     FROM period AS a, period AS b
34369    WHERE((a.period_id=pPeriodid)
34370      AND (a.period_end < b.period_start))
34371    LIMIT 1;
34372   IF (FOUND) THEN
34373     RETURN -5;
34374   END IF;
34375
34376 --  Delete the period
34377   DELETE FROM period
34378   WHERE (period_id=pPeriodid);
34379
34380   RETURN 1;
34381
34382 END;
34383 $_$;
34384
34385
34386 ALTER FUNCTION public.deleteaccountingperiod(integer) OWNER TO admin;
34387
34388 --
34389 -- TOC entry 1399 (class 1255 OID 146565967)
34390 -- Dependencies: 4536 8
34391 -- Name: deleteaccountingyearperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
34392 --
34393
34394 CREATE FUNCTION deleteaccountingyearperiod(integer) RETURNS integer
34395     LANGUAGE plpgsql
34396     AS $_$
34397 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34398 -- See www.xtuple.com/CPAL for the full text of the software license.
34399 DECLARE
34400   pPeriodid ALIAS FOR $1;
34401   _check RECORD;
34402
34403 BEGIN
34404
34405 --  Check to make sure that the passed yearperiod is not closed
34406   IF ( ( SELECT yearperiod_closed
34407          FROM yearperiod
34408          WHERE (yearperiod_id=pPeriodid) ) ) THEN
34409     RETURN -1;
34410   END IF;
34411
34412   -- this yearperiod is in use by existing periods
34413   IF (EXISTS(SELECT period_id
34414              FROM period
34415              WHERE (period_yearperiod_id=pPeriodid))) THEN
34416     RETURN -2;
34417   END IF;
34418
34419 --  Delete the yearperiod
34420   DELETE FROM yearperiod
34421   WHERE (yearperiod_id=pPeriodid);
34422
34423   RETURN 1;
34424
34425 END;
34426 $_$;
34427
34428
34429 ALTER FUNCTION public.deleteaccountingyearperiod(integer) OWNER TO admin;
34430
34431 --
34432 -- TOC entry 1400 (class 1255 OID 146565968)
34433 -- Dependencies: 4536 8
34434 -- Name: deleteaddress(integer); Type: FUNCTION; Schema: public; Owner: admin
34435 --
34436
34437 CREATE FUNCTION deleteaddress(integer) RETURNS integer
34438     LANGUAGE plpgsql
34439     AS $_$
34440 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34441 -- See www.xtuple.com/CPAL for the full text of the software license.
34442 DECLARE
34443   paddrId     ALIAS FOR $1;
34444   _count      INTEGER := 0;
34445 BEGIN
34446   SELECT count(*) INTO _count
34447     FROM cntct
34448     WHERE (cntct_active
34449       AND  (cntct_addr_id = paddrId));
34450   IF (_count > 0) THEN
34451     RETURN -1;
34452   END IF;
34453
34454   SELECT count(*) INTO _count
34455     FROM vendinfo
34456     WHERE (vend_active
34457       AND  (vend_addr_id = paddrId));
34458   IF (_count > 0) THEN
34459     RETURN -2;
34460   END IF;
34461
34462   SELECT count(*) INTO _count
34463     FROM shiptoinfo
34464     WHERE (shipto_active
34465       AND  (shipto_addr_id = paddrId));
34466   IF (_count > 0) THEN
34467     RETURN -3;
34468   END IF;
34469
34470   SELECT count(*) INTO _count
34471     FROM vendaddrinfo
34472     WHERE (vendaddr_addr_id = paddrId);
34473   IF (_count > 0) THEN
34474     RETURN -4;
34475   END IF;
34476
34477   SELECT count(*) INTO _count
34478     FROM whsinfo
34479     WHERE (warehous_active
34480       AND  (warehous_addr_id = paddrId));
34481   IF (_count > 0) THEN
34482     RETURN -5;
34483   END IF;
34484
34485   UPDATE cntct SET cntct_addr_id = NULL WHERE (cntct_addr_id = paddrId);
34486   UPDATE vendinfo SET vend_addr_id = NULL WHERE (vend_addr_id = paddrId);
34487   UPDATE shiptoinfo SET shipto_addr_id = NULL WHERE (shipto_addr_id =paddrId);
34488   UPDATE vendaddrinfo SET vendaddr_addr_id = NULL
34489     WHERE (vendaddr_addr_id = paddrId);
34490   UPDATE whsinfo SET warehous_addr_id = NULL WHERE (warehous_addr_id=paddrId);
34491
34492   DELETE FROM addr WHERE addr_id = paddrId;
34493   RETURN 0;
34494 END;
34495 $_$;
34496
34497
34498 ALTER FUNCTION public.deleteaddress(integer) OWNER TO admin;
34499
34500 --
34501 -- TOC entry 1401 (class 1255 OID 146565969)
34502 -- Dependencies: 4536 8
34503 -- Name: deleteapcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
34504 --
34505
34506 CREATE FUNCTION deleteapcheck(integer) RETURNS integer
34507     LANGUAGE plpgsql
34508     AS $_$
34509 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34510 -- See www.xtuple.com/CPAL for the full text of the software license.
34511 BEGIN
34512   RAISE NOTICE 'deleteAPCheck() is deprecated - use deleteCheck() instead';
34513   RETURN deleteCheck($1);
34514 END;
34515 $_$;
34516
34517
34518 ALTER FUNCTION public.deleteapcheck(integer) OWNER TO admin;
34519
34520 --
34521 -- TOC entry 1402 (class 1255 OID 146565970)
34522 -- Dependencies: 4536 8
34523 -- Name: deletebankadjustmenttype(integer); Type: FUNCTION; Schema: public; Owner: admin
34524 --
34525
34526 CREATE FUNCTION deletebankadjustmenttype(integer) RETURNS integer
34527     LANGUAGE plpgsql
34528     AS $_$
34529 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34530 -- See www.xtuple.com/CPAL for the full text of the software license.
34531 DECLARE
34532   pBankadjtypeid ALIAS FOR $1;
34533   _check INTEGER;
34534
34535 BEGIN
34536
34537 -- Check to see if the the adjustment type is being used in any adjustments
34538   SELECT bankadj_bankadjtype_id INTO _check
34539     FROM bankadj
34540    WHERE (bankadj_bankadjtype_id=pBankadjtypeid)
34541    LIMIT 1;
34542   IF (FOUND) THEN
34543     RETURN -1;
34544   END IF;
34545
34546 --  Delete the Account
34547   DELETE FROM bankadjtype
34548   WHERE (bankadjtype_id=pbankadjtypeid);
34549
34550   RETURN 0;
34551
34552 END;
34553 $_$;
34554
34555
34556 ALTER FUNCTION public.deletebankadjustmenttype(integer) OWNER TO admin;
34557
34558 --
34559 -- TOC entry 1403 (class 1255 OID 146565971)
34560 -- Dependencies: 4536 8
34561 -- Name: deletebankreconciliation(integer); Type: FUNCTION; Schema: public; Owner: admin
34562 --
34563
34564 CREATE FUNCTION deletebankreconciliation(integer) RETURNS integer
34565     LANGUAGE plpgsql
34566     AS $_$
34567 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34568 -- See www.xtuple.com/CPAL for the full text of the software license.
34569 DECLARE
34570   pbankrecid    ALIAS FOR $1;
34571 BEGIN
34572   DELETE FROM bankrecitem
34573   WHERE bankrecitem_bankrec_id=pbankrecid;
34574
34575   DELETE FROM bankrec
34576   WHERE bankrec_id=pbankrecid;
34577
34578   RETURN 0;
34579 END;
34580 $_$;
34581
34582
34583 ALTER FUNCTION public.deletebankreconciliation(integer) OWNER TO admin;
34584
34585 --
34586 -- TOC entry 1404 (class 1255 OID 146565972)
34587 -- Dependencies: 4536 8
34588 -- Name: deletebom(integer); Type: FUNCTION; Schema: public; Owner: admin
34589 --
34590
34591 CREATE FUNCTION deletebom(integer) RETURNS integer
34592     LANGUAGE plpgsql
34593     AS $_$
34594 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34595 -- See www.xtuple.com/CPAL for the full text of the software license.
34596 DECLARE
34597   pItemid ALIAS FOR $1;
34598   _result INTEGER;
34599
34600 BEGIN
34601
34602   IF (fetchmetricbool('RevControl')) THEN
34603     SELECT rev_id INTO _result
34604     FROM rev
34605     WHERE ((rev_target_id=pItemid)
34606     AND (rev_target_type = 'BOM'))
34607     LIMIT 1;
34608     IF (FOUND) THEN
34609       RAISE EXCEPTION 'Bill of Materials has revision control records and may not be deleted.';
34610     END IF;
34611   END IF;
34612
34613   DELETE FROM bomhead
34614   WHERE (bomhead_item_id=pItemid);
34615   DELETE FROM bomitem
34616   WHERE (bomitem_parent_item_id=pItemid);
34617
34618   RETURN 0;
34619
34620 END;
34621 $_$;
34622
34623
34624 ALTER FUNCTION public.deletebom(integer) OWNER TO admin;
34625
34626 --
34627 -- TOC entry 1405 (class 1255 OID 146565973)
34628 -- Dependencies: 4536 8
34629 -- Name: deletebomworkset(integer); Type: FUNCTION; Schema: public; Owner: admin
34630 --
34631
34632 CREATE FUNCTION deletebomworkset(integer) RETURNS integer
34633     LANGUAGE plpgsql
34634     AS $_$
34635 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34636 -- See www.xtuple.com/CPAL for the full text of the software license.
34637 DECLARE
34638   pWorksetid ALIAS FOR $1;
34639
34640 BEGIN
34641
34642 --  All done with the bomwork set indicated by pWorksetid, delete all of it
34643   DELETE FROM bomwork
34644   WHERE (bomwork_set_id=pWorksetid);
34645
34646   RETURN 1;
34647
34648 END;
34649 $_$;
34650
34651
34652 ALTER FUNCTION public.deletebomworkset(integer) OWNER TO admin;
34653
34654 --
34655 -- TOC entry 1406 (class 1255 OID 146565974)
34656 -- Dependencies: 4536 8
34657 -- Name: deletebudget(integer); Type: FUNCTION; Schema: public; Owner: admin
34658 --
34659
34660 CREATE FUNCTION deletebudget(integer) RETURNS integer
34661     LANGUAGE plpgsql
34662     AS $_$
34663 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34664 -- See www.xtuple.com/CPAL for the full text of the software license.
34665 DECLARE
34666   pBudgheadid ALIAS FOR $1;
34667
34668 BEGIN
34669   DELETE FROM budgitem WHERE (budgitem_budghead_id=pBudgheadid);
34670   DELETE FROM budghead WHERE (budghead_id=pBudgheadid);
34671
34672   RETURN pBudgheadid;
34673 END;
34674 $_$;
34675
34676
34677 ALTER FUNCTION public.deletebudget(integer) OWNER TO admin;
34678
34679 --
34680 -- TOC entry 1407 (class 1255 OID 146565975)
34681 -- Dependencies: 4536 8
34682 -- Name: deletebudgetitems(integer); Type: FUNCTION; Schema: public; Owner: admin
34683 --
34684
34685 CREATE FUNCTION deletebudgetitems(integer) RETURNS integer
34686     LANGUAGE plpgsql
34687     AS $_$
34688 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34689 -- See www.xtuple.com/CPAL for the full text of the software license.
34690 DECLARE
34691   pBudgheadid ALIAS FOR $1;
34692
34693 BEGIN
34694   DELETE FROM budgitem WHERE (budgitem_budghead_id=pBudgheadid);
34695
34696   RETURN pBudgheadid;
34697 END;
34698 $_$;
34699
34700
34701 ALTER FUNCTION public.deletebudgetitems(integer) OWNER TO admin;
34702
34703 --
34704 -- TOC entry 1409 (class 1255 OID 146565976)
34705 -- Dependencies: 4536 8
34706 -- Name: deletecashrcpt(integer); Type: FUNCTION; Schema: public; Owner: admin
34707 --
34708
34709 CREATE FUNCTION deletecashrcpt(integer) RETURNS integer
34710     LANGUAGE plpgsql
34711     AS $_$
34712 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34713 -- See www.xtuple.com/CPAL for the full text of the software license.
34714 DECLARE
34715   pcashrcptid ALIAS FOR $1;
34716   _ccreceipt    BOOLEAN;
34717
34718 BEGIN
34719
34720   IF EXISTS(SELECT cashrcpt_id
34721             FROM cashrcpt
34722             JOIN ccpay ON (cashrcpt_cust_id=ccpay_cust_id)
34723                        AND ((CASE WHEN TRIM(COALESCE(cashrcpt_docnumber, ''))='' THEN TEXT(cashrcpt_id)
34724                                   ELSE cashrcpt_docnumber
34725                              END)=ccpay_order_number)
34726             WHERE ((cashrcpt_fundstype IN ('A', 'D', 'M', 'V'))
34727                AND (ccpay_status NOT IN ('D', 'X'))
34728                AND (ccpay_id NOT IN (SELECT payco_ccpay_id FROM payco))
34729                AND (cashrcpt_id=pcashrcptid))) THEN
34730     RETURN -1;
34731   END IF;
34732
34733   IF EXISTS(SELECT cashrcpt_id
34734             FROM cashrcpt
34735             WHERE ( (cashrcpt_id=pcashrcptid)
34736               AND   (cashrcpt_posted) )) THEN
34737     RETURN -2;
34738   END IF;
34739
34740   -- If there are applications for this Cash Receipt then
34741   -- it has been posted and reversed.  Void instead of delete.
34742   IF EXISTS(SELECT cashrcpt_id
34743             FROM cashrcpt JOIN cashrcptitem ON (cashrcptitem_cashrcpt_id=cashrcpt_id)
34744                           JOIN arapply ON ((arapply_reftype='CRA') AND
34745                                            (arapply_ref_id=cashrcptitem_id))
34746             WHERE (cashrcpt_id=pcashrcptid))
34747      OR
34748      EXISTS(SELECT cashrcpt_id
34749             FROM cashrcpt JOIN cashrcptmisc ON (cashrcptmisc_cashrcpt_id=cashrcpt_id)
34750                           JOIN arapply ON ((arapply_reftype='CRD') AND
34751                                            (arapply_ref_id=cashrcptmisc_id))
34752             WHERE (cashrcpt_id=pcashrcptid)) THEN
34753     UPDATE cashrcpt SET cashrcpt_void = TRUE
34754     WHERE (cashrcpt_id=pcashrcptid);
34755     RETURN 1;
34756   END IF;
34757
34758   DELETE FROM cashrcptitem
34759   WHERE (cashrcptitem_cashrcpt_id=pcashrcptid);
34760
34761   DELETE FROM cashrcptmisc
34762   WHERE (cashrcptmisc_cashrcpt_id=pcashrcptid);
34763
34764   DELETE FROM cashrcpt
34765   WHERE (cashrcpt_id=pcashrcptid);
34766
34767   RETURN 1;
34768
34769 END;
34770 $_$;
34771
34772
34773 ALTER FUNCTION public.deletecashrcpt(integer) OWNER TO admin;
34774
34775 --
34776 -- TOC entry 1410 (class 1255 OID 146565977)
34777 -- Dependencies: 4536 8
34778 -- Name: deletecharacteristic(integer); Type: FUNCTION; Schema: public; Owner: admin
34779 --
34780
34781 CREATE FUNCTION deletecharacteristic(integer) RETURNS integer
34782     LANGUAGE plpgsql
34783     AS $_$
34784 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34785 -- See www.xtuple.com/CPAL for the full text of the software license.
34786 DECLARE
34787   pCharid ALIAS FOR $1;
34788   _check INTEGER;
34789   _r RECORD;
34790
34791 BEGIN
34792
34793 --  Cache the specifics of the characteristic
34794   SELECT * INTO _r
34795   FROM char
34796   WHERE (char_id=pCharid);
34797   IF (NOT(FOUND)) THEN
34798     RETURN 0;
34799   END IF;
34800
34801 --  If the passed characteristic is used
34802   SELECT * INTO _r
34803   FROM charass
34804   WHERE (charass_char_id=pCharid)
34805   LIMIT 1;
34806   IF (FOUND) THEN
34807     IF (_r.charass_target_type = 'I') THEN
34808       RETURN -1;
34809     ELSIF (_r.charass_target_type = 'C') THEN
34810       RETURN -2;
34811     ELSIF (_r.charass_target_type = 'ADDR') THEN
34812       RETURN -3;
34813     ELSIF (_r.charass_target_type = 'CNTCT') THEN
34814       RETURN -4;
34815     ELSIF (_r.charass_target_type = 'CRMACCT') THEN
34816       RETURN -5;
34817     ELSIF (_r.charass_target_type = 'INCDT      ') THEN
34818       RETURN -6;
34819     ELSIF (_r.charass_target_type = 'EMP') THEN
34820       RETURN -7;
34821     ELSIF (_r.charass_target_type = 'QU') THEN
34822       RETURN -8;
34823     ELSIF (_r.charass_target_type = 'SO') THEN
34824       RETURN -9;
34825     ELSIF (_r.charass_target_type = 'INV') THEN
34826       RETURN -10;
34827     ELSIF (_r.charass_target_type = 'V') THEN
34828       RETURN -11;
34829     ELSIF (_r.charass_target_type = 'PO') THEN
34830       RETURN -12;
34831     ELSIF (_r.charass_target_type = 'VO') THEN
34832       RETURN -13;
34833     ELSE
34834       RETURN -99;
34835     END IF;
34836   END IF;
34837
34838 --  Delete the passed characterisitic
34839   DELETE FROM char
34840   WHERE (char_id=pCharid);
34841
34842   RETURN pCharid;
34843
34844 END;
34845 $_$;
34846
34847
34848 ALTER FUNCTION public.deletecharacteristic(integer) OWNER TO admin;
34849
34850 --
34851 -- TOC entry 1411 (class 1255 OID 146565978)
34852 -- Dependencies: 4536 8
34853 -- Name: deletecheck(integer); Type: FUNCTION; Schema: public; Owner: admin
34854 --
34855
34856 CREATE FUNCTION deletecheck(integer) RETURNS integer
34857     LANGUAGE plpgsql
34858     AS $_$
34859 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34860 -- See www.xtuple.com/CPAL for the full text of the software license.
34861 DECLARE
34862   pCheckid ALIAS FOR $1;
34863
34864 BEGIN
34865   IF (SELECT (NOT checkhead_void) OR checkhead_posted OR checkhead_replaced
34866               OR checkhead_deleted
34867               OR (checkhead_ach_batch IS NOT NULL AND checkhead_printed)
34868       FROM checkhead
34869       WHERE (checkhead_id=pCheckid) ) THEN
34870     RETURN -1;
34871   END IF;
34872
34873   UPDATE checkhead
34874   SET checkhead_deleted=TRUE
34875   WHERE (checkhead_id=pCheckid);
34876
34877   RETURN 1;
34878
34879 END;
34880 $_$;
34881
34882
34883 ALTER FUNCTION public.deletecheck(integer) OWNER TO admin;
34884
34885 --
34886 -- TOC entry 1412 (class 1255 OID 146565979)
34887 -- Dependencies: 4536 8
34888 -- Name: deleteclasscode(integer); Type: FUNCTION; Schema: public; Owner: admin
34889 --
34890
34891 CREATE FUNCTION deleteclasscode(integer) RETURNS integer
34892     LANGUAGE plpgsql
34893     AS $_$
34894 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34895 -- See www.xtuple.com/CPAL for the full text of the software license.
34896 DECLARE
34897   pClasscodeid ALIAS FOR $1;
34898   _check INTEGER;
34899
34900 BEGIN
34901
34902 --  Check to see if any items are assigned to the passed classcode
34903   SELECT item_id INTO _check
34904   FROM item
34905   WHERE (item_classcode_id=pClasscodeid)
34906   LIMIT 1;
34907   IF (FOUND) THEN
34908     RETURN -1;
34909   END IF;
34910
34911 --  Delete the passed classcode
34912   DELETE FROM classcode
34913   WHERE (classcode_id=pClasscodeid);
34914
34915   RETURN pClasscodeid;
34916
34917 END;
34918 $_$;
34919
34920
34921 ALTER FUNCTION public.deleteclasscode(integer) OWNER TO admin;
34922
34923 --
34924 -- TOC entry 1413 (class 1255 OID 146565980)
34925 -- Dependencies: 4536 8
34926 -- Name: deletecompany(integer); Type: FUNCTION; Schema: public; Owner: admin
34927 --
34928
34929 CREATE FUNCTION deletecompany(integer) RETURNS integer
34930     LANGUAGE plpgsql
34931     AS $_$
34932 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34933 -- See www.xtuple.com/CPAL for the full text of the software license.
34934 DECLARE
34935   pcompanyid ALIAS FOR $1;
34936
34937 BEGIN
34938   IF (EXISTS(SELECT accnt_id
34939              FROM accnt, company
34940              WHERE ((accnt_company=company_number)
34941                AND  (company_id=pcompanyid))
34942             )) THEN
34943     RETURN -1;
34944   END IF;
34945
34946   DELETE FROM company
34947   WHERE (company_id=pcompanyid);
34948
34949   RETURN pcompanyid;
34950
34951 END;
34952 $_$;
34953
34954
34955 ALTER FUNCTION public.deletecompany(integer) OWNER TO admin;
34956
34957 --
34958 -- TOC entry 1414 (class 1255 OID 146565981)
34959 -- Dependencies: 4536 8
34960 -- Name: deletecreditmemo(integer); Type: FUNCTION; Schema: public; Owner: admin
34961 --
34962
34963 CREATE FUNCTION deletecreditmemo(integer) RETURNS boolean
34964     LANGUAGE plpgsql
34965     AS $_$
34966 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34967 -- See www.xtuple.com/CPAL for the full text of the software license.
34968 DECLARE
34969   pCmheadid ALIAS FOR $1;
34970
34971 BEGIN
34972
34973   DELETE FROM cmitem
34974   WHERE (cmitem_cmhead_id=pCmheadid);
34975
34976   DELETE FROM cmhead
34977   WHERE (cmhead_id=pCmheadid);
34978
34979   RETURN TRUE;
34980
34981 END;
34982 $_$;
34983
34984
34985 ALTER FUNCTION public.deletecreditmemo(integer) OWNER TO admin;
34986
34987 --
34988 -- TOC entry 1415 (class 1255 OID 146565982)
34989 -- Dependencies: 4536 8
34990 -- Name: deletecustomer(integer); Type: FUNCTION; Schema: public; Owner: admin
34991 --
34992
34993 CREATE FUNCTION deletecustomer(integer) RETURNS integer
34994     LANGUAGE plpgsql
34995     AS $_$
34996 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
34997 -- See www.xtuple.com/CPAL for the full text of the software license.
34998 DECLARE
34999   pCustid ALIAS FOR $1;
35000
35001 BEGIN
35002
35003   PERFORM shipto_id
35004   FROM shiptoinfo
35005   WHERE (shipto_cust_id=pCustid)
35006   LIMIT 1;
35007   IF (FOUND) THEN
35008     RETURN -1;
35009   END IF;
35010
35011   PERFORM cohead_id
35012   FROM cohead
35013   WHERE (cohead_cust_id=pCustid)
35014   LIMIT 1;
35015   IF (FOUND) THEN
35016     RETURN -2;
35017   END IF;
35018
35019   PERFORM cmhead_id
35020   FROM cmhead
35021   WHERE (cmhead_cust_id=pCustid)
35022   LIMIT 1;
35023   IF (FOUND) THEN
35024     RETURN -3;
35025   END IF;
35026
35027   PERFORM cohist_id
35028   FROM cohist
35029   WHERE (cohist_cust_id=pCustid)
35030   LIMIT 1;
35031   IF (FOUND) THEN
35032     RETURN -4;
35033   END IF;
35034
35035   PERFORM aropen_id
35036   FROM aropen
35037   WHERE (aropen_cust_id=pCustid)
35038   LIMIT 1;
35039   IF (FOUND) THEN
35040     RETURN -5;
35041   END IF;
35042
35043   PERFORM checkhead_recip_id
35044     FROM checkhead
35045    WHERE ((checkhead_recip_id=pCustid)
35046      AND  (checkhead_recip_type='C'))
35047    LIMIT 1;
35048    IF (FOUND) THEN
35049      RETURN -6;
35050    END IF;
35051
35052   PERFORM invchead_id
35053      FROM invchead
35054     WHERE(invchead_cust_id=pCustid)
35055     LIMIT 1;
35056   IF (FOUND) THEN
35057     RETURN -7;
35058   END IF;
35059
35060   PERFORM quhead_id
35061      FROM quhead
35062     WHERE(quhead_cust_id=pCustid)
35063     LIMIT 1;
35064   IF (FOUND) THEN
35065     RETURN -8;
35066   END IF;
35067
35068   DELETE FROM taxreg
35069    WHERE ((taxreg_rel_type='C')
35070      AND  (taxreg_rel_id=pCustid));
35071
35072   DELETE FROM ipsass
35073   WHERE (ipsass_cust_id=pCustid);
35074
35075   DELETE FROM custinfo
35076   WHERE (cust_id=pCustid);
35077
35078   UPDATE crmacct SET crmacct_cust_id = NULL
35079   WHERE (crmacct_cust_id=pCustid);
35080
35081   RETURN 0;
35082
35083 END;
35084 $_$;
35085
35086
35087 ALTER FUNCTION public.deletecustomer(integer) OWNER TO admin;
35088
35089 --
35090 -- TOC entry 1416 (class 1255 OID 146565983)
35091 -- Dependencies: 4536 8
35092 -- Name: deletecustomertype(integer); Type: FUNCTION; Schema: public; Owner: admin
35093 --
35094
35095 CREATE FUNCTION deletecustomertype(integer) RETURNS integer
35096     LANGUAGE plpgsql
35097     AS $_$
35098 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35099 -- See www.xtuple.com/CPAL for the full text of the software license.
35100 DECLARE
35101   pCusttypeid ALIAS FOR $1;
35102
35103 BEGIN
35104
35105   IF EXISTS(SELECT 1
35106               FROM custinfo
35107              WHERE (cust_custtype_id=pCusttypeid)) THEN
35108     RETURN -1;
35109   END IF;
35110
35111   DELETE FROM ipsass
35112   WHERE (ipsass_custtype_id=pCusttypeid);
35113
35114   DELETE FROM salesaccnt
35115   WHERE (salesaccnt_custtype_id=pCusttypeid);
35116
35117   DELETE FROM araccnt
35118   WHERE (araccnt_custtype_id=pCusttypeid);
35119
35120   DELETE FROM custform
35121   WHERE (custform_custtype_id=pCusttypeid);
35122
35123   DELETE FROM custtype
35124   WHERE (custtype_id=pCusttypeid);
35125
35126   RETURN pCusttypeid;
35127
35128 END;
35129 $_$;
35130
35131
35132 ALTER FUNCTION public.deletecustomertype(integer) OWNER TO admin;
35133
35134 --
35135 -- TOC entry 1305 (class 1255 OID 146565984)
35136 -- Dependencies: 4536 8
35137 -- Name: deleteempgrp(integer); Type: FUNCTION; Schema: public; Owner: admin
35138 --
35139
35140 CREATE FUNCTION deleteempgrp(integer) RETURNS integer
35141     LANGUAGE plpgsql
35142     AS $_$
35143 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35144 -- See www.xtuple.com/CPAL for the full text of the software license.
35145 DECLARE
35146   pempgrpid ALIAS FOR $1;
35147
35148 BEGIN
35149 --  Check to see if any employees are assigned to the passed empgrp
35150   PERFORM empgrpitem_emp_id
35151   FROM empgrpitem
35152   WHERE (empgrpitem_empgrp_id=pempgrpid)
35153   LIMIT 1;
35154   IF (FOUND) THEN
35155     RETURN -1;
35156   END IF;
35157
35158   DELETE FROM empgrp     WHERE (empgrp_id=pempgrpid);
35159
35160   RETURN 0;
35161 END;
35162 $_$;
35163
35164
35165 ALTER FUNCTION public.deleteempgrp(integer) OWNER TO admin;
35166
35167 --
35168 -- TOC entry 1386 (class 1255 OID 146565985)
35169 -- Dependencies: 4536 8
35170 -- Name: deleteexpiredips(); Type: FUNCTION; Schema: public; Owner: admin
35171 --
35172
35173 CREATE FUNCTION deleteexpiredips() RETURNS boolean
35174     LANGUAGE plpgsql
35175     AS $$
35176 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35177 -- See www.xtuple.com/CPAL for the full text of the software license.
35178 DECLARE
35179   _r RECORD;
35180
35181 BEGIN
35182
35183   FOR _r IN SELECT ipshead_id
35184     FROM ipshead
35185     WHERE (ipshead_expires <= current_date)
35186   LOOP
35187
35188     DELETE FROM ipsass
35189       WHERE (ipsass_ipshead_id=_r.ipshead_id);
35190     DELETE FROM ipsiteminfo
35191       WHERE (ipsitem_ipshead_id=_r.ipshead_id);
35192     DELETE FROM ipsfreight
35193       WHERE (ipsfreight_ipshead_id=_r.ipshead_id);
35194     DELETE FROM ipshead
35195       WHERE (ipshead_id=_r.ipshead_id);
35196   END LOOP;
35197
35198   RETURN TRUE;
35199
35200 END;
35201 $$;
35202
35203
35204 ALTER FUNCTION public.deleteexpiredips() OWNER TO admin;
35205
35206 --
35207 -- TOC entry 1397 (class 1255 OID 146565986)
35208 -- Dependencies: 4536 8
35209 -- Name: deletefile(integer); Type: FUNCTION; Schema: public; Owner: admin
35210 --
35211
35212 CREATE FUNCTION deletefile(integer) RETURNS boolean
35213     LANGUAGE plpgsql
35214     AS $_$
35215 declare
35216   pId ALIAS FOR $1;
35217 begin
35218   delete from file
35219   where ( file_id in (
35220     select file_id
35221     from file
35222       join docass on (docass_target_id=file_id)
35223                  and (docass_target_type='FILE')
35224     where ( docass_id = pId ) ) );
35225
35226   delete from docass where docass_id = pId;
35227
35228   return true;
35229 end;
35230 $_$;
35231
35232
35233 ALTER FUNCTION public.deletefile(integer) OWNER TO admin;
35234
35235 --
35236 -- TOC entry 1417 (class 1255 OID 146565987)
35237 -- Dependencies: 4536 8
35238 -- Name: deleteflgrp(integer); Type: FUNCTION; Schema: public; Owner: admin
35239 --
35240
35241 CREATE FUNCTION deleteflgrp(integer) RETURNS integer
35242     LANGUAGE plpgsql
35243     AS $_$
35244 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35245 -- See www.xtuple.com/CPAL for the full text of the software license.
35246 DECLARE
35247   pFlgrpid ALIAS FOR $1;
35248   _r RECORD;
35249
35250 BEGIN
35251
35252   FOR _r IN SELECT flgrp_id
35253             FROM flgrp
35254             WHERE (flgrp_flgrp_id=pFlgrpid) LOOP
35255     PERFORM deleteFlgrp(_r.flgrp_id);
35256   END LOOP;
35257
35258   DELETE FROM flitem
35259   WHERE (flitem_flgrp_id=pFlgrpid);
35260
35261   DELETE FROM flspec
35262   WHERE (flspec_flgrp_id=pFlgrpid);
35263
35264   DELETE FROM flgrp
35265   WHERE (flgrp_id=pFlgrpid);
35266
35267   RETURN 1;
35268
35269 END;
35270 $_$;
35271
35272
35273 ALTER FUNCTION public.deleteflgrp(integer) OWNER TO admin;
35274
35275 --
35276 -- TOC entry 1418 (class 1255 OID 146565988)
35277 -- Dependencies: 4536 8
35278 -- Name: deleteform(integer); Type: FUNCTION; Schema: public; Owner: admin
35279 --
35280
35281 CREATE FUNCTION deleteform(integer) RETURNS integer
35282     LANGUAGE plpgsql
35283     AS $_$
35284 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35285 -- See www.xtuple.com/CPAL for the full text of the software license.
35286 DECLARE
35287   pFormid ALIAS FOR $1;
35288   _key TEXT;
35289   _check INTEGER;
35290
35291 BEGIN
35292
35293 --  Cache the key of the passed form
35294   SELECT form_key INTO _key
35295   FROM form
35296   WHERE (form_id=pFormid);
35297   IF (NOT(FOUND)) THEN
35298     RETURN 0;
35299   END IF;
35300
35301 --  Handle checks based on the type of the form
35302   IF (_key='Chck') THEN
35303     SELECT bankaccnt_id INTO _check
35304     FROM bankaccnt
35305     WHERE (bankaccnt_check_form_id=pFormid)
35306     LIMIT 1;
35307     IF (FOUND) THEN
35308       RETURN -1;
35309     END IF;
35310
35311   END IF;
35312
35313 --  Delete the form
35314   DELETE FROM form
35315   WHERE (form_id=pFormid);
35316
35317   RETURN pFormid;
35318
35319 END;
35320 $_$;
35321
35322
35323 ALTER FUNCTION public.deleteform(integer) OWNER TO admin;
35324
35325 --
35326 -- TOC entry 1419 (class 1255 OID 146565989)
35327 -- Dependencies: 4536 8
35328 -- Name: deletefreightclass(integer); Type: FUNCTION; Schema: public; Owner: admin
35329 --
35330
35331 CREATE FUNCTION deletefreightclass(integer) RETURNS integer
35332     LANGUAGE plpgsql
35333     AS $_$
35334 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35335 -- See www.xtuple.com/CPAL for the full text of the software license.
35336 DECLARE
35337   pFreightClassid ALIAS FOR $1;
35338   _check INTEGER;
35339
35340 BEGIN
35341
35342 --  Check to see if any items are assigned to the passed freightclass
35343   SELECT item_id INTO _check
35344   FROM item
35345   WHERE (item_freightclass_id=pFreightClassid)
35346   LIMIT 1;
35347   IF (FOUND) THEN
35348     RETURN -1;
35349   END IF;
35350
35351 --  Delete the passed freightclass
35352   DELETE FROM freightclass
35353   WHERE (freightclass_id=pFreightClassid);
35354
35355   RETURN pFreightClassid;
35356
35357 END;
35358 $_$;
35359
35360
35361 ALTER FUNCTION public.deletefreightclass(integer) OWNER TO admin;
35362
35363 --
35364 -- TOC entry 1420 (class 1255 OID 146565990)
35365 -- Dependencies: 4536 8
35366 -- Name: deleteglseries(integer); Type: FUNCTION; Schema: public; Owner: admin
35367 --
35368
35369 CREATE FUNCTION deleteglseries(integer) RETURNS integer
35370     LANGUAGE plpgsql
35371     AS $_$
35372 DECLARE
35373   pSequence ALIAS FOR $1;
35374
35375 BEGIN
35376
35377   DELETE FROM glseries
35378   WHERE (glseries_sequence=pSequence);
35379
35380   RETURN pSequence;
35381
35382 END;
35383 $_$;
35384
35385
35386 ALTER FUNCTION public.deleteglseries(integer) OWNER TO admin;
35387
35388 --
35389 -- TOC entry 1421 (class 1255 OID 146565991)
35390 -- Dependencies: 4536 8
35391 -- Name: deleteglseries(integer, text); Type: FUNCTION; Schema: public; Owner: admin
35392 --
35393
35394 CREATE FUNCTION deleteglseries(integer, text) RETURNS boolean
35395     LANGUAGE plpgsql
35396     AS $_$
35397 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35398 -- See www.xtuple.com/CPAL for the full text of the software license.
35399 DECLARE
35400   pSequence ALIAS FOR $1;
35401   pNotes ALIAS FOR $2;
35402   _trialbalid INTEGER;
35403   _count INTEGER;
35404   _r RECORD;
35405
35406 BEGIN
35407
35408 --  March through all of the G/L Transactions for the passed sequence
35409   FOR _r IN SELECT gltrans_id, gltrans_date, gltrans_accnt_id, gltrans_amount, gltrans_posted, gltrans_rec,
35410                    accnt_forwardupdate, period_id, period_closed, period_freeze
35411             FROM accnt, gltrans LEFT OUTER JOIN period ON (gltrans_date BETWEEN period_start AND period_end)
35412             WHERE ( (gltrans_accnt_id=accnt_id)
35413              AND (NOT gltrans_deleted)
35414              AND (gltrans_sequence=pSequence) ) LOOP
35415
35416 --  If we can post into a Trial Balance, do so
35417     IF ( (NOT _r.period_closed) AND 
35418        ( (NOT _r.period_freeze) OR (checkPrivilege('PostFrozenPeriod')) ) AND
35419        (  NOT _r.gltrans_rec) AND
35420        ( _r.gltrans_posted ) ) THEN
35421
35422 --  Try to find an existing trialbal
35423       SELECT trialbal_id INTO _trialbalid
35424       FROM trialbal
35425       WHERE ( (trialbal_period_id=_r.period_id)
35426        AND (trialbal_accnt_id=_r.gltrans_accnt_id) );
35427
35428       GET DIAGNOSTICS _count = ROW_COUNT;
35429       IF (_count > 0) THEN
35430
35431 --  We found a trialbal, update it with the G/L Transaction
35432 --  Note - two stage update to avoid any funny value caching logic
35433         IF (_r.gltrans_amount > 0) THEN
35434           UPDATE trialbal
35435           SET trialbal_credits = (trialbal_credits - _r.gltrans_amount)
35436           WHERE (trialbal_id=_trialbalid);
35437         ELSE
35438           UPDATE trialbal
35439           SET trialbal_debits = (trialbal_debits - (_r.gltrans_amount * -1))
35440           WHERE (trialbal_id=_trialbalid);
35441         END IF;
35442
35443         UPDATE trialbal
35444         SET trialbal_ending = (trialbal_beginning - trialbal_debits + trialbal_credits),
35445             trialbal_dirty=TRUE
35446         WHERE (trialbal_id=_trialbalid);
35447
35448       ELSE
35449         RAISE EXCEPTION 'Can not delete G/L Series.  Trial balance record not found.';
35450       END IF;
35451
35452 --  Forward update if we should
35453       IF (_r.accnt_forwardupdate AND fetchmetricbool('ManualForwardUpdate')) THEN
35454         PERFORM forwardUpdateTrialBalance(_trialbalid);
35455       END IF;
35456
35457 --  Delete any bank reconciliation records if this was marked cleared but non reconciled
35458     DELETE FROM bankrecitem
35459     WHERE ((bankrecitem_source='GL')
35460     AND (bankrecitem_source_id=_r.gltrans_id));
35461
35462 --  Unflag any journals as posted as a result of this series
35463     UPDATE sltrans SET
35464       sltrans_posted=false,
35465       sltrans_gltrans_journalnumber=null
35466     FROM gltrans
35467     WHERE ((gltrans_sequence=pSequence)
35468     AND (sltrans_gltrans_journalnumber=gltrans_journalnumber));
35469     
35470 --  Mark the G/L Transaction as deleted
35471       UPDATE gltrans SET
35472         gltrans_posted=false,
35473         gltrans_deleted=true,
35474         gltrans_notes=gltrans_notes || E'\n' || pNotes
35475       WHERE (gltrans_id=_r.gltrans_id);
35476
35477     ELSIF (_r.period_freeze) THEN
35478         RAISE EXCEPTION 'Can not delete a G/L Transaction in a frozen period';
35479     ELSIF (_r.period_closed) THEN
35480         RAISE EXCEPTION 'Can not delete a G/L Transaction on account % in a closed period', formatGlAccount(_r.gltrans_accnt_id);
35481     ELSIF (_r.gltrans_rec) THEN
35482         RAISE EXCEPTION 'Can not delete a G/L Transaction that has been reconciled';
35483     ELSIF (NOT _r.gltrans_posted) THEN
35484         RAISE EXCEPTION 'Can not delete a G/L Transaction that has not been posted to Trial Balance';
35485     END IF;
35486
35487   END LOOP;
35488
35489   RETURN true;
35490
35491 END;
35492 $_$;
35493
35494
35495 ALTER FUNCTION public.deleteglseries(integer, text) OWNER TO admin;
35496
35497 --
35498 -- TOC entry 1422 (class 1255 OID 146565992)
35499 -- Dependencies: 4536 8
35500 -- Name: deleteincident(integer); Type: FUNCTION; Schema: public; Owner: admin
35501 --
35502
35503 CREATE FUNCTION deleteincident(integer) RETURNS integer
35504     LANGUAGE plpgsql
35505     AS $_$
35506 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35507 -- See www.xtuple.com/CPAL for the full text of the software license.
35508 DECLARE
35509   pincdtid    ALIAS FOR $1;
35510   _count      INTEGER := 0;
35511   _incdtnbr   INTEGER := 0;
35512 BEGIN
35513   SELECT COUNT(*) INTO _count
35514   FROM todoitem
35515   WHERE (todoitem_incdt_id=pincdtid);
35516   IF (_count > 0) THEN
35517     RETURN -1;
35518   END IF;
35519
35520   DELETE FROM comment
35521    WHERE((comment_source='INCDT')
35522      AND (comment_source_id=pincdtid));
35523
35524   DELETE FROM incdthist
35525    WHERE (incdthist_incdt_id=pincdtid);
35526
35527   DELETE FROM imageass
35528   WHERE ((imageass_source='INCDT')
35529      AND (imageass_source_id=pincdtid));
35530
35531   DELETE FROM url
35532   WHERE ((url_source='INCDT')
35533      AND (url_source_id=pincdtid));
35534
35535   SELECT incdt_number INTO _incdtnbr
35536   FROM incdt
35537   WHERE (incdt_id=pincdtid);
35538
35539   DELETE FROM incdt
35540     WHERE (incdt_id=pincdtid);
35541
35542 -- Incident #11538 needs to be fully resolved before release can be implemented
35543 --    PERFORM releaseIncidentNumber(_incdtnbr);
35544
35545   RETURN 0;
35546 END;
35547 $_$;
35548
35549
35550 ALTER FUNCTION public.deleteincident(integer) OWNER TO admin;
35551
35552 --
35553 -- TOC entry 1423 (class 1255 OID 146565993)
35554 -- Dependencies: 4536 8
35555 -- Name: deleteinvoice(integer); Type: FUNCTION; Schema: public; Owner: admin
35556 --
35557
35558 CREATE FUNCTION deleteinvoice(integer) RETURNS integer
35559     LANGUAGE plpgsql
35560     AS $_$
35561 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35562 -- See www.xtuple.com/CPAL for the full text of the software license.
35563 DECLARE
35564   pInvcheadid ALIAS FOR $1;
35565
35566 BEGIN
35567   UPDATE shipitem SET shipitem_invoiced=FALSE, shipitem_invcitem_id=NULL
35568   FROM invcitem
35569   WHERE ((shipitem_invoiced)
35570     AND  (shipitem_invcitem_id=invcitem_id)
35571     AND  (invcitem_invchead_id=pInvcheadid));
35572
35573   UPDATE coitem SET coitem_status = 'O'
35574   WHERE ((coitem_status = 'C')
35575     AND  (coitem_id IN (SELECT cobill_coitem_id
35576                         FROM cobill, invcitem
35577                         WHERE ((cobill_invcitem_id=invcitem_id)
35578                           AND  (invcitem_invchead_id=pInvcheadid)))));
35579
35580   UPDATE cobill SET cobill_invcnum=NULL, cobill_invcitem_id=NULL
35581   FROM invcitem
35582   WHERE ((cobill_invcitem_id=invcitem_id)
35583     AND  (invcitem_invchead_id=pInvcheadid));
35584
35585   UPDATE invdetail SET invdetail_invcitem_id=NULL
35586   FROM invcitem
35587   WHERE ((invdetail_invcitem_id=invcitem_id)
35588     AND  (invcitem_invchead_id=pInvcheadid));
35589
35590   UPDATE cobmisc SET cobmisc_invcnumber=NULL, cobmisc_invchead_id=NULL,
35591                      cobmisc_posted=FALSE
35592   WHERE (cobmisc_invchead_id=pInvcheadid);
35593
35594   DELETE FROM aropenalloc
35595   WHERE (aropenalloc_doctype='I')
35596     AND (aropenalloc_doc_id=pInvcheadid);
35597
35598   DELETE FROM charass
35599   WHERE (charass_target_type='INV')
35600     AND (charass_target_id=pInvcheadid);
35601
35602   DELETE FROM invcitem
35603   WHERE (invcitem_invchead_id=pInvcheadid);
35604
35605   DELETE FROM invchead
35606   WHERE (invchead_id=pInvcheadid);
35607
35608   RETURN pInvcheadid;
35609
35610 END;
35611 $_$;
35612
35613
35614 ALTER FUNCTION public.deleteinvoice(integer) OWNER TO admin;
35615
35616 --
35617 -- TOC entry 1424 (class 1255 OID 146565994)
35618 -- Dependencies: 4536 8
35619 -- Name: deleteipsitem(integer); Type: FUNCTION; Schema: public; Owner: admin
35620 --
35621
35622 CREATE FUNCTION deleteipsitem(pipsitemid integer) RETURNS integer
35623     LANGUAGE plpgsql
35624     AS $$
35625 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35626 -- See www.xtuple.com/CPAL for the full text of the software license.
35627 DECLARE
35628
35629 BEGIN
35630
35631   DELETE FROM ipsiteminfo WHERE ipsitem_id=pIpsItemId;
35632
35633   RETURN 1;
35634 END;
35635 $$;
35636
35637
35638 ALTER FUNCTION public.deleteipsitem(pipsitemid integer) OWNER TO admin;
35639
35640 --
35641 -- TOC entry 1425 (class 1255 OID 146565995)
35642 -- Dependencies: 4536 8
35643 -- Name: deleteipsprodcat(integer); Type: FUNCTION; Schema: public; Owner: admin
35644 --
35645
35646 CREATE FUNCTION deleteipsprodcat(pipsitemid integer) RETURNS integer
35647     LANGUAGE plpgsql
35648     AS $$
35649 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35650 -- See www.xtuple.com/CPAL for the full text of the software license.
35651 DECLARE
35652
35653 BEGIN
35654
35655   DELETE FROM ipsiteminfo WHERE ipsitem_id=pIpsItemId;
35656   
35657   RETURN 1;
35658 END;
35659 $$;
35660
35661
35662 ALTER FUNCTION public.deleteipsprodcat(pipsitemid integer) OWNER TO admin;
35663
35664 --
35665 -- TOC entry 1426 (class 1255 OID 146565996)
35666 -- Dependencies: 4536 8
35667 -- Name: deleteitem(integer); Type: FUNCTION; Schema: public; Owner: admin
35668 --
35669
35670 CREATE FUNCTION deleteitem(integer) RETURNS integer
35671     LANGUAGE plpgsql
35672     AS $_$
35673 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35674 -- See www.xtuple.com/CPAL for the full text of the software license.
35675 DECLARE
35676   pItemid ALIAS FOR $1;
35677   _result INTEGER;
35678
35679 BEGIN
35680
35681   SELECT bomitem_id INTO _result
35682   FROM bomitem
35683   WHERE (bomitem_item_id=pItemid)
35684   LIMIT 1;
35685   IF (FOUND) THEN
35686     RETURN -1;
35687   END IF;
35688
35689   SELECT itemsite_id INTO _result
35690   FROM itemsite
35691   WHERE (itemsite_item_id=pItemid)
35692   LIMIT 1;
35693   IF (FOUND) THEN
35694     RETURN -2;
35695   END IF;
35696
35697   SELECT itemsub_id INTO _result
35698   FROM itemsub
35699   WHERE (itemsub_sub_item_id=pItemid)
35700   LIMIT 1;
35701   IF (FOUND) THEN
35702     RETURN -3;
35703   END IF;
35704
35705   IF (fetchmetricbool('RevControl')) THEN
35706     SELECT rev_id INTO _result
35707     FROM rev
35708     WHERE ((rev_target_id=pItemid)
35709     AND (rev_target_type = 'BOM'))
35710     LIMIT 1;
35711     IF (FOUND) THEN
35712       RETURN -6;
35713     END IF;
35714   END IF;
35715
35716   DELETE FROM bomhead
35717   WHERE (bomhead_item_id=pItemid);
35718   DELETE FROM bomitem
35719   WHERE (bomitem_item_id=pItemid);
35720
35721   DELETE FROM itemcost
35722   WHERE (itemcost_item_id=pItemid);
35723   DELETE FROM costhist
35724   WHERE (costhist_item_id=pItemid);
35725
35726   DELETE FROM itemsub
35727   WHERE (itemsub_parent_item_id=pItemid);
35728   DELETE FROM itemsub
35729   WHERE (itemsub_sub_item_id=pItemid);
35730
35731   DELETE FROM itemsrcp
35732   WHERE (itemsrcp_itemsrc_id IN (SELECT itemsrc_id FROM itemsrc WHERE (itemsrc_item_id=pItemid)));
35733   DELETE FROM itemsrc
35734   WHERE (itemsrc_item_id=pItemid);
35735
35736   DELETE FROM itemalias
35737   WHERE (itemalias_item_id=pItemid);
35738
35739   DELETE FROM itemgrpitem
35740   WHERE (itemgrpitem_item_id=pItemid);
35741
35742   DELETE FROM ipsiteminfo
35743   WHERE (ipsitem_item_id=pItemid);
35744
35745   DELETE FROM imageass
35746   WHERE ( (imageass_source='I')
35747     AND   (imageass_source_id=pItemid) );
35748
35749   DELETE FROM locitem
35750   WHERE (locitem_item_id=pItemid);
35751
35752   DELETE FROM itemtax
35753    WHERE(itemtax_item_id=pItemid);
35754
35755   DELETE FROM itemsite
35756   WHERE (itemsite_item_id=pItemid);
35757
35758   DELETE FROM itemuom
35759    WHERE(itemuom_itemuomconv_id IN (SELECT itemuomconv_id
35760                                       FROM itemuomconv
35761                                      WHERE(itemuomconv_item_id=pItemid)));
35762
35763   DELETE FROM itemuomconv
35764    WHERE(itemuomconv_item_id=pItemid);
35765
35766   DELETE FROM item
35767   WHERE (item_id=pItemid);
35768
35769   RETURN 0;
35770
35771 END;
35772 $_$;
35773
35774
35775 ALTER FUNCTION public.deleteitem(integer) OWNER TO admin;
35776
35777 --
35778 -- TOC entry 1427 (class 1255 OID 146565997)
35779 -- Dependencies: 4536 8
35780 -- Name: deleteitemcost(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
35781 --
35782
35783 CREATE FUNCTION deleteitemcost(integer, integer) RETURNS integer
35784     LANGUAGE plpgsql
35785     AS $_$
35786 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35787 -- See www.xtuple.com/CPAL for the full text of the software license.
35788 DECLARE
35789   pItemId ALIAS FOR $1;
35790   pCostElemId ALIAS FOR $2;
35791   _itemcost_id INTEGER;
35792   _postcost_return BOOLEAN;
35793   _std_cost NUMERIC;
35794
35795 BEGIN
35796   SELECT itemcost_id INTO _itemcost_id
35797   FROM itemcost
35798   WHERE ( (itemcost_item_id = pItemId) AND (itemcost_costelem_id = pCostElemId) );
35799
35800   IF (NOT FOUND) THEN
35801         RAISE EXCEPTION 'itemcost % not found for. ', pItemId || ' & ' || pCostElemId;
35802   END IF;
35803
35804   SELECT itemcost_stdcost INTO _std_cost
35805   FROM itemcost
35806   WHERE (itemcost_id = _itemcost_id);
35807
35808   IF (_std_cost > 0) THEN
35809 --Actual Cost is updated to zero to ensure inventory is valued correctly
35810     PERFORM updateCost(_itemcost_id, 0);
35811   END IF;
35812
35813   DELETE FROM itemcost
35814   WHERE (itemcost_id=_itemcost_id);
35815  
35816   RETURN _itemcost_id;  
35817
35818 END;
35819 $_$;
35820
35821
35822 ALTER FUNCTION public.deleteitemcost(integer, integer) OWNER TO admin;
35823
35824 --
35825 -- TOC entry 1428 (class 1255 OID 146565998)
35826 -- Dependencies: 4536 8
35827 -- Name: deleteitemsite(integer); Type: FUNCTION; Schema: public; Owner: admin
35828 --
35829
35830 CREATE FUNCTION deleteitemsite(integer) RETURNS integer
35831     LANGUAGE plpgsql
35832     AS $_$
35833 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
35834 -- See www.xtuple.com/CPAL for the full text of the software license.
35835 DECLARE
35836   pItemsiteid ALIAS FOR $1;
35837   _result INTEGER;
35838   _lotserial BOOLEAN;
35839   _bbom BOOLEAN;
35840   _mfg BOOLEAN;
35841   _standard BOOLEAN;
35842
35843 BEGIN
35844
35845   IF ( ( SELECT ( (itemsite_qtyonhand <> 0) OR (itemsite_nnqoh <> 0) )
35846          FROM itemsite
35847          WHERE (itemsite_id=pItemsiteid) ) ) THEN
35848     RETURN -9;
35849   END IF;
35850
35851   SELECT metric_value='t' INTO _bbom
35852     FROM metric
35853    WHERE (metric_name='BBOM');
35854
35855   SELECT metric_value='t' INTO _lotserial
35856     FROM metric
35857    WHERE (metric_name='LotSerialControl');
35858
35859   SELECT metric_value NOT IN ('PostBooks', 'Standard') INTO _mfg
35860     FROM metric
35861    WHERE (metric_name='Application');
35862
35863   SELECT metric_value='Standard' INTO _standard
35864     FROM metric
35865    WHERE (metric_name='Application');
35866
35867   SELECT invhist_id INTO _result
35868   FROM invhist
35869   WHERE (invhist_itemsite_id=pItemsiteid)
35870   LIMIT 1;
35871   IF (FOUND) THEN
35872     RETURN -1;
35873   END IF;
35874
35875   IF (_lotserial) THEN
35876     SELECT lsdetail_id INTO _result
35877     FROM lsdetail
35878     WHERE (lsdetail_itemsite_id=pItemsiteid)
35879     LIMIT 1;
35880     IF (FOUND) THEN
35881       RETURN -1;
35882     END IF;
35883   END IF;
35884
35885   SELECT wo_id INTO _result
35886   FROM wo
35887   WHERE (wo_itemsite_id=pItemsiteid)
35888   LIMIT 1;
35889   IF (FOUND) THEN
35890     RETURN -2;
35891   END IF;
35892
35893   SELECT womatl_id INTO _result
35894   FROM womatl
35895   WHERE (womatl_itemsite_id=pItemsiteid)
35896   LIMIT 1;
35897   IF (FOUND) THEN
35898     RETURN -2;
35899   END IF;
35900
35901   SELECT womatlvar_id INTO _result
35902   FROM womatlvar
35903   WHERE ( (womatlvar_parent_itemsite_id=pItemsiteid)
35904    OR (womatlvar_component_itemsite_id=pItemsiteid) )
35905   LIMIT 1;
35906   IF (FOUND) THEN
35907     RETURN -2;
35908   END IF;
35909
35910   IF (_bbom) THEN
35911     SELECT brdvar_id INTO _result
35912     FROM xtmfg.brdvar
35913     WHERE ( (brdvar_itemsite_id=pItemsiteid)
35914      OR (brdvar_parent_itemsite_id=pItemsiteid) )
35915     LIMIT 1;
35916     IF (FOUND) THEN
35917       RETURN -2;
35918     END IF;
35919   END IF;
35920
35921   SELECT coitem_id INTO _result
35922   FROM coitem
35923   WHERE (coitem_itemsite_id=pItemsiteid)
35924   LIMIT 1;
35925   IF (FOUND) THEN
35926     RETURN -3;
35927   END IF;
35928
35929   SELECT cohist_id INTO _result
35930   FROM cohist
35931   WHERE (cohist_itemsite_id=pItemsiteid)
35932   LIMIT 1;
35933   IF (FOUND) THEN
35934     RETURN -3;
35935   END IF;
35936
35937   SELECT quitem_id INTO _result
35938   FROM quitem
35939   WHERE (quitem_itemsite_id=pItemsiteid)
35940   LIMIT 1;
35941   IF (FOUND) THEN
35942     RETURN -3;
35943   END IF;
35944
35945   SELECT cmitem_id INTO _result
35946   FROM cmitem
35947   WHERE (cmitem_itemsite_id=pItemsiteid)
35948   LIMIT 1;
35949   IF (FOUND) THEN
35950     RETURN -3;
35951   END IF;
35952
35953
35954   SELECT poitem_id INTO _result
35955   FROM poitem
35956   WHERE (poitem_itemsite_id=pItemsiteid)
35957   LIMIT 1;
35958   IF (FOUND) THEN
35959     RETURN -4;
35960   END IF;
35961
35962   SELECT recv_id INTO _result
35963   FROM recv
35964   WHERE (recv_itemsite_id=pItemsiteid)
35965   LIMIT 1;
35966   IF (FOUND) THEN
35967     RETURN -4;
35968   END IF;
35969
35970   SELECT poreject_id INTO _result
35971   FROM poreject
35972   WHERE (poreject_itemsite_id=pItemsiteid)
35973   LIMIT 1;
35974   IF (FOUND) THEN
35975     RETURN -4;
35976   END IF;
35977
35978   SELECT pr_id INTO _result
35979   FROM pr
35980   WHERE (pr_itemsite_id=pItemsiteid)
35981   LIMIT 1;
35982   IF (FOUND) THEN
35983     RETURN -4;
35984   END IF;
35985
35986   IF (_mfg OR _standard) THEN
35987     SELECT planord_id INTO _result
35988     FROM planord
35989     WHERE (planord_itemsite_id=pItemsiteid)
35990     LIMIT 1;
35991     IF (FOUND) THEN
35992       RETURN -5;
35993     END IF;
35994   END IF;
35995
35996   IF (_mfg) THEN
35997     SELECT pschitem_id INTO _result
35998     FROM xtmfg.pschitem
35999     WHERE (pschitem_itemsite_id=pItemsiteid)
36000     LIMIT 1;
36001     IF (FOUND) THEN
36002       RETURN -6;
36003     END IF;
36004
36005     SELECT woopervar_id INTO _result
36006     FROM xtmfg.woopervar
36007     WHERE (woopervar_parent_itemsite_id=pItemsiteid)
36008     LIMIT 1;
36009     IF (FOUND) THEN
36010       RETURN -2;
36011     END IF;
36012     
36013   END IF;
36014
36015   IF (_mfg OR _standard) THEN
36016     SELECT itemsite_id INTO _result
36017     FROM itemsite
36018     WHERE (itemsite_supply_itemsite_id=pItemsiteid)
36019     LIMIT 1;
36020     IF (FOUND) THEN
36021       RETURN -7;
36022     END IF;
36023   END IF;
36024
36025   DELETE FROM invcnt
36026   WHERE (invcnt_itemsite_id=pItemsiteid);
36027
36028   DELETE FROM itemloc
36029   WHERE (itemloc_itemsite_id=pItemsiteid);
36030   DELETE FROM itemlocdist
36031   WHERE (itemlocdist_itemsite_id=pItemsiteid);
36032
36033   IF (_bbom) THEN
36034     DELETE FROM xtmfg.brddist
36035     WHERE (brddist_itemsite_id=pItemsiteid);
36036   END IF;
36037
36038   DELETE FROM itemsite
36039   WHERE (itemsite_id=pItemsiteid);
36040
36041   RETURN 0;
36042
36043 END;
36044 $_$;
36045
36046
36047 ALTER FUNCTION public.deleteitemsite(integer) OWNER TO admin;
36048
36049 --
36050 -- TOC entry 1429 (class 1255 OID 146565999)
36051 -- Dependencies: 4536 8
36052 -- Name: deleteitemuom(integer); Type: FUNCTION; Schema: public; Owner: admin
36053 --
36054
36055 CREATE FUNCTION deleteitemuom(integer) RETURNS integer
36056     LANGUAGE plpgsql
36057     AS $_$
36058 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36059 -- See www.xtuple.com/CPAL for the full text of the software license.
36060 DECLARE
36061   pItemuomid ALIAS FOR $1;
36062
36063 BEGIN
36064   DELETE FROM itemuom WHERE itemuom_id=pItemuomid;
36065
36066   RETURN 0;
36067 END;
36068 $_$;
36069
36070
36071 ALTER FUNCTION public.deleteitemuom(integer) OWNER TO admin;
36072
36073 --
36074 -- TOC entry 1430 (class 1255 OID 146566000)
36075 -- Dependencies: 4536 8
36076 -- Name: deleteitemuomconv(integer); Type: FUNCTION; Schema: public; Owner: admin
36077 --
36078
36079 CREATE FUNCTION deleteitemuomconv(integer) RETURNS integer
36080     LANGUAGE plpgsql
36081     AS $_$
36082 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36083 -- See www.xtuple.com/CPAL for the full text of the software license.
36084 DECLARE
36085   pItemuomconvid ALIAS FOR $1;
36086   _fromuomid     INTEGER;
36087   _invuomid      INTEGER;
36088   _itemid        INTEGER;
36089   _touomid       INTEGER;
36090
36091 BEGIN
36092   SELECT itemuomconv_item_id, item_inv_uom_id,
36093          itemuomconv_from_uom_id, itemuomconv_to_uom_id
36094           INTO _itemid, _invuomid, _fromuomid, _touomid
36095   FROM itemuomconv JOIN item ON (itemuomconv_item_id=item_id)
36096   WHERE (itemuomconv_id=pItemuomconvid);
36097
36098   IF EXISTS(SELECT *
36099             FROM uomusedforitem(_itemid)
36100             WHERE ((uom_id IN (_fromuomid, _touomid))
36101                AND (uom_id != _invuomid)) ) THEN
36102     RETURN -1;
36103   END IF;
36104
36105   DELETE FROM itemuom WHERE itemuom_itemuomconv_id=pItemuomconvid;
36106   DELETE FROM itemuomconv WHERE itemuomconv_id=pItemuomconvid;
36107
36108   RETURN 0;
36109 END;
36110 $_$;
36111
36112
36113 ALTER FUNCTION public.deleteitemuomconv(integer) OWNER TO admin;
36114
36115 --
36116 -- TOC entry 1431 (class 1255 OID 146566001)
36117 -- Dependencies: 4536 8
36118 -- Name: deletelocation(integer); Type: FUNCTION; Schema: public; Owner: admin
36119 --
36120
36121 CREATE FUNCTION deletelocation(integer) RETURNS integer
36122     LANGUAGE plpgsql
36123     AS $_$
36124 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36125 -- See www.xtuple.com/CPAL for the full text of the software license.
36126 DECLARE
36127   pLocationid ALIAS FOR $1;
36128   _check INTEGER;
36129
36130 BEGIN
36131
36132 --  Check to see if any itemsite used the passed location as their default
36133   SELECT itemsite_id INTO _check
36134   FROM itemsite
36135   WHERE (itemsite_location_id=pLocationid)
36136   LIMIT 1;
36137   IF (FOUND) THEN
36138     RETURN -1;
36139   END IF;
36140
36141 --  Check to see if any inventory is currently stored at the passed location
36142   SELECT itemloc_id INTO _check
36143   FROM itemloc
36144   WHERE (itemloc_location_id=pLocationid)
36145   LIMIT 1;
36146   IF (FOUND) THEN
36147     RETURN -2;
36148   END IF;
36149
36150 --  Check to see if any undistributed inventory transactions are currently posted at the passed location
36151   SELECT itemlocdist_id INTO _check
36152   FROM itemlocdist
36153   WHERE ( (itemlocdist_source_type='L')
36154   AND (itemlocdist_source_id=pLocationid) )
36155   LIMIT 1;
36156   IF (FOUND) THEN
36157     RETURN -3;
36158   END IF;
36159
36160 --  Check to see if the passed location has any Inventory Detail posted against it
36161   SELECT invdetail_id INTO _check
36162   FROM invdetail
36163   WHERE (invdetail_location_id=pLocationid)
36164   LIMIT 1;
36165   IF (FOUND) THEN
36166     RETURN -4;
36167   END IF;
36168
36169 --  Delete any associated locitem records
36170   DELETE FROM locitem
36171   WHERE (locitem_location_id=pLocationid);
36172
36173 --  Delete the location record
36174   DELETE FROM location
36175   WHERE (location_id=pLocationid);
36176
36177   RETURN pLocationid;
36178
36179 END;
36180 $_$;
36181
36182
36183 ALTER FUNCTION public.deletelocation(integer) OWNER TO admin;
36184
36185 --
36186 -- TOC entry 1432 (class 1255 OID 146566002)
36187 -- Dependencies: 4536 8
36188 -- Name: deletemetasql(integer); Type: FUNCTION; Schema: public; Owner: admin
36189 --
36190
36191 CREATE FUNCTION deletemetasql(integer) RETURNS integer
36192     LANGUAGE plpgsql
36193     AS $_$
36194 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36195 -- See www.xtuple.com/CPAL for the full text of the software license.
36196 DECLARE
36197   pid ALIAS FOR $1;
36198 BEGIN
36199   DELETE FROM metasql WHERE metasql_id = pid;
36200   RETURN 0;
36201 END;
36202 $_$;
36203
36204
36205 ALTER FUNCTION public.deletemetasql(integer) OWNER TO admin;
36206
36207 --
36208 -- TOC entry 1435 (class 1255 OID 146566003)
36209 -- Dependencies: 4536 8
36210 -- Name: deleteopenrecurringitems(integer, text, timestamp with time zone, boolean); Type: FUNCTION; Schema: public; Owner: admin
36211 --
36212
36213 CREATE FUNCTION deleteopenrecurringitems(integer, text, timestamp with time zone, boolean) RETURNS integer
36214     LANGUAGE plpgsql
36215     AS $_$
36216 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36217 -- See www.xtuple.com/CPAL for the full text of the software license.
36218 DECLARE
36219   pParentid     ALIAS FOR $1;
36220   pType         TEXT                     := UPPER($2);
36221   pDatetime     TIMESTAMP WITH TIME ZONE := COALESCE($3, startOfTime());
36222   pInclParent   BOOLEAN                  := COALESCE($4, FALSE);
36223
36224   _count         INTEGER := 0;
36225   _delchildstmt  TEXT;
36226   _delparentstmt TEXT;
36227   _rt            RECORD;
36228   _tmp           INTEGER;
36229 BEGIN
36230   RAISE DEBUG 'deleteOpenRecurringItems(%, %, %)', pParentid, pType, pDatetime;
36231
36232   IF (pParentid IS NULL) THEN
36233     RETURN -11;
36234   END IF;
36235
36236   SELECT * INTO _rt FROM recurtype WHERE (UPPER(recurtype_type)=pType);
36237   GET DIAGNOSTICS _count = ROW_COUNT;
36238   IF (_count <= 0) THEN
36239     RETURN -10;
36240   END IF;
36241
36242   -- 2 deletes avoid reparenting problems if the parent gets deleted first
36243   IF (_rt.recurtype_delfunc IS NULL) THEN
36244     _delchildstmt := 'DELETE FROM [fulltable] '
36245                   || ' WHERE (NOT ([done])'
36246                   || '    AND ([schedcol]>''$2'')'
36247                   || '    AND ([table]_recurring_[table]_id=$1)'
36248                   || '    AND ([table]_id!=$1));';
36249
36250     _delparentstmt := 'DELETE FROM [fulltable] USING recur'
36251                    || ' WHERE (NOT ([done])'
36252                    || '    AND ([schedcol]>''$2'')'
36253                    || '    AND ([table]_recurring_[table]_id=$1)'
36254                    || '    AND ([table]_id=$1));';
36255
36256   ELSE
36257     _delchildstmt := 'SELECT [delfunc]([table]_id)'
36258                   || '  FROM [fulltable] '
36259                   || ' WHERE (NOT ([done])'
36260                   || '    AND ([schedcol]>''$2'')'
36261                   || '    AND ([table]_recurring_[table]_id=$1)'
36262                   || '    AND ([table]_id!=$1));';
36263     _delparentstmt := 'SELECT [delfunc]([table]_id)'
36264                    || '  FROM [fulltable] '
36265                    || ' WHERE (NOT ([done])'
36266                    || '    AND ([schedcol]>''$2'')'
36267                    || '    AND ([table]_recurring_[table]_id=$1)'
36268                    || '    AND ([table]_id!=$1));';
36269     _delchildstmt  := REPLACE(_delchildstmt,  '[delfunc]', _rt.recurtype_delfunc);
36270     _delparentstmt := REPLACE(_delparentstmt, '[delfunc]', _rt.recurtype_delfunc);
36271   END IF;
36272
36273   RAISE DEBUG '_delchildstmt has been set to %', _delchildstmt;
36274
36275   _delchildstmt := REPLACE(_delchildstmt, '[fulltable]', _rt.recurtype_table);
36276   _delchildstmt := REPLACE(_delchildstmt, '[table]',
36277                             REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
36278   _delchildstmt := REPLACE(_delchildstmt, '[done]',  _rt.recurtype_donecheck);
36279   _delchildstmt := REPLACE(_delchildstmt, '[schedcol]', _rt.recurtype_schedcol);
36280
36281   _delparentstmt := REPLACE(_delparentstmt, '[fulltable]', _rt.recurtype_table);
36282   _delparentstmt := REPLACE(_delparentstmt, '[table]',
36283                             REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
36284   _delparentstmt := REPLACE(_delparentstmt, '[done]',  _rt.recurtype_donecheck);
36285   _delparentstmt := REPLACE(_delparentstmt, '[schedcol]', _rt.recurtype_schedcol);
36286
36287   RAISE DEBUG 'substitutions changed _delchildstmt to %', _delchildstmt;
36288
36289   IF (_rt.recurtype_delfunc IS NULL) THEN
36290     -- 8.4+: EXECUTE _delchildstmt  USING pDatetime, pType;
36291     RAISE DEBUG '% with % and %', _delchildstmt, pType, pDatetime;
36292     EXECUTE REPLACE(REPLACE(_delchildstmt, '$1', pParentid::TEXT),
36293                                            '$2', pDatetime::TEXT);
36294     GET DIAGNOSTICS _count = ROW_COUNT;
36295
36296     IF (pInclParent) THEN
36297       -- 8.4+: EXECUTE _delparentstmt USING pDatetime, pType;
36298       RAISE DEBUG '% with % and %', _delparentstmt, pType, pDatetime;
36299       EXECUTE REPLACE(REPLACE(_delparentstmt, '$1', pParentid::TEXT),
36300                                               '$2', pDatetime::TEXT);
36301       GET DIAGNOSTICS _tmp   = ROW_COUNT;
36302       _count := _count + _tmp;
36303     END IF;
36304
36305   ELSE
36306     -- 8.4+: FOR _tmp IN EXECUTE _delchildstmt USING pDatetime, pType LOOP
36307     FOR _tmp IN EXECUTE REPLACE(REPLACE(_delchildstmt, '$1', pParentid::TEXT),
36308                                                        '$2', pDatetime::TEXT)
36309     LOOP
36310       IF _tmp < 0 THEN
36311         RETURN _tmp;
36312       END IF;
36313       _count := _count + 1;
36314     END LOOP;
36315
36316     IF (pInclParent) THEN
36317       -- 8.4+: EXECUTE _delparentstmt INTO _tmp USING pDatetime, pType;
36318       EXECUTE REPLACE(REPLACE(_delparentstmt, '$1', pParentid::TEXT),
36319                                               '$2', pDatetime::TEXT) INTO _tmp;
36320       IF (_tmp < 0) THEN
36321         RETURN _tmp;
36322       END IF;
36323       _count := _count + 1;
36324     END IF;
36325   END IF;
36326
36327   RAISE DEBUG 'deleteOpenrecurringItems() returning %', _count;
36328   RETURN _count;
36329 END;
36330 $_$;
36331
36332
36333 ALTER FUNCTION public.deleteopenrecurringitems(integer, text, timestamp with time zone, boolean) OWNER TO admin;
36334
36335 --
36336 -- TOC entry 1436 (class 1255 OID 146566004)
36337 -- Dependencies: 4536 8
36338 -- Name: deleteopportunity(integer); Type: FUNCTION; Schema: public; Owner: admin
36339 --
36340
36341 CREATE FUNCTION deleteopportunity(integer) RETURNS integer
36342     LANGUAGE plpgsql
36343     AS $_$
36344 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36345 -- See www.xtuple.com/CPAL for the full text of the software license.
36346 DECLARE
36347   pOpheadid ALIAS FOR $1;
36348   _test INTEGER;
36349 BEGIN
36350
36351   SELECT todoitem_id INTO _test
36352     FROM todoitem
36353    WHERE(todoitem_ophead_id=pOpheadid)
36354    LIMIT 1;
36355   IF(FOUND) THEN
36356     RETURN -1;
36357   END IF;
36358
36359   SELECT quhead_id INTO _test
36360     FROM quhead
36361    WHERE(quhead_ophead_id=pOpheadid)
36362    LIMIT 1;
36363   IF(FOUND) THEN
36364     RETURN -2;
36365   END IF;
36366
36367   SELECT cohead_id INTO _test
36368     FROM cohead
36369    WHERE(cohead_ophead_id=pOpheadid)
36370    LIMIT 1;
36371   IF(FOUND) THEN
36372     RETURN -3;
36373   END IF;
36374
36375   DELETE
36376     FROM charass
36377    WHERE((charass_target_type='OPP')
36378      AND (charass_target_id=pOpheadid));
36379
36380   DELETE
36381     FROM comment
36382    WHERE((comment_source='OPP')
36383      AND (comment_source_id=pOpheadid));
36384
36385   DELETE
36386     FROM ophead
36387    WHERE(ophead_id=pOpheadid);
36388   
36389   return 0;
36390 END;
36391 $_$;
36392
36393
36394 ALTER FUNCTION public.deleteopportunity(integer) OWNER TO admin;
36395
36396 --
36397 -- TOC entry 1437 (class 1255 OID 146566005)
36398 -- Dependencies: 4536 8
36399 -- Name: deletepackage(integer); Type: FUNCTION; Schema: public; Owner: admin
36400 --
36401
36402 CREATE FUNCTION deletepackage(integer) RETURNS integer
36403     LANGUAGE plpgsql
36404     AS $_$
36405 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36406 -- See www.xtuple.com/CPAL for the full text of the software license.
36407 DECLARE
36408   ppkgheadid    ALIAS FOR $1;
36409   _i            INTEGER := 0;
36410   _pkgname      TEXT;
36411   _r            RECORD;
36412   _tabs         TEXT[] := ARRAY['cmd',  'cmdarg', 'image',  'metasql',
36413                                 'priv', 'report', 'script', 'uiform'];
36414   _debug        BOOL := false;
36415
36416 BEGIN
36417   IF (EXISTS(SELECT *
36418              FROM pkgdep
36419              WHERE (pkgdep_parent_pkghead_id=ppkgheadid))) THEN
36420     RETURN -1;
36421   END IF;
36422
36423   SELECT pkghead_name INTO _pkgname
36424   FROM pkghead
36425   WHERE (pkghead_id=ppkgheadid);
36426   IF (NOT FOUND) THEN
36427     RETURN -2;
36428   END IF;
36429
36430   IF (LOWER(_pkgname) = 'public' OR LOWER(_pkgname) = 'api') THEN
36431     RETURN -3;
36432   END IF;
36433
36434   FOR _i IN ARRAY_LOWER(_tabs,1)..ARRAY_UPPER(_tabs,1) LOOP
36435     EXECUTE 'ALTER TABLE ' || _pkgname || '.pkg' || _tabs[_i] ||
36436             ' DISABLE TRIGGER pkg' || _tabs[_i] || 'altertrigger;';
36437   END LOOP;
36438
36439   DELETE FROM pkghead WHERE pkghead_id=ppkgheadid;
36440
36441   RETURN ppkgheadid;
36442 END;
36443 $_$;
36444
36445
36446 ALTER FUNCTION public.deletepackage(integer) OWNER TO admin;
36447
36448 --
36449 -- TOC entry 1438 (class 1255 OID 146566006)
36450 -- Dependencies: 4536 8
36451 -- Name: deletepo(integer); Type: FUNCTION; Schema: public; Owner: admin
36452 --
36453
36454 CREATE FUNCTION deletepo(integer) RETURNS boolean
36455     LANGUAGE plpgsql
36456     AS $_$
36457 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36458 -- See www.xtuple.com/CPAL for the full text of the software license.
36459 DECLARE
36460   pPoheadid ALIAS FOR $1;
36461   _poitemid INTEGER;
36462
36463 BEGIN
36464
36465   IF ( ( SELECT pohead_status
36466          FROM pohead
36467          WHERE (pohead_id=pPoheadid) ) = 'U' ) THEN
36468
36469     -- Unlink from any Sales Orders
36470     UPDATE coitem SET coitem_order_type=NULL,
36471                       coitem_order_id=NULL
36472     FROM poitem 
36473     WHERE ( (coitem_order_type='P')
36474       AND   (coitem_order_id=poitem_id)
36475       AND   (poitem_pohead_id=pPoheadid) );
36476
36477     DELETE FROM poitem
36478     WHERE (poitem_pohead_id=pPoheadid);
36479
36480     DELETE FROM pohead
36481     WHERE (pohead_id=pPoheadid);
36482
36483     RETURN TRUE;
36484
36485   ELSE
36486     RETURN FALSE;
36487   END IF;
36488
36489 END;
36490 $_$;
36491
36492
36493 ALTER FUNCTION public.deletepo(integer) OWNER TO admin;
36494
36495 --
36496 -- TOC entry 1439 (class 1255 OID 146566007)
36497 -- Dependencies: 4536 8
36498 -- Name: deletepoitem(integer); Type: FUNCTION; Schema: public; Owner: admin
36499 --
36500
36501 CREATE FUNCTION deletepoitem(integer) RETURNS integer
36502     LANGUAGE plpgsql
36503     AS $_$
36504 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36505 -- See www.xtuple.com/CPAL for the full text of the software license.
36506 DECLARE
36507   pPoitemid ALIAS FOR $1;
36508   _poheadid INTEGER := -1;
36509   _status CHARACTER;
36510
36511 BEGIN
36512   SELECT poitem_pohead_id, poitem_status INTO _poheadid, _status
36513   FROM poitem
36514   WHERE (poitem_id=pPoitemid);
36515
36516   IF NOT(FOUND) THEN
36517     RETURN 0;
36518   END IF;
36519
36520   IF ( _status = 'U' ) THEN
36521     DELETE FROM poitem
36522     WHERE (poitem_id=pPoitemid);
36523   ELSE   
36524     IF ( _status = 'O' ) THEN
36525       PERFORM recv_id
36526       FROM recv
36527       WHERE ( (recv_order_type='PO')
36528        AND (recv_orderitem_id=pPoitemid) );
36529       IF (FOUND) THEN
36530         RETURN -10;
36531       ELSE
36532         RETURN -20;
36533       END IF;
36534     ELSE
36535       RETURN -10;
36536     END IF;
36537   END IF;
36538
36539   PERFORM poitem_id
36540   FROM poitem
36541   WHERE poitem_pohead_id = _poheadid;
36542
36543   IF NOT(FOUND) THEN
36544     DELETE FROM pohead
36545     WHERE (pohead_id = _poheadid);
36546   END IF;
36547   
36548   RETURN 0;
36549
36550 END;
36551 $_$;
36552
36553
36554 ALTER FUNCTION public.deletepoitem(integer) OWNER TO admin;
36555
36556 --
36557 -- TOC entry 1441 (class 1255 OID 146566009)
36558 -- Dependencies: 4536 8
36559 -- Name: deletepr(integer); Type: FUNCTION; Schema: public; Owner: admin
36560 --
36561
36562 CREATE FUNCTION deletepr(integer) RETURNS boolean
36563     LANGUAGE plpgsql
36564     AS $_$
36565 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36566 -- See www.xtuple.com/CPAL for the full text of the software license.
36567 DECLARE
36568   pPrid ALIAS FOR $1;
36569
36570 BEGIN
36571
36572   DELETE FROM pr
36573   WHERE ( (pr_status='O')
36574    AND (pr_id=pPrid) );
36575
36576   RETURN TRUE;
36577
36578 END;
36579 $_$;
36580
36581
36582 ALTER FUNCTION public.deletepr(integer) OWNER TO admin;
36583
36584 --
36585 -- TOC entry 1440 (class 1255 OID 146566008)
36586 -- Dependencies: 4536 8
36587 -- Name: deletepr(character, integer); Type: FUNCTION; Schema: public; Owner: admin
36588 --
36589
36590 CREATE FUNCTION deletepr(character, integer) RETURNS boolean
36591     LANGUAGE plpgsql
36592     AS $_$
36593 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36594 -- See www.xtuple.com/CPAL for the full text of the software license.
36595 DECLARE
36596   pParentType ALIAS FOR $1;
36597   pParentId ALIAS FOR $2;
36598
36599 BEGIN
36600
36601   DELETE FROM pr
36602   WHERE ((pr_status='O')
36603    AND (pr_order_type=pParentType)
36604    AND (pr_order_id=pParentId));
36605
36606   RETURN TRUE;
36607
36608 END;
36609 $_$;
36610
36611
36612 ALTER FUNCTION public.deletepr(character, integer) OWNER TO admin;
36613
36614 --
36615 -- TOC entry 1442 (class 1255 OID 146566010)
36616 -- Dependencies: 4536 8
36617 -- Name: deleteproductcategory(integer); Type: FUNCTION; Schema: public; Owner: admin
36618 --
36619
36620 CREATE FUNCTION deleteproductcategory(integer) RETURNS integer
36621     LANGUAGE plpgsql
36622     AS $_$
36623 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36624 -- See www.xtuple.com/CPAL for the full text of the software license.
36625 DECLARE
36626   pProdcatid ALIAS FOR $1;
36627   _check INTEGER;
36628
36629 BEGIN
36630
36631 --  Check to see if any items are assigned to the passed classcode
36632   SELECT item_id INTO _check
36633   FROM item
36634   WHERE (item_prodcat_id=pProdcatid)
36635   LIMIT 1;
36636   IF (FOUND) THEN
36637     RETURN -1;
36638   END IF;
36639
36640 --  Delete any assocated records
36641   DELETE FROM salesaccnt
36642   WHERE (salesaccnt_prodcat_id=pProdcatid);
36643
36644 --  Delete the passed prodcat
36645   DELETE FROM prodcat
36646   WHERE (prodcat_id=pProdcatid);
36647
36648   RETURN pProdcatid;
36649
36650 END;
36651 $_$;
36652
36653
36654 ALTER FUNCTION public.deleteproductcategory(integer) OWNER TO admin;
36655
36656 --
36657 -- TOC entry 1408 (class 1255 OID 146566011)
36658 -- Dependencies: 4536 8
36659 -- Name: deleteprofitcenter(integer); Type: FUNCTION; Schema: public; Owner: admin
36660 --
36661
36662 CREATE FUNCTION deleteprofitcenter(integer) RETURNS integer
36663     LANGUAGE plpgsql
36664     AS $_$
36665 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36666 -- See www.xtuple.com/CPAL for the full text of the software license.
36667 DECLARE
36668   pid ALIAS FOR $1;
36669
36670 BEGIN
36671   IF (EXISTS(SELECT accnt_id
36672              FROM accnt, prftcntr
36673              WHERE ((accnt_company=prftcntr_number)
36674                AND  (prftcntr_id=pid))
36675             )) THEN
36676     RETURN -1;
36677   END IF;
36678
36679   DELETE FROM prftcntr
36680   WHERE (prftcntr_id=pid);
36681
36682   RETURN pid;
36683
36684 END;
36685 $_$;
36686
36687
36688 ALTER FUNCTION public.deleteprofitcenter(integer) OWNER TO admin;
36689
36690 --
36691 -- TOC entry 1444 (class 1255 OID 146566012)
36692 -- Dependencies: 4536 8
36693 -- Name: deleteproject(integer); Type: FUNCTION; Schema: public; Owner: admin
36694 --
36695
36696 CREATE FUNCTION deleteproject(integer) RETURNS integer
36697     LANGUAGE plpgsql
36698     AS $_$
36699 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36700 -- See www.xtuple.com/CPAL for the full text of the software license.
36701 DECLARE
36702   pPrjid ALIAS FOR $1;
36703   _result INTEGER;
36704 BEGIN
36705
36706   SELECT quhead_id INTO _result
36707     FROM quhead
36708    WHERE (quhead_prj_id=pPrjid)
36709    LIMIT 1;
36710   IF (FOUND) THEN
36711     RETURN -1;
36712   END IF;
36713
36714   SELECT cohead_id INTO _result
36715     FROM cohead
36716    WHERE (cohead_prj_id=pPrjid)
36717    LIMIT 1;
36718   IF (FOUND) THEN
36719     RETURN -2;
36720   END IF;
36721
36722   SELECT wo_id INTO _result
36723     FROM wo
36724    WHERE (wo_prj_id=pPrjid)
36725    LIMIT 1;
36726   IF (FOUND) THEN
36727     RETURN -3;
36728   END IF;
36729
36730   SELECT pr_id INTO _result
36731     FROM pr
36732    WHERE (pr_prj_id=pPrjid)
36733    LIMIT 1;
36734   IF (FOUND) THEN
36735     RETURN -4;
36736   END IF;
36737
36738   SELECT poitem_id INTO _result
36739     FROM poitem
36740    WHERE (poitem_prj_id=pPrjid)
36741    LIMIT 1;
36742   IF (FOUND) THEN
36743     RETURN -5;
36744   END IF;
36745
36746   SELECT invchead_id INTO _result
36747     FROM invchead
36748    WHERE (invchead_prj_id=pPrjid)
36749    LIMIT 1;
36750   IF (FOUND) THEN
36751     RETURN -6;
36752   END IF;
36753
36754   DELETE FROM comment
36755   WHERE ((comment_source='J')
36756   AND (comment_source_id=pPrjid));
36757
36758   DELETE FROM comment
36759   WHERE ((comment_source='TA')
36760   AND (comment_source_id IN (
36761     SELECT prjtask_id
36762     FROM prjtask
36763     WHERE (prjtask_prj_id=pPrjId))));
36764
36765   DELETE FROM prjtask
36766    WHERE (prjtask_prj_id=pPrjid);
36767
36768   UPDATE prj
36769      SET prj_recurring_prj_id=null
36770    WHERE(prj_recurring_prj_id=pPrjid);
36771
36772   DELETE FROM prj
36773    WHERE (prj_id=pPrjid);
36774   RETURN pPrjid;
36775 END;
36776 $_$;
36777
36778
36779 ALTER FUNCTION public.deleteproject(integer) OWNER TO admin;
36780
36781 --
36782 -- TOC entry 1445 (class 1255 OID 146566013)
36783 -- Dependencies: 4536 8
36784 -- Name: deleteprojecttask(integer); Type: FUNCTION; Schema: public; Owner: admin
36785 --
36786
36787 CREATE FUNCTION deleteprojecttask(integer) RETURNS integer
36788     LANGUAGE plpgsql
36789     AS $_$
36790 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36791 -- See www.xtuple.com/CPAL for the full text of the software license.
36792 DECLARE
36793   pPrjtaskid ALIAS FOR $1;
36794   _row RECORD;
36795   _result INTEGER;
36796 BEGIN
36797
36798   SELECT * INTO _row
36799     FROM prjtask
36800    WHERE (prjtask_id=pPrjtaskid)
36801    LIMIT 1;
36802   IF (NOT FOUND) THEN
36803     RETURN -1;
36804   END IF;
36805
36806   IF (COALESCE(_row.prjtask_hours_actual, 0.0) > 0.0) THEN
36807     RETURN -2;
36808   END IF;
36809
36810   IF (COALESCE(_row.prjtask_exp_actual, 0.0) > 0.0) THEN
36811     RETURN -3;
36812   END IF;
36813
36814   DELETE FROM comment
36815   WHERE ((comment_source='TA')
36816   AND (comment_source_id=pPrjtaskid));
36817
36818   DELETE FROM prjtask
36819    WHERE (prjtask_id=pPrjtaskid);
36820
36821   RETURN 0;
36822
36823 END;
36824 $_$;
36825
36826
36827 ALTER FUNCTION public.deleteprojecttask(integer) OWNER TO admin;
36828
36829 --
36830 -- TOC entry 1446 (class 1255 OID 146566014)
36831 -- Dependencies: 4536 8
36832 -- Name: deleteqryhead(integer); Type: FUNCTION; Schema: public; Owner: admin
36833 --
36834
36835 CREATE FUNCTION deleteqryhead(integer) RETURNS integer
36836     LANGUAGE plpgsql
36837     AS $_$
36838 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36839 -- See www.xtuple.com/CPAL for the full text of the software license.
36840 DECLARE
36841   pqryheadid    ALIAS FOR $1;
36842
36843 BEGIN
36844   DELETE FROM qryitem WHERE (qryitem_qryhead_id=pqryheadid);
36845   DELETE FROM qryhead WHERE (qryhead_id=pqryheadid);
36846
36847   RETURN pqryheadid;
36848 END;
36849 $_$;
36850
36851
36852 ALTER FUNCTION public.deleteqryhead(integer) OWNER TO admin;
36853
36854 --
36855 -- TOC entry 1448 (class 1255 OID 146566016)
36856 -- Dependencies: 4536 8
36857 -- Name: deletequote(integer); Type: FUNCTION; Schema: public; Owner: admin
36858 --
36859
36860 CREATE FUNCTION deletequote(integer) RETURNS integer
36861     LANGUAGE plpgsql
36862     AS $_$
36863 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36864 -- See www.xtuple.com/CPAL for the full text of the software license.
36865 DECLARE
36866   pQuheadid ALIAS FOR $1;
36867 BEGIN
36868   RETURN deleteQuote(pQuheadid, NULL::TEXT);
36869 END;
36870 $_$;
36871
36872
36873 ALTER FUNCTION public.deletequote(integer) OWNER TO admin;
36874
36875 --
36876 -- TOC entry 1447 (class 1255 OID 146566015)
36877 -- Dependencies: 4536 8
36878 -- Name: deletequote(integer, text); Type: FUNCTION; Schema: public; Owner: admin
36879 --
36880
36881 CREATE FUNCTION deletequote(integer, text) RETURNS integer
36882     LANGUAGE plpgsql
36883     AS $_$
36884 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36885 -- See www.xtuple.com/CPAL for the full text of the software license.
36886 DECLARE
36887   pQuheadid     ALIAS FOR $1;
36888   pQuoteNumber  ALIAS FOR $2;
36889
36890   _quNumberScheme       TEXT;
36891   _quoteNumber          TEXT;
36892   _quitemid             INTEGER;
36893   _result               INTEGER;
36894
36895 BEGIN
36896
36897   SELECT fetchMetricText('QUNumberGeneration') INTO _quNumberScheme;
36898
36899   IF (pQuoteNumber IS NULL) THEN
36900     SELECT quhead_number INTO _quoteNumber
36901     FROM quhead
36902     WHERE (quhead_id=pQuheadid);
36903   ELSE
36904     _quoteNumber := pQuoteNumber;
36905   END IF;
36906
36907   PERFORM deleteQuoteItem(quitem_id)
36908   FROM quitem
36909   WHERE (quitem_quhead_id=pQuheadid);
36910
36911   DELETE FROM charass
36912   WHERE (charass_target_type='QU')
36913     AND (charass_target_id=pQuheadid);
36914
36915   DELETE FROM quhead
36916   WHERE (quhead_id=pQuheadid);
36917
36918   IF (_quoteNumber IS NOT NULL) THEN
36919     IF (_quNumberScheme IN ('A', 'O')) THEN
36920       -- do not release quote # if quote converted to sales order
36921       IF (NOT EXISTS (SELECT cohead_id
36922                       FROM cohead
36923                       WHERE (cohead_number=_quoteNumber))) THEN
36924         _result = releaseQuNumber(_quoteNumber);
36925       END IF;
36926     ELSEIF (_quNumberScheme = 'S') THEN
36927       _result = releaseSoNumber(_quoteNumber);
36928     END IF;
36929   END IF;
36930
36931   -- Don't care about result of release number
36932   RETURN 0;
36933
36934 END;
36935 $_$;
36936
36937
36938 ALTER FUNCTION public.deletequote(integer, text) OWNER TO admin;
36939
36940 --
36941 -- TOC entry 1449 (class 1255 OID 146566017)
36942 -- Dependencies: 4536 8
36943 -- Name: deletequote(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
36944 --
36945
36946 CREATE FUNCTION deletequote(integer, integer) RETURNS integer
36947     LANGUAGE plpgsql
36948     AS $_$
36949 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
36950 -- See www.xtuple.com/CPAL for the full text of the software license.
36951 DECLARE
36952   pQuheadid ALIAS FOR $1;
36953   pQuoteNumber  ALIAS FOR $2;
36954 BEGIN
36955   RETURN deleteQuote(pQuheadid, pQuoteNumber::TEXT);
36956 END;
36957 $_$;
36958
36959
36960 ALTER FUNCTION public.deletequote(integer, integer) OWNER TO admin;
36961
36962 --
36963 -- TOC entry 1450 (class 1255 OID 146566018)
36964 -- Dependencies: 4536 8
36965 -- Name: deletequoteitem(integer); Type: FUNCTION; Schema: public; Owner: admin
36966 --
36967
36968 CREATE FUNCTION deletequoteitem(integer) RETURNS integer
36969     LANGUAGE plpgsql
36970     AS $_$
36971 DECLARE
36972   pQuitemid ALIAS FOR $1;
36973
36974   _result               INTEGER;
36975
36976 BEGIN
36977
36978   DELETE FROM charass
36979   WHERE (charass_target_type='QI')
36980     AND (charass_target_id=pQuitemid);
36981
36982   DELETE FROM quitem
36983   WHERE (quitem_id=pQuitemid);
36984
36985   RETURN 0;
36986
36987 END;
36988 $_$;
36989
36990
36991 ALTER FUNCTION public.deletequoteitem(integer) OWNER TO admin;
36992
36993 --
36994 -- TOC entry 1451 (class 1255 OID 146566019)
36995 -- Dependencies: 4536 8
36996 -- Name: deleterecvfororder(text, integer); Type: FUNCTION; Schema: public; Owner: admin
36997 --
36998
36999 CREATE FUNCTION deleterecvfororder(text, integer) RETURNS integer
37000     LANGUAGE plpgsql
37001     AS $_$
37002 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37003 -- See www.xtuple.com/CPAL for the full text of the software license.
37004 DECLARE
37005   pordertype    ALIAS FOR $1;
37006   porderid      ALIAS FOR $2;
37007
37008 BEGIN
37009   DELETE FROM recv
37010   USING orderitem
37011   WHERE ((recv_orderitem_id=orderitem_id)
37012     AND  (recv_order_type=orderitem_orderhead_type)
37013     AND  (NOT recv_posted)
37014     AND  (orderitem_orderhead_id=porderid)
37015     AND  (orderitem_orderhead_type=pordertype));
37016
37017   RETURN 0;
37018
37019 END;
37020 $_$;
37021
37022
37023 ALTER FUNCTION public.deleterecvfororder(text, integer) OWNER TO admin;
37024
37025 --
37026 -- TOC entry 1452 (class 1255 OID 146566020)
37027 -- Dependencies: 4536 8
37028 -- Name: deletesalescategory(integer); Type: FUNCTION; Schema: public; Owner: admin
37029 --
37030
37031 CREATE FUNCTION deletesalescategory(integer) RETURNS integer
37032     LANGUAGE plpgsql
37033     AS $_$
37034 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37035 -- See www.xtuple.com/CPAL for the full text of the software license.
37036 DECLARE
37037   pSalescatid ALIAS FOR $1;
37038
37039 BEGIN
37040
37041   PERFORM invcitem_salescat_id
37042   FROM invchead, invcitem
37043   WHERE ( (invcitem_invchead_id=invchead_id)
37044    AND (NOT invchead_posted)
37045    AND (invcitem_salescat_id=pSalescatid) );
37046   IF (FOUND) THEN
37047     RETURN -1;
37048   END IF;
37049
37050   PERFORM invcitem_salescat_id
37051   FROM invchead, invcitem
37052   WHERE ( (invcitem_invchead_id=invchead_id)
37053    AND (invchead_posted)
37054    AND (invcitem_salescat_id=pSalescatid) );
37055   IF (FOUND) THEN
37056     RETURN -2;
37057   END IF;
37058
37059   PERFORM aropen_salescat_id
37060      FROM aropen
37061     WHERE (aropen_salescat_id=pSalescatid);
37062   IF (FOUND) THEN
37063     RETURN -3;
37064   END IF;
37065
37066   DELETE FROM salescat
37067   WHERE (salescat_id=pSalescatid);
37068
37069   RETURN 0;
37070
37071 END;
37072 $_$;
37073
37074
37075 ALTER FUNCTION public.deletesalescategory(integer) OWNER TO admin;
37076
37077 --
37078 -- TOC entry 1453 (class 1255 OID 146566021)
37079 -- Dependencies: 4536 8
37080 -- Name: deleteshippingcharge(integer); Type: FUNCTION; Schema: public; Owner: admin
37081 --
37082
37083 CREATE FUNCTION deleteshippingcharge(integer) RETURNS integer
37084     LANGUAGE plpgsql
37085     AS $_$
37086 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37087 -- See www.xtuple.com/CPAL for the full text of the software license.
37088 DECLARE
37089   pShipchrgid ALIAS FOR $1;
37090
37091 BEGIN
37092
37093   IF EXISTS(SELECT 1
37094               FROM custinfo
37095              WHERE (cust_shipchrg_id=pShipchrgid)) THEN
37096     RETURN -1;
37097   END IF;
37098
37099   DELETE FROM shipchrg
37100   WHERE (shipchrg_id=pShipchrgid);
37101
37102   RETURN pShipchrgid;
37103
37104 END;
37105 $_$;
37106
37107
37108 ALTER FUNCTION public.deleteshippingcharge(integer) OWNER TO admin;
37109
37110 --
37111 -- TOC entry 1455 (class 1255 OID 146566022)
37112 -- Dependencies: 4536 8
37113 -- Name: deleteshippingchargetype(integer); Type: FUNCTION; Schema: public; Owner: admin
37114 --
37115
37116 CREATE FUNCTION deleteshippingchargetype(integer) RETURNS integer
37117     LANGUAGE plpgsql
37118     AS $_$
37119 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37120 -- See www.xtuple.com/CPAL for the full text of the software license.
37121 DECLARE
37122   pShipchrgid ALIAS FOR $1;
37123   _check INTEGER;
37124
37125 BEGIN
37126
37127 --  Check to see if the passed shipchrg is used as a default for any customers
37128   SELECT cust_id INTO _check
37129   FROM custinfo
37130   WHERE (cust_shipchrg_id=pShipchrgid)
37131   LIMIT 1;
37132   IF (FOUND) THEN
37133     RETURN -1;
37134   END IF;
37135
37136 --  Check to see if the passed shipchrg is used as a default for any shiptos
37137   SELECT shipto_id INTO _check
37138   FROM shiptoinfo
37139   WHERE (shipto_shipchrg_id=pShipchrgid)
37140   LIMIT 1;
37141   IF (FOUND) THEN
37142     RETURN -2;
37143   END IF;
37144
37145 --  Check to see if the passed shipchrg is used on any sales orders
37146   SELECT cohead_id INTO _check
37147   FROM cohead
37148   WHERE (cohead_shipchrg_id=pShipchrgid)
37149   LIMIT 1;
37150   IF (FOUND) THEN
37151     RETURN -3;
37152   END IF;
37153
37154 --  Check to see if the passed shipchrg is used on any shippers
37155   SELECT shiphead_id INTO _check
37156   FROM shiphead
37157   WHERE (shiphead_shipchrg_id=pShipchrgid)
37158   LIMIT 1;
37159   IF (FOUND) THEN
37160     RETURN -4;
37161   END IF;
37162
37163 --  Check to see if the passed shipchrg is used on any invoices
37164   SELECT invchead_id INTO _check
37165   FROM invchead
37166   WHERE (invchead_shipchrg_id=pShipchrgid)
37167   LIMIT 1;
37168   IF (FOUND) THEN
37169     RETURN -5;
37170   END IF;
37171
37172 --  Delete the passed shipchrg
37173   DELETE FROM shipchrg
37174   WHERE (shipchrg_id=pShipchrgid);
37175
37176   RETURN pShipchrgid;
37177
37178 END;
37179 $_$;
37180
37181
37182 ALTER FUNCTION public.deleteshippingchargetype(integer) OWNER TO admin;
37183
37184 --
37185 -- TOC entry 1456 (class 1255 OID 146566023)
37186 -- Dependencies: 4536 8
37187 -- Name: deleteshipto(integer); Type: FUNCTION; Schema: public; Owner: admin
37188 --
37189
37190 CREATE FUNCTION deleteshipto(integer) RETURNS integer
37191     LANGUAGE plpgsql
37192     AS $_$
37193 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37194 -- See www.xtuple.com/CPAL for the full text of the software license.
37195 DECLARE
37196   pShiptoid ALIAS FOR $1;
37197
37198 BEGIN
37199
37200   PERFORM asohist_id
37201   FROM asohist
37202   WHERE (asohist_shipto_id=pShiptoid)
37203   LIMIT 1;
37204   IF (FOUND) THEN
37205     RETURN -1;
37206   END IF;
37207
37208   PERFORM cohead_id
37209   FROM cohead
37210   WHERE (cohead_shipto_id=pShiptoid)
37211   LIMIT 1;
37212   IF (FOUND) THEN
37213     RETURN -2;
37214   END IF;
37215
37216   PERFORM cmhead_id
37217   FROM cmhead
37218   WHERE (cmhead_shipto_id=pShiptoid)
37219   LIMIT 1;
37220   IF (FOUND) THEN
37221     RETURN -3;
37222   END IF;
37223
37224   PERFORM cohist_id
37225   FROM cohist
37226   WHERE (cohist_shipto_id=pShiptoid)
37227   LIMIT 1;
37228   IF (FOUND) THEN
37229     RETURN -4;
37230   END IF;
37231
37232   PERFORM quhead_id
37233   FROM quhead
37234   WHERE (quhead_shipto_id=pShiptoid)
37235   LIMIT 1;
37236   IF (FOUND) THEN
37237     RETURN -5;
37238   END IF;
37239
37240   PERFORM invchead_id
37241   FROM invchead
37242   WHERE (invchead_shipto_id=pShiptoid)
37243   LIMIT 1;
37244   IF (FOUND) THEN
37245     RETURN -6;
37246   END IF;
37247
37248   DELETE FROM ipsass
37249   WHERE (ipsass_shipto_id=pShiptoid);
37250
37251   DELETE FROM shiptoinfo
37252   WHERE (shipto_id=pShiptoid);
37253
37254   RETURN 0;
37255
37256 END;
37257 $_$;
37258
37259
37260 ALTER FUNCTION public.deleteshipto(integer) OWNER TO admin;
37261
37262 --
37263 -- TOC entry 1457 (class 1255 OID 146566024)
37264 -- Dependencies: 4536 8
37265 -- Name: deleteso(integer); Type: FUNCTION; Schema: public; Owner: admin
37266 --
37267
37268 CREATE FUNCTION deleteso(integer) RETURNS integer
37269     LANGUAGE plpgsql
37270     AS $_$
37271 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37272 -- See www.xtuple.com/CPAL for the full text of the software license.
37273 DECLARE
37274   pSoheadid    ALIAS FOR $1;
37275 BEGIN
37276   RETURN deleteSo(pSoheadid, NULL);
37277 END;
37278 $_$;
37279
37280
37281 ALTER FUNCTION public.deleteso(integer) OWNER TO admin;
37282
37283 --
37284 -- TOC entry 1458 (class 1255 OID 146566025)
37285 -- Dependencies: 4536 8
37286 -- Name: deleteso(integer, text); Type: FUNCTION; Schema: public; Owner: admin
37287 --
37288
37289 CREATE FUNCTION deleteso(integer, text) RETURNS integer
37290     LANGUAGE plpgsql
37291     AS $_$
37292 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37293 -- See www.xtuple.com/CPAL for the full text of the software license.
37294 DECLARE
37295   pSoheadid     ALIAS FOR $1;
37296   pSonumber     ALIAS FOR $2;
37297
37298   _r            RECORD;
37299   _coitemid     INTEGER;
37300   _result       INTEGER;
37301   _poStatus     INTEGER := 0;
37302
37303 BEGIN
37304 -- Get cohead
37305   SELECT * INTO _r FROM cohead WHERE (cohead_id=pSoheadid);
37306
37307    IF (NOT FOUND) THEN
37308      RETURN 0;
37309    END IF;
37310
37311 -- Cannot delete if credit card payments
37312   IF (EXISTS(SELECT ccpay_id
37313              FROM ccpay, payco
37314              WHERE ((ccpay_status IN ('C'))
37315                AND  (ccpay_id=payco_ccpay_id)
37316                AND  (payco_cohead_id=pSoheadid)))) THEN
37317     RETURN -1;
37318   END IF;
37319
37320 -- Cannot delete if credit card history
37321   IF (EXISTS(SELECT ccpay_id
37322              FROM ccpay, payco
37323              WHERE ((ccpay_status != 'C')
37324                AND  (ccpay_id=payco_ccpay_id)
37325                AND  (payco_cohead_id=pSoheadid)))) THEN
37326     RETURN -2;
37327   END IF;
37328
37329 -- Delete Sales Order Items
37330   FOR _coitemid IN
37331     SELECT coitem_id
37332     FROM coitem
37333     WHERE ( (coitem_cohead_id=pSoheadid)
37334       AND   (coitem_subnumber=0) ) LOOP
37335
37336     SELECT deleteSoItem(_coitemid) INTO _result;
37337     IF (_result < 0) THEN
37338       IF (_result = -20) THEN
37339         _poStatus := _poStatus - 1;
37340       ELSE
37341         RETURN _result;
37342       END IF;
37343     END IF;
37344
37345   END LOOP;
37346
37347   DELETE FROM pack
37348   WHERE (pack_head_id=pSoheadid and pack_head_type = 'SO');
37349
37350   DELETE FROM charass
37351   WHERE (charass_target_type='SO')
37352     AND (charass_target_id=pSoheadid);
37353
37354   DELETE FROM cohead
37355   WHERE (cohead_id=pSoheadid);
37356
37357   IF (fetchMetricBool('AutoCreateProjectsForOrders')) THEN
37358     PERFORM deleteProject(_r.cohead_prj_id);
37359   END IF;
37360
37361   DELETE FROM aropenalloc
37362   WHERE ((aropenalloc_doctype='S')
37363     AND  (aropenalloc_doc_id=pSoheadid));
37364
37365   IF ( (NOT _r.cohead_wasquote) AND (NOT _r.cohead_imported) ) THEN
37366     IF (COALESCE(pSonumber,'') != '') THEN
37367       _result = releaseSoNumber(pSonumber);
37368     ELSEIF (_r.cohead_number IS NOT NULL) THEN
37369       _result = releaseSoNumber(_r.cohead_number);
37370     END IF;
37371   END IF;
37372
37373   IF (_poStatus < 0) THEN
37374     RETURN -20;
37375   ELSE
37376     RETURN 0;
37377   END IF;
37378
37379 END;
37380 $_$;
37381
37382
37383 ALTER FUNCTION public.deleteso(integer, text) OWNER TO admin;
37384
37385 --
37386 -- TOC entry 1459 (class 1255 OID 146566026)
37387 -- Dependencies: 4536 8
37388 -- Name: deletesoitem(integer); Type: FUNCTION; Schema: public; Owner: admin
37389 --
37390
37391 CREATE FUNCTION deletesoitem(integer) RETURNS integer
37392     LANGUAGE plpgsql
37393     AS $_$
37394 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37395 -- See www.xtuple.com/CPAL for the full text of the software license.
37396 DECLARE
37397   pSoitemid     ALIAS FOR $1;
37398
37399   _r            RECORD;
37400   _s            RECORD;
37401   _result       INTEGER;
37402   _deletePO     INTEGER := 0;
37403   _recvId       INTEGER := -1;
37404   _poStatus     TEXT;
37405   _jobItem      BOOLEAN;
37406
37407 BEGIN
37408 -- Get coitem
37409    SELECT * INTO _r FROM coitem WHERE (coitem_id=pSoitemid);
37410
37411    IF (NOT FOUND) THEN
37412      RETURN -999;
37413    END IF;
37414
37415 -- Cannot delete if shipped
37416   IF (_r.coitem_qtyshipped > 0) THEN
37417     RETURN -101;
37418   END IF;
37419
37420 -- Cannot delete if issued to shipping
37421   SELECT shipitem_id INTO _result
37422   FROM shipitem JOIN shiphead ON (shiphead_id=shipitem_shiphead_id AND shiphead_order_type='SO')
37423   WHERE (shipitem_orderitem_id=pSoitemid)
37424   LIMIT 1;
37425   IF (FOUND) THEN
37426     RETURN -102;
37427   END IF;
37428
37429 -- Cannot delete if returned
37430   IF (fetchMetricBool('MultiWhs')) THEN
37431     SELECT raitem_id INTO _result
37432     FROM raitem
37433     WHERE ( (raitem_orig_coitem_id=pSoitemid)
37434        OR   (raitem_new_coitem_id=pSoitemid) )
37435     LIMIT 1;
37436     IF (FOUND) THEN
37437       RETURN -103;
37438     END IF;
37439   END IF;
37440
37441 -- Cannot delete if any inventory history
37442   SELECT invhist_id INTO _result
37443   FROM invhist
37444   WHERE ( (invhist_ordnumber=formatSoNumber(pSoitemid))
37445     AND   (invhist_ordtype='SO') )
37446   LIMIT 1;
37447   IF (FOUND) THEN
37448     RETURN -105;
37449   END IF;
37450
37451 -- If Kit, check deletion of component items
37452   IF (_r.coitem_subnumber = 0) THEN
37453     FOR _s IN
37454       SELECT *
37455       FROM coitem
37456       WHERE ((coitem_cohead_id = _r.coitem_cohead_id)
37457         AND  (coitem_linenumber = _r.coitem_linenumber)
37458         AND  (coitem_subnumber > 0))
37459     LOOP
37460       IF ((COALESCE(_s.coitem_order_id, -1) > 0)
37461        AND (_s.coitem_order_type = 'P')) THEN
37462         SELECT poitem_status, COALESCE(recv_id, -1)
37463           INTO _poStatus, _recvId
37464         FROM poitem LEFT OUTER JOIN recv
37465                ON ((recv_orderitem_id=poitem_id)
37466                  AND (recv_order_type='PO'))
37467         WHERE (poitem_id = _s.coitem_order_id);
37468
37469         IF ((_recvId > 0) OR (_poStatus = 'C')) THEN
37470           RETURN -10;
37471         ELSIF ((_recvId = -1) AND (_poStatus = 'O')) THEN
37472           _deletePO := _deletePO - 1;
37473         END IF;
37474       END IF;
37475     END LOOP;
37476   END IF;
37477
37478
37479   SELECT (itemsite_costmethod='J') INTO _jobItem
37480   FROM coitem JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
37481   WHERE (coitem_id=pSoitemid);
37482
37483   IF (_jobItem AND _r.coitem_order_type='W') THEN
37484 -- Delete associated Job Work Order
37485     SELECT deleteWo(_r.coitem_order_id, TRUE, TRUE) INTO _result;
37486     IF (_result < 0) THEN
37487       RETURN -104;
37488     END IF;
37489   ELSIF (_r.coitem_order_type='W') THEN
37490 -- Delete associated Job Work Order
37491     SELECT deleteWo(_r.coitem_order_id, TRUE) INTO _result;
37492     IF (_result < 0) THEN
37493       -- Cannot delete so break association
37494       PERFORM changeWoProject(_r.coitem_order_id, -1, TRUE);
37495     END IF;
37496   ELSIF (_r.coitem_order_type='R') THEN
37497 -- Delete associated Purchase Request
37498     PERFORM deletePr(_r.coitem_order_id);
37499   ELSIF (_r.coitem_order_type='P') THEN
37500 -- Delete associated Purchase Order Item
37501     SELECT deletepoitem(_r.coitem_order_id) INTO _result;
37502     IF ((_result < 0) AND (_result <> -20)) THEN
37503       RETURN _result;
37504     ELSIF (_result = -20) THEN
37505       _deletePO := _deletePO - 1;
37506     END IF;
37507   END IF;
37508
37509 -- Delete characteristic assignments
37510   DELETE FROM charass
37511   WHERE (charass_target_type='SI')
37512     AND (charass_target_id=pSoitemid);
37513
37514 -- Delete reservations
37515   IF (fetchMetricBool('EnableSOReservationsByLocation')) THEN
37516     DELETE FROM reserve
37517     WHERE (reserve_demand_type='SO')
37518       AND (reserve_demand_id=pSoitemid);
37519   END IF;
37520
37521 -- Delete the coitem
37522   DELETE FROM coitem
37523   WHERE (coitem_id=pSoitemid);
37524
37525   IF (_deletePO < 0) THEN
37526     RETURN -20;
37527   ELSE
37528     RETURN 0;
37529   END IF;
37530
37531 END;
37532 $_$;
37533
37534
37535 ALTER FUNCTION public.deletesoitem(integer) OWNER TO admin;
37536
37537 --
37538 -- TOC entry 1460 (class 1255 OID 146566027)
37539 -- Dependencies: 4536 8
37540 -- Name: deletestandardjournal(integer); Type: FUNCTION; Schema: public; Owner: admin
37541 --
37542
37543 CREATE FUNCTION deletestandardjournal(integer) RETURNS integer
37544     LANGUAGE plpgsql
37545     AS $_$
37546 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37547 -- See www.xtuple.com/CPAL for the full text of the software license.
37548 DECLARE
37549   pStdjrnlid ALIAS FOR $1;
37550
37551 BEGIN
37552
37553   DELETE FROM stdjrnlitem
37554   WHERE (stdjrnlitem_stdjrnl_id=pStdjrnlid);
37555
37556   DELETE FROM stdjrnlgrpitem
37557   WHERE (stdjrnlgrpitem_stdjrnl_id=pStdjrnlid);
37558
37559   DELETE FROM stdjrnl
37560   WHERE (stdjrnl_id=pStdjrnlid);
37561
37562   RETURN 1;
37563
37564 END;
37565 $_$;
37566
37567
37568 ALTER FUNCTION public.deletestandardjournal(integer) OWNER TO admin;
37569
37570 --
37571 -- TOC entry 1461 (class 1255 OID 146566028)
37572 -- Dependencies: 4536 8
37573 -- Name: deletestandardjournalgroup(integer); Type: FUNCTION; Schema: public; Owner: admin
37574 --
37575
37576 CREATE FUNCTION deletestandardjournalgroup(integer) RETURNS integer
37577     LANGUAGE plpgsql
37578     AS $_$
37579 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37580 -- See www.xtuple.com/CPAL for the full text of the software license.
37581 DECLARE
37582   pStdjrnlgrpid ALIAS FOR $1;
37583
37584 BEGIN
37585
37586   DELETE FROM stdjrnlgrpitem
37587   WHERE (stdjrnlgrpitem_stdjrnlgrp_id=pStdjrnlgrpid);
37588
37589   DELETE FROM stdjrnlgrp
37590   WHERE (stdjrnlgrp_id=pStdjrnlgrpid);
37591
37592   RETURN 1;
37593
37594 END;
37595 $_$;
37596
37597
37598 ALTER FUNCTION public.deletestandardjournalgroup(integer) OWNER TO admin;
37599
37600 --
37601 -- TOC entry 1462 (class 1255 OID 146566029)
37602 -- Dependencies: 4536 8
37603 -- Name: deletesubaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
37604 --
37605
37606 CREATE FUNCTION deletesubaccount(integer) RETURNS integer
37607     LANGUAGE plpgsql
37608     AS $_$
37609 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37610 -- See www.xtuple.com/CPAL for the full text of the software license.
37611 DECLARE
37612   pid ALIAS FOR $1;
37613
37614 BEGIN
37615   IF (EXISTS(SELECT accnt_id
37616              FROM accnt, subaccnt
37617              WHERE ((accnt_company=subaccnt_number)
37618                AND  (subaccnt_id=pid))
37619             )) THEN
37620     RETURN -1;
37621   END IF;
37622
37623   DELETE FROM subaccnt
37624   WHERE (subaccnt_id=pid);
37625
37626   RETURN pid;
37627
37628 END;
37629 $_$;
37630
37631
37632 ALTER FUNCTION public.deletesubaccount(integer) OWNER TO admin;
37633
37634 --
37635 -- TOC entry 1433 (class 1255 OID 146566030)
37636 -- Dependencies: 4536 8
37637 -- Name: deletesubaccounttype(integer); Type: FUNCTION; Schema: public; Owner: admin
37638 --
37639
37640 CREATE FUNCTION deletesubaccounttype(integer) RETURNS integer
37641     LANGUAGE plpgsql
37642     AS $_$
37643 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37644 -- See www.xtuple.com/CPAL for the full text of the software license.
37645 DECLARE
37646   pSubAccntTypeid ALIAS FOR $1;
37647   _check INTEGER;
37648
37649 BEGIN
37650
37651 --  Check to see if the passed subaccnttype is used in any accounts
37652   SELECT accnt_id INTO _check
37653   FROM accnt, subaccnttype
37654   WHERE ( (accnt_subaccnttype_code=subaccnttype_code)
37655    AND (subaccnttype_id=pSubAccntTypeid) )
37656   LIMIT 1;
37657   IF (FOUND) THEN
37658     RETURN -1;
37659   END IF;
37660
37661 --  Delete the Sub Account Type
37662   DELETE FROM subaccnttype
37663   WHERE (subaccnttype_id=pSubAccntTypeid);
37664
37665   RETURN 0;
37666
37667 END;
37668 $_$;
37669
37670
37671 ALTER FUNCTION public.deletesubaccounttype(integer) OWNER TO admin;
37672
37673 --
37674 -- TOC entry 1464 (class 1255 OID 146566031)
37675 -- Dependencies: 4536 8
37676 -- Name: deletetax(integer); Type: FUNCTION; Schema: public; Owner: admin
37677 --
37678
37679 CREATE FUNCTION deletetax(integer) RETURNS integer
37680     LANGUAGE plpgsql
37681     AS $_$
37682 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37683 -- See www.xtuple.com/CPAL for the full text of the software license.
37684 DECLARE
37685   ptaxid        ALIAS FOR $1;
37686 BEGIN
37687   -- these checks allow nice error reporting instead of throwing an SQL error
37688   IF EXISTS(SELECT taxass_id FROM taxass WHERE (taxass_tax_id=ptaxid)) THEN
37689     RETURN -10;
37690   END IF;
37691   IF EXISTS(SELECT taxhist_id FROM taxhist WHERE (taxhist_tax_id=ptaxid)) THEN
37692     RETURN -20;
37693   END IF;
37694
37695   DELETE FROM taxrate WHERE (taxrate_tax_id = ptaxid);
37696   DELETE FROM tax WHERE (tax_id = ptaxid);
37697
37698   RETURN ptaxid;
37699
37700 END;
37701 $_$;
37702
37703
37704 ALTER FUNCTION public.deletetax(integer) OWNER TO admin;
37705
37706 --
37707 -- TOC entry 1465 (class 1255 OID 146566032)
37708 -- Dependencies: 4536 8
37709 -- Name: deletetaxclass(integer); Type: FUNCTION; Schema: public; Owner: admin
37710 --
37711
37712 CREATE FUNCTION deletetaxclass(integer) RETURNS integer
37713     LANGUAGE plpgsql
37714     AS $_$
37715 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37716 -- See www.xtuple.com/CPAL for the full text of the software license.
37717 DECLARE
37718 pTaxclassid ALIAS FOR $1;
37719 _result INTEGER;
37720
37721 BEGIN
37722
37723 -- Check to find if the tax class is used in any tax code
37724 SELECT tax_id INTO _result
37725 FROM tax
37726 WHERE (tax_taxclass_id = pTaxclassid);
37727 IF (FOUND) THEN
37728    RETURN -1;
37729 END IF;
37730
37731 -- Delete the tax class if the above condition doesn't match
37732 DELETE FROM taxclass WHERE taxclass_id = pTaxclassid ;
37733
37734 RETURN pTaxclassid;
37735
37736 END;
37737 $_$;
37738
37739
37740 ALTER FUNCTION public.deletetaxclass(integer) OWNER TO admin;
37741
37742 --
37743 -- TOC entry 1466 (class 1255 OID 146566033)
37744 -- Dependencies: 4536 8
37745 -- Name: deletetaxtype(integer); Type: FUNCTION; Schema: public; Owner: admin
37746 --
37747
37748 CREATE FUNCTION deletetaxtype(integer) RETURNS integer
37749     LANGUAGE plpgsql
37750     AS $_$
37751 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37752 -- See www.xtuple.com/CPAL for the full text of the software license.
37753 DECLARE
37754   pTaxtypeid ALIAS FOR $1;
37755   _result INTEGER;
37756 BEGIN
37757
37758   SELECT taxtype_id
37759     INTO _result
37760     FROM taxtype
37761    WHERE ((taxtype_sys)
37762      AND  (taxtype_id=pTaxtypeid));
37763   IF (FOUND) THEN
37764     RETURN -1;
37765   END IF;
37766
37767   SELECT taxass_id
37768     INTO _result
37769     FROM taxass
37770    WHERE (taxass_taxtype_id=pTaxtypeid);
37771   IF (FOUND) THEN
37772     RETURN -2;
37773   END IF;
37774
37775   SELECT taxhist_id
37776     INTO _result
37777     FROM taxhist
37778    WHERE (taxhist_taxtype_id=pTaxtypeid);
37779   IF (FOUND) THEN
37780     RETURN -3;
37781   END IF;
37782
37783   DELETE
37784     FROM taxtype
37785    WHERE (taxtype_id=pTaxtypeid);
37786
37787   RETURN pTaxtypeid;
37788
37789 END;
37790 $_$;
37791
37792
37793 ALTER FUNCTION public.deletetaxtype(integer) OWNER TO admin;
37794
37795 --
37796 -- TOC entry 1467 (class 1255 OID 146566034)
37797 -- Dependencies: 4536 8
37798 -- Name: deletetaxzone(integer); Type: FUNCTION; Schema: public; Owner: admin
37799 --
37800
37801 CREATE FUNCTION deletetaxzone(integer) RETURNS integer
37802     LANGUAGE plpgsql
37803     AS $_$
37804 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37805 -- See www.xtuple.com/CPAL for the full text of the software license.
37806 DECLARE
37807 pTaxzoneid ALIAS FOR $1;
37808 _result INTEGER;
37809
37810 BEGIN
37811
37812 -- Check to find if the tax zone is used in any tax assignment
37813 SELECT taxass_id INTO _result
37814 FROM taxass
37815 WHERE (taxass_taxzone_id=pTaxzoneid);
37816 IF (FOUND) THEN
37817    RETURN -1;
37818 END IF;
37819
37820 -- Check to find if the tax zone has been referenced in any tax registration
37821 SELECT taxreg_id INTO _result 
37822 FROM taxreg
37823 WHERE (taxreg_taxzone_id=pTaxzoneid);
37824 IF (FOUND) THEN
37825    RETURN -2;
37826 END IF;
37827
37828 -- Delete the tax zone if none of the above conditions match
37829 DELETE FROM taxzone WHERE taxzone_id = pTaxzoneid ;
37830
37831 RETURN pTaxzoneid;
37832
37833 END;
37834 $_$;
37835
37836
37837 ALTER FUNCTION public.deletetaxzone(integer) OWNER TO admin;
37838
37839 --
37840 -- TOC entry 1468 (class 1255 OID 146566035)
37841 -- Dependencies: 4536 8
37842 -- Name: deletetodoitem(integer); Type: FUNCTION; Schema: public; Owner: admin
37843 --
37844
37845 CREATE FUNCTION deletetodoitem(integer) RETURNS integer
37846     LANGUAGE plpgsql
37847     AS $_$
37848 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37849 -- See www.xtuple.com/CPAL for the full text of the software license.
37850 DECLARE
37851   ptodoItemId ALIAS FOR $1;
37852 BEGIN
37853   DELETE FROM alarm WHERE ( (alarm_source='TODO') AND (alarm_source_id=ptodoItemId) );
37854   DELETE FROM todoitem WHERE todoitem_id = ptodoItemId;
37855   RETURN 0;
37856 END;
37857 $_$;
37858
37859
37860 ALTER FUNCTION public.deletetodoitem(integer) OWNER TO admin;
37861
37862 --
37863 -- TOC entry 1469 (class 1255 OID 146566036)
37864 -- Dependencies: 4536 8
37865 -- Name: deleteunusedclasscodes(); Type: FUNCTION; Schema: public; Owner: admin
37866 --
37867
37868 CREATE FUNCTION deleteunusedclasscodes() RETURNS integer
37869     LANGUAGE plpgsql
37870     AS $$
37871 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37872 -- See www.xtuple.com/CPAL for the full text of the software license.
37873 BEGIN
37874
37875   DELETE FROM classcode
37876   WHERE (classcode_id NOT IN (SELECT DISTINCT item_classcode_id FROM item));
37877
37878   RETURN 0;
37879
37880 END;
37881 $$;
37882
37883
37884 ALTER FUNCTION public.deleteunusedclasscodes() OWNER TO admin;
37885
37886 --
37887 -- TOC entry 1470 (class 1255 OID 146566037)
37888 -- Dependencies: 4536 8
37889 -- Name: deleteunusedfreightclasses(); Type: FUNCTION; Schema: public; Owner: admin
37890 --
37891
37892 CREATE FUNCTION deleteunusedfreightclasses() RETURNS integer
37893     LANGUAGE plpgsql
37894     AS $$
37895 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37896 -- See www.xtuple.com/CPAL for the full text of the software license.
37897 BEGIN
37898
37899   DELETE FROM freightclass
37900   WHERE (freightclass_id NOT IN (SELECT DISTINCT COALESCE(item_freightclass_id, 0) FROM item));
37901
37902   RETURN 0;
37903
37904 END;
37905 $$;
37906
37907
37908 ALTER FUNCTION public.deleteunusedfreightclasses() OWNER TO admin;
37909
37910 --
37911 -- TOC entry 1471 (class 1255 OID 146566038)
37912 -- Dependencies: 4536 8
37913 -- Name: deleteunusedproductcategories(); Type: FUNCTION; Schema: public; Owner: admin
37914 --
37915
37916 CREATE FUNCTION deleteunusedproductcategories() RETURNS integer
37917     LANGUAGE plpgsql
37918     AS $$
37919 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37920 -- See www.xtuple.com/CPAL for the full text of the software license.
37921 BEGIN
37922
37923 --  Delete any associated records
37924   DELETE FROM salesaccnt
37925   WHERE ( (salesaccnt_prodcat_id <> -1)
37926    AND (salesaccnt_prodcat_id NOT IN (SELECT DISTINCT item_prodcat_id FROM item)) );
37927
37928   DELETE FROM prodcat
37929   WHERE (prodcat_id NOT IN (SELECT DISTINCT item_prodcat_id FROM item));
37930
37931   RETURN 0;
37932
37933 END;
37934 $$;
37935
37936
37937 ALTER FUNCTION public.deleteunusedproductcategories() OWNER TO admin;
37938
37939 --
37940 -- TOC entry 1472 (class 1255 OID 146566039)
37941 -- Dependencies: 4536 8
37942 -- Name: deleteuom(integer); Type: FUNCTION; Schema: public; Owner: admin
37943 --
37944
37945 CREATE FUNCTION deleteuom(integer) RETURNS integer
37946     LANGUAGE plpgsql
37947     AS $_$
37948 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37949 -- See www.xtuple.com/CPAL for the full text of the software license.
37950 DECLARE
37951   pUomid ALIAS FOR $1;
37952
37953 BEGIN
37954
37955   DELETE FROM uomconv WHERE uomconv_from_uom_id=pUomid;
37956   DELETE FROM uomconv WHERE uomconv_to_uom_id=pUomid;
37957   DELETE FROM uom WHERE uom_id=pUomid;
37958
37959   RETURN 0;
37960 END;
37961 $_$;
37962
37963
37964 ALTER FUNCTION public.deleteuom(integer) OWNER TO admin;
37965
37966 --
37967 -- TOC entry 1473 (class 1255 OID 146566040)
37968 -- Dependencies: 4536 8
37969 -- Name: deleteuomconv(integer); Type: FUNCTION; Schema: public; Owner: admin
37970 --
37971
37972 CREATE FUNCTION deleteuomconv(integer) RETURNS integer
37973     LANGUAGE plpgsql
37974     AS $_$
37975 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
37976 -- See www.xtuple.com/CPAL for the full text of the software license.
37977 DECLARE
37978   pUomconvid ALIAS FOR $1;
37979
37980 BEGIN
37981   DELETE FROM uomconv WHERE uomconv_id=pUomconvid;
37982
37983   RETURN 0;
37984 END;
37985 $_$;
37986
37987
37988 ALTER FUNCTION public.deleteuomconv(integer) OWNER TO admin;
37989
37990 --
37991 -- TOC entry 1474 (class 1255 OID 146566041)
37992 -- Dependencies: 4536 8
37993 -- Name: deleteurl(integer); Type: FUNCTION; Schema: public; Owner: admin
37994 --
37995
37996 CREATE FUNCTION deleteurl(integer) RETURNS boolean
37997     LANGUAGE plpgsql
37998     AS $_$
37999 declare
38000   pId ALIAS FOR $1;
38001 begin
38002   delete from urlinfo
38003   where ( url_id in (
38004     select url_id
38005     from urlinfo
38006       join docass on (docass_target_id=url_id)
38007                  and (docass_target_type='URL')
38008       where ( docass_id = pId ) ) );
38009
38010   delete from docass where docass_id = pId;
38011
38012   return true;
38013 end;
38014 $_$;
38015
38016
38017 ALTER FUNCTION public.deleteurl(integer) OWNER TO admin;
38018
38019 --
38020 -- TOC entry 1475 (class 1255 OID 146566042)
38021 -- Dependencies: 4536 8
38022 -- Name: deleteuserpreference(text); Type: FUNCTION; Schema: public; Owner: admin
38023 --
38024
38025 CREATE FUNCTION deleteuserpreference(text) RETURNS boolean
38026     LANGUAGE plpgsql
38027     AS $_$
38028 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38029 -- See www.xtuple.com/CPAL for the full text of the software license.
38030 DECLARE
38031   pPrefname ALIAS FOR $1;
38032   _return BOOLEAN;
38033
38034 BEGIN
38035
38036   SELECT deleteUserPreference(getEffectiveXtUser(), pPrefname) INTO _return;
38037
38038   RETURN _return;
38039
38040 END;
38041 $_$;
38042
38043
38044 ALTER FUNCTION public.deleteuserpreference(text) OWNER TO admin;
38045
38046 --
38047 -- TOC entry 1476 (class 1255 OID 146566043)
38048 -- Dependencies: 4536 8
38049 -- Name: deleteuserpreference(text, text); Type: FUNCTION; Schema: public; Owner: admin
38050 --
38051
38052 CREATE FUNCTION deleteuserpreference(text, text) RETURNS boolean
38053     LANGUAGE plpgsql
38054     AS $_$
38055 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38056 -- See www.xtuple.com/CPAL for the full text of the software license.
38057 DECLARE
38058   pUsername ALIAS FOR $1;
38059   pPrefname ALIAS FOR $2;
38060
38061 BEGIN
38062
38063   DELETE FROM usrpref
38064   WHERE ( (usrpref_username=pUsername)
38065    AND (usrpref_name=pPrefname) );
38066
38067   RETURN TRUE;
38068
38069 END;
38070 $_$;
38071
38072
38073 ALTER FUNCTION public.deleteuserpreference(text, text) OWNER TO admin;
38074
38075 --
38076 -- TOC entry 1479 (class 1255 OID 146566044)
38077 -- Dependencies: 4536 8
38078 -- Name: deletevendoraddress(integer); Type: FUNCTION; Schema: public; Owner: admin
38079 --
38080
38081 CREATE FUNCTION deletevendoraddress(integer) RETURNS integer
38082     LANGUAGE plpgsql
38083     AS $_$
38084 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38085 -- See www.xtuple.com/CPAL for the full text of the software license.
38086 DECLARE
38087   pVendaddrid ALIAS FOR $1;
38088   _test INTEGER;
38089
38090 BEGIN
38091
38092 --  Check to see if the passed vendor address is used in pohead
38093   SELECT pohead_id INTO _test
38094   FROM pohead
38095   WHERE (pohead_vendaddr_id=pVendaddrid)
38096   LIMIT 1;
38097   IF (FOUND) THEN
38098     RETURN -1;
38099   END IF;
38100
38101 --  Delete the passed vendor address
38102   DELETE FROM vendaddrinfo
38103   WHERE (vendaddr_id=pVendaddrid);
38104
38105   RETURN 0;
38106
38107 END;
38108 $_$;
38109
38110
38111 ALTER FUNCTION public.deletevendoraddress(integer) OWNER TO admin;
38112
38113 --
38114 -- TOC entry 1480 (class 1255 OID 146566045)
38115 -- Dependencies: 4536 8
38116 -- Name: deletevendortype(integer); Type: FUNCTION; Schema: public; Owner: admin
38117 --
38118
38119 CREATE FUNCTION deletevendortype(integer) RETURNS integer
38120     LANGUAGE plpgsql
38121     AS $_$
38122 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38123 -- See www.xtuple.com/CPAL for the full text of the software license.
38124 DECLARE
38125   pVendtypeid ALIAS FOR $1;
38126   _test INTEGER;
38127
38128 BEGIN
38129
38130 --  Check to see if the passed vendor type is used in vendinfo
38131   SELECT vend_id INTO _test
38132   FROM vendinfo
38133   WHERE (vend_vendtype_id=pVendtypeid)
38134   LIMIT 1;
38135   IF (FOUND) THEN
38136     RETURN -1;
38137   END IF;
38138
38139 --  Delete the passed vendor type
38140   DELETE FROM vendtype
38141   WHERE (vendtype_id=pVendtypeid);
38142
38143   RETURN 0;
38144
38145 END;
38146 $_$;
38147
38148
38149 ALTER FUNCTION public.deletevendortype(integer) OWNER TO admin;
38150
38151 --
38152 -- TOC entry 1481 (class 1255 OID 146566046)
38153 -- Dependencies: 4536 8
38154 -- Name: deletewo(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
38155 --
38156
38157 CREATE FUNCTION deletewo(integer, boolean) RETURNS integer
38158     LANGUAGE plpgsql
38159     AS $_$
38160 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38161 -- See www.xtuple.com/CPAL for the full text of the software license.
38162 DECLARE
38163   pWoid ALIAS FOR $1;
38164   deleteChildren ALIAS FOR $2;
38165
38166 BEGIN
38167   RETURN deleteWo(pWoid, deleteChildren, FALSE);
38168 END;
38169 $_$;
38170
38171
38172 ALTER FUNCTION public.deletewo(integer, boolean) OWNER TO admin;
38173
38174 --
38175 -- TOC entry 1482 (class 1255 OID 146566047)
38176 -- Dependencies: 4536 8
38177 -- Name: deletewo(integer, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
38178 --
38179
38180 CREATE FUNCTION deletewo(integer, boolean, boolean) RETURNS integer
38181     LANGUAGE plpgsql
38182     AS $_$
38183 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38184 -- See www.xtuple.com/CPAL for the full text of the software license.
38185 DECLARE
38186   pWoid ALIAS FOR $1;
38187   deleteChildren ALIAS FOR $2;
38188   deleteForce ALIAS FOR $3;
38189   woStatus CHAR(1);
38190   itemType CHAR(1);
38191   ordtype CHAR(1);
38192   ordid INTEGER;
38193   returnCode INTEGER;
38194   _wotcCnt      INTEGER;
38195   _routings BOOLEAN;
38196
38197 BEGIN
38198   SELECT wo_status, wo_ordtype, wo_ordid, item_type
38199   INTO   woStatus, ordtype, ordid, itemType
38200   FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
38201           JOIN item ON (item_id=itemsite_item_id)
38202   WHERE (wo_id=pWoid);
38203
38204   IF (NOT woStatus IN ('O', 'E', 'C')) THEN
38205     RETURN -3;
38206   END IF;
38207
38208   IF (NOT deleteForce) THEN
38209     IF (itemType = 'J') THEN
38210       RETURN -2;
38211     END IF;
38212   END IF;
38213
38214   SELECT fetchMetricBool('Routings') INTO _routings;
38215
38216   IF _routings THEN
38217     SELECT count(*) INTO _wotcCnt
38218     FROM xtmfg.wotc
38219     WHERE (wotc_wo_id=pWoid);
38220     IF (_wotcCnt > 0) THEN
38221       RETURN -1;
38222     END IF;
38223   END IF;
38224
38225   IF (woStatus = 'R') THEN
38226     PERFORM postEvent('RWoRequestCancel', 'W', wo_id,
38227                       itemsite_warehous_id, formatWoNumber(wo_id),
38228                       NULL, NULL, NULL, NULL)
38229     FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
38230             JOIN item ON (item_id=itemsite_item_id)
38231     WHERE (wo_id=pWoid);
38232
38233      RETURN 0;
38234   ELSE
38235     IF (woStatus = 'E') THEN
38236       returnCode := (SELECT implodeWo(pWoid, FALSE));
38237     END IF;
38238   END IF;
38239
38240   IF (woStatus IN ('O', 'E', 'C')) THEN
38241     DELETE FROM womatl
38242     WHERE (womatl_wo_id=pWoid);
38243
38244     IF _routings THEN
38245       DELETE FROM xtmfg.wooper
38246       WHERE (wooper_wo_id=pWoid);
38247     END IF;
38248
38249     IF (ordtype = 'S') THEN
38250       UPDATE coitem SET coitem_order_type=NULL, coitem_order_id=NULL
38251       WHERE coitem_id=ordid;
38252     END IF;
38253
38254     DELETE FROM wo
38255     WHERE (wo_id=pWoid);
38256   END IF;
38257
38258   IF (deleteChildren) THEN
38259     returnCode := (SELECT MAX(deleteWo(wo_id, TRUE))
38260                    FROM wo
38261                    WHERE ((wo_ordtype='W')
38262                     AND (wo_ordid=pWoid)));
38263   END IF;
38264
38265   RETURN 0;
38266 END;
38267 $_$;
38268
38269
38270 ALTER FUNCTION public.deletewo(integer, boolean, boolean) OWNER TO admin;
38271
38272 --
38273 -- TOC entry 1483 (class 1255 OID 146566048)
38274 -- Dependencies: 4536 8
38275 -- Name: deletewomaterial(integer); Type: FUNCTION; Schema: public; Owner: admin
38276 --
38277
38278 CREATE FUNCTION deletewomaterial(integer) RETURNS integer
38279     LANGUAGE plpgsql
38280     AS $_$
38281 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38282 -- See www.xtuple.com/CPAL for the full text of the software license.
38283 DECLARE
38284   pWomatlid ALIAS FOR $1;
38285
38286 BEGIN
38287
38288   UPDATE wo
38289   SET wo_adhoc=TRUE
38290   FROM womatl
38291   WHERE ((womatl_wo_id=wo_id)
38292    AND (womatl_id=pWomatlid));
38293
38294 --  Delete any created P/R for this Womatl
38295   PERFORM deletePr('W', pWomatlid);
38296
38297   DELETE FROM womatl
38298   WHERE (womatl_id=pWomatlid);
38299
38300   RETURN 0;
38301 END;
38302 $_$;
38303
38304
38305 ALTER FUNCTION public.deletewomaterial(integer) OWNER TO admin;
38306
38307 --
38308 -- TOC entry 1484 (class 1255 OID 146566049)
38309 -- Dependencies: 4536 8
38310 -- Name: detachccpayfromso(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
38311 --
38312
38313 CREATE FUNCTION detachccpayfromso(integer, integer, integer) RETURNS integer
38314     LANGUAGE plpgsql
38315     AS $_$
38316 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38317 -- See www.xtuple.com/CPAL for the full text of the software license.
38318 DECLARE
38319   pcoheadid             ALIAS FOR $1;
38320   pwarehousid           ALIAS FOR $2;
38321   pcustid               ALIAS FOR $3;
38322
38323 BEGIN
38324   RAISE NOTICE 'detachCCPayFromSO(INTEGER, INTEGER, INTEGER): deprecated';
38325   RETURN 0;
38326 END;
38327 $_$;
38328
38329
38330 ALTER FUNCTION public.detachccpayfromso(integer, integer, integer) OWNER TO admin;
38331
38332 --
38333 -- TOC entry 1485 (class 1255 OID 146566050)
38334 -- Dependencies: 4536 8
38335 -- Name: detachcontact(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
38336 --
38337
38338 CREATE FUNCTION detachcontact(integer, integer) RETURNS integer
38339     LANGUAGE plpgsql
38340     AS $_$
38341 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38342 -- See www.xtuple.com/CPAL for the full text of the software license.
38343 DECLARE
38344   pcntctId    ALIAS FOR $1;
38345   pcrmacctId  ALIAS FOR $2;
38346 BEGIN
38347   UPDATE cntct SET cntct_crmacct_id = NULL
38348   WHERE cntct_id = pcntctId
38349     AND cntct_crmacct_id = pcrmacctId;
38350
38351   UPDATE crmacct SET crmacct_cntct_id_1 = NULL
38352   WHERE crmacct_id = pcrmacctId
38353     AND crmacct_cntct_id_1 = pcntctId;
38354
38355   UPDATE crmacct SET crmacct_cntct_id_2 = NULL
38356   WHERE crmacct_id = pcrmacctId
38357     AND crmacct_cntct_id_2 = pcntctId;
38358
38359   RETURN 0;
38360 END;
38361 $_$;
38362
38363
38364 ALTER FUNCTION public.detachcontact(integer, integer) OWNER TO admin;
38365
38366 --
38367 -- TOC entry 1486 (class 1255 OID 146566051)
38368 -- Dependencies: 4536 8
38369 -- Name: detag(text); Type: FUNCTION; Schema: public; Owner: admin
38370 --
38371
38372 CREATE FUNCTION detag(text) RETURNS text
38373     LANGUAGE plpgsql IMMUTABLE
38374     AS $_$
38375 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38376 -- See www.xtuple.com/CPAL for the full text of the software license.
38377 DECLARE
38378   pSource ALIAS FOR $1;
38379   _result TEXT := '';
38380
38381 BEGIN
38382   SELECT regexp_replace(pSource, E'<[^>]*>', '', 'g') INTO _result;
38383   RETURN _result;
38384 END;
38385 $_$;
38386
38387
38388 ALTER FUNCTION public.detag(text) OWNER TO admin;
38389
38390 --
38391 -- TOC entry 1487 (class 1255 OID 146566052)
38392 -- Dependencies: 4536 8
38393 -- Name: detailednnqoh(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
38394 --
38395
38396 CREATE FUNCTION detailednnqoh(integer, boolean) RETURNS numeric
38397     LANGUAGE plpgsql
38398     AS $_$
38399 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38400 -- See www.xtuple.com/CPAL for the full text of the software license.
38401 DECLARE
38402   pItemsiteid ALIAS FOR $1;
38403   pABS ALIAS FOR $2;
38404   _qoh NUMERIC;
38405
38406 BEGIN
38407
38408   IF (pABS) THEN
38409     SELECT SUM(noNeg(itemloc_qty)) INTO _qoh
38410     FROM itemloc, location
38411     WHERE ( (itemloc_location_id=location_id)
38412      AND (NOT location_netable)
38413      AND (itemloc_itemsite_id=pItemsiteid) );
38414   ELSE
38415     SELECT SUM(itemloc_qty) INTO _qoh
38416     FROM itemloc, location
38417     WHERE ( (itemloc_location_id=location_id)
38418      AND (NOT location_netable)
38419      AND (itemloc_itemsite_id=pItemsiteid) );
38420   END IF;
38421
38422   IF (_qoh IS NULL) THEN
38423     _qoh := 0;
38424   END IF;
38425
38426   RETURN _qoh;
38427
38428 END;
38429 $_$;
38430
38431
38432 ALTER FUNCTION public.detailednnqoh(integer, boolean) OWNER TO admin;
38433
38434 --
38435 -- TOC entry 1488 (class 1255 OID 146566053)
38436 -- Dependencies: 4536 8
38437 -- Name: detailedqoh(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
38438 --
38439
38440 CREATE FUNCTION detailedqoh(integer, boolean) RETURNS numeric
38441     LANGUAGE plpgsql
38442     AS $_$
38443 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38444 -- See www.xtuple.com/CPAL for the full text of the software license.
38445 DECLARE
38446   pItemsiteid ALIAS FOR $1;
38447   pABS ALIAS FOR $2;
38448   _qoh NUMERIC;
38449
38450 BEGIN
38451
38452   IF (pABS) THEN
38453     SELECT SUM(noNeg(itemloc_qty)) INTO _qoh
38454     FROM itemloc LEFT OUTER JOIN location ON (itemloc_location_id=location_id)
38455     WHERE ( ( (location_id IS NULL) OR (location_netable) )
38456      AND (itemloc_itemsite_id=pItemsiteid) );
38457   ELSE
38458     SELECT SUM(itemloc_qty) INTO _qoh
38459     FROM itemloc LEFT OUTER JOIN location ON (itemloc_location_id=location_id)
38460     WHERE ( ( (location_id IS NULL) OR (location_netable) )
38461      AND (itemloc_itemsite_id=pItemsiteid) );
38462   END IF;
38463
38464   IF (_qoh IS NULL) THEN
38465     _qoh := 0;
38466   END IF;
38467
38468   RETURN _qoh;
38469
38470 END;
38471 $_$;
38472
38473
38474 ALTER FUNCTION public.detailedqoh(integer, boolean) OWNER TO admin;
38475
38476 --
38477 -- TOC entry 1491 (class 1255 OID 146566054)
38478 -- Dependencies: 4536 8
38479 -- Name: determinediscountdate(integer, date); Type: FUNCTION; Schema: public; Owner: admin
38480 --
38481
38482 CREATE FUNCTION determinediscountdate(integer, date) RETURNS date
38483     LANGUAGE plpgsql
38484     AS $_$
38485 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38486 -- See www.xtuple.com/CPAL for the full text of the software license.
38487 DECLARE
38488   pTermsid ALIAS FOR $1;
38489   pSourceDate ALIAS FOR $2;
38490   _discDate DATE;
38491   _p RECORD;
38492
38493 BEGIN
38494
38495   SELECT terms_type, terms_discdays, terms_cutoffday INTO _p
38496   FROM terms
38497   WHERE (terms_id=pTermsid);
38498   IF (NOT FOUND) THEN
38499     _discDate := pSourceDate;
38500
38501 --  Handle type D terms
38502   ELSIF (_p.terms_type = 'D') THEN
38503     _discDate := (pSourceDate + _p.terms_discdays);
38504
38505 --  Handle type P terms
38506   ELSIF (_p.terms_type = 'P') THEN
38507     IF (date_part('day', pSourceDate) <= _p.terms_cutoffday) THEN
38508       _discDate := (DATE(date_trunc('month', pSourceDate)) + (_p.terms_discdays - 1));
38509     ELSE
38510       _discDate := (DATE(date_trunc('month', pSourceDate)) + (_p.terms_discdays - 1) + INTERVAL '1 month');
38511     END IF;
38512
38513 --  Handle unknown terms
38514   ELSE
38515     _discDate := pSourceDate;
38516   END IF;
38517
38518   RETURN _discDate;
38519
38520 END;
38521 $_$;
38522
38523
38524 ALTER FUNCTION public.determinediscountdate(integer, date) OWNER TO admin;
38525
38526 --
38527 -- TOC entry 1492 (class 1255 OID 146566055)
38528 -- Dependencies: 4536 8
38529 -- Name: determineduedate(integer, date); Type: FUNCTION; Schema: public; Owner: admin
38530 --
38531
38532 CREATE FUNCTION determineduedate(integer, date) RETURNS date
38533     LANGUAGE plpgsql
38534     AS $_$
38535 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38536 -- See www.xtuple.com/CPAL for the full text of the software license.
38537 DECLARE
38538   pTermsid ALIAS FOR $1;
38539   pSourceDate ALIAS FOR $2;
38540   _dueDate DATE;
38541   _p RECORD;
38542
38543 BEGIN
38544
38545   SELECT terms_type, terms_duedays, terms_cutoffday INTO _p
38546   FROM terms
38547   WHERE (terms_id=pTermsid);
38548   IF (NOT FOUND) THEN
38549     _dueDate := pSourceDate;
38550
38551 --  Handle type D terms
38552   ELSIF (_p.terms_type = 'D') THEN
38553     _dueDate := (pSourceDate + _p.terms_duedays);
38554
38555 --  Handle type P terms
38556   ELSIF (_p.terms_type = 'P') THEN
38557     IF (date_part('day', pSourceDate) <= _p.terms_cutoffday) THEN
38558       _dueDate := (DATE(date_trunc('month', pSourceDate)) + (_p.terms_duedays - 1));
38559     ELSE
38560       _dueDate := (DATE(date_trunc('month', pSourceDate)) + (_p.terms_duedays - 1) + INTERVAL '1 month');
38561     END IF;
38562
38563 --  Handle unknown terms
38564   ELSE
38565     _dueDate := pSourceDate;
38566   END IF;
38567
38568   RETURN _dueDate;
38569
38570 END;
38571 $_$;
38572
38573
38574 ALTER FUNCTION public.determineduedate(integer, date) OWNER TO admin;
38575
38576 --
38577 -- TOC entry 1493 (class 1255 OID 146566056)
38578 -- Dependencies: 8
38579 -- Name: digest(text, text); Type: FUNCTION; Schema: public; Owner: admin
38580 --
38581
38582 CREATE FUNCTION digest(text, text) RETURNS bytea
38583     LANGUAGE c IMMUTABLE STRICT
38584     AS '$libdir/pgcrypto', 'pg_digest';
38585
38586
38587 ALTER FUNCTION public.digest(text, text) OWNER TO admin;
38588
38589 --
38590 -- TOC entry 1494 (class 1255 OID 146566057)
38591 -- Dependencies: 8
38592 -- Name: digest(bytea, text); Type: FUNCTION; Schema: public; Owner: admin
38593 --
38594
38595 CREATE FUNCTION digest(bytea, text) RETURNS bytea
38596     LANGUAGE c IMMUTABLE STRICT
38597     AS '$libdir/pgcrypto', 'pg_digest';
38598
38599
38600 ALTER FUNCTION public.digest(bytea, text) OWNER TO admin;
38601
38602 --
38603 -- TOC entry 1495 (class 1255 OID 146566058)
38604 -- Dependencies: 4536 8
38605 -- Name: disablepackage(text); Type: FUNCTION; Schema: public; Owner: admin
38606 --
38607
38608 CREATE FUNCTION disablepackage(text) RETURNS integer
38609     LANGUAGE plpgsql
38610     AS $_$
38611 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38612 -- See www.xtuple.com/CPAL for the full text of the software license.
38613 DECLARE
38614   ppkgname ALIAS FOR $1;
38615   _i       INTEGER := 0;
38616   _tabs    TEXT[] := ARRAY['cmd',  'cmdarg', 'image',  'metasql',
38617                            'priv', 'report', 'script', 'uiform'];
38618
38619 BEGIN
38620   IF (version() < 'PostgreSQL 8.2') THEN
38621     RETURN -1;
38622   END IF;
38623
38624   FOR _i IN ARRAY_LOWER(_tabs,1)..ARRAY_UPPER(_tabs,1) LOOP
38625     EXECUTE 'ALTER TABLE ' || ppkgname || '.pkg' || _tabs[_i] ||
38626             ' NO INHERIT public.' || _tabs[_i] || ';';
38627   END LOOP;
38628   
38629   RETURN 0;
38630 END;
38631 $_$;
38632
38633
38634 ALTER FUNCTION public.disablepackage(text) OWNER TO admin;
38635
38636 --
38637 -- TOC entry 1496 (class 1255 OID 146566059)
38638 -- Dependencies: 4536 8
38639 -- Name: disablepackage(integer); Type: FUNCTION; Schema: public; Owner: admin
38640 --
38641
38642 CREATE FUNCTION disablepackage(integer) RETURNS integer
38643     LANGUAGE plpgsql
38644     AS $_$
38645 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38646 -- See www.xtuple.com/CPAL for the full text of the software license.
38647 DECLARE
38648   ppkgheadid    ALIAS FOR $1;
38649   _pkgname      TEXT;
38650
38651 BEGIN
38652   SELECT pkghead_name INTO _pkgname
38653   FROM pkghead
38654   WHERE (pkghead_id=ppkgheadid);
38655   IF (NOT FOUND) THEN
38656     RETURN -2;
38657   END IF;
38658
38659   RETURN disablePackage(_pkgname);
38660 END;
38661 $_$;
38662
38663
38664 ALTER FUNCTION public.disablepackage(integer) OWNER TO admin;
38665
38666 --
38667 -- TOC entry 1497 (class 1255 OID 146566060)
38668 -- Dependencies: 4536 8
38669 -- Name: distributeitemlocseries(integer); Type: FUNCTION; Schema: public; Owner: admin
38670 --
38671
38672 CREATE FUNCTION distributeitemlocseries(integer) RETURNS integer
38673     LANGUAGE plpgsql
38674     AS $_$
38675 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38676 -- See www.xtuple.com/CPAL for the full text of the software license.
38677 DECLARE
38678   pItemlocSeries   ALIAS FOR $1;
38679   _distCounter     INTEGER;
38680   _itemlocdist     RECORD;
38681   _itemlocid       INTEGER;
38682   _invhistid       INTEGER;
38683   _check           BOOLEAN;
38684   _debug           BOOLEAN := true;
38685 BEGIN
38686
38687   IF (_debug) THEN
38688     RAISE NOTICE 'distributeItemlocSeries, series=%', pItemlocSeries;
38689   END IF;
38690
38691   _distCounter := 0;
38692
38693 --  March through all of the itemlocdists for pItemlocSeries
38694   FOR _itemlocdist IN SELECT itemlocdist_id AS itemlocdistid,
38695                              itemlocdist_source_type AS type,
38696                              itemlocdist_source_id AS sourceid,
38697                              itemlocdist_qty AS qty,
38698                              itemlocdist_itemsite_id AS itemsiteid,
38699                              itemsite_freeze,
38700                              itemlocdist_invhist_id AS invhistid,
38701                              itemlocdist_ls_id AS lotserialid,
38702                              itemlocdist_expiration AS expiration,
38703                              itemlocdist_flush,
38704                              itemlocdist_warranty AS warranty,
38705                              itemlocdist_series AS series
38706                       FROM itemlocdist, itemsite
38707                       WHERE ( (itemlocdist_itemsite_id=itemsite_id)
38708                        AND (itemlocdist_series=pItemlocSeries) )
38709                       ORDER BY itemlocdist_flush DESC LOOP
38710
38711     _distCounter := _distCounter + 1;
38712     IF (_debug) THEN
38713       RAISE NOTICE 'itemlocdist loop %', _distCounter;
38714       RAISE NOTICE 'itemlocdistid=%', _itemlocdist.itemlocdistid;
38715       RAISE NOTICE 'type=%', _itemlocdist.type;
38716       RAISE NOTICE 'sourceid=%', _itemlocdist.sourceid;
38717       RAISE NOTICE 'qty=%', _itemlocdist.qty;
38718       RAISE NOTICE 'itemsiteid=%', _itemlocdist.itemsiteid;
38719       RAISE NOTICE 'freeze=%', _itemlocdist.itemsite_freeze;
38720       RAISE NOTICE 'invhistid=%', _itemlocdist.invhistid;
38721       RAISE NOTICE 'lotserialid=%', _itemlocdist.lotserialid;
38722       RAISE NOTICE 'expiration=%', _itemlocdist.expiration;
38723       RAISE NOTICE 'flush=%', _itemlocdist.itemlocdist_flush;
38724       RAISE NOTICE 'warranty=%', _itemlocdist.warranty;
38725     END IF;
38726
38727 --  Commit invhist to itemsite
38728     IF (NOT _itemlocdist.itemsite_freeze) THEN
38729         PERFORM postInvHist(_itemlocdist.invhistid);
38730     END IF;
38731
38732 --  Mark the invhist tuple for the itemlocdist in question as having detail
38733     UPDATE invhist
38734     SET invhist_hasdetail=TRUE
38735     WHERE ( (NOT invhist_hasdetail)
38736      AND (invhist_id=_itemlocdist.invhistid) );
38737
38738 --  If this itemlocdist is a flush, write a invdetail tuple that records the empty
38739     IF (_itemlocdist.itemlocdist_flush) THEN
38740       INSERT INTO invdetail
38741       ( invdetail_invhist_id, invdetail_location_id, invdetail_ls_id,
38742         invdetail_qty, invdetail_qty_before, invdetail_qty_after, invdetail_expiration,
38743         invdetail_warrpurc )
38744       SELECT _itemlocdist.invhistid, itemloc_location_id, itemloc_ls_id,
38745              (itemloc_qty * -1), itemloc_qty, 0, itemloc_expiration, 
38746              _itemlocdist.warranty
38747       FROM itemloc
38748       WHERE ( (itemloc_qty <> 0)
38749        AND (itemloc_id=_itemlocdist.sourceid) );
38750
38751 --  Delete the flushed itemloc if its parent itemsite is not frozen
38752       IF (NOT _itemlocdist.itemsite_freeze) THEN
38753         DELETE FROM itemloc
38754         WHERE (itemloc_id=_itemlocdist.sourceid);
38755       END IF;
38756
38757     ELSE
38758 --  If this is a location type distribution, check to see if the target itemloc
38759 --  already exists
38760       IF (_itemlocdist.type = 'L') THEN
38761         SELECT itemloc_id INTO _itemlocid
38762         FROM itemloc
38763         WHERE ( (itemloc_itemsite_id=_itemlocdist.itemsiteid)
38764          AND (itemloc_location_id=_itemlocdist.sourceid)
38765          AND (COALESCE(itemloc_ls_id,-1)=COALESCE(_itemlocdist.lotserialid,-1))
38766          AND (COALESCE(itemloc_expiration,endOfTime())=COALESCE(_itemlocdist.expiration,endOfTime()))
38767          AND (COALESCE(itemloc_warrpurc,endoftime())=COALESCE(_itemlocdist.warranty,endoftime())) );
38768
38769 --  Nope, create it
38770         IF (NOT FOUND) THEN
38771           SELECT NEXTVAL('itemloc_itemloc_id_seq') INTO _itemlocid;
38772
38773           INSERT INTO itemloc
38774           ( itemloc_id, itemloc_itemsite_id,
38775             itemloc_location_id, itemloc_qty,
38776             itemloc_ls_id, itemloc_expiration,
38777             itemloc_warrpurc )
38778           VALUES
38779           ( _itemlocid, _itemlocdist.itemsiteid,
38780             _itemlocdist.sourceid, 0,
38781             _itemlocdist.lotserialid, _itemlocdist.expiration,
38782             _itemlocdist.warranty );
38783         END IF;
38784
38785       ELSE
38786         _itemlocid = _itemlocdist.sourceid;
38787
38788         IF (_itemlocid IS NOT NULL AND (SELECT count(itemloc_id) = 0 FROM itemloc WHERE itemloc_id=_itemlocid)) THEN
38789           RAISE EXCEPTION 'No record to distribute against. Someone else may have already distributed this record.';
38790         END IF;
38791       END IF;
38792
38793 --  Record the invdetail
38794       INSERT INTO invdetail
38795       (invdetail_invhist_id, invdetail_location_id, invdetail_ls_id,
38796        invdetail_qty, invdetail_qty_before, invdetail_qty_after, invdetail_expiration,
38797        invdetail_warrpurc)
38798       SELECT _itemlocdist.invhistid, itemloc_location_id, _itemlocdist.lotserialid,
38799              _itemlocdist.qty, itemloc_qty, (itemloc_qty + _itemlocdist.qty),
38800              itemloc_expiration,_itemlocdist.warranty
38801       FROM itemloc
38802       WHERE (itemloc_id=_itemlocid);
38803
38804 --  Update the itemloc_qty if its parent itemsite is not frozen
38805       IF (NOT _itemlocdist.itemsite_freeze) THEN
38806         UPDATE itemloc
38807         SET itemloc_qty = (itemloc_qty + _itemlocdist.qty)
38808         WHERE (itemloc_id=_itemlocid);
38809       END IF;
38810
38811 --  Adjust QOH if this itemlocdist is to/from a non-netable location
38812       IF ( SELECT (NOT location_netable)
38813            FROM itemloc, location
38814            WHERE ( (itemloc_location_id=location_id)
38815             AND (itemloc_id=_itemlocid) ) ) THEN
38816
38817 --  Record the netable->non-netable (or visaveras) invhist
38818         SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
38819         INSERT INTO invhist
38820         ( invhist_id, invhist_itemsite_id, 
38821           invhist_transtype, invhist_invqty,
38822           invhist_qoh_before, invhist_qoh_after,
38823           invhist_docnumber, invhist_comments,
38824           invhist_invuom, invhist_unitcost,
38825           invhist_costmethod, invhist_value_before, invhist_value_after,
38826           invhist_series ) 
38827         SELECT _invhistid, itemsite_id, 
38828                'NN', (_itemlocdist.qty * -1),
38829                itemsite_qtyonhand, (itemsite_qtyonhand - _itemlocdist.qty),
38830                invhist_docnumber, invhist_comments,
38831                uom_name, stdCost(item_id),
38832                itemsite_costmethod, itemsite_value,
38833                (itemsite_value + (_itemlocdist.qty * -1 * CASE WHEN(itemsite_costmethod='A') THEN avgcost(itemsite_id)
38834                                                                ELSE stdCost(itemsite_item_id)
38835                                                           END)),
38836                _itemlocdist.series
38837         FROM item, itemsite, invhist, uom
38838         WHERE ((itemsite_item_id=item_id)
38839          AND (item_inv_uom_id=uom_id)
38840          AND (itemsite_controlmethod <> 'N')
38841          AND (itemsite_id=_itemlocdist.itemsiteid)
38842          AND (invhist_id=_itemlocdist.invhistid));
38843
38844 --  Adjust the parent itemsite
38845         IF (NOT _itemlocdist.itemsite_freeze) THEN
38846           UPDATE itemsite
38847           SET itemsite_qtyonhand = (itemsite_qtyonhand - _itemlocdist.qty),
38848               itemsite_nnqoh = (itemsite_nnqoh + _itemlocdist.qty)
38849           FROM itemloc
38850           WHERE ((itemloc_itemsite_id=itemsite_id)
38851            AND (itemloc_id=_itemlocid));
38852         END IF;
38853       END IF;
38854
38855     END IF;
38856
38857 --  If, after the distribution, the target itemloc_qty = 0, delete the itemloc
38858 --  if its parent itemsite is not frozen
38859     IF (NOT _itemlocdist.itemsite_freeze) THEN
38860       DELETE FROM itemloc
38861       WHERE ( (itemloc_qty=0)
38862        AND (itemloc_id=_itemlocid) );
38863     END IF;
38864
38865   END LOOP;
38866
38867   DELETE FROM itemlocdist
38868   WHERE (itemlocdist_series=pItemlocSeries);
38869
38870   RETURN _distCounter;
38871
38872 END;
38873 $_$;
38874
38875
38876 ALTER FUNCTION public.distributeitemlocseries(integer) OWNER TO admin;
38877
38878 --
38879 -- TOC entry 1498 (class 1255 OID 146566062)
38880 -- Dependencies: 4536 8
38881 -- Name: distributetodefault(integer); Type: FUNCTION; Schema: public; Owner: admin
38882 --
38883
38884 CREATE FUNCTION distributetodefault(integer) RETURNS integer
38885     LANGUAGE plpgsql
38886     AS $_$
38887 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38888 -- See www.xtuple.com/CPAL for the full text of the software license.
38889 DECLARE
38890   pItemlocdistid ALIAS FOR $1;
38891
38892 BEGIN
38893
38894   RETURN distributeToDefault(pItemlocdistid, 'O');
38895
38896 END;
38897 $_$;
38898
38899
38900 ALTER FUNCTION public.distributetodefault(integer) OWNER TO admin;
38901
38902 --
38903 -- TOC entry 1499 (class 1255 OID 146566063)
38904 -- Dependencies: 4536 8
38905 -- Name: distributetodefault(integer, text); Type: FUNCTION; Schema: public; Owner: admin
38906 --
38907
38908 CREATE FUNCTION distributetodefault(integer, text) RETURNS integer
38909     LANGUAGE plpgsql
38910     AS $_$
38911 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38912 -- See www.xtuple.com/CPAL for the full text of the software license.
38913 DECLARE
38914   pItemlocdistid ALIAS FOR $1;
38915   pTranstype ALIAS FOR $2;
38916   _locationid INTEGER;
38917   _itemlocdistid INTEGER;
38918   _qty NUMERIC;
38919
38920 BEGIN
38921
38922 --  Make sure that the itemsite in question has a default location
38923   SELECT CASE WHEN (pTranstype='R') THEN itemsite_recvlocation_id
38924               WHEN (pTranstype='I') THEN itemsite_issuelocation_id
38925               ELSE itemsite_location_id
38926          END INTO _locationid
38927   FROM itemlocdist, itemsite
38928   WHERE ( (itemlocdist_itemsite_id=itemsite_id)
38929    AND (itemlocdist_id=pItemlocdistid) );
38930   IF ( (NOT FOUND) OR (_locationid = -1) ) THEN
38931     RETURN -1;
38932   END IF;
38933
38934 --  Determine the remaining qty required to distribute
38935   SELECT (p.itemlocdist_qty - COALESCE(SUM(c.itemlocdist_qty), 0)) INTO _qty
38936   FROM itemlocdist AS p LEFT OUTER JOIN itemlocdist AS c ON (c.itemlocdist_itemlocdist_id=p.itemlocdist_id)
38937   WHERE (p.itemlocdist_id=pItemlocdistid)
38938   GROUP BY p.itemlocdist_qty;
38939
38940   IF (_qty = 0) THEN
38941     RETURN -2;
38942   END IF;
38943
38944 --  Check to see if an itemlocdist with the correct location/lotserial/expiration already exists
38945   SELECT target.itemlocdist_id INTO _itemlocdistid
38946   FROM itemlocdist AS source, itemlocdist AS target, itemloc, itemsite
38947   WHERE ( (target.itemlocdist_source_type='L')
38948    AND (target.itemlocdist_source_id=_locationid)
38949    AND (target.itemlocdist_itemsite_id=source.itemlocdist_itemsite_id)
38950    AND (COALESCE(target.itemlocdist_ls_id)=COALESCE(source.itemlocdist_ls_id))
38951    AND (target.itemlocdist_expiration=source.itemlocdist_expiration)
38952    AND (target.itemlocdist_itemlocdist_id=source.itemlocdist_itemlocdist_id)
38953    AND (target.itemlocdist_itemsite_id=itemsite_id)
38954    AND (source.itemlocdist_id=pItemlocdistid) );
38955
38956   IF (FOUND) THEN
38957     UPDATE itemlocdist
38958     SET itemlocdist_qty = (itemlocdist_qty + _qty)
38959     WHERE (itemlocdist_id=_itemlocdistid);
38960
38961     RETURN _itemlocdistid;
38962   END IF;
38963
38964 --  Create a new itemlocdist
38965   SELECT NEXTVAL('itemlocdist_itemlocdist_id_seq') INTO _itemlocdistid;
38966
38967   INSERT INTO itemlocdist
38968   ( itemlocdist_id, itemlocdist_itemlocdist_id, itemlocdist_source_type,
38969     itemlocdist_ls_id, itemlocdist_expiration,
38970     itemlocdist_source_id, itemlocdist_itemsite_id, itemlocdist_qty )
38971   SELECT _itemlocdistid, pItemlocdistid, 'L',
38972          itemlocdist_ls_id, itemlocdist_expiration,
38973          _locationid, itemlocdist_itemsite_id, _qty
38974   FROM itemlocdist
38975   WHERE (itemlocdist_id=pItemlocdistid);
38976
38977   RETURN _itemlocdistid;
38978
38979 END;
38980 $_$;
38981
38982
38983 ALTER FUNCTION public.distributetodefault(integer, text) OWNER TO admin;
38984
38985 --
38986 -- TOC entry 1500 (class 1255 OID 146566064)
38987 -- Dependencies: 4536 8
38988 -- Name: distributetodefaultitemloc(integer); Type: FUNCTION; Schema: public; Owner: admin
38989 --
38990
38991 CREATE FUNCTION distributetodefaultitemloc(integer) RETURNS integer
38992     LANGUAGE plpgsql
38993     AS $_$
38994 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
38995 -- See www.xtuple.com/CPAL for the full text of the software license.
38996 DECLARE
38997   pItemlocdistid ALIAS FOR $1;
38998
38999 BEGIN
39000
39001   RETURN distributeToDefaultItemLoc(pItemlocdistid, 'O');
39002
39003 END;
39004 $_$;
39005
39006
39007 ALTER FUNCTION public.distributetodefaultitemloc(integer) OWNER TO admin;
39008
39009 --
39010 -- TOC entry 1501 (class 1255 OID 146566065)
39011 -- Dependencies: 4536 8
39012 -- Name: distributetodefaultitemloc(integer, text); Type: FUNCTION; Schema: public; Owner: admin
39013 --
39014
39015 CREATE FUNCTION distributetodefaultitemloc(integer, text) RETURNS integer
39016     LANGUAGE plpgsql
39017     AS $_$
39018 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39019 -- See www.xtuple.com/CPAL for the full text of the software license.
39020 DECLARE
39021   pItemlocdistid ALIAS FOR $1;
39022   pTranstype ALIAS FOR $2;
39023   _itemlocid INTEGER;
39024   _itemlocdistid INTEGER;
39025   _qty NUMERIC;
39026
39027 BEGIN
39028
39029 --  Make sure that the itemsite in question has a default location
39030   SELECT itemloc_id INTO _itemlocid
39031     FROM itemlocdist, itemsite, itemloc
39032    WHERE ((itemlocdist_itemsite_id=itemsite_id)
39033      AND ( (itemsite_location_id=itemloc_location_id AND pTranstype='O') OR
39034            (itemsite_recvlocation_id=itemloc_location_id AND pTranstype='R') OR
39035            (itemsite_issuelocation_id=itemloc_location_id AND pTranstype='I') )
39036      AND (itemloc_itemsite_id=itemsite_id)
39037      AND (itemlocdist_id=pItemlocdistid));
39038   IF ( (NOT FOUND) OR (_itemlocid = -1) ) THEN
39039     RETURN -1;
39040   END IF;
39041
39042 --  Determine the remaining qty required to distribute
39043   SELECT (p.itemlocdist_qty - COALESCE(SUM(c.itemlocdist_qty), 0)) INTO _qty
39044     FROM itemlocdist AS p LEFT OUTER JOIN itemlocdist AS c
39045       ON (c.itemlocdist_itemlocdist_id=p.itemlocdist_id)
39046    WHERE (p.itemlocdist_id=pItemlocdistid)
39047    GROUP BY p.itemlocdist_qty;
39048
39049   IF (_qty = 0) THEN
39050     RETURN -2;
39051   END IF;
39052
39053 --  Check to see if an itemlocdist with the correct location/lotserial/expiration already exists
39054   SELECT target.itemlocdist_id INTO _itemlocdistid
39055   FROM itemlocdist AS source, itemlocdist AS target
39056   WHERE ( (target.itemlocdist_source_type='I')
39057    AND (target.itemlocdist_source_id=_itemlocid)
39058    AND (COALESCE(target.itemlocdist_ls_id,-1)=COALESCE(source.itemlocdist_ls_id,-1))
39059    AND (target.itemlocdist_expiration=source.itemlocdist_expiration)
39060    AND (target.itemlocdist_itemlocdist_id=source.itemlocdist_id)
39061    AND (source.itemlocdist_id=pItemlocdistid) );
39062
39063   IF (FOUND) THEN
39064     UPDATE itemlocdist
39065     SET itemlocdist_qty = (itemlocdist_qty + _qty)
39066     WHERE (itemlocdist_id=_itemlocdistid);
39067
39068     RETURN _itemlocdistid;
39069   END IF;
39070
39071 --  Create a new itemlocdist
39072   SELECT NEXTVAL('itemlocdist_itemlocdist_id_seq') INTO _itemlocdistid;
39073
39074   INSERT INTO itemlocdist
39075   ( itemlocdist_id, itemlocdist_itemlocdist_id,
39076     itemlocdist_source_type, itemlocdist_source_id,
39077     itemlocdist_qty, itemlocdist_expiration )
39078   VALUES
39079   ( _itemlocdistid, pItemlocdistid,
39080     'I', _itemlocid,
39081     _qty, endOfTime() );
39082
39083   RETURN _itemlocdistid;
39084
39085 END;
39086 $_$;
39087
39088
39089 ALTER FUNCTION public.distributetodefaultitemloc(integer, text) OWNER TO admin;
39090
39091 --
39092 -- TOC entry 1502 (class 1255 OID 146566066)
39093 -- Dependencies: 4536 8
39094 -- Name: distributetolocations(integer); Type: FUNCTION; Schema: public; Owner: admin
39095 --
39096
39097 CREATE FUNCTION distributetolocations(integer) RETURNS integer
39098     LANGUAGE plpgsql
39099     AS $_$
39100 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39101 -- See www.xtuple.com/CPAL for the full text of the software license.
39102 DECLARE
39103   pItemlocdistid ALIAS FOR $1;
39104   _distCounter INTEGER;
39105   _itemlocdist RECORD;
39106   _itemlocid INTEGER;
39107   _runningQty NUMERIC;
39108   _tmp RECORD;
39109
39110 BEGIN
39111
39112   _distCounter := 0;
39113   _runningQty  := 0;
39114
39115 -- A scenario can occur where two people try to post distributions
39116 -- to the same itemsite against two or more lot/serial/mlc locations
39117 -- leading to a deadlock. This line tries to prevent that by locking
39118 -- ahead of time all the itemsites that the transaction will need
39119 -- before any of the other tables are locked individually.
39120   SELECT itemsite_id
39121     INTO _tmp
39122     FROM itemsite
39123    WHERE(itemsite_id in (SELECT DISTINCT itemlocdist_itemsite_id
39124                            FROM itemlocdist
39125                           WHERE(itemlocdist_id=pItemlocdistid)))
39126      FOR UPDATE;
39127
39128 --  March through all of the itemlocdist owned by the passed parent itemlocdist
39129   FOR _itemlocdist IN SELECT c.itemlocdist_id AS itemlocdistid,
39130                              c.itemlocdist_source_type AS type,
39131                              c.itemlocdist_source_id AS sourceid,
39132                              c.itemlocdist_qty AS qty,
39133                              p.itemlocdist_itemsite_id AS itemsiteid,
39134                              itemsite_freeze,
39135                              p.itemlocdist_invhist_id AS invhistid,
39136                              p.itemlocdist_ls_id AS lotserialid,
39137                              p.itemlocdist_expiration AS expiration,
39138                              p.itemlocdist_warranty AS warranty,
39139                              p.itemlocdist_order_type AS ordertype,
39140                              p.itemlocdist_order_id AS orderid,
39141                              p.itemlocdist_series AS series
39142                       FROM itemlocdist AS c, itemlocdist AS p, itemsite
39143                       WHERE ( (c.itemlocdist_itemlocdist_id=p.itemlocdist_id)
39144                        AND (p.itemlocdist_source_type='O')
39145                        AND (p.itemlocdist_itemsite_id=itemsite_id)
39146                        AND (p.itemlocdist_id=pItemlocdistid) ) LOOP
39147
39148     _distCounter := _distCounter + 1;
39149
39150 --  If the target for this itemlocdist is a location, check to see if the
39151 --  required itemloc already exists
39152     IF (_itemlocdist.type = 'L') THEN
39153       SELECT itemloc_id INTO _itemlocid
39154       FROM itemloc
39155       WHERE ( (itemloc_itemsite_id=_itemlocdist.itemsiteid)
39156        AND (itemloc_location_id=_itemlocdist.sourceid)
39157        AND (COALESCE(itemloc_ls_id, -1)=COALESCE(_itemlocdist.lotserialid, -1))
39158        AND (COALESCE(itemloc_expiration,endOfTime())=COALESCE(_itemlocdist.expiration,endOfTime()))
39159        AND (COALESCE(itemloc_warrpurc,endoftime())=COALESCE(_itemlocdist.warranty,endoftime())) );
39160
39161 --  Nope, make it
39162       IF (NOT FOUND) THEN
39163         SELECT NEXTVAL('itemloc_itemloc_id_seq') INTO _itemlocid;
39164         INSERT INTO itemloc
39165         ( itemloc_id, itemloc_itemsite_id,
39166           itemloc_location_id, itemloc_qty,
39167           itemloc_ls_id, itemloc_expiration,
39168           itemloc_warrpurc )
39169         VALUES
39170         ( _itemlocid, _itemlocdist.itemsiteid,
39171           _itemlocdist.sourceid, 0,
39172           _itemlocdist.lotserialid, _itemlocdist.expiration,
39173           _itemlocdist.warranty );
39174       END IF;
39175
39176     ELSE
39177 --  Yep, cache it
39178       _itemlocid = _itemlocdist.sourceid;
39179
39180       IF (_itemlocid IS NOT NULL AND (SELECT count(itemloc_id) = 0 FROM itemloc WHERE itemloc_id=_itemlocid)) THEN
39181         RAISE EXCEPTION 'No record to distribute against. Someone else may have already distributed this record.';
39182       END IF;
39183     END IF;
39184
39185 --  Record the invdetail for this itemlocdist
39186     INSERT INTO invdetail
39187     ( invdetail_invhist_id, invdetail_location_id, invdetail_ls_id,
39188       invdetail_qty, invdetail_qty_before, invdetail_qty_after, invdetail_expiration, 
39189       invdetail_warrpurc )
39190     SELECT _itemlocdist.invhistid, itemloc_location_id, itemloc_ls_id,
39191            _itemlocdist.qty, itemloc_qty, (itemloc_qty + _itemlocdist.qty),
39192            itemloc_expiration,_itemlocdist.warranty
39193     FROM itemloc
39194     WHERE (itemloc_id=_itemlocid);
39195
39196 --  Update the parent invhist to indicate that it has invdetail records
39197     UPDATE invhist
39198     SET invhist_hasdetail=TRUE
39199     WHERE ((invhist_hasdetail=FALSE)
39200      AND (invhist_id=_itemlocdist.invhistid));
39201
39202 --  Update the itemloc_qty if its parent itemsite is not frozen
39203     IF (NOT _itemlocdist.itemsite_freeze) THEN
39204       UPDATE itemloc
39205       SET itemloc_qty = (itemloc_qty + _itemlocdist.qty)
39206       WHERE (itemloc_id=_itemlocid);
39207
39208       PERFORM postInvHist(_itemlocdist.invhistid);
39209
39210 --  Handle reservation data
39211       IF ( (SELECT fetchMetricBool('EnableSOReservationsByLocation')) AND
39212            (_itemlocdist.qty < 0) ) THEN
39213
39214 --  If a shipment on a sales order, record reservation change before updating
39215 --  so it can be reversed later if necessary
39216         IF (_itemlocdist.ordertype = 'SO') THEN
39217           INSERT INTO shipitemlocrsrv
39218           SELECT nextval('shipitemlocrsrv_shipitemlocrsrv_id_seq'),
39219             shipitem_id, itemloc_itemsite_id, itemloc_location_id,
39220             itemloc_ls_id, itemloc_expiration, itemloc_warrpurc,
39221             least((_itemlocdist.qty * -1.0), reserve_qty)
39222           FROM shipitem, itemloc
39223             JOIN reserve ON (itemloc_id=reserve_supply_id AND reserve_supply_type='I')
39224           WHERE ( (shipitem_invhist_id=_itemlocdist.invhistid)
39225             AND   (itemloc_id=_itemlocid)
39226             AND   (reserve_demand_type=_itemlocdist.ordertype)
39227             AND   (reserve_demand_id=_itemlocdist.orderid) );
39228         END IF;
39229
39230 --  Update the reservation
39231         UPDATE reserve
39232         SET reserve_qty = (reserve_qty + _itemlocdist.qty)
39233         WHERE ( (reserve_supply_id=_itemlocid)
39234           AND   (reserve_supply_type='I')
39235           AND   (reserve_demand_type=_itemlocdist.ordertype)
39236           AND   (reserve_demand_id=_itemlocdist.orderid) );
39237           
39238 --  Delete reservation if fully distributed
39239         DELETE FROM reserve
39240         WHERE ( (reserve_supply_id=_itemlocid)
39241           AND   (reserve_supply_type='I')
39242           AND   (reserve_demand_type=_itemlocdist.ordertype)
39243           AND   (reserve_demand_id=_itemlocdist.orderid)
39244           AND   (reserve_qty=0) );
39245       END IF;
39246     END IF;
39247
39248 --  Adjust QOH if this itemlocdist is to/from a non-netable location
39249     IF ( SELECT (NOT location_netable)
39250          FROM itemloc, location
39251          WHERE ((itemloc_location_id=location_id)
39252           AND (itemloc_id=_itemlocid)) ) THEN
39253
39254 --  Record the invhist record for the netable->non-netable (or visaversa)
39255       INSERT INTO invhist
39256       ( invhist_itemsite_id,
39257         invhist_transtype, invhist_invqty,
39258         invhist_qoh_before, invhist_qoh_after,
39259         invhist_docnumber, invhist_comments,
39260         invhist_invuom, invhist_unitcost,
39261         invhist_costmethod, invhist_value_before, invhist_value_after,
39262         invhist_series )
39263       SELECT itemsite_id,
39264              'NN', (_itemlocdist.qty * -1),
39265              itemsite_qtyonhand, (itemsite_qtyonhand - _itemlocdist.qty),
39266              invhist_docnumber, invhist_comments,
39267              uom_name, stdCost(item_id),
39268              itemsite_costmethod, itemsite_value,
39269              (itemsite_value + (_itemlocdist.qty * -1 * CASE WHEN(itemsite_costmethod='A') THEN avgcost(itemsite_id)
39270                                                              ELSE stdCost(itemsite_item_id)
39271                                                         END)),
39272              _itemlocdist.series
39273       FROM item, itemsite, invhist, uom
39274       WHERE ( (itemsite_item_id=item_id)
39275        AND (item_inv_uom_id=uom_id)
39276        AND (itemsite_controlmethod <> 'N')
39277        AND (itemsite_id=_itemlocdist.itemsiteid)
39278        AND (invhist_id=_itemlocdist.invhistid) );
39279
39280 --  Update the itemsite_qoh
39281       IF (NOT _itemlocdist.itemsite_freeze) THEN
39282         UPDATE itemsite
39283         SET itemsite_qtyonhand = (itemsite_qtyonhand - _itemlocdist.qty),
39284             itemsite_nnqoh = (itemsite_nnqoh + _itemlocdist.qty)
39285         FROM itemloc
39286         WHERE ((itemloc_itemsite_id=itemsite_id)
39287          AND (itemloc_id=_itemlocid));
39288       END IF;
39289     END IF;
39290
39291 --  Cache the running qty.
39292     _runningQty := _runningQty + _itemlocdist.qty;
39293
39294 --  Dene with the child itemlocdist, so delete it
39295     DELETE FROM itemlocdist
39296     WHERE (itemlocdist_id=_itemlocdist.itemlocdistid);
39297
39298 --  If the target itemloc is now at qty=0, delete it if its parent
39299 --  itemsite is not frozen
39300     IF (NOT _itemlocdist.itemsite_freeze) THEN
39301       DELETE FROM itemloc
39302       WHERE ( (itemloc_qty=0)
39303        AND (itemloc_id=_itemlocid) );
39304     END IF;
39305
39306   END LOOP;
39307
39308 --  If the running qty for the detailed distributions is the same as the
39309 --  total qty to distribute indicated by the parent itemlocdist, then the
39310 --  parent itemlocdist has been fully distributed and should be deleted.
39311   IF ( ( SELECT itemlocdist_qty
39312          FROM itemlocdist
39313          WHERE (itemlocdist_id=pItemlocdistid) ) = _runningQty) THEN
39314     DELETE FROM itemlocdist
39315     WHERE (itemlocdist_id=pItemlocdistid);
39316   ELSE
39317 --  There is still some more qty to distribute in the parent itemlocdist.
39318 --  Update the qty to distribute with the qty that has been distributed.
39319     UPDATE itemlocdist
39320     SET itemlocdist_qty = (itemlocdist_qty - _runningQty)
39321     WHERE (itemlocdist_id=pItemlocdistid);
39322   END IF;
39323
39324   RETURN _distCounter;
39325
39326 END;
39327 $_$;
39328
39329
39330 ALTER FUNCTION public.distributetolocations(integer) OWNER TO admin;
39331
39332 --
39333 -- TOC entry 1504 (class 1255 OID 146566068)
39334 -- Dependencies: 4536 8
39335 -- Name: distributevoucherline(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
39336 --
39337
39338 CREATE FUNCTION distributevoucherline(integer, integer, integer) RETURNS integer
39339     LANGUAGE plpgsql
39340     AS $_$
39341 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39342 -- See www.xtuple.com/CPAL for the full text of the software license.
39343 DECLARE
39344   pVoucherId ALIAS FOR $1;
39345   pPoitemId ALIAS FOR $2;
39346   pCurrId ALIAS FOR $3;
39347   _count INTEGER;
39348   _costelemId INTEGER;
39349   _close BOOLEAN;
39350   _r RECORD;
39351   _qtyOrdered NUMERIC;
39352   _voitemId INTEGER;
39353   _taxtypeid INTEGER;
39354
39355 BEGIN
39356
39357 --  Make sure the P/O and Voucher are same currency
39358
39359   SELECT COALESCE(COUNT(*),0) INTO _count
39360         FROM poitem JOIN pohead ON (pohead_id=poitem_pohead_id)
39361         WHERE ((poitem_id=pPoitemid)
39362         AND (pohead_curr_id=pCurrId));
39363   IF (_count = 0) THEN
39364         RETURN -3;
39365   END IF;
39366
39367 --  Validate and get cost element
39368
39369         SELECT COALESCE(COUNT(*),0) INTO _count
39370                 FROM itemcost, item, itemsite, poitem
39371                 WHERE ((itemcost_item_id=item_id)
39372                 AND (item_id=itemsite_item_id)
39373                 AND (itemsite_id=poitem_itemsite_id)
39374                 AND (poitem_id=pPoitemId));
39375
39376         IF (_count > 1) THEN
39377                 RETURN -5;
39378         ELSEIF (_count = 1) THEN
39379                 SELECT itemcost_costelem_id INTO _costelemId
39380                         FROM itemcost, item, itemsite, poitem
39381                         WHERE ((itemcost_item_id=item_id)
39382                         AND (item_id=itemsite_item_id)
39383                         AND (itemsite_id=poitem_itemsite_id)
39384                         AND (poitem_id=pPoitemId));
39385         ELSE
39386                 SELECT costelem_id INTO _costelemId
39387                         FROM costelem
39388                         WHERE (costelem_type='Material');
39389         END IF;
39390
39391
39392 --  Clear previous distributions
39393
39394         UPDATE recv SET recv_vohead_id=NULL, recv_voitem_id=NULL
39395                 WHERE ((recv_vohead_id=pVoucherId)
39396                 AND (recv_orderitem_id=pPoitemId)
39397                 AND (recv_order_type='PO'));
39398         UPDATE poreject SET poreject_vohead_id=NULL, poreject_voitem_id=NULL
39399                 WHERE ((poreject_vohead_id=pVoucherId)
39400                 AND (poreject_poitem_id=pPoitemId));
39401         DELETE FROM vodist
39402                 WHERE ((vodist_poitem_id=pPoitemId)
39403                 AND (vodist_vohead_id=pVoucherId));
39404         DELETE FROM voitem
39405                 WHERE ((voitem_poitem_id=pPoitemId)
39406                 AND (voitem_vohead_id=pVoucherId));
39407
39408 --  Determine Line balances
39409
39410         SELECT  COALESCE(SUM(qty_received),0) AS qty_received,
39411                 COALESCE(SUM(qty_rejected),0) AS qty_rejected,
39412                 COALESCE(SUM(qty_vouchered),0) AS qty_vouchered,
39413                 round(COALESCE(SUM(balance),0),2) AS balance,
39414                 round(COALESCE(SUM(freight),0),2) AS freight INTO _r
39415          FROM   (
39416                 SELECT  recv_qty AS qty_received,
39417                         0 AS qty_rejected,
39418                         0 AS qty_vouchered,
39419                         (recv_qty * COALESCE(recv_purchcost, poitem_unitprice)) AS balance,
39420                         recv_freight AS freight
39421                 FROM poitem JOIN recv ON ((recv_orderitem_id=poitem_id) AND
39422                                           (recv_order_type='PO'))
39423                 WHERE ( (recv_vohead_id IS NULL)
39424                         AND (NOT recv_invoiced)
39425                         AND (recv_posted)
39426                         AND (poitem_id=pPoitemId) )
39427
39428                 UNION ALL
39429
39430                 SELECT  0 AS qty_received,
39431                         (poreject_qty) AS qty_rejected,
39432                         0 AS qty_vouchered,
39433                         (poreject_qty * -1 * COALESCE(recv_purchcost, poitem_unitprice)) AS balance,
39434                         0 AS freight
39435                 FROM poitem JOIN poreject ON (poreject_poitem_id=poitem_id)
39436                             LEFT OUTER JOIN recv ON (recv_id=poreject_recv_id)
39437                 WHERE ( (poreject_posted)
39438                         AND (poreject_vohead_id IS NULL)
39439                         AND (NOT poreject_invoiced)
39440                         AND (poitem_id=pPoitemId) )
39441
39442                 UNION ALL
39443
39444                 SELECT  0 AS qty_received,
39445                         0 AS qty_rejected,
39446                         voitem_qty AS qty_vouchered,
39447                         0 AS balance,
39448                         0 AS freight
39449                 FROM voitem, poitem
39450                 WHERE ( (voitem_poitem_id=pPoitemId)
39451                         AND (poitem_id=voitem_poitem_id) )
39452                 ) AS data;
39453
39454                 SELECT poitem_qty_ordered INTO _qtyOrdered
39455                 FROM poitem
39456                 WHERE (poitem_id=pPoitemId);
39457
39458         IF _r.balance < 0 THEN
39459                 RETURN -4;
39460         ELSEIF ( ((_r.qty_received <> 0) OR (_r.qty_received <> 0)) AND (_r.qty_received - _r.qty_rejected = 0) ) THEN
39461                 RETURN -2;
39462         ELSEIF ((_r.qty_received - _r.qty_rejected) = 0) THEN
39463                 RETURN 0;
39464         END IF;
39465
39466 -- Determine whether to close P/O item
39467
39468         IF (_r.qty_received -_r.qty_rejected + _r.qty_vouchered) >= _qtyOrdered THEN
39469                 _close:=True;
39470         ELSE
39471                 _close:=False;
39472         END IF;
39473
39474
39475 -- Create distribution
39476
39477         INSERT INTO vodist
39478                 (vodist_poitem_id,vodist_vohead_id,vodist_costelem_id,vodist_amount,vodist_qty,vodist_expcat_id)
39479                 VALUES (pPoitemId,pVoucherId,_costelemId,_r.balance,(_r.qty_received -_r.qty_rejected),-1);
39480
39481 -- Create voucher item
39482         SELECT poitem_taxtype_id INTO _taxtypeid
39483         FROM poitem
39484         WHERE (poitem_id=pPoitemId);
39485
39486         SELECT NEXTVAL('voitem_voitem_id_seq') INTO _voitemId;
39487
39488         INSERT INTO voitem (voitem_id,voitem_vohead_id,voitem_poitem_id,voitem_close,voitem_qty,voitem_freight, voitem_taxtype_id)
39489                 VALUES (_voitemId,pVoucherId,pPoitemId,_close,(_r.qty_received -_r.qty_rejected),_r.freight, _taxtypeid);
39490
39491 -- Tag receipt records
39492
39493         UPDATE recv
39494         SET recv_vohead_id=pVoucherId, recv_voitem_id=_voitemId
39495         WHERE ((recv_orderitem_id=pPoitemId)
39496           AND  (recv_order_type='PO')
39497           AND  (recv_vohead_id IS NULL));
39498
39499         UPDATE poreject
39500         SET poreject_vohead_id=pVoucherId,poreject_voitem_id=_voitemId
39501         WHERE ((poreject_poitem_id=pPoitemId)
39502         AND (NOT poreject_invoiced)
39503         AND (poreject_vohead_id IS NULL));
39504
39505
39506   RETURN 1;
39507
39508 END;
39509 $_$;
39510
39511
39512 ALTER FUNCTION public.distributevoucherline(integer, integer, integer) OWNER TO admin;
39513
39514 --
39515 -- TOC entry 1505 (class 1255 OID 146566069)
39516 -- Dependencies: 4536 8
39517 -- Name: dopostcosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
39518 --
39519
39520 CREATE FUNCTION dopostcosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS integer
39521     LANGUAGE plpgsql
39522     AS $_$
39523 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39524 -- See www.xtuple.com/CPAL for the full text of the software license.
39525 DECLARE
39526
39527   pMaterial ALIAS FOR $1;
39528   plowerMaterial ALIAS FOR $2;
39529   pdirectLabor ALIAS FOR $3;
39530   plowerDirectLabor ALIAS FOR $4;
39531   poverhead ALIAS FOR $5;
39532   plowerOverhead ALIAS FOR $6;
39533   pmachOverhead ALIAS FOR $7;
39534   plowerMachOverhead ALIAS FOR $8;
39535   pUser ALIAS FOR $9;
39536   plowerUser ALIAS FOR $10;
39537   prollUp ALIAS FOR $11;
39538   _item RECORD;
39539   _result INTEGER := 0;
39540
39541 BEGIN
39542
39543   PERFORM resetLowLevelCode(-1);
39544
39545   FOR _item IN SELECT costUpdate_item_id
39546             FROM costUpdate
39547             ORDER BY costUpdate_lowlevel_code DESC LOOP
39548     PERFORM doPostCosts(_item.costUpdate_item_id, FALSE,
39549                        pMaterial, plowerMaterial, pdirectLabor,
39550                        plowerDirectLabor, poverhead, plowerOverhead,
39551                        pmachOverhead, plowerMachOverhead,
39552                        puser, plowerUser, prollUp);
39553   END LOOP;
39554
39555   RETURN _result;
39556
39557 END;
39558  $_$;
39559
39560
39561 ALTER FUNCTION public.dopostcosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
39562
39563 --
39564 -- TOC entry 1506 (class 1255 OID 146566070)
39565 -- Dependencies: 4536 8
39566 -- Name: dopostcosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
39567 --
39568
39569 CREATE FUNCTION dopostcosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS integer
39570     LANGUAGE plpgsql
39571     AS $_$
39572 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39573 -- See www.xtuple.com/CPAL for the full text of the software license.
39574 DECLARE
39575
39576   pItemId ALIAS FOR $1;
39577   pResetLowLevel ALIAS FOR $2;
39578   pMaterial ALIAS FOR $3;
39579   plowerMaterial ALIAS FOR $4;
39580   pdirectLabor ALIAS FOR $5;
39581   plowerDirectLabor ALIAS FOR $6;
39582   poverhead ALIAS FOR $7;
39583   plowerOverhead ALIAS FOR $8;
39584   pmachOverhead ALIAS FOR $9;
39585   plowerMachOverhead ALIAS FOR $10;
39586   pUser ALIAS FOR $11;
39587   plowerUser ALIAS FOR $12;
39588   prollUp ALIAS FOR $13;
39589   _itemcost RECORD;
39590   _result INTEGER;
39591
39592 BEGIN
39593
39594     IF (pResetLowLevel) THEN
39595         PERFORM resetLowLevelCode(pItemId);
39596     END IF;
39597
39598     FOR _itemcost IN SELECT itemcost_id, costelem_sys, costelem_type,
39599                             itemcost_lowlevel,
39600                             costUpdate_lowlevel_code, costUpdate_item_type
39601             FROM itemcost, costelem, costUpdate
39602             WHERE itemcost_item_id = pItemId
39603               AND costUpdate_item_id = itemcost_item_id
39604               AND itemcost_costelem_id = costelem_id LOOP
39605       IF (NOT _itemcost.costelem_sys) THEN
39606         IF ( (pUser) AND ( NOT _itemcost.itemcost_lowlevel) ) THEN
39607           PERFORM postCost(_itemcost.itemcost_id);
39608           _result := _result + 1;
39609         END IF;
39610         IF ( (plowerUser) AND ( _itemcost.itemcost_lowlevel) ) THEN
39611           PERFORM postCost(_itemcost.itemcost_id);
39612           _result := _result + 1;
39613         END IF;
39614       END IF;
39615
39616       IF (_itemcost.costelem_type = 'Material') THEN
39617         IF ( (pMaterial) AND ( NOT _itemcost.itemcost_lowlevel) ) THEN
39618           PERFORM postCost(_itemcost.itemcost_id);
39619           _result := _result + 1;
39620         END IF;
39621         IF ( (plowerMaterial) AND ( _itemcost.itemcost_lowlevel) ) THEN
39622           PERFORM postCost(_itemcost.itemcost_id);
39623           _result := _result + 1;
39624         END IF;
39625       END IF;
39626
39627       IF (_itemcost.costelem_type = 'Direct Labor') THEN
39628         IF ( (pdirectLabor) AND ( NOT _itemcost.itemcost_lowlevel) ) THEN
39629           PERFORM postCost(_itemcost.itemcost_id);
39630           _result := _result + 1;
39631         END IF;
39632         IF ( (plowerDirectLabor) AND ( _itemcost.itemcost_lowlevel) ) THEN
39633           PERFORM postCost(_itemcost.itemcost_id);
39634           _result := _result + 1;
39635         END IF;
39636       END IF;
39637
39638       IF (_itemcost.costelem_type = 'Overhead') THEN
39639         IF ( (poverhead) AND ( NOT _itemcost.itemcost_lowlevel) ) THEN
39640           PERFORM postCost(_itemcost.itemcost_id);
39641           _result := _result + 1;
39642         END IF;
39643         IF ( (plowerOverhead) AND ( _itemcost.itemcost_lowlevel) ) THEN
39644           PERFORM postCost(_itemcost.itemcost_id);
39645           _result := _result + 1;
39646         END IF;
39647       END IF;
39648
39649       IF (_itemcost.costelem_type = 'Machine Overhead') THEN
39650         IF ( (pmachOverhead) AND ( NOT _itemcost.itemcost_lowlevel) ) THEN
39651           PERFORM postCost(_itemcost.itemcost_id);
39652           _result := _result + 1;
39653         END IF;
39654         IF ( (plowerMachOverhead) AND ( _itemcost.itemcost_lowlevel) ) THEN
39655           PERFORM postCost(_itemcost.itemcost_id);
39656           _result := _result + 1;
39657         END IF;
39658       END IF;
39659
39660     END LOOP;
39661
39662     IF (prollUp) THEN    
39663       PERFORM rollUpStandardCost(pItemId);
39664       _result := _result + 1;
39665     END IF;
39666
39667     RETURN _result;
39668
39669 END;
39670  $_$;
39671
39672
39673 ALTER FUNCTION public.dopostcosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
39674
39675 --
39676 -- TOC entry 1507 (class 1255 OID 146566071)
39677 -- Dependencies: 4536 8
39678 -- Name: doupdatecosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
39679 --
39680
39681 CREATE FUNCTION doupdatecosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS integer
39682     LANGUAGE plpgsql
39683     AS $_$
39684 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39685 -- See www.xtuple.com/CPAL for the full text of the software license.
39686 DECLARE
39687
39688   plowerMaterial ALIAS FOR $1;
39689   pdirectLabor ALIAS FOR $2;
39690   plowerDirectLabor ALIAS FOR $3;
39691   poverhead ALIAS FOR $4;
39692   plowerOverhead ALIAS FOR $5;
39693   pmachOverhead ALIAS FOR $6;
39694   plowerMachOverhead ALIAS FOR $7;
39695   plowerUser ALIAS FOR $8;
39696   prollUp ALIAS FOR $9;
39697
39698 BEGIN
39699   RETURN doUpdateCosts(plowerMaterial, pdirectLabor, plowerDirectLabor,
39700                        poverhead, plowerOverhead, pmachOverhead,
39701                        plowerMachOverhead, plowerUser, prollUp, TRUE);
39702 END;
39703 $_$;
39704
39705
39706 ALTER FUNCTION public.doupdatecosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
39707
39708 --
39709 -- TOC entry 1509 (class 1255 OID 146566073)
39710 -- Dependencies: 4536 8
39711 -- Name: doupdatecosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
39712 --
39713
39714 CREATE FUNCTION doupdatecosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS integer
39715     LANGUAGE plpgsql
39716     AS $_$
39717 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39718 -- See www.xtuple.com/CPAL for the full text of the software license.
39719 DECLARE
39720
39721   plowerMaterial ALIAS FOR $1;
39722   pdirectLabor ALIAS FOR $2;
39723   plowerDirectLabor ALIAS FOR $3;
39724   poverhead ALIAS FOR $4;
39725   plowerOverhead ALIAS FOR $5;
39726   pmachOverhead ALIAS FOR $6;
39727   plowerMachOverhead ALIAS FOR $7;
39728   plowerUser ALIAS FOR $8;
39729   prollUp ALIAS FOR $9;
39730   pActual ALIAS FOR $10;
39731   _item RECORD;
39732   _bom RECORD;
39733   _result INTEGER := 0;
39734
39735 BEGIN
39736
39737   PERFORM resetLowLevelCode(-1);
39738
39739   FOR _item IN SELECT costUpdate_item_id
39740             FROM costUpdate
39741             ORDER BY costUpdate_lowlevel_code DESC LOOP
39742     PERFORM doUpdateCosts(_item.costUpdate_item_id, false, plowerMaterial,
39743                   pdirectLabor, plowerDirectLabor, poverhead, plowerOverhead,
39744                   pmachOverhead, plowerMachOverhead, plowerUser, prollUp,
39745                   pActual);
39746   END LOOP;
39747
39748   RETURN _result;
39749
39750 END;
39751  $_$;
39752
39753
39754 ALTER FUNCTION public.doupdatecosts(boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
39755
39756 --
39757 -- TOC entry 1508 (class 1255 OID 146566072)
39758 -- Dependencies: 4536 8
39759 -- Name: doupdatecosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
39760 --
39761
39762 CREATE FUNCTION doupdatecosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS integer
39763     LANGUAGE plpgsql
39764     AS $_$
39765 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39766 -- See www.xtuple.com/CPAL for the full text of the software license.
39767 DECLARE
39768
39769   pItemId ALIAS FOR $1;
39770   pResetLowLevel ALIAS FOR $2;
39771   plowerMaterial ALIAS FOR $3;
39772   pdirectLabor ALIAS FOR $4;
39773   plowerDirectLabor ALIAS FOR $5;
39774   poverhead ALIAS FOR $6;
39775   plowerOverhead ALIAS FOR $7;
39776   pmachOverhead ALIAS FOR $8;
39777   plowerMachOverhead ALIAS FOR $9;
39778   plowerUser ALIAS FOR $10;
39779   prollUp ALIAS FOR $11;
39780
39781 BEGIN
39782     RETURN doUpdateCosts(pItemId, pResetLowLevel, plowerMaterial, pdirectLabor,
39783                          plowerDirectLabor, poverhead, plowerOverhead,
39784                          pmachOverhead, plowerMachOverhead, plowerUser, prollUp,
39785                          TRUE);
39786 END;
39787 $_$;
39788
39789
39790 ALTER FUNCTION public.doupdatecosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
39791
39792 --
39793 -- TOC entry 1510 (class 1255 OID 146566074)
39794 -- Dependencies: 4536 8
39795 -- Name: doupdatecosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
39796 --
39797
39798 CREATE FUNCTION doupdatecosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) RETURNS integer
39799     LANGUAGE plpgsql
39800     AS $_$
39801 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39802 -- See www.xtuple.com/CPAL for the full text of the software license.
39803 DECLARE
39804
39805   pItemId ALIAS FOR $1;
39806   pResetLowLevel ALIAS FOR $2;
39807   plowerMaterial ALIAS FOR $3;
39808   pdirectLabor ALIAS FOR $4;
39809   plowerDirectLabor ALIAS FOR $5;
39810   poverhead ALIAS FOR $6;
39811   plowerOverhead ALIAS FOR $7;
39812   pmachOverhead ALIAS FOR $8;
39813   plowerMachOverhead ALIAS FOR $9;
39814   plowerUser ALIAS FOR $10;
39815   prollUp ALIAS FOR $11;
39816   pUpdateActual ALIAS FOR $12;
39817   _item RECORD;
39818   _bom RECORD;
39819   _result INTEGER := 0;
39820   _resultFromReset INTEGER;
39821   _counterNum INTEGER;
39822   _feedBackNum INTEGER;
39823
39824 BEGIN
39825
39826     IF (pResetLowLevel) THEN
39827         PERFORM resetLowLevelCode(pItemId);
39828     END IF;
39829
39830     SELECT costUpdate_item_id AS item_id, costUpdate_item_type AS item_type
39831         INTO _item
39832     FROM costUpdate
39833     WHERE costUpdate_item_id = pItemId;
39834
39835     IF ((plowerMaterial) AND ((_item.item_type <> 'P') AND (_item.item_type <> 'O'))) THEN    
39836       PERFORM updateSorACost(_item.item_id, 'Material', TRUE, lowerCost(_item.item_id, 'Material', pUpdateActual), pUpdateActual);
39837     END IF;
39838
39839     IF (pdirectLabor) THEN    
39840       PERFORM updateSorACost(_item.item_id, 'Direct Labor', FALSE, xtmfg.directLaborCost(_item.item_id), pUpdateActual);
39841     END IF;
39842
39843     IF (plowerDirectLabor) THEN    
39844       PERFORM updateSorACost(_item.item_id, 'Direct Labor', TRUE, lowerCost(_item.item_id, 'Direct Labor', pUpdateActual), pUpdateActual);
39845     END IF;
39846
39847     IF (poverhead) THEN    
39848       PERFORM updateSorACost(_item.item_id, 'Overhead', FALSE, xtmfg.overheadCost(_item.item_id), pUpdateActual);
39849     END IF;
39850
39851     IF (plowerOverhead) THEN    
39852       PERFORM updateSorACost(_item.item_id, 'Overhead', TRUE, lowerCost(_item.item_id, 'Overhead', pUpdateActual), pUpdateActual);
39853     END IF;
39854
39855     IF (pmachOverhead) THEN    
39856       PERFORM updateSorACost(_item.item_id, 'Machine Overhead', FALSE, xtmfg.machineOverheadCost(_item.item_id), pUpdateActual);
39857     END IF;
39858
39859     IF (plowerMachOverhead) THEN    
39860       PERFORM updateSorACost(_item.item_id, 'Machine Overhead', TRUE, lowerCost(_item.item_id, 'Machine Overhead', pUpdateActual), pUpdateActual);
39861     END IF;
39862
39863     IF (plowerUser) THEN    
39864       PERFORM updateLowerUserCosts(_item.item_id, pUpdateActual);
39865     END IF;
39866
39867     IF (prollUp) THEN    
39868       PERFORM rollUpSorACost(_item.item_id, pUpdateActual);
39869     END IF;
39870
39871     RETURN _result;
39872
39873 END;
39874  $_$;
39875
39876
39877 ALTER FUNCTION public.doupdatecosts(integer, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean) OWNER TO admin;
39878
39879 --
39880 -- TOC entry 1443 (class 1255 OID 146566075)
39881 -- Dependencies: 4536 8
39882 -- Name: dropifexists(text, text); Type: FUNCTION; Schema: public; Owner: admin
39883 --
39884
39885 CREATE FUNCTION dropifexists(text, text) RETURNS integer
39886     LANGUAGE plpgsql
39887     AS $_$
39888 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39889 -- See www.xtuple.com/CPAL for the full text of the software license.
39890 BEGIN
39891   RETURN dropIfExists($1, $2, 'public');
39892 END;
39893 $_$;
39894
39895
39896 ALTER FUNCTION public.dropifexists(text, text) OWNER TO admin;
39897
39898 --
39899 -- TOC entry 1477 (class 1255 OID 146566076)
39900 -- Dependencies: 4536 8
39901 -- Name: dropifexists(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
39902 --
39903
39904 CREATE FUNCTION dropifexists(text, text, text) RETURNS integer
39905     LANGUAGE plpgsql
39906     AS $_$
39907 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39908 -- See www.xtuple.com/CPAL for the full text of the software license.
39909 BEGIN
39910   RETURN dropIfExists($1, $2, $3, false);
39911 END;
39912 $_$;
39913
39914
39915 ALTER FUNCTION public.dropifexists(text, text, text) OWNER TO admin;
39916
39917 --
39918 -- TOC entry 1511 (class 1255 OID 146566077)
39919 -- Dependencies: 4536 8
39920 -- Name: dropifexists(text, text, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
39921 --
39922
39923 CREATE FUNCTION dropifexists(text, text, text, boolean) RETURNS integer
39924     LANGUAGE plpgsql
39925     AS $_$
39926 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
39927 -- See www.xtuple.com/CPAL for the full text of the software license.
39928 DECLARE
39929   pType         ALIAS FOR $1;
39930   pObject       ALIAS FOR $2;
39931   pSchema       ALIAS FOR $3;
39932   pCascade      ALIAS FOR $4;
39933   _table        TEXT;
39934   _query        TEXT;
39935 BEGIN
39936   IF (UPPER(pType) = 'INDEX') THEN
39937     _query = 'DROP INDEX ' || quote_ident(LOWER(pSchema)) || '.' || quote_ident(LOWER(pObject));
39938     
39939     BEGIN
39940       EXECUTE _query;
39941     EXCEPTION WHEN undefined_object OR invalid_schema_name THEN
39942                 RETURN 0;
39943               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
39944     END;
39945
39946   ELSEIF (UPPER(pType) = 'TABLE') THEN
39947     _query = 'DROP TABLE ' || quote_ident(LOWER(pSchema)) || '.' || quote_ident(LOWER(pObject)); 
39948     
39949     IF (pCascade) THEN
39950       _query = _query || ' CASCADE';
39951     END IF;
39952
39953     BEGIN
39954       EXECUTE _query;
39955     EXCEPTION WHEN undefined_table OR invalid_schema_name THEN
39956                 RETURN 0;
39957               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
39958     END;
39959
39960   ELSIF (UPPER(pType) = 'VIEW') THEN
39961     _query = 'DROP VIEW ' || quote_ident(LOWER(pSchema)) || '.' || quote_ident(LOWER(pObject));
39962
39963     IF (pCascade) THEN
39964       _query = _query || ' CASCADE';
39965     END IF;
39966     
39967     BEGIN
39968       EXECUTE _query;
39969     EXCEPTION WHEN undefined_table OR invalid_schema_name THEN
39970                 RETURN 0;
39971               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
39972     END;
39973
39974   ELSIF (UPPER(pType) = 'TRIGGER') THEN
39975     SELECT relname INTO _table
39976     FROM pg_trigger, pg_class
39977     WHERE ((tgrelid=pg_class.oid)
39978       AND  (UPPER(tgname)=UPPER(pObject)));
39979     IF (NOT FOUND) THEN
39980       _table := '[no table]';
39981     END IF;
39982
39983     _query = 'DROP TRIGGER ' || quote_ident(LOWER(pObject)) ||
39984              ' ON ' || quote_ident(LOWER(pSchema)) || '.' || quote_ident(LOWER(_table));
39985     BEGIN
39986       EXECUTE _query;
39987     EXCEPTION WHEN undefined_object THEN
39988                 RETURN 0;
39989               WHEN undefined_table OR invalid_schema_name THEN
39990                 RETURN 0;
39991               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
39992     END;
39993
39994   ELSIF (UPPER(pType) = 'FUNCTION') THEN
39995     _query = 'DROP FUNCTION ' || (LOWER(pSchema)) || '.' ||
39996                                    (LOWER(pObject));
39997     BEGIN
39998       EXECUTE _query;
39999     EXCEPTION WHEN undefined_object OR undefined_function OR invalid_schema_name THEN
40000                 RETURN 0;
40001               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
40002     END;
40003
40004   ELSIF (UPPER(pType) = 'CONSTRAINT') THEN
40005     IF( (SELECT count(*)
40006            FROM pg_constraint, pg_class, pg_namespace
40007           WHERE((conrelid=pg_class.oid)
40008             AND (connamespace=pg_namespace.oid)
40009             AND (conname=pObject)
40010             AND (nspname=pSchema))
40011          ) > 1 ) THEN
40012       RAISE EXCEPTION 'dropIfExists called on constraint name that matches more than 1 constraint.';
40013     END IF;
40014     SELECT relname INTO _table
40015     FROM pg_constraint, pg_class, pg_namespace
40016     WHERE ((conrelid=pg_class.oid)
40017       AND  (connamespace=pg_namespace.oid)
40018       AND  (conname=pObject)
40019       AND  (nspname=pSchema));
40020     IF (NOT FOUND) THEN
40021       RETURN 0;
40022     END IF;
40023     _query = 'ALTER TABLE ' || quote_ident(LOWER(pSchema)) || '.' || quote_ident(LOWER(_table))
40024              || ' DROP CONSTRAINT ' || quote_ident(LOWER(pObject));
40025     BEGIN
40026       EXECUTE _query;
40027     EXCEPTION WHEN undefined_table OR invalid_schema_name THEN
40028                 RETURN 0;
40029               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
40030     END;
40031
40032   ELSIF (UPPER(pType) = 'SCHEMA') THEN
40033     _query = 'DROP SCHEMA ' || quote_ident(LOWER(pObject));
40034     BEGIN
40035       EXECUTE _query;
40036     EXCEPTION WHEN invalid_schema_name THEN
40037                 RETURN 0;
40038               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
40039     END;
40040
40041   ELSIF (UPPER(pType) = 'TYPE') THEN
40042     _query = 'DROP TYPE ' || quote_ident(LOWER(pSchema)) || '.' ||
40043                                quote_ident(LOWER(pObject));
40044     IF (pCascade) THEN
40045       _query = _query || ' CASCADE';
40046     END IF;
40047     
40048     BEGIN
40049       EXECUTE _query;
40050     EXCEPTION WHEN undefined_object OR invalid_schema_name THEN
40051                 RETURN 0;
40052               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
40053     END;
40054
40055   ELSE
40056     RAISE EXCEPTION 'dropIfExists(%, %): unknown pType %', pType, pObject, pType;
40057   END IF;
40058
40059   RETURN 1;
40060
40061 END;
40062 $_$;
40063
40064
40065 ALTER FUNCTION public.dropifexists(text, text, text, boolean) OWNER TO admin;
40066
40067 --
40068 -- TOC entry 1512 (class 1255 OID 146566078)
40069 -- Dependencies: 4536 8
40070 -- Name: dropifexists(text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
40071 --
40072
40073 CREATE FUNCTION dropifexists(text, text, text, text) RETURNS integer
40074     LANGUAGE plpgsql
40075     AS $_$
40076 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40077 -- See www.xtuple.com/CPAL for the full text of the software license.
40078 DECLARE
40079   pType         ALIAS FOR $1;
40080   pObject       ALIAS FOR $2;
40081   pSchema       ALIAS FOR $3;
40082   pRelation     ALIAS FOR $4;
40083   _table        TEXT;
40084   _query        TEXT;
40085 BEGIN
40086   IF (UPPER(pType) = 'CONSTRAINT') THEN
40087     SELECT relname INTO _table
40088     FROM pg_constraint, pg_class, pg_namespace
40089     WHERE ((conrelid=pg_class.oid)
40090       AND  (connamespace=pg_namespace.oid)
40091       AND  (conname=pObject)
40092       AND  (relname=pRelation)
40093       AND  (nspname=pSchema));
40094     IF (NOT FOUND) THEN
40095       RETURN 0;
40096     END IF;
40097     _query = 'ALTER TABLE ' || quote_ident(LOWER(pSchema)) || '.' || quote_ident(LOWER(pRelation))
40098              || ' DROP CONSTRAINT ' || quote_ident(LOWER(pObject));
40099     BEGIN
40100       EXECUTE _query;
40101     EXCEPTION WHEN undefined_table OR invalid_schema_name THEN
40102                 RETURN 0;
40103               WHEN OTHERS THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
40104     END;
40105
40106   ELSE
40107     RAISE EXCEPTION 'dropIfExists(%, %, %, %): pType % is not supported when relation is specified', pType, pObject, pSchema, pRelation, pType;
40108   END IF;
40109
40110   RETURN 1;
40111 END;
40112 $_$;
40113
40114
40115 ALTER FUNCTION public.dropifexists(text, text, text, text) OWNER TO admin;
40116
40117 --
40118 -- TOC entry 1513 (class 1255 OID 146566079)
40119 -- Dependencies: 4536 8
40120 -- Name: dropstdopntable(); Type: FUNCTION; Schema: public; Owner: admin
40121 --
40122
40123 CREATE FUNCTION dropstdopntable() RETURNS boolean
40124     LANGUAGE plpgsql
40125     AS $$
40126 BEGIN
40127   IF((SELECT metric_value != 'Manufacturing' FROM metric WHERE metric_name = 'Application')) THEN
40128     PERFORM dropIfExists('TABLE', 'stdopn');
40129     RETURN true;
40130   END IF;
40131   RETURN false;
40132 END;
40133 $$;
40134
40135
40136 ALTER FUNCTION public.dropstdopntable() OWNER TO admin;
40137
40138 --
40139 -- TOC entry 1514 (class 1255 OID 146566080)
40140 -- Dependencies: 4536 8
40141 -- Name: editccnumber(text, text); Type: FUNCTION; Schema: public; Owner: admin
40142 --
40143
40144 CREATE FUNCTION editccnumber(text, text) RETURNS text
40145     LANGUAGE plpgsql
40146     AS $_$
40147 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40148 -- See www.xtuple.com/CPAL for the full text of the software license.
40149 DECLARE
40150   pCcardnum ALIAS FOR $1;
40151   pCcardtype ALIAS FOR $2;
40152   card_length INTEGER;
40153   card_valid boolean := false;
40154   starting_digits TEXT;
40155   _sum INTEGER := 0;
40156   _digit INTEGER := 0;
40157   _timesTwo BOOLEAN := false;
40158 BEGIN
40159
40160 -- Check the card type
40161   IF (pCcardtype NOT IN ('M', 'V', 'A', 'D')) THEN
40162 -- Unknown Card Type
40163    RETURN -1;
40164   END IF;
40165
40166   card_length := length(pCcardnum);
40167
40168 -- Process Master Card Checking length
40169 -- Process Master Card Starting digits
40170   IF (pCcardtype = 'M') THEN
40171     IF (card_length != 16) THEN
40172 -- Bad Card Length Card Type
40173       RETURN -2;
40174     END IF;
40175     starting_digits := substr(pCcardnum, 1, 2);
40176     IF (starting_digits < '51' OR starting_digits > '55') THEN
40177 -- Bad Starting digits
40178       RETURN -6;
40179     END IF;
40180   END IF;
40181
40182 -- Process Visa Card Checking length
40183 -- Process Visa Card Starting digits
40184   IF (pCcardtype = 'V') THEN
40185     IF (card_length != 13 AND card_length != 16) THEN
40186 -- Bad Card Length Card Type
40187       RETURN -3;
40188     END IF;
40189     starting_digits := substr(pCcardnum, 1, 1);
40190     IF (starting_digits != '4') THEN
40191 -- Bad Starting digits
40192       RETURN -7;
40193     END IF;
40194   END IF;
40195
40196 -- Process American Express Card Checking length
40197 -- Process American Express Card Starting digits
40198   IF (pCcardtype = 'A') THEN
40199     IF (card_length != 15) THEN
40200 -- Bad Card Length Card Type
40201       RETURN -4;
40202     END IF;
40203     starting_digits := substr(pCcardnum, 1, 2);
40204     IF (starting_digits != '34' AND starting_digits != '37') THEN
40205 -- Bad Starting digits
40206       RETURN -8;
40207     END IF;
40208   END IF;
40209
40210 -- Process Discover Card Checking length
40211 -- Process Discover Card Starting digits
40212   IF (pCcardtype = 'D') THEN
40213     IF (card_length != 16) THEN
40214 -- Bad Card Length Card Type
40215       RETURN -5;
40216     END IF;
40217     starting_digits := substr(pCcardnum, 1, 4);
40218     IF (starting_digits != '6011') THEN
40219 -- Bad Starting digits
40220       RETURN -9;
40221     END IF;
40222   END IF;
40223
40224 -- Now comes the fun part of doing the "check" for the check sum
40225 -- perform a luhn checksum
40226   FOR i IN REVERSE card_length .. 1 LOOP
40227     _digit := int4(substr(pCcardnum, i, 1));
40228     IF (_timesTwo) THEN
40229       _digit := _digit * 2;
40230       IF (_digit > 9) THEN
40231         _digit := _digit - 9;
40232       END IF;
40233     END IF;
40234     _sum := _sum + _digit;
40235     _timesTwo := NOT _timesTwo;
40236   END LOOP;
40237
40238   IF (mod(_sum, 10) != 0) THEN
40239     RETURN -10;
40240   END IF;
40241
40242   RETURN 0; -- No Error
40243
40244 END;
40245 $_$;
40246
40247
40248 ALTER FUNCTION public.editccnumber(text, text) OWNER TO admin;
40249
40250 --
40251 -- TOC entry 1515 (class 1255 OID 146566081)
40252 -- Dependencies: 4536 8
40253 -- Name: enablepackage(text); Type: FUNCTION; Schema: public; Owner: admin
40254 --
40255
40256 CREATE FUNCTION enablepackage(text) RETURNS integer
40257     LANGUAGE plpgsql
40258     AS $_$
40259 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40260 -- See www.xtuple.com/CPAL for the full text of the software license.
40261 DECLARE
40262   ppkgname  ALIAS FOR $1;
40263   _i        INTEGER := 0;
40264   _tabs     TEXT[] := ARRAY['cmd',  'cmdarg', 'image',  'metasql',
40265                             'priv', 'report', 'script', 'uiform'];
40266
40267 BEGIN
40268   IF (version() < 'PostgreSQL 8.2') THEN
40269     RETURN -1;
40270   END IF;
40271
40272   FOR _i IN ARRAY_LOWER(_tabs,1)..ARRAY_UPPER(_tabs,1) LOOP
40273     EXECUTE 'ALTER TABLE ' || ppkgname || '.pkg' || _tabs[_i] ||
40274             ' INHERIT public.' || _tabs[_i] || ';';
40275   END LOOP;
40276
40277   RETURN 0;
40278 END;
40279 $_$;
40280
40281
40282 ALTER FUNCTION public.enablepackage(text) OWNER TO admin;
40283
40284 --
40285 -- TOC entry 1516 (class 1255 OID 146566082)
40286 -- Dependencies: 4536 8
40287 -- Name: enablepackage(integer); Type: FUNCTION; Schema: public; Owner: admin
40288 --
40289
40290 CREATE FUNCTION enablepackage(integer) RETURNS integer
40291     LANGUAGE plpgsql
40292     AS $_$
40293 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40294 -- See www.xtuple.com/CPAL for the full text of the software license.
40295 DECLARE
40296   ppkgheadid    ALIAS FOR $1;
40297   _pkgname      TEXT;
40298
40299 BEGIN
40300   SELECT pkghead_name INTO _pkgname
40301   FROM pkghead
40302   WHERE (pkghead_id=ppkgheadid);
40303   IF (NOT FOUND) THEN
40304     RETURN -2;
40305   END IF;
40306
40307   RETURN enablePackage(_pkgname);
40308 END;
40309 $_$;
40310
40311
40312 ALTER FUNCTION public.enablepackage(integer) OWNER TO admin;
40313
40314 --
40315 -- TOC entry 1517 (class 1255 OID 146566083)
40316 -- Dependencies: 8
40317 -- Name: encrypt(bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
40318 --
40319
40320 CREATE FUNCTION encrypt(bytea, bytea, text) RETURNS bytea
40321     LANGUAGE c IMMUTABLE STRICT
40322     AS '$libdir/pgcrypto', 'pg_encrypt';
40323
40324
40325 ALTER FUNCTION public.encrypt(bytea, bytea, text) OWNER TO admin;
40326
40327 --
40328 -- TOC entry 1518 (class 1255 OID 146566084)
40329 -- Dependencies: 8
40330 -- Name: encrypt_iv(bytea, bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
40331 --
40332
40333 CREATE FUNCTION encrypt_iv(bytea, bytea, bytea, text) RETURNS bytea
40334     LANGUAGE c IMMUTABLE STRICT
40335     AS '$libdir/pgcrypto', 'pg_encrypt_iv';
40336
40337
40338 ALTER FUNCTION public.encrypt_iv(bytea, bytea, bytea, text) OWNER TO admin;
40339
40340 --
40341 -- TOC entry 1519 (class 1255 OID 146566085)
40342 -- Dependencies: 8
40343 -- Name: endoftime(); Type: FUNCTION; Schema: public; Owner: admin
40344 --
40345
40346 CREATE FUNCTION endoftime() RETURNS date
40347     LANGUAGE sql IMMUTABLE
40348     AS $$
40349 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40350 -- See www.xtuple.com/CPAL for the full text of the software license.
40351 SELECT DATE('2100-01-01') as result;
40352 $$;
40353
40354
40355 ALTER FUNCTION public.endoftime() OWNER TO admin;
40356
40357 --
40358 -- TOC entry 1520 (class 1255 OID 146566086)
40359 -- Dependencies: 4536 8
40360 -- Name: entercount(integer, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
40361 --
40362
40363 CREATE FUNCTION entercount(integer, numeric, text) RETURNS integer
40364     LANGUAGE plpgsql
40365     AS $_$
40366 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40367 -- See www.xtuple.com/CPAL for the full text of the software license.
40368 DECLARE
40369   pInvcntid ALIAS FOR $1;
40370   pQty ALIAS FOR $2;
40371   pComments ALIAS FOR $3;
40372 BEGIN
40373
40374   UPDATE invcnt
40375   SET invcnt_qoh_after = pQty,
40376       invcnt_comments = CASE WHEN ( (LENGTH(invcnt_comments) = 0) AND
40377                                     (LENGTH(pComments) > 0) ) THEN pComments
40378                              WHEN (LENGTH(pComments) > 0) THEN (invcnt_comments || E'\n' || pComments)
40379                              ELSE invcnt_comments
40380                         END,
40381       invcnt_cntdate = CURRENT_TIMESTAMP,
40382       invcnt_cnt_username = getEffectiveXtUser()
40383   WHERE (invcnt_id=pInvcntid);
40384
40385   RETURN 0;
40386 END;
40387 $_$;
40388
40389
40390 ALTER FUNCTION public.entercount(integer, numeric, text) OWNER TO admin;
40391
40392 --
40393 -- TOC entry 1521 (class 1255 OID 146566087)
40394 -- Dependencies: 4536 8
40395 -- Name: enterporeceipt(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
40396 --
40397
40398 CREATE FUNCTION enterporeceipt(integer, numeric) RETURNS integer
40399     LANGUAGE plpgsql
40400     AS $_$
40401 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40402 -- See www.xtuple.com/CPAL for the full text of the software license.
40403 BEGIN
40404   RETURN enterReceipt('PO', $1, $2, 0.0, '', NULL, NULL);
40405 END;
40406 $_$;
40407
40408
40409 ALTER FUNCTION public.enterporeceipt(integer, numeric) OWNER TO admin;
40410
40411 --
40412 -- TOC entry 1522 (class 1255 OID 146566088)
40413 -- Dependencies: 4536 8
40414 -- Name: enterporeceipt(integer, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
40415 --
40416
40417 CREATE FUNCTION enterporeceipt(integer, numeric, text) RETURNS integer
40418     LANGUAGE plpgsql
40419     AS $_$
40420 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40421 -- See www.xtuple.com/CPAL for the full text of the software license.
40422 BEGIN
40423   RETURN enterPoReceipt('PO', $1, $2, 0.0, $3, NULL, NULL);
40424 END;
40425 $_$;
40426
40427
40428 ALTER FUNCTION public.enterporeceipt(integer, numeric, text) OWNER TO admin;
40429
40430 --
40431 -- TOC entry 1489 (class 1255 OID 146566089)
40432 -- Dependencies: 4536 8
40433 -- Name: enterporeceipt(integer, numeric, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
40434 --
40435
40436 CREATE FUNCTION enterporeceipt(integer, numeric, numeric, text) RETURNS integer
40437     LANGUAGE plpgsql
40438     AS $_$
40439 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40440 -- See www.xtuple.com/CPAL for the full text of the software license.
40441 BEGIN
40442   RETURN enterPoReceipt('PO', $1, $2, $3, $4, NULL, NULL);
40443 END;
40444 $_$;
40445
40446
40447 ALTER FUNCTION public.enterporeceipt(integer, numeric, numeric, text) OWNER TO admin;
40448
40449 --
40450 -- TOC entry 1490 (class 1255 OID 146566090)
40451 -- Dependencies: 4536 8
40452 -- Name: enterporeceipt(integer, numeric, numeric, text, integer, date); Type: FUNCTION; Schema: public; Owner: admin
40453 --
40454
40455 CREATE FUNCTION enterporeceipt(integer, numeric, numeric, text, integer, date) RETURNS integer
40456     LANGUAGE plpgsql
40457     AS $_$
40458 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40459 -- See www.xtuple.com/CPAL for the full text of the software license.
40460 BEGIN
40461   RETURN enterReceipt('PO', $1, $2, $3, $4, $5, $6);
40462 END;
40463 $_$;
40464
40465
40466 ALTER FUNCTION public.enterporeceipt(integer, numeric, numeric, text, integer, date) OWNER TO admin;
40467
40468 --
40469 -- TOC entry 1503 (class 1255 OID 146566091)
40470 -- Dependencies: 4536 8
40471 -- Name: enterporeturn(integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
40472 --
40473
40474 CREATE FUNCTION enterporeturn(integer, numeric, integer) RETURNS integer
40475     LANGUAGE plpgsql
40476     AS $_$
40477 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40478 -- See www.xtuple.com/CPAL for the full text of the software license.
40479 BEGIN
40480   RETURN enterPoReturn($1, $2, $3, NULL);
40481 END;
40482 $_$;
40483
40484
40485 ALTER FUNCTION public.enterporeturn(integer, numeric, integer) OWNER TO admin;
40486
40487 --
40488 -- TOC entry 1523 (class 1255 OID 146566092)
40489 -- Dependencies: 4536 8
40490 -- Name: enterporeturn(integer, numeric, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
40491 --
40492
40493 CREATE FUNCTION enterporeturn(integer, numeric, integer, integer) RETURNS integer
40494     LANGUAGE plpgsql
40495     AS $_$
40496 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40497 -- See www.xtuple.com/CPAL for the full text of the software license.
40498 DECLARE
40499   pPoitemid ALIAS FOR $1;
40500   pQty ALIAS FOR $2;
40501   pRjctcodeid ALIAS FOR $3;
40502   pRecvid ALIAS FOR $4;
40503   _porejectid INTEGER;
40504
40505 BEGIN
40506
40507   SELECT NEXTVAL('poreject_poreject_id_seq') INTO _porejectid;
40508
40509   INSERT INTO poreject
40510   ( poreject_id, poreject_date, poreject_ponumber, poreject_poitem_id, poreject_trans_username,
40511     poreject_agent_username, poreject_itemsite_id,
40512     poreject_vend_id, poreject_vend_item_number, poreject_vend_item_descrip, poreject_vend_uom,
40513     poreject_qty, poreject_rjctcode_id, poreject_posted, poreject_invoiced, poreject_recv_id )
40514   SELECT _porejectid, CURRENT_TIMESTAMP, pohead_number, poitem_id, getEffectiveXtUser(),
40515          pohead_agent_username, poitem_itemsite_id,
40516          pohead_vend_id, poitem_vend_item_number, poitem_vend_item_descrip, poitem_vend_uom,
40517          pQty, pRjctcodeid, FALSE, FALSE, pRecvid
40518   FROM poitem JOIN pohead ON (pohead_id=poitem_pohead_id)
40519   WHERE (poitem_id=pPoitemid);
40520
40521   RETURN _porejectid;
40522
40523 END;
40524 $_$;
40525
40526
40527 ALTER FUNCTION public.enterporeturn(integer, numeric, integer, integer) OWNER TO admin;
40528
40529 --
40530 -- TOC entry 1524 (class 1255 OID 146566093)
40531 -- Dependencies: 4536 8
40532 -- Name: enterreceipt(text, integer, numeric, numeric, text, integer, date); Type: FUNCTION; Schema: public; Owner: admin
40533 --
40534
40535 CREATE FUNCTION enterreceipt(text, integer, numeric, numeric, text, integer, date) RETURNS integer
40536     LANGUAGE plpgsql
40537     AS $_$
40538 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40539 -- See www.xtuple.com/CPAL for the full text of the software license.
40540 BEGIN
40541   RETURN enterReceipt($1, $2, $3, $4, $5, $6, $7, NULL);
40542 END;
40543 $_$;
40544
40545
40546 ALTER FUNCTION public.enterreceipt(text, integer, numeric, numeric, text, integer, date) OWNER TO admin;
40547
40548 --
40549 -- TOC entry 1525 (class 1255 OID 146566094)
40550 -- Dependencies: 4536 8
40551 -- Name: enterreceipt(text, integer, numeric, numeric, text, integer, date, numeric); Type: FUNCTION; Schema: public; Owner: admin
40552 --
40553
40554 CREATE FUNCTION enterreceipt(text, integer, numeric, numeric, text, integer, date, numeric) RETURNS integer
40555     LANGUAGE plpgsql
40556     AS $_$
40557 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40558 -- See www.xtuple.com/CPAL for the full text of the software license.
40559 DECLARE
40560   pordertype    ALIAS FOR $1;
40561   porderitemid  ALIAS FOR $2;
40562   pQty          ALIAS FOR $3;
40563   pFreight      ALIAS FOR $4;
40564   pNotes        ALIAS FOR $5;
40565   pcurrid       ALIAS FOR $6;   -- NULL is handled by SELECT ... INTO _o
40566   precvdate     ALIAS FOR $7;   -- NULL is handled by INSERT INTO recv
40567   pRecvCost     ALIAS FOR $8;
40568   _timestamp    TIMESTAMP;
40569   _o            RECORD;
40570   _recvid       INTEGER;
40571   _warehouseid  INTEGER;
40572   _recvcost     NUMERIC;
40573
40574 BEGIN
40575   IF(precvdate IS NULL OR precvdate = CURRENT_DATE) THEN
40576     _timestamp := CURRENT_TIMESTAMP;
40577   ELSE
40578     _timestamp := precvdate;
40579   END IF;
40580   SELECT NEXTVAL('recv_recv_id_seq') INTO _recvid;
40581
40582   DELETE FROM recv
40583   WHERE ((NOT recv_posted)
40584     AND  (recv_order_type=pordertype)
40585     AND  (recv_orderitem_id=porderitemid) );
40586
40587   IF (pQty > 0) THEN
40588     IF (pordertype='PO') THEN
40589       SELECT pohead_number AS orderhead_number,
40590            poitem_id AS orderitem_id,
40591            pohead_agent_username AS orderhead_agent_username,
40592            CASE WHEN (poitem_itemsite_id = -1) THEN NULL
40593                 ELSE poitem_itemsite_id
40594            END AS itemsite_id,
40595            vend_id,
40596            COALESCE(poitem_vend_item_number, '') AS vend_item_number,
40597            COALESCE(poitem_vend_item_descrip, '') AS vend_item_descrip,
40598            COALESCE(poitem_vend_uom, '') AS vend_uom,
40599            poitem_duedate AS duedate,
40600            poitem_unitprice AS orderitem_unitcost,
40601            pohead_curr_id AS orderitem_unitcost_curr_id,
40602            pohead_curr_id AS freight_curr_id,
40603            poitem_rlsd_duedate AS rlsd_duedate INTO _o
40604         FROM pohead
40605           JOIN poitem ON (pohead_id=poitem_pohead_id)
40606           JOIN vendinfo ON (pohead_vend_id=vend_id)
40607         WHERE (poitem_id=porderitemid);
40608         
40609     ELSIF (pordertype='RA') THEN
40610        SELECT rahead_number AS orderhead_number,
40611            raitem_id AS orderitem_id,
40612            ''::text AS orderhead_agent_username,
40613            raitem_itemsite_id AS itemsite_id,
40614            NULL::integer AS vend_id,
40615            ''::text AS vend_item_number,
40616            ''::text AS vend_item_descrip,
40617            ''::text AS vend_uom,
40618            raitem_scheddate AS duedate,
40619            raitem_unitprice AS orderitem_unitcost,
40620            rahead_curr_id AS orderitem_unitcost_curr_id,
40621            rahead_curr_id AS freight_curr_id,
40622            raitem_scheddate AS rlsd_duedate INTO _o
40623         FROM rahead
40624           JOIN raitem ON (rahead_id=raitem_rahead_id)
40625         WHERE (raitem_id=porderitemid);
40626         
40627     ELSIF (pordertype='TO') THEN
40628          SELECT tohead_number AS orderhead_number,
40629            toitem_id AS orderitem_id,
40630            tohead_agent_username AS orderhead_agent_username,
40631            itemsite_id,
40632            NULL::integer AS vend_id,
40633            ''::text AS vend_item_number,
40634            ''::text AS vend_item_descrip,
40635            ''::text AS vend_uom,
40636            toitem_duedate AS duedate,
40637            toitem_stdcost AS orderitem_unitcost,
40638            baseCurrId() AS orderitem_unitcost_curr_id,
40639            toitem_freight_curr_id AS freight_curr_id,
40640            toitem_duedate AS rlsd_duedate INTO _o
40641         FROM itemsite, tohead
40642           JOIN toitem ON (tohead_id=toitem_tohead_id)
40643         WHERE ((toitem_id=porderitemid)
40644           AND  (tohead_dest_warehous_id=itemsite_warehous_id)
40645           AND  (toitem_item_id=itemsite_item_id));
40646     END IF;
40647
40648     --Make sure user has site privileges
40649      IF ((FOUND) AND (_o.itemsite_id IS NOT NULL)) THEN
40650        SELECT warehous_id INTO _warehouseid
40651        FROM itemsite,site()
40652        WHERE ((itemsite_id=_o.itemsite_id)
40653          AND (warehous_id=itemsite_warehous_id));
40654           
40655        IF (NOT FOUND) THEN
40656          RETURN 0;
40657         END IF;
40658       END IF;   
40659
40660     --Make sure we aren't trying to receive a Kit
40661     IF ((FOUND) AND (_o.itemsite_id IS NOT NULL)) THEN
40662       IF (SELECT (item_type='K')
40663           FROM itemsite, item
40664           WHERE ((itemsite_id=_o.itemsite_id)
40665             AND  (item_id=itemsite_item_id))) THEN
40666         RETURN 0;
40667       END IF;
40668     END IF;   
40669
40670     IF (NOT FOUND) THEN
40671       RETURN -1;
40672     END IF;
40673
40674     -- default to orderitem_unitcost if recv_purchcost is not specified
40675     IF(pRecvCost IS NULL) THEN
40676       _recvcost := _o.orderitem_unitcost;
40677     ELSE
40678       _recvcost := pRecvCost;
40679     END IF;
40680
40681     INSERT INTO recv
40682     ( recv_id, recv_date,
40683       recv_order_number, recv_order_type, recv_orderitem_id,
40684       recv_trans_usr_name, recv_agent_username, recv_itemsite_id,
40685       recv_vend_id, recv_vend_item_number, recv_vend_item_descrip,
40686       recv_vend_uom, recv_qty, recv_duedate,
40687       recv_purchcost, recv_purchcost_curr_id,
40688       recv_notes, recv_freight, recv_freight_curr_id, recv_rlsd_duedate
40689     ) VALUES (
40690       _recvid, _timestamp,
40691       _o.orderhead_number, pordertype, _o.orderitem_id::INTEGER,
40692       getEffectiveXtUser(), _o.orderhead_agent_username, _o.itemsite_id::INTEGER,
40693       _o.vend_id::INTEGER, _o.vend_item_number, _o.vend_item_descrip,
40694       _o.vend_uom, pQty, _o.duedate,
40695       _recvcost, _o.orderitem_unitcost_curr_id::INTEGER,
40696       pNotes, pFreight, _o.freight_curr_id::INTEGER, _o.rlsd_duedate);
40697   END IF;
40698
40699   RETURN _recvid;
40700
40701 END;
40702 $_$;
40703
40704
40705 ALTER FUNCTION public.enterreceipt(text, integer, numeric, numeric, text, integer, date, numeric) OWNER TO admin;
40706
40707 --
40708 -- TOC entry 1526 (class 1255 OID 146566095)
40709 -- Dependencies: 4536 8
40710 -- Name: expirecreditcard(integer, bytea); Type: FUNCTION; Schema: public; Owner: admin
40711 --
40712
40713 CREATE FUNCTION expirecreditcard(integer, bytea) RETURNS text
40714     LANGUAGE plpgsql
40715     AS $_$
40716 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40717 -- See www.xtuple.com/CPAL for the full text of the software license.
40718 DECLARE
40719   pCust ALIAS FOR $1;
40720   pKey ALIAS FOR $2;
40721   num_updated INTEGER;
40722   cc_year INTEGER;
40723   cc_month INTEGER;
40724   cc_year_t TEXT;
40725   cc_month_t TEXT;
40726   _dr RECORD;
40727   _cc RECORD;
40728   bf TEXT;
40729
40730 BEGIN
40731
40732   num_updated := 0;
40733   bf := 'bf';
40734
40735   select cast(date_part('year', CURRENT_DATE) AS INTEGER) AS check_year, cast(date_part('month', CURRENT_DATE) AS INTEGER) AS check_month INTO _dr;
40736
40737   FOR _cc IN SELECT ccard_id, 
40738                     decrypt(setbytea(ccard_month_expired), setbytea(pKey), 'bf') AS ccard_month_expired,
40739                     decrypt(setbytea(ccard_year_expired), setbytea(pKey), 'bf') AS ccard_year_expired
40740       FROM ccard
40741       WHERE ( (ccard_cust_id=pCust)
40742         AND   (ccard_active) ) LOOP
40743
40744       SELECT formatbytea(_cc.ccard_month_expired) INTO cc_month_t;
40745       SELECT formatbytea(_cc.ccard_year_expired) INTO cc_year_t;
40746       SELECT cast(cc_month_t AS INTEGER) INTO cc_month;
40747       SELECT cast(cc_year_t AS INTEGER) INTO cc_year;
40748
40749       IF (cc_year < _dr.check_year) THEN
40750 --  We have an expired card
40751         UPDATE ccard set ccard_active = FALSE where ccard_id = _cc.ccard_id;
40752         num_updated := num_updated + 1;
40753       ELSIF (cc_year = _dr.check_year AND cc_month < _dr.check_month) THEN
40754 --  We have an expired card
40755         UPDATE ccard set ccard_active = FALSE where ccard_id = _cc.ccard_id;
40756         num_updated := num_updated + 1;
40757       END IF;
40758
40759   END LOOP;
40760
40761   RETURN num_updated;
40762
40763 END;
40764 $_$;
40765
40766
40767 ALTER FUNCTION public.expirecreditcard(integer, bytea) OWNER TO admin;
40768
40769 --
40770 -- TOC entry 1527 (class 1255 OID 146566096)
40771 -- Dependencies: 4536 8
40772 -- Name: explodebom(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
40773 --
40774
40775 CREATE FUNCTION explodebom(integer, integer, integer) RETURNS integer
40776     LANGUAGE plpgsql
40777     AS $_$
40778 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40779 -- See www.xtuple.com/CPAL for the full text of the software license.
40780 DECLARE
40781   pItemid ALIAS FOR $1;
40782   pParentid ALIAS FOR $2;
40783   pLevel ALIAS FOR $3;
40784   _revid INTEGER;
40785
40786 BEGIN
40787
40788   SELECT getActiveRevId('BOM',pItemid) INTO _revid;
40789
40790   RETURN explodeBOM(pItemid, _revid, pParentid, pLevel);
40791
40792 END;
40793 $_$;
40794
40795
40796 ALTER FUNCTION public.explodebom(integer, integer, integer) OWNER TO admin;
40797
40798 --
40799 -- TOC entry 1528 (class 1255 OID 146566097)
40800 -- Dependencies: 4536 8
40801 -- Name: explodebom(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
40802 --
40803
40804 CREATE FUNCTION explodebom(integer, integer, integer, integer) RETURNS integer
40805     LANGUAGE plpgsql
40806     AS $_$
40807 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40808 -- See www.xtuple.com/CPAL for the full text of the software license.
40809 DECLARE
40810   pItemid ALIAS FOR $1;
40811   pRevisionid ALIAS FOR $2;
40812   pParentid ALIAS FOR $3;
40813   pLevel ALIAS FOR $4;
40814   _bomworkid INTEGER;
40815   _level INTEGER;
40816   _p RECORD;
40817   _r RECORD;
40818   _temp TEXT;
40819
40820 BEGIN
40821
40822   _level := (pLevel + 1);
40823
40824 --  Cache some parameters about the parent
40825   SELECT bomwork_item_id, bomwork_set_id, bomwork_qtyreq,
40826          bomwork_seqnumber, bomwork_effective, bomwork_expires INTO _p
40827   FROM bomwork
40828   WHERE (bomwork_id=pParentid);
40829
40830 --  Step through all of the components of the parent component
40831   FOR _r IN SELECT bomitem.*,
40832                    item_id,
40833                    (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyfxd) AS qtyfxd,
40834                    (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyper) AS qtyper,
40835                    CASE WHEN (_p.bomwork_effective > bomitem_effective) THEN _p.bomwork_effective
40836                         ELSE bomitem_effective
40837                    END AS effective,
40838                    CASE WHEN (_p.bomwork_expires < bomitem_expires) THEN _p.bomwork_expires
40839                         ELSE bomitem_expires
40840                    END AS expires,
40841                    stdcost(item_id, bomitem_id) AS standardcost, actcost(item_id, bomitem_id) AS actualcost
40842   FROM bomitem(pItemid, pRevisionid), item
40843   WHERE ( (bomitem_item_id=item_id)
40844   AND (bomitem_expires > _p.bomwork_effective) ) LOOP
40845
40846 --  Insert the current component and some bomitem parameters into the bomwork set
40847     SELECT NEXTVAL('bomwork_bomwork_id_seq') INTO _bomworkid;
40848     INSERT INTO bomwork
40849     ( bomwork_id, bomwork_set_id, bomwork_parent_id, bomwork_level,
40850       bomwork_parent_seqnumber, bomwork_seqnumber,
40851       bomwork_item_id, bomwork_createwo, bomwork_qtyreq,
40852       bomwork_qtyfxd, bomwork_qtyper, bomwork_scrap, bomwork_issuemethod,
40853       bomwork_effective, bomwork_expires,
40854       bomwork_stdunitcost, bomwork_actunitcost, 
40855       bomwork_notes, bomwork_ref,
40856       bomwork_bomitem_id, bomwork_ecn )
40857     VALUES
40858     ( _bomworkid, _p.bomwork_set_id, pParentid, _level,
40859       _p.bomwork_seqnumber, _r.bomitem_seqnumber,
40860       _r.item_id, _r.bomitem_createwo, (_p.bomwork_qtyreq * _r.qtyper + _r.qtyfxd),
40861       _r.qtyfxd, _r.qtyper, _r.bomitem_scrap, _r.bomitem_issuemethod,
40862       _r.effective, _r.expires,
40863       _r.standardcost, _r.actualcost,
40864       _r.bomitem_notes, _r.bomitem_ref,
40865       _r.bomitem_id, _r.bomitem_ecn );
40866
40867 --  Recursively repeat for this component's components
40868     PERFORM explodeBOM(_r.item_id, _bomworkid, _level);
40869   END LOOP;
40870
40871   RETURN 1;
40872
40873 END;
40874 $_$;
40875
40876
40877 ALTER FUNCTION public.explodebom(integer, integer, integer, integer) OWNER TO admin;
40878
40879 --
40880 -- TOC entry 1529 (class 1255 OID 146566098)
40881 -- Dependencies: 4536 8
40882 -- Name: explodekit(integer, integer, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
40883 --
40884
40885 CREATE FUNCTION explodekit(integer, integer, integer, integer, numeric) RETURNS integer
40886     LANGUAGE plpgsql
40887     AS $_$
40888 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40889 -- See www.xtuple.com/CPAL for the full text of the software license.
40890 DECLARE
40891   pSoheadid ALIAS FOR $1;
40892   pLinenumber ALIAS FOR $2;
40893   pSubnumber ALIAS FOR $3;
40894   pItemsiteid ALIAS FOR $4;
40895   pQty ALIAS FOR $5;
40896 BEGIN
40897   RETURN explodeKit(pSoheadid, pLinenumber, pSubnumber, pItemsiteid, pQty, CURRENT_DATE, NULL);
40898 END;
40899 $_$;
40900
40901
40902 ALTER FUNCTION public.explodekit(integer, integer, integer, integer, numeric) OWNER TO admin;
40903
40904 --
40905 -- TOC entry 1434 (class 1255 OID 146566099)
40906 -- Dependencies: 4536 8
40907 -- Name: explodekit(integer, integer, integer, integer, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
40908 --
40909
40910 CREATE FUNCTION explodekit(integer, integer, integer, integer, numeric, date, date) RETURNS integer
40911     LANGUAGE plpgsql
40912     AS $_$
40913 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40914 -- See www.xtuple.com/CPAL for the full text of the software license.
40915 DECLARE
40916   pSoheadid ALIAS FOR $1;
40917   pLinenumber ALIAS FOR $2;
40918   pSubnumber ALIAS FOR $3;
40919   pItemsiteid ALIAS FOR $4;
40920   pQty ALIAS FOR $5;
40921   pScheddate ALIAS FOR $6;
40922   pPromdate ALIAS FOR $7;
40923 BEGIN
40924   RETURN explodeKit(pSoheadid, pLinenumber, pSubnumber, pItemsiteid, pQty, CURRENT_DATE, NULL, '');
40925 END;
40926 $_$;
40927
40928
40929 ALTER FUNCTION public.explodekit(integer, integer, integer, integer, numeric, date, date) OWNER TO admin;
40930
40931 --
40932 -- TOC entry 1454 (class 1255 OID 146566100)
40933 -- Dependencies: 4536 8
40934 -- Name: explodekit(integer, integer, integer, integer, numeric, date, date, text); Type: FUNCTION; Schema: public; Owner: admin
40935 --
40936
40937 CREATE FUNCTION explodekit(integer, integer, integer, integer, numeric, date, date, text) RETURNS integer
40938     LANGUAGE plpgsql
40939     AS $_$
40940 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
40941 -- See www.xtuple.com/CPAL for the full text of the software license.
40942 DECLARE
40943   pSoheadid ALIAS FOR $1;
40944   pLinenumber ALIAS FOR $2;
40945   pSubnumber ALIAS FOR $3;
40946   pItemsiteid ALIAS FOR $4;
40947   pQty ALIAS FOR $5;
40948   pScheddate ALIAS FOR $6;
40949   pPromdate ALIAS FOR $7;
40950   pMemo ALIAS FOR $8;
40951   _subnumber INTEGER := COALESCE(pSubnumber,0);
40952   _revid INTEGER;
40953   _itemid INTEGER;
40954   _warehousid INTEGER;
40955   _item RECORD;
40956   _type TEXT;
40957   _coitemid INTEGER;
40958   _count INTEGER;
40959   _orderid INTEGER := 0;
40960   _itemsrcid INTEGER;
40961 BEGIN
40962
40963   SELECT getActiveRevId('BOM',itemsite_item_id), itemsite_warehous_id, itemsite_item_id
40964     INTO _revid, _warehousid, _itemid
40965     FROM itemsite
40966    WHERE(itemsite_id=pItemsiteid);
40967   IF(NOT FOUND) THEN
40968     RAISE EXCEPTION 'No Item Site for the specified line was found.';
40969   END IF;
40970
40971   FOR _item IN
40972   SELECT bomitem_id, 
40973          itemsite_id,
40974          itemsite_warehous_id,
40975          COALESCE((itemsite_active AND item_active), false) AS active,
40976          COALESCE((itemsite_sold AND item_sold), false) AS sold,
40977          item_id,
40978          item_type,
40979          item_price_uom_id,
40980          itemsite_createsopr,itemsite_createwo,itemsite_createsopo, itemsite_dropship,
40981          bomitem_uom_id,
40982          itemuomtouomratio(item_id, bomitem_uom_id, item_inv_uom_id) AS invuomratio,
40983          roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id),(bomitem_qtyfxd + bomitem_qtyper * pQty) * (1 + bomitem_scrap)) AS qty
40984     FROM bomitem JOIN item ON (item_id=bomitem_item_id)
40985                   LEFT OUTER JOIN itemsite ON ((itemsite_item_id=item_id) AND (itemsite_warehous_id=_warehousid))
40986    WHERE((bomitem_parent_item_id=_itemid)
40987      AND (bomitem_rev_id=_revid)
40988      AND (CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1)))
40989    ORDER BY bomitem_seqnumber LOOP
40990     IF (NOT _item.active) THEN
40991       RAISE EXCEPTION 'One or more of the components for the kit is inactive for the selected item site.';
40992     ELSIF (NOT _item.sold) THEN
40993       RAISE EXCEPTION 'One or more of the components for the kit is not sold for the selected item site.';
40994     ELSIF (_item.item_type='F') THEN
40995       SELECT explodeKit(pSoheadid, pLinenumber, _subnumber, _item.itemsite_id, _item.qty)
40996         INTO _subnumber;
40997     ELSE
40998       IF (_item.itemsite_createsopr) THEN
40999         _type := 'R';
41000       ELSIF (_item.itemsite_createsopo) THEN
41001         _type := 'P';
41002       ELSIF (_item.itemsite_createwo) THEN
41003         _type := 'W';
41004       ELSE
41005         _type := NULL;
41006       END IF;
41007       _subnumber := _subnumber + 1;
41008       _coitemid = nextval('coitem_coitem_id_seq');
41009       raise notice 'coitem id: %',_coitemid;
41010       INSERT INTO coitem
41011             (coitem_id, coitem_cohead_id,
41012              coitem_linenumber, coitem_subnumber,
41013              coitem_itemsite_id, coitem_status,
41014              coitem_scheddate, coitem_promdate,
41015              coitem_qtyord, coitem_qty_uom_id, coitem_qty_invuomratio,
41016              coitem_qtyshipped, coitem_qtyreturned,
41017              coitem_unitcost, coitem_custprice,
41018              coitem_price, coitem_price_uom_id, coitem_price_invuomratio,
41019              coitem_order_type, coitem_order_id,
41020              coitem_custpn, coitem_memo,
41021              coitem_prcost)
41022       VALUES (_coitemid, pSoheadid,
41023              pLinenumber, _subnumber,
41024              _item.itemsite_id, 'O',
41025              pScheddate, pPromdate,
41026              _item.qty, _item.bomitem_uom_id, _item.invuomratio,
41027              0, 0,
41028              stdCost(_item.item_id), 0,
41029              0, _item.item_price_uom_id, 1,
41030              _type, -1,
41031              '', pMemo,
41032              0);
41033
41034       IF (_item.itemsite_createsopr) THEN
41035         SELECT createPR(cohead_number::INTEGER, 'S', _coitemid) INTO _orderid
41036         FROM cohead
41037         WHERE (cohead_id=pSoheadid);
41038         IF (_orderid > 0) THEN
41039           UPDATE coitem SET coitem_order_id=_orderid
41040           WHERE (coitem_id=_coitemid);
41041         ELSE
41042           RAISE EXCEPTION 'Could not explode kit. CreatePR failed, result=%', _orderid; 
41043         END IF;
41044       END IF;
41045
41046       IF (_item.itemsite_createsopo) THEN
41047         SELECT itemsrc_id INTO _itemsrcid
41048         FROM itemsrc
41049         WHERE ((itemsrc_item_id=_item.item_id)
41050         AND (itemsrc_default));
41051
41052         GET DIAGNOSTICS _count = ROW_COUNT;
41053         IF (_count > 0) THEN
41054           PERFORM createPurchaseToSale(_coitemid, _itemsrcid, _item.itemsite_dropship);
41055         ELSE
41056           RAISE WARNING 'One or more Kit items are flagged as purchase-to-order for this site, but no default item source is defined.';
41057         END IF;
41058       END IF;
41059      
41060     END IF;
41061   END LOOP;
41062
41063   RETURN _subnumber;
41064 END;
41065 $_$;
41066
41067
41068 ALTER FUNCTION public.explodekit(integer, integer, integer, integer, numeric, date, date, text) OWNER TO admin;
41069
41070 --
41071 -- TOC entry 1530 (class 1255 OID 146566102)
41072 -- Dependencies: 4536 8
41073 -- Name: explodephantomorder(integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
41074 --
41075
41076 CREATE FUNCTION explodephantomorder(integer, integer, numeric) RETURNS integer
41077     LANGUAGE plpgsql
41078     AS $_$
41079 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41080 -- See www.xtuple.com/CPAL for the full text of the software license.
41081 DECLARE
41082   pPlanordid ALIAS FOR $1;
41083   pPhantomid ALIAS FOR $2;
41084   pQty       ALIAS FOR $3;
41085   _b RECORD;
41086
41087 BEGIN
41088   FOR _b IN SELECT planord_number, c.itemsite_id AS componentsiteid,
41089                    calculatenextworkingdate(c.itemsite_warehous_id, planord_startdate, (c.itemsite_leadtime * -1)) AS startdate,
41090                    planord_startdate AS duedate,
41091                    bomitem_createwo, c.itemsite_planning_type AS planningtype,
41092                    (itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, (bomitem_qtyfxd + pQty * bomitem_qtyper) * (1 + bomitem_scrap))) AS qtyreq,
41093                    item_type
41094               FROM bomitem, planord, itemsite AS p, itemsite AS c, item
41095              WHERE ((bomitem_parent_item_id=p.itemsite_item_id)
41096                AND (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id))
41097                AND (bomitem_item_id=c.itemsite_item_id)
41098                AND (p.itemsite_warehous_id=c.itemsite_warehous_id)
41099                AND (c.itemsite_item_id=item_id)
41100                AND (woEffectiveDate(planord_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
41101                AND (p.itemsite_id=pPhantomid)
41102                AND (planord_id=pPlanordid)) LOOP
41103
41104     IF (_b.item_type = 'F') THEN
41105       PERFORM explodePhantomOrder(pPlanordid, _b.componentsiteid, _b.qtyreq);
41106     ELSE
41107 --  Create the Planned Requirement
41108       INSERT INTO planreq
41109       ( planreq_source, planreq_source_id,
41110         planreq_itemsite_id, planreq_qty )
41111       VALUES
41112       ( 'P', pPlanordid,
41113         _b.componentsiteid, _b.qtyreq );
41114
41115       IF (_b.bomitem_createwo AND _b.planningtype != 'N') THEN
41116         PERFORM createPlannedOrder( pPlanordid, _b.planord_number, _b.componentsiteid,
41117                                     _b.qtyreq, _b.startdate, _b.duedate,
41118                                     FALSE, FALSE, NULL, NULL);
41119       END IF;
41120     END IF;
41121
41122   END LOOP;
41123
41124   RETURN pPlanordid;
41125 END;
41126 $_$;
41127
41128
41129 ALTER FUNCTION public.explodephantomorder(integer, integer, numeric) OWNER TO admin;
41130
41131 --
41132 -- TOC entry 1531 (class 1255 OID 146566103)
41133 -- Dependencies: 4536 8
41134 -- Name: explodewo(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
41135 --
41136
41137 CREATE FUNCTION explodewo(integer, boolean) RETURNS integer
41138     LANGUAGE plpgsql
41139     AS $_$
41140 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41141 -- See www.xtuple.com/CPAL for the full text of the software license.
41142 DECLARE
41143   pWoid ALIAS FOR $1;
41144   pExplodeChildren ALIAS FOR $2;
41145   resultCode INTEGER;
41146   newWo RECORD;
41147   _newwoid INTEGER;
41148   _p RECORD;
41149   _r RECORD;
41150   _bbom BOOLEAN;
41151
41152 BEGIN
41153 -- Find out if Breeder BOMs are enabled
41154   SELECT metric_value='t' INTO _bbom
41155          FROM metric
41156          WHERE (metric_name='BBOM');
41157
41158 --  Make sure that this W/O is Open
41159   SELECT wo_id INTO resultCode
41160   FROM wo
41161   WHERE ((wo_status='O')
41162    AND (wo_id=pWoid));
41163   IF (NOT FOUND) THEN
41164     RETURN -4;
41165   END IF;
41166
41167 --  Make sure that all Component Item Sites exist and are valid
41168 --  Item Sites must be active and not Job Costed
41169   SELECT bomitem_id INTO resultCode
41170   FROM wo, bomitem, itemsite
41171   WHERE ( (wo_itemsite_id=itemsite_id)
41172    AND (itemsite_item_id=bomitem_parent_item_id)
41173    AND (woEffectiveDate(wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
41174    AND (wo_id=pWoid)
41175    AND (bomitem_rev_id=wo_bom_rev_id)
41176    AND (bomitem_item_id NOT IN
41177         ( SELECT component.itemsite_item_id
41178           FROM itemsite AS component, itemsite AS parent
41179           WHERE ( (wo_itemsite_id=parent.itemsite_id)
41180            AND (parent.itemsite_item_id=bomitem_parent_item_id)
41181            AND (bomitem_item_id=component.itemsite_item_id)
41182            AND (woEffectiveDate(wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
41183            AND (component.itemsite_active)
41184            AND (component.itemsite_warehous_id=parent.itemsite_warehous_id) ) ) ) )
41185   LIMIT 1;
41186   IF (FOUND) THEN
41187     RETURN -2;
41188   END IF;
41189
41190 --  If the Parent Item is a Breeder, make sure that all the
41191 --  Co-Product/By-Product Item Sites exist
41192   IF (_bbom) THEN
41193
41194     IF ( ( SELECT (item_type='B')
41195            FROM wo, itemsite, item
41196            WHERE ( (wo_itemsite_id=itemsite_id)
41197             AND (itemsite_item_id=item_id)
41198             AND (wo_id=pWoid) ) ) ) THEN
41199       SELECT bbomitem_id INTO resultCode
41200       FROM wo, xtmfg.bbomitem, itemsite
41201       WHERE ( (wo_itemsite_id=itemsite_id)
41202        AND (itemsite_item_id=bbomitem_parent_item_id)
41203        AND (woEffectiveDate(wo_startdate) BETWEEN bbomitem_effective AND (bbomitem_expires - 1))
41204        AND (wo_id=pWoid)
41205        AND (bbomitem_item_id NOT IN
41206             ( SELECT component.itemsite_item_id
41207               FROM itemsite AS component, itemsite AS parent
41208               WHERE ( (wo_itemsite_id=parent.itemsite_id)
41209                AND (parent.itemsite_item_id=bbomitem_parent_item_id)
41210                AND (bbomitem_item_id=component.itemsite_item_id)
41211                AND (woEffectiveDate(wo_startdate) BETWEEN bbomitem_effective AND (bbomitem_expires - 1))
41212                AND (component.itemsite_active)
41213                AND (component.itemsite_warehous_id=parent.itemsite_warehous_id) ) ) ) )
41214       LIMIT 1;
41215       IF (FOUND) THEN
41216         RETURN -3;
41217       END IF;
41218     END IF;
41219   END IF;
41220
41221 --  Create the W/O Material Requirements
41222   INSERT INTO womatl
41223   ( womatl_wo_id, womatl_bomitem_id, womatl_wooper_id, womatl_schedatwooper,
41224     womatl_itemsite_id, womatl_duedate,
41225     womatl_uom_id, womatl_qtyfxd, womatl_qtyper, womatl_scrap,
41226     womatl_qtyreq,
41227     womatl_qtyiss, womatl_qtywipscrap,
41228     womatl_lastissue, womatl_lastreturn, womatl_cost,
41229     womatl_picklist, womatl_createwo, womatl_issuewo,
41230     womatl_issuemethod, womatl_notes, womatl_ref,
41231     womatl_price )
41232   SELECT wo_id, bomitem_id, bomitem_booitem_seq_id, bomitem_schedatwooper,
41233          matl_itemsite, duedate,
41234          bomitem_uom_id, bomitem_qtyfxd, bomitem_qtyper, bomitem_scrap,
41235          qtyreq, 0, 0,
41236          startOfTime(), startOfTime(), 0,
41237          item_picklist, ( (item_type='M') AND (bomitem_createwo) ), issuewo,
41238          bomitem_issuemethod, bomitem_notes, bomitem_ref,
41239          CASE WHEN (price=-9999.0) THEN 0.0
41240               ELSE price
41241          END
41242   FROM (SELECT *, cs.itemsite_id AS matl_itemsite,
41243                CASE WHEN bomitem_schedatwooper THEN COALESCE(calcWooperStartStub(wo_id,bomitem_booitem_seq_id), wo_startdate)
41244                     ELSE wo_startdate
41245                END AS duedate,
41246                roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id), (bomitem_qtyfxd + bomitem_qtyper * wo_qtyord) * (1 + bomitem_scrap)) AS qtyreq,
41247                CASE WHEN ( (item_type='M') AND (bomitem_issuewo) ) THEN TRUE
41248                     WHEN (cs.itemsite_costmethod='J') THEN TRUE
41249                     ELSE FALSE
41250                END AS issuewo,
41251                CASE WHEN (cohead_id IS NULL) THEN item_listprice
41252                     ELSE (SELECT itemprice_price
41253                           FROM itemIpsPrice(item_id, cohead_cust_id, cohead_shipto_id, 
41254                                       roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id), (bomitem_qtyfxd + bomitem_qtyper * wo_qtyord) * (1 + bomitem_scrap)),
41255                                       bomitem_uom_id, bomitem_uom_id, cohead_curr_id, CURRENT_DATE, CURRENT_DATE, cohead_warehous_id) LIMIT 1)
41256                END AS price
41257         FROM wo JOIN itemsite ps ON (ps.itemsite_id=wo_itemsite_id)
41258                 JOIN bomitem ON (bomitem_parent_item_id=ps.itemsite_item_id AND
41259                                  bomitem_rev_id=wo_bom_rev_id AND
41260                                  woEffectiveDate(wo_startdate) BETWEEN bomitem_effective and (bomitem_expires - 1))
41261                 JOIN itemsite cs ON (cs.itemsite_item_id=bomitem_item_id AND
41262                                      cs.itemsite_warehous_id=ps.itemsite_warehous_id)
41263                 JOIN item ON (item_id=cs.itemsite_item_id)
41264                 LEFT OUTER JOIN coitem ON (wo_ordtype='S' AND
41265                                            wo_ordid=coitem_id)
41266                 LEFT OUTER JOIN cohead ON (cohead_id=coitem_cohead_id)
41267         WHERE ( (wo_id=pWoid)
41268           AND   ((bomitem_char_id IS NULL)
41269              OR  EXISTS (
41270                  SELECT charass_id
41271                  FROM coitem,charass
41272                  WHERE ((charass_target_type='SI')
41273                    AND  (charass_target_id=coitem_id)
41274                    AND  (charass_char_id=bomitem_char_id)
41275                    AND  (charass_value=bomitem_value)
41276                    AND  (wo_ordtype='S')
41277                    AND  (coitem_id=wo_ordid)))) )
41278         ) AS data;
41279
41280 --  Update any created P/R's the have the project id as the parent WO.
41281   UPDATE pr SET pr_prj_id=wo_prj_id
41282     FROM womatl, wo
41283    WHERE ((wo_id=pWoid)
41284      AND  (womatl_wo_id=wo_id)
41285      AND  (pr_order_type='W')
41286      AND  (pr_order_id=womatl_id));
41287
41288 --  If the parent Item is a Breeder, create the brddist
41289 --  records for the Co-Products and By-Products
41290   IF (_bbom) THEN
41291
41292     INSERT INTO xtmfg.brddist
41293     ( brddist_wo_id, brddist_wo_qty, brddist_itemsite_id,
41294       brddist_stdqtyper, brddist_qty, brddist_posted )
41295     SELECT wo_id, 0, cs.itemsite_id,
41296            bbomitem_qtyper, 0, FALSE
41297     FROM wo, xtmfg.bbomitem,
41298          itemsite AS ps, itemsite AS cs, item
41299     WHERE ( (bbomitem_parent_item_id=ps.itemsite_item_id)
41300      AND (wo_itemsite_id=ps.itemsite_id)
41301      AND (ps.itemsite_item_id=item_id)
41302      AND (item_type='B')
41303      AND (bbomitem_item_id=cs.itemsite_item_id)
41304      AND (cs.itemsite_warehous_id=ps.itemsite_warehous_id)
41305      AND (wo_id=pWoid) );
41306
41307   END IF;
41308
41309 --  Insert the W/O Operations if routings enabled
41310   IF ( ( SELECT (metric_value='t')
41311          FROM metric
41312          WHERE (metric_name='Routings') ) ) THEN
41313
41314     INSERT INTO xtmfg.wooper
41315     ( wooper_wo_id, wooper_booitem_id, wooper_seqnumber,
41316       wooper_wrkcnt_id, wooper_stdopn_id,
41317       wooper_descrip1, wooper_descrip2, wooper_toolref,
41318       wooper_sutime, wooper_sucosttype, wooper_surpt,
41319       wooper_rntime, wooper_rncosttype, wooper_rnrpt,
41320       wooper_rnqtyper,
41321       wooper_produom, wooper_invproduomratio,
41322       wooper_issuecomp, wooper_rcvinv,
41323       wooper_suconsumed, wooper_sucomplete,
41324       wooper_rnconsumed, wooper_rncomplete,
41325       wooper_qtyrcv, wooper_instruc, wooper_scheduled,
41326       wooper_wip_location_id, wooper_price )
41327     SELECT wo_id, booitem_id, booitem_seqnumber,
41328            booitem_wrkcnt_id, booitem_stdopn_id,
41329            booitem_descrip1, booitem_descrip2, booitem_toolref,
41330            CASE WHEN (booitem_surpt) THEN booitem_sutime
41331                 ELSE 0
41332            END, booitem_sucosttype, booitem_surpt,
41333            CASE WHEN ((booitem_rnqtyper = 0) OR (booitem_invproduomratio = 0)) THEN 0
41334                 WHEN (NOT booitem_rnrpt) THEN 0
41335                 ELSE ( ( booitem_rntime /
41336                          booitem_rnqtyper /
41337                          booitem_invproduomratio ) * wo_qtyord )
41338            END, booitem_rncosttype, booitem_rnrpt,
41339            CASE WHEN (booitem_rnqtyper = 0) THEN 0
41340                 WHEN (NOT booitem_rnrpt) THEN 0
41341                 ELSE (booitem_rntime / booitem_rnqtyper)
41342            END,
41343            booitem_produom, booitem_invproduomratio,
41344            booitem_issuecomp, booitem_rcvinv,
41345            0::NUMERIC, FALSE,
41346            0::NUMERIC, FALSE,
41347            0::NUMERIC, booitem_instruc,
41348            calculatenextworkingdate(itemsite_warehous_id,wo_startdate,booitem_execday-1),
41349            booitem_wip_location_id,
41350            (xtmfg.directlaborcostoper(booitem_id) + xtmfg.overheadcostoper(booitem_id) + xtmfg.machineoverheadcostoper(booitem_id))
41351     FROM xtmfg.booitem, wo, itemsite
41352     WHERE ((wo_itemsite_id=itemsite_id)
41353      AND (itemsite_item_id=booitem_item_id)
41354      AND (booitem_rev_id=wo_boo_rev_id)
41355      AND (woEffectiveDate(wo_startdate) BETWEEN booitem_effective AND (booitem_expires - 1))
41356      AND (wo_id=pWoid));
41357
41358 --  Update womatls item to link to wooper items when the respective
41359 --  bomitem record indicates a booitem issue link.
41360     UPDATE womatl
41361     SET womatl_wooper_id=wooper_id
41362     FROM wo,xtmfg.wooper,xtmfg.booitem
41363     WHERE ((womatl_wooper_id=booitem_seq_id)
41364      AND (wooper_booitem_id=booitem_id)
41365      AND (womatl_wo_id=wo_id)
41366      AND (wooper_wo_id=wo_id)
41367      AND (wo_boo_rev_id=booitem_rev_id)
41368      AND (wo_id=pWoid));
41369     END IF;
41370
41371 -- Handle all of the Phantom material requirements
41372   WHILE ( ( SELECT COUNT(*)
41373             FROM womatl, itemsite, item
41374             WHERE ( (womatl_itemsite_id=itemsite_id)
41375              AND (itemsite_item_id=item_id)
41376              AND (womatl_wo_id=pWoid)
41377              AND (item_type='F') ) ) > 0 ) LOOP
41378
41379     FOR _p IN SELECT wo_qtyord, wo_startdate, womatl_id, womatl_wooper_id
41380               FROM wo, womatl, itemsite, item
41381               WHERE ( (womatl_itemsite_id=itemsite_id)
41382                AND (itemsite_item_id=item_id)
41383                AND (item_type='F')
41384                AND (womatl_wo_id=wo_id)
41385                AND (wo_id=pWoid) ) LOOP
41386
41387       INSERT INTO womatl
41388       ( womatl_wo_id, womatl_itemsite_id, womatl_wooper_id,
41389         womatl_schedatwooper, womatl_duedate,
41390         womatl_uom_id, womatl_qtyfxd, womatl_qtyper, womatl_scrap,
41391         womatl_qtyreq,
41392         womatl_qtyiss, womatl_qtywipscrap,
41393         womatl_lastissue, womatl_lastreturn,
41394         womatl_cost, womatl_picklist,
41395         womatl_createwo, womatl_issuewo,
41396         womatl_issuemethod, womatl_notes, womatl_ref )
41397       SELECT pWoid, cs.itemsite_id, _p.womatl_wooper_id,
41398              womatl_schedatwooper, womatl_duedate,
41399              bomitem_uom_id, bomitem_qtyfxd, (bomitem_qtyper * womatl_qtyper), bomitem_scrap,
41400              roundQty(itemuomfractionalbyuom(bomitem_item_id, bomitem_uom_id), 
41401                      (bomitem_qtyfxd + _p.wo_qtyord * bomitem_qtyper * womatl_qtyper) * (1 + bomitem_scrap)),
41402              0, 0,
41403              startOfTime(), startOfTime(),
41404              0, ci.item_picklist,
41405              ( (ci.item_type='M') AND (bomitem_createwo) ), ( (ci.item_type='M') AND (bomitem_issuewo) ),
41406              bomitem_issuemethod, bomitem_notes, bomitem_ref
41407       FROM womatl JOIN wo ON (wo_id=womatl_wo_id)
41408                   JOIN itemsite ps ON (ps.itemsite_id=womatl_itemsite_id)
41409                   JOIN item pi ON (pi.item_id=ps.itemsite_item_id)
41410                   JOIN bomitem ON ( (bomitem_parent_item_id=pi.item_id) AND
41411                                     (woEffectiveDate(_p.wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1)) AND
41412                                     (bomitem_rev_id=getActiveRevId('BOM', pi.item_id)) )
41413                   JOIN item ci ON (ci.item_id=bomitem.bomitem_item_id)
41414                   JOIN itemsite cs ON ( (cs.itemsite_item_id=ci.item_id) AND
41415                                         (cs.itemsite_warehous_id=ps.itemsite_warehous_id) )
41416       WHERE (womatl_id=_p.womatl_id);
41417
41418       DELETE FROM womatl
41419       WHERE (womatl_id=_p.womatl_id);
41420
41421     END LOOP;
41422   END LOOP;
41423
41424 --  Create W/Os for manufactured component items
41425   FOR newWo IN SELECT wo_number, nextWoSubnumber(wo_number) AS nextSubnumber,
41426                       itemsite_id, itemsite_leadtime, womatl_duedate,
41427                       womatl_wo_id, womatl_qtyreq, womatl_uom_id, wo_prj_id,
41428                       item_id, item_inv_uom_id, womatl_id
41429                FROM womatl, wo, itemsite, item
41430                WHERE ( (womatl_wo_id=wo_id)
41431                 AND (womatl_itemsite_id=itemsite_id)
41432                 AND (womatl_createwo)
41433                 AND (itemsite_wosupply)
41434                 AND (itemsite_item_id=item_id)
41435                 AND (wo_id=pWoid) )
41436                ORDER BY womatl_id LOOP
41437
41438     SELECT createWo( newWo.wo_number, newWo.itemsite_id, 1, 
41439                      itemuomtouom(newWo.item_id,newWo.womatl_uom_id,newWo.item_inv_uom_id,newWo.womatl_qtyreq),
41440                       newWo.itemsite_leadtime, newWo.womatl_duedate, '',
41441                       'W', newWo.womatl_wo_id, newWo.wo_prj_id ) INTO _newwoid;
41442
41443     UPDATE wo SET wo_womatl_id = newWo.womatl_id WHERE wo_id=_newwoid;
41444
41445   END LOOP;
41446
41447   UPDATE wo
41448   SET wo_status='E', wo_adhoc=FALSE
41449   WHERE (wo_id=pWoid);
41450
41451   IF (pExplodeChildren) THEN
41452     SELECT MAX(explodeWo(wo_id, TRUE)) INTO resultCode
41453     FROM wo
41454     WHERE ( (wo_ordtype='W')
41455      AND (wo_ordid=pWoid) );
41456   END IF;
41457
41458   RETURN pWoid;
41459 END;
41460 $_$;
41461
41462
41463 ALTER FUNCTION public.explodewo(integer, boolean) OWNER TO admin;
41464
41465 --
41466 -- TOC entry 1532 (class 1255 OID 146566105)
41467 -- Dependencies: 4536 8
41468 -- Name: explodewoeffective(); Type: FUNCTION; Schema: public; Owner: admin
41469 --
41470
41471 CREATE FUNCTION explodewoeffective() RETURNS text
41472     LANGUAGE plpgsql
41473     AS $$
41474 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41475 -- See www.xtuple.com/CPAL for the full text of the software license.
41476 DECLARE
41477   _value TEXT;
41478
41479 BEGIN
41480
41481   SELECT metric_value INTO _value
41482   FROM metric
41483   WHERE (metric_name='ExplodeWOEffective');
41484
41485   RETURN _value;
41486
41487 END;
41488 $$;
41489
41490
41491 ALTER FUNCTION public.explodewoeffective() OWNER TO admin;
41492
41493 --
41494 -- TOC entry 1533 (class 1255 OID 146566106)
41495 -- Dependencies: 8
41496 -- Name: fetchapmemonumber(); Type: FUNCTION; Schema: public; Owner: admin
41497 --
41498
41499 CREATE FUNCTION fetchapmemonumber() RETURNS integer
41500     LANGUAGE sql
41501     AS $$
41502 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41503 -- See www.xtuple.com/CPAL for the full text of the software license.
41504   SELECT fetchNextNumber('APMemoNumber')::INTEGER;
41505 $$;
41506
41507
41508 ALTER FUNCTION public.fetchapmemonumber() OWNER TO admin;
41509
41510 --
41511 -- TOC entry 1534 (class 1255 OID 146566107)
41512 -- Dependencies: 8
41513 -- Name: fetcharmemonumber(); Type: FUNCTION; Schema: public; Owner: admin
41514 --
41515
41516 CREATE FUNCTION fetcharmemonumber() RETURNS text
41517     LANGUAGE sql
41518     AS $$
41519 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41520 -- See www.xtuple.com/CPAL for the full text of the software license.
41521   SELECT fetchNextNumber('ARMemoNumber');
41522 $$;
41523
41524
41525 ALTER FUNCTION public.fetcharmemonumber() OWNER TO admin;
41526
41527 --
41528 -- TOC entry 1535 (class 1255 OID 146566108)
41529 -- Dependencies: 8
41530 -- Name: fetchcashrcptnumber(); Type: FUNCTION; Schema: public; Owner: admin
41531 --
41532
41533 CREATE FUNCTION fetchcashrcptnumber() RETURNS text
41534     LANGUAGE sql
41535     AS $$
41536 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41537 -- See www.xtuple.com/CPAL for the full text of the software license.
41538   SELECT fetchNextNumber('CashRcptNumber');
41539 $$;
41540
41541
41542 ALTER FUNCTION public.fetchcashrcptnumber() OWNER TO admin;
41543
41544 --
41545 -- TOC entry 1536 (class 1255 OID 146566109)
41546 -- Dependencies: 8
41547 -- Name: fetchcmnumber(); Type: FUNCTION; Schema: public; Owner: admin
41548 --
41549
41550 CREATE FUNCTION fetchcmnumber() RETURNS text
41551     LANGUAGE sql
41552     AS $$
41553 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41554 -- See www.xtuple.com/CPAL for the full text of the software license.
41555   SELECT fetchNextNumber('CmNumber');
41556 $$;
41557
41558
41559 ALTER FUNCTION public.fetchcmnumber() OWNER TO admin;
41560
41561 --
41562 -- TOC entry 1537 (class 1255 OID 146566110)
41563 -- Dependencies: 8
41564 -- Name: fetchcrmaccountnumber(); Type: FUNCTION; Schema: public; Owner: admin
41565 --
41566
41567 CREATE FUNCTION fetchcrmaccountnumber() RETURNS integer
41568     LANGUAGE sql
41569     AS $$
41570 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41571 -- See www.xtuple.com/CPAL for the full text of the software license.
41572   SELECT fetchNextNumber('CRMAccountNumber')::INTEGER;
41573 $$;
41574
41575
41576 ALTER FUNCTION public.fetchcrmaccountnumber() OWNER TO admin;
41577
41578 --
41579 -- TOC entry 1538 (class 1255 OID 146566111)
41580 -- Dependencies: 8
41581 -- Name: fetchdefaultfob(integer); Type: FUNCTION; Schema: public; Owner: admin
41582 --
41583
41584 CREATE FUNCTION fetchdefaultfob(pwarehousid integer) RETURNS text
41585     LANGUAGE sql
41586     AS $_$
41587 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41588 -- See www.xtuple.com/CPAL for the full text of the software license.
41589   SELECT warehous_fob
41590     FROM whsinfo
41591    WHERE (warehous_id=$1);
41592 $_$;
41593
41594
41595 ALTER FUNCTION public.fetchdefaultfob(pwarehousid integer) OWNER TO admin;
41596
41597 --
41598 -- TOC entry 1539 (class 1255 OID 146566112)
41599 -- Dependencies: 4536 8
41600 -- Name: fetchdefaultshipvia(); Type: FUNCTION; Schema: public; Owner: admin
41601 --
41602
41603 CREATE FUNCTION fetchdefaultshipvia() RETURNS text
41604     LANGUAGE plpgsql
41605     AS $$
41606 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41607 -- See www.xtuple.com/CPAL for the full text of the software license.
41608 DECLARE
41609   _returnVal TEXT;
41610 BEGIN
41611   SELECT shipvia_code INTO _returnVal
41612   FROM shipvia
41613   WHERE shipvia_id=
41614         (SELECT CAST(metric_value AS integer)
41615         FROM metric
41616         WHERE metric_name = 'DefaultShipViaId');
41617   RETURN _returnVal;
41618 END;
41619 $$;
41620
41621
41622 ALTER FUNCTION public.fetchdefaultshipvia() OWNER TO admin;
41623
41624 --
41625 -- TOC entry 1540 (class 1255 OID 146566113)
41626 -- Dependencies: 4536 8
41627 -- Name: fetchglsequence(); Type: FUNCTION; Schema: public; Owner: admin
41628 --
41629
41630 CREATE FUNCTION fetchglsequence() RETURNS integer
41631     LANGUAGE plpgsql
41632     AS $$
41633 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41634 -- See www.xtuple.com/CPAL for the full text of the software license.
41635 DECLARE
41636   _sequence INTEGER;
41637
41638 BEGIN
41639
41640     SELECT NEXTVAL('gltrans_sequence_seq') INTO _sequence;
41641     RETURN _sequence;
41642
41643 END;
41644 $$;
41645
41646
41647 ALTER FUNCTION public.fetchglsequence() OWNER TO admin;
41648
41649 --
41650 -- TOC entry 1541 (class 1255 OID 146566114)
41651 -- Dependencies: 8
41652 -- Name: fetchincidentnumber(); Type: FUNCTION; Schema: public; Owner: admin
41653 --
41654
41655 CREATE FUNCTION fetchincidentnumber() RETURNS integer
41656     LANGUAGE sql
41657     AS $$
41658 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41659 -- See www.xtuple.com/CPAL for the full text of the software license.
41660   SELECT fetchNextNumber('IncidentNumber')::integer;
41661 $$;
41662
41663
41664 ALTER FUNCTION public.fetchincidentnumber() OWNER TO admin;
41665
41666 --
41667 -- TOC entry 1542 (class 1255 OID 146566115)
41668 -- Dependencies: 8
41669 -- Name: fetchinvcnumber(); Type: FUNCTION; Schema: public; Owner: admin
41670 --
41671
41672 CREATE FUNCTION fetchinvcnumber() RETURNS integer
41673     LANGUAGE sql
41674     AS $$
41675 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41676 -- See www.xtuple.com/CPAL for the full text of the software license.
41677   SELECT fetchNextNumber('InvcNumber')::integer;
41678 $$;
41679
41680
41681 ALTER FUNCTION public.fetchinvcnumber() OWNER TO admin;
41682
41683 --
41684 -- TOC entry 1543 (class 1255 OID 146566116)
41685 -- Dependencies: 4536 8
41686 -- Name: fetchitemuomconvtypes(integer); Type: FUNCTION; Schema: public; Owner: admin
41687 --
41688
41689 CREATE FUNCTION fetchitemuomconvtypes(integer) RETURNS text[]
41690     LANGUAGE plpgsql
41691     AS $_$
41692 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41693 -- See www.xtuple.com/CPAL for the full text of the software license.
41694 DECLARE
41695   pItemUomConvId ALIAS FOR $1;
41696   _p RECORD;
41697   _result text[];
41698   _cnt INTEGER;
41699
41700 BEGIN
41701
41702   _cnt := 0;
41703
41704   FOR _p IN SELECT
41705     uomtype_name
41706   FROM itemuomconv, itemuom, uomtype
41707   WHERE ((itemuomconv_id=pItemUomConvId)
41708   AND (itemuomconv_id=itemuom_itemuomconv_id)
41709   AND (itemuom_uomtype_id=uomtype_id))
41710   LOOP
41711     _result[_cnt] := _p.uomtype_name; 
41712     _cnt := _cnt + 1;
41713   END LOOP;
41714
41715   RETURN _result;
41716 END;
41717 $_$;
41718
41719
41720 ALTER FUNCTION public.fetchitemuomconvtypes(integer) OWNER TO admin;
41721
41722 --
41723 -- TOC entry 1544 (class 1255 OID 146566117)
41724 -- Dependencies: 4536 8
41725 -- Name: fetchjournalnumber(text); Type: FUNCTION; Schema: public; Owner: admin
41726 --
41727
41728 CREATE FUNCTION fetchjournalnumber(text) RETURNS integer
41729     LANGUAGE plpgsql
41730     AS $_$
41731 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41732 -- See www.xtuple.com/CPAL for the full text of the software license.
41733 DECLARE
41734   pUse ALIAS FOR $1;
41735   _number INTEGER;
41736
41737 BEGIN
41738
41739   SELECT nextval('journal_number_seq') INTO _number;
41740
41741   INSERT INTO jrnluse
41742   (jrnluse_date, jrnluse_number, jrnluse_use)
41743   VALUES
41744   (CURRENT_TIMESTAMP, _number, pUse);
41745
41746   RETURN _number;
41747   
41748 END;
41749 $_$;
41750
41751
41752 ALTER FUNCTION public.fetchjournalnumber(text) OWNER TO admin;
41753
41754 --
41755 -- TOC entry 1545 (class 1255 OID 146566118)
41756 -- Dependencies: 4536 8
41757 -- Name: fetchmetricbool(text); Type: FUNCTION; Schema: public; Owner: admin
41758 --
41759
41760 CREATE FUNCTION fetchmetricbool(text) RETURNS boolean
41761     LANGUAGE plpgsql STABLE
41762     AS $_$
41763 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41764 -- See www.xtuple.com/CPAL for the full text of the software license.
41765 DECLARE
41766   _pMetricName ALIAS FOR $1;
41767   _returnVal BOOLEAN;
41768 BEGIN
41769   SELECT CASE 
41770     WHEN MIN(metric_value) = 't' THEN
41771      true
41772     ELSE
41773      false
41774     END INTO _returnVal
41775     FROM metric
41776    WHERE metric_name = _pMetricName;
41777   RETURN _returnVal;
41778 END;
41779 $_$;
41780
41781
41782 ALTER FUNCTION public.fetchmetricbool(text) OWNER TO admin;
41783
41784 --
41785 -- TOC entry 1546 (class 1255 OID 146566119)
41786 -- Dependencies: 4536 8
41787 -- Name: fetchmetrictext(text); Type: FUNCTION; Schema: public; Owner: admin
41788 --
41789
41790 CREATE FUNCTION fetchmetrictext(text) RETURNS text
41791     LANGUAGE plpgsql STABLE
41792     AS $_$
41793 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41794 -- See www.xtuple.com/CPAL for the full text of the software license.
41795 DECLARE
41796   _pMetricName ALIAS FOR $1;
41797   _returnVal TEXT;
41798 BEGIN
41799   SELECT metric_value::TEXT INTO _returnVal
41800     FROM metric
41801    WHERE metric_name = _pMetricName;
41802   RETURN _returnVal;
41803 END;
41804 $_$;
41805
41806
41807 ALTER FUNCTION public.fetchmetrictext(text) OWNER TO admin;
41808
41809 --
41810 -- TOC entry 1547 (class 1255 OID 146566120)
41811 -- Dependencies: 4536 8
41812 -- Name: fetchmetricvalue(text); Type: FUNCTION; Schema: public; Owner: admin
41813 --
41814
41815 CREATE FUNCTION fetchmetricvalue(text) RETURNS numeric
41816     LANGUAGE plpgsql STABLE
41817     AS $_$
41818 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41819 -- See www.xtuple.com/CPAL for the full text of the software license.
41820 DECLARE
41821   _pMetricName ALIAS FOR $1;
41822   _returnVal INTEGER;
41823 BEGIN
41824   SELECT CASE WHEN (isNumeric(metric_value)) THEN metric_value::INTEGER
41825               ELSE NULL
41826          END INTO _returnVal
41827     FROM metric
41828    WHERE metric_name = _pMetricName;
41829   RETURN _returnVal;
41830 END;
41831 $_$;
41832
41833
41834 ALTER FUNCTION public.fetchmetricvalue(text) OWNER TO admin;
41835
41836 --
41837 -- TOC entry 1548 (class 1255 OID 146566121)
41838 -- Dependencies: 4536 8
41839 -- Name: fetchnextchecknumber(integer); Type: FUNCTION; Schema: public; Owner: admin
41840 --
41841
41842 CREATE FUNCTION fetchnextchecknumber(integer) RETURNS integer
41843     LANGUAGE plpgsql
41844     AS $_$
41845 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41846 -- See www.xtuple.com/CPAL for the full text of the software license.
41847 DECLARE
41848   pBankaccntid ALIAS FOR $1;
41849   _nextChkNumber INTEGER;
41850
41851 BEGIN
41852
41853   SELECT bankaccnt_nextchknum INTO _nextChkNumber
41854   FROM bankaccnt
41855   WHERE (bankaccnt_id=pBankaccntid);
41856
41857   UPDATE bankaccnt
41858   SET bankaccnt_nextchknum = (bankaccnt_nextchknum + 1)
41859   WHERE (bankaccnt_id=pBankaccntid);
41860
41861   RETURN _nextChkNumber;
41862
41863 END;
41864 $_$;
41865
41866
41867 ALTER FUNCTION public.fetchnextchecknumber(integer) OWNER TO admin;
41868
41869 --
41870 -- TOC entry 1549 (class 1255 OID 146566122)
41871 -- Dependencies: 4536 8
41872 -- Name: fetchnextnumber(text); Type: FUNCTION; Schema: public; Owner: admin
41873 --
41874
41875 CREATE FUNCTION fetchnextnumber(text) RETURNS text
41876     LANGUAGE plpgsql
41877     AS $_$
41878 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41879 -- See www.xtuple.com/CPAL for the full text of the software license.
41880 DECLARE
41881   psequence     ALIAS FOR $1;
41882   _number       TEXT;
41883   _numcol       TEXT;
41884   _select       TEXT;
41885   _table        TEXT;
41886   _test         TEXT;
41887   _nextnum      INTEGER;
41888   _seqiss       seqiss;
41889   __seqiss      seqiss[];
41890   _not_issued       BOOLEAN;
41891
41892 BEGIN
41893   SELECT CAST(orderseq_number AS text), orderseq_number, orderseq_table, orderseq_numcol, COALESCE(orderseq_seqiss, ARRAY[]::seqiss[])
41894     INTO _number, _nextnum, _table, _numcol, __seqiss
41895   FROM orderseq
41896   WHERE (orderseq_name=psequence) FOR UPDATE;
41897
41898   IF (NOT FOUND) THEN
41899     RAISE EXCEPTION 'Invalid orderseq_name %', psequence;
41900   END IF;
41901   
41902   LOOP
41903
41904     _seqiss := (_nextnum, now());
41905
41906     SELECT count(*) = 0 INTO _not_issued
41907     FROM (SELECT UNNEST(__seqiss) AS issued) data
41908     WHERE (issued).seqiss_number = _nextnum;
41909
41910     _nextnum := _nextnum + 1;
41911
41912     -- Test if the number has been issued, but not committed
41913     IF (_not_issued) THEN
41914
41915       -- Test if the number has been committed
41916       _select := 'SELECT ' || quote_ident(_numcol) ||
41917                  ' FROM '  || quote_ident(_table) ||
41918                  ' WHERE (' || quote_ident(_numcol) || '=' ||
41919                  quote_literal(_number) || ');';
41920
41921       EXECUTE _select INTO _test;
41922
41923       IF (_test IS NULL OR NOT FOUND) THEN
41924         EXIT;
41925       END IF;
41926
41927     END IF;
41928
41929     -- Number in use, try again
41930     _number = _nextnum::text;
41931
41932   END LOOP;
41933
41934   UPDATE orderseq SET 
41935     orderseq_number = _nextnum
41936   WHERE (orderseq_name=psequence);
41937
41938   IF (fetchMetricBool('EnableGaplessNumbering')) THEN
41939     UPDATE orderseq SET 
41940       orderseq_seqiss = orderseq_seqiss || _seqiss
41941     WHERE (orderseq_name=psequence);
41942   END IF;
41943
41944   RETURN _number;
41945
41946 END;
41947 $_$;
41948
41949
41950 ALTER FUNCTION public.fetchnextnumber(text) OWNER TO admin;
41951
41952 --
41953 -- TOC entry 1550 (class 1255 OID 146566123)
41954 -- Dependencies: 8
41955 -- Name: fetchponumber(); Type: FUNCTION; Schema: public; Owner: admin
41956 --
41957
41958 CREATE FUNCTION fetchponumber() RETURNS text
41959     LANGUAGE sql
41960     AS $$
41961 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41962 -- See www.xtuple.com/CPAL for the full text of the software license.
41963   SELECT fetchNextNumber('PoNumber');
41964 $$;
41965
41966
41967 ALTER FUNCTION public.fetchponumber() OWNER TO admin;
41968
41969 --
41970 -- TOC entry 1551 (class 1255 OID 146566124)
41971 -- Dependencies: 4536 8
41972 -- Name: fetchprefwarehousid(); Type: FUNCTION; Schema: public; Owner: admin
41973 --
41974
41975 CREATE FUNCTION fetchprefwarehousid() RETURNS integer
41976     LANGUAGE plpgsql
41977     AS $$
41978 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
41979 -- See www.xtuple.com/CPAL for the full text of the software license.
41980 DECLARE
41981   _result INTEGER;
41982 BEGIN
41983     SELECT CAST(usrpref_value AS INTEGER) INTO _result
41984     FROM usrpref
41985     WHERE ((usrpref_username=getEffectiveXtUser())
41986     AND (usrpref_name='PreferredWarehouse'));
41987
41988     RETURN _result;
41989 END;
41990 $$;
41991
41992
41993 ALTER FUNCTION public.fetchprefwarehousid() OWNER TO admin;
41994
41995 --
41996 -- TOC entry 1552 (class 1255 OID 146566125)
41997 -- Dependencies: 8
41998 -- Name: fetchprnumber(); Type: FUNCTION; Schema: public; Owner: admin
41999 --
42000
42001 CREATE FUNCTION fetchprnumber() RETURNS integer
42002     LANGUAGE sql
42003     AS $$
42004 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42005 -- See www.xtuple.com/CPAL for the full text of the software license.
42006   SELECT fetchNextNumber('PrNumber')::INTEGER;
42007 $$;
42008
42009
42010 ALTER FUNCTION public.fetchprnumber() OWNER TO admin;
42011
42012 --
42013 -- TOC entry 1553 (class 1255 OID 146566126)
42014 -- Dependencies: 8
42015 -- Name: fetchqunumber(); Type: FUNCTION; Schema: public; Owner: admin
42016 --
42017
42018 CREATE FUNCTION fetchqunumber() RETURNS text
42019     LANGUAGE sql
42020     AS $$
42021 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42022 -- See www.xtuple.com/CPAL for the full text of the software license.
42023   SELECT fetchNextNumber('QuNumber');
42024 $$;
42025
42026
42027 ALTER FUNCTION public.fetchqunumber() OWNER TO admin;
42028
42029 --
42030 -- TOC entry 1554 (class 1255 OID 146566127)
42031 -- Dependencies: 4536 8
42032 -- Name: fetchshipmentnumber(); Type: FUNCTION; Schema: public; Owner: admin
42033 --
42034
42035 CREATE FUNCTION fetchshipmentnumber() RETURNS text
42036     LANGUAGE plpgsql
42037     AS $$
42038 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42039 -- See www.xtuple.com/CPAL for the full text of the software license.
42040 DECLARE
42041   _number               TEXT;
42042   _test                 INTEGER;
42043
42044 BEGIN
42045   LOOP
42046
42047     SELECT CAST(nextval('shipment_number_seq') AS TEXT) INTO _number;
42048     
42049     SELECT shiphead_id INTO _test
42050       FROM shiphead
42051      WHERE (shiphead_number=_number);
42052     IF (NOT FOUND) THEN
42053       EXIT;
42054     END IF;
42055
42056   END LOOP;
42057
42058   RETURN _number;
42059   
42060 END;
42061 $$;
42062
42063
42064 ALTER FUNCTION public.fetchshipmentnumber() OWNER TO admin;
42065
42066 --
42067 -- TOC entry 1555 (class 1255 OID 146566128)
42068 -- Dependencies: 8
42069 -- Name: fetchsonumber(); Type: FUNCTION; Schema: public; Owner: admin
42070 --
42071
42072 CREATE FUNCTION fetchsonumber() RETURNS text
42073     LANGUAGE sql
42074     AS $$
42075 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42076 -- See www.xtuple.com/CPAL for the full text of the software license.
42077   SELECT fetchNextNumber('SoNumber');
42078 $$;
42079
42080
42081 ALTER FUNCTION public.fetchsonumber() OWNER TO admin;
42082
42083 --
42084 -- TOC entry 1556 (class 1255 OID 146566129)
42085 -- Dependencies: 8
42086 -- Name: fetchtonumber(); Type: FUNCTION; Schema: public; Owner: admin
42087 --
42088
42089 CREATE FUNCTION fetchtonumber() RETURNS text
42090     LANGUAGE sql
42091     AS $$
42092 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42093 -- See www.xtuple.com/CPAL for the full text of the software license.
42094   SELECT fetchNextNumber('ToNumber');
42095 $$;
42096
42097
42098 ALTER FUNCTION public.fetchtonumber() OWNER TO admin;
42099
42100 --
42101 -- TOC entry 1557 (class 1255 OID 146566130)
42102 -- Dependencies: 4536 8
42103 -- Name: fetchusrprefbool(text); Type: FUNCTION; Schema: public; Owner: admin
42104 --
42105
42106 CREATE FUNCTION fetchusrprefbool(text) RETURNS boolean
42107     LANGUAGE plpgsql
42108     AS $_$
42109 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42110 -- See www.xtuple.com/CPAL for the full text of the software license.
42111 DECLARE
42112   _pPrefName ALIAS FOR $1;
42113   _returnVal BOOLEAN;
42114 BEGIN
42115   SELECT CASE 
42116     WHEN MIN(usrpref_value) = 't' THEN
42117      true
42118     ELSE
42119      false
42120     END INTO _returnVal
42121   FROM usrpref
42122   WHERE ( (usrpref_username=getEffectiveXtUser())
42123     AND   (usrpref_name=_pPrefName) );
42124   RETURN _returnVal;
42125 END;
42126 $_$;
42127
42128
42129 ALTER FUNCTION public.fetchusrprefbool(text) OWNER TO admin;
42130
42131 --
42132 -- TOC entry 1558 (class 1255 OID 146566131)
42133 -- Dependencies: 8
42134 -- Name: fetchvonumber(); Type: FUNCTION; Schema: public; Owner: admin
42135 --
42136
42137 CREATE FUNCTION fetchvonumber() RETURNS integer
42138     LANGUAGE sql
42139     AS $$
42140 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42141 -- See www.xtuple.com/CPAL for the full text of the software license.
42142   SELECT fetchNextNumber('VcNumber')::INTEGER;
42143 $$;
42144
42145
42146 ALTER FUNCTION public.fetchvonumber() OWNER TO admin;
42147
42148 --
42149 -- TOC entry 1559 (class 1255 OID 146566132)
42150 -- Dependencies: 8
42151 -- Name: fetchwonumber(); Type: FUNCTION; Schema: public; Owner: admin
42152 --
42153
42154 CREATE FUNCTION fetchwonumber() RETURNS integer
42155     LANGUAGE sql
42156     AS $$
42157 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42158 -- See www.xtuple.com/CPAL for the full text of the software license.
42159   SELECT fetchNextNumber('WoNumber')::INTEGER;
42160 $$;
42161
42162
42163 ALTER FUNCTION public.fetchwonumber() OWNER TO admin;
42164
42165 --
42166 -- TOC entry 1560 (class 1255 OID 146566133)
42167 -- Dependencies: 4536 8
42168 -- Name: financialreport(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
42169 --
42170
42171 CREATE FUNCTION financialreport(integer, integer, integer) RETURNS boolean
42172     LANGUAGE plpgsql
42173     AS $_$
42174 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42175 -- See www.xtuple.com/CPAL for the full text of the software license.
42176 DECLARE
42177   pFlheadid ALIAS FOR $1;
42178   pPeriodid ALIAS FOR $2;
42179   pPrjid    ALIAS FOR $3;
42180   _result bool;
42181
42182 BEGIN
42183
42184   SELECT financialreport(pFlheadid,pPeriodid,'M', pPrjid) INTO _result;
42185
42186   RETURN _result;
42187 END;
42188 $_$;
42189
42190
42191 ALTER FUNCTION public.financialreport(integer, integer, integer) OWNER TO admin;
42192
42193 --
42194 -- TOC entry 1561 (class 1255 OID 146566134)
42195 -- Dependencies: 4536 8
42196 -- Name: financialreport(integer, integer, character, integer); Type: FUNCTION; Schema: public; Owner: admin
42197 --
42198
42199 CREATE FUNCTION financialreport(integer, integer, character, integer) RETURNS boolean
42200     LANGUAGE plpgsql
42201     AS $_$
42202 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42203 -- See www.xtuple.com/CPAL for the full text of the software license.
42204 DECLARE
42205   pFlheadid ALIAS FOR $1;
42206   pPeriodid ALIAS FOR $2;
42207   pInterval ALIAS FOR $3;
42208   pPrjid    ALIAS FOR $4;
42209
42210   _r RECORD;
42211   _t RECORD;
42212   _s RECORD;
42213
42214 BEGIN
42215
42216 -- Validate Interval
42217    IF pInterval <> 'M' AND pInterval <> 'Q' AND pInterval <> 'Y' THEN
42218      RAISE EXCEPTION 'Invalid Interval --> %', pInterval;
42219    END IF;
42220
42221 -- Get rid of any old reporting done by this user for the specified criteria
42222   DELETE FROM flrpt
42223    WHERE ((flrpt_flhead_id=pFlheadid)
42224      AND  (flrpt_period_id=pPeriodId)
42225      AND  (flrpt_interval=pInterval)
42226      AND  (flrpt_username=getEffectiveXtUser()));
42227
42228 -- Find out if we need to show a Grand Total and which if any of the values
42229 -- we want to show in that grand total.
42230   SELECT flhead_showtotal,
42231          CASE WHEN(flhead_showstart) THEN 0.00
42232               ELSE NULL
42233          END AS beginning,
42234          CASE WHEN(flhead_showend) THEN 0.00
42235               ELSE NULL
42236          END AS ending,
42237          CASE WHEN(flhead_showdelta) THEN 0.00
42238               ELSE NULL
42239          END AS debits,
42240          CASE WHEN(flhead_showdelta) THEN 0.00
42241               ELSE NULL
42242          END AS credits,
42243          CASE WHEN(flhead_showbudget) THEN 0.00
42244               ELSE NULL
42245          END AS budget,
42246          CASE WHEN(flhead_showdiff) THEN 0.00
42247               ELSE NULL
42248          END AS diff,
42249          CASE WHEN(flhead_showcustom) THEN 0.00
42250               ELSE NULL
42251          END AS custom,
42252          CASE WHEN(flhead_usealttotal) THEN flhead_alttotal
42253               ELSE NULL
42254          END AS altname INTO _r
42255     FROM flhead
42256    WHERE (flhead_id=pFlheadid);
42257   IF (NOT FOUND) THEN
42258     return FALSE;
42259   END IF;
42260
42261 -- If showing a Grand Total then create a record as a Group which acts
42262 -- as a parent to the whole report. This allows the code to update as
42263 -- it would for normal group total values.
42264   IF (_r.flhead_showtotal) THEN
42265     INSERT INTO flrpt
42266            (flrpt_flhead_id, flrpt_period_id, flrpt_username,
42267             flrpt_order, flrpt_level, flrpt_type, flrpt_type_id,
42268             flrpt_beginning, flrpt_ending,
42269             flrpt_debits, flrpt_credits, flrpt_budget, flrpt_diff,
42270             flrpt_custom, flrpt_altname, flrpt_interval )
42271     VALUES (pFlheadid, pPeriodid, getEffectiveXtUser(),
42272             0, -1, 'G', -1,
42273             _r.beginning, _r.ending,
42274             _r.debits, _r.credits, _r.budget, _r.diff,
42275             _r.custom, _r.altname, pInterval );
42276   END IF;
42277
42278   PERFORM insertFlGroup(pFlheadid, pPeriodid, -1, 0, FALSE, pInterval, pPrjid);
42279
42280 -- go through the list of records that need percentages calculated and perform
42281 -- those calculations.
42282   FOR _t IN SELECT flrpt_order, CASE WHEN(flgrp_prcnt_flgrp_id = -1) THEN flgrp_flgrp_id ELSE flgrp_prcnt_flgrp_id END AS flgrp_id
42283               FROM flrpt, flgrp
42284              WHERE ((flrpt_flhead_id=pFlheadid)
42285                AND  (flrpt_period_id=pPeriodid)
42286                AND  (flrpt_interval=pInterval)
42287                AND  (flrpt_username=getEffectiveXtUser())
42288                AND  (flrpt_type='G')
42289                AND  (flrpt_type_id=flgrp_id))
42290              UNION
42291             SELECT flrpt_order, CASE WHEN(flitem_prcnt_flgrp_id = -1) THEN flitem_flgrp_id ELSE flitem_prcnt_flgrp_id END AS flgrp_id
42292               FROM flrpt, flitem
42293              WHERE ((flrpt_flhead_id=pFlheadid)
42294                AND  (flrpt_period_id=pPeriodid)
42295                AND  (flrpt_interval=pInterval)
42296                AND  (flrpt_username=getEffectiveXtUser())
42297                AND  (flrpt_type='I')
42298                AND  (flrpt_type_id=flitem_id))
42299              UNION
42300             SELECT flrpt_order, CASE WHEN(flspec_prcnt_flgrp_id = -1) THEN flspec_flgrp_id ELSE flspec_prcnt_flgrp_id END AS flgrp_id
42301               FROM flrpt, flspec
42302              WHERE ((flrpt_flhead_id=pFlheadid)
42303                AND  (flrpt_period_id=pPeriodid)
42304                AND  (flrpt_interval=pInterval)
42305                AND  (flrpt_username=getEffectiveXtUser())
42306                AND  (flrpt_type='S')
42307                AND  (flrpt_type_id=flspec_id)) LOOP
42308
42309     IF( (_t.flgrp_id=-1) OR (NOT (SELECT flgrp_summarize FROM flgrp WHERE flgrp_id=_t.flgrp_id)) ) THEN
42310       SELECT COALESCE(SUM(flrpt_beginning),0) AS beginningTotal,
42311              COALESCE(SUM(flrpt_ending),0) AS endingTotal,
42312              COALESCE(SUM(flrpt_debits),0) AS debitsTotal,
42313              COALESCE(SUM(flrpt_credits),0) AS creditsTotal,
42314              COALESCE(SUM(flrpt_budget),0) AS budgetTotal,
42315              COALESCE(SUM(flrpt_diff), 0) AS diffTotal,
42316              COALESCE(SUM(flrpt_custom), 0) AS customTotal INTO _s
42317         FROM flrpt
42318        WHERE ((flrpt_flhead_id=pFlheadid)
42319          AND  (flrpt_period_id=pPeriodid)
42320          AND  (flrpt_interval=pInterval)
42321          AND  (flrpt_username=getEffectiveXtUser())
42322          AND  (flrpt_type != 'T')
42323          AND  (flrpt_parent_id=_t.flgrp_id));
42324     ELSE
42325       SELECT COALESCE(SUM(flrpt_beginning),0) AS beginningTotal,
42326              COALESCE(SUM(flrpt_ending),0) AS endingTotal,
42327              COALESCE(SUM(flrpt_debits),0) AS debitsTotal,
42328              COALESCE(SUM(flrpt_credits),0) AS creditsTotal,
42329              COALESCE(SUM(flrpt_budget),0) AS budgetTotal,
42330              COALESCE(SUM(flrpt_diff), 0) AS diffTotal,
42331              COALESCE(SUM(flrpt_custom), 0) AS customTotal INTO _s
42332         FROM flrpt
42333        WHERE ((flrpt_flhead_id=pFlheadid)
42334          AND  (flrpt_period_id=pPeriodid)
42335          AND  (flrpt_interval=pInterval)
42336          AND  (flrpt_username=getEffectiveXtUser())
42337          AND  (flrpt_type = 'G')
42338          AND  (flrpt_type_id=_t.flgrp_id));
42339     END IF;
42340
42341     UPDATE flrpt SET flrpt_beginningprcnt = flrpt_beginningprcnt + flrpt_beginning / CASE WHEN (_s.beginningTotal=0) THEN 1 ELSE _s.beginningTotal END,
42342                      flrpt_endingprcnt = flrpt_endingprcnt + flrpt_ending / CASE WHEN (_s.endingTotal=0) THEN 1 ELSE _s.endingTotal END,
42343                      flrpt_debitsprcnt = flrpt_debitsprcnt + flrpt_debits / CASE WHEN (_s.debitsTotal=0) THEN 1 ELSE _s.debitsTotal END,
42344                      flrpt_creditsprcnt = flrpt_creditsprcnt + flrpt_credits / CASE WHEN (_s.creditsTotal=0) THEN 1 ELSE _s.creditsTotal END,
42345                      flrpt_budgetprcnt = flrpt_budgetprcnt + flrpt_budget / CASE WHEN (_s.budgetTotal=0) THEN 1 ELSE _s.budgetTotal END,
42346                      flrpt_diffprcnt = flrpt_diffprcnt + flrpt_diff / CASE WHEN (_s.diffTotal=0) THEN 1 ELSE _s.diffTotal END,
42347                      flrpt_customprcnt = flrpt_customprcnt + flrpt_custom / CASE WHEN (_s.customTotal=0) THEN 1 ELSE _s.customTotal END
42348      WHERE ((flrpt_flhead_id=pFlheadid)
42349        AND  (flrpt_period_id=pPeriodid)
42350        AND  (flrpt_interval=pInterval)
42351        AND  (flrpt_username=getEffectiveXtUser())
42352        AND  (flrpt_order=_t.flrpt_order));
42353   END LOOP;
42354
42355
42356 -- Update any subtotal records to reflect the percentage values of the parents
42357 -- since those are calculated after the subtotal records were created.
42358   FOR _t IN SELECT a.flrpt_order AS flrpt_order,
42359                    b.flrpt_beginningprcnt AS flrpt_beginningprcnt,
42360                    b.flrpt_endingprcnt AS flrpt_endingprcnt,
42361                    b.flrpt_debitsprcnt AS flrpt_debitsprcnt,
42362                    b.flrpt_creditsprcnt AS flrpt_creditsprcnt,
42363                    b.flrpt_budgetprcnt AS flrpt_budgetprcnt,
42364                    b.flrpt_diffprcnt AS flrpt_diffprcnt,
42365                    b.flrpt_customprcnt AS flrpt_customprcnt
42366               FROM flrpt AS a, flrpt AS b
42367              WHERE ((a.flrpt_flhead_id=pFlheadid)
42368                AND  (a.flrpt_period_id=pPeriodid)
42369                AND  (a.flrpt_interval=pInterval)
42370                AND  (a.flrpt_username=getEffectiveXtUser())
42371                AND  (a.flrpt_type='T')
42372                AND  (b.flrpt_flhead_id=a.flrpt_flhead_id)
42373                AND  (b.flrpt_period_id=a.flrpt_period_id)
42374                AND  (b.flrpt_interval=pInterval)
42375                AND  (b.flrpt_username=a.flrpt_username)
42376                AND  (b.flrpt_type='G')
42377                AND  (b.flrpt_type_id=a.flrpt_parent_id)) LOOP
42378     UPDATE flrpt SET flrpt_beginningprcnt=flrpt_beginningprcnt + _t.flrpt_beginningprcnt,
42379                      flrpt_endingprcnt=flrpt_endingprcnt + _t.flrpt_endingprcnt,
42380                      flrpt_debitsprcnt=flrpt_debitsprcnt + _t.flrpt_debitsprcnt,
42381                      flrpt_creditsprcnt=flrpt_creditsprcnt + _t.flrpt_creditsprcnt,
42382                      flrpt_budgetprcnt=flrpt_budgetprcnt + _t.flrpt_budgetprcnt,
42383                      flrpt_diffprcnt=flrpt_diffprcnt + _t.flrpt_diffprcnt,
42384                      flrpt_customprcnt=flrpt_customprcnt + _t.flrpt_customprcnt
42385                WHERE ((flrpt_flhead_id=pFlheadid)
42386                  AND  (flrpt_period_id=pPeriodid)
42387                  AND  (flrpt_interval=pInterval)
42388                  AND  (flrpt_username=getEffectiveXtUser())
42389                  AND  (flrpt_order=_t.flrpt_order));
42390   END LOOP;
42391
42392 -- If showing a Grand total then move the record we created early to the
42393 -- end of the report and marked as a Total record.
42394   IF (_r.flhead_showtotal) THEN
42395     UPDATE flrpt
42396        SET flrpt_order = COALESCE((SELECT MAX(flrpt_order)
42397                                      FROM flrpt
42398                                     WHERE ((flrpt_flhead_id=pFlheadid)
42399                                       AND  (flrpt_period_id=pPeriodid)
42400                                       AND  (flrpt_interval=pInterval)
42401                                       AND  (flrpt_username=getEffectiveXtUser()))
42402                                   ), 0) + 1,
42403            flrpt_level = 0,
42404            flrpt_type = 'T'
42405      WHERE ((flrpt_flhead_id=pFlheadid)
42406        AND  (flrpt_period_id=pPeriodid)
42407        AND  (flrpt_interval=pInterval)
42408        AND  (flrpt_username=getEffectiveXtUser())
42409        AND  (flrpt_order=0)
42410        AND  (flrpt_level = -1)
42411        AND  (flrpt_type = 'G')
42412        AND  (flrpt_type_id=-1));
42413   END IF;
42414
42415   return TRUE;
42416 END;
42417 $_$;
42418
42419
42420 ALTER FUNCTION public.financialreport(integer, integer, character, integer) OWNER TO admin;
42421
42422 --
42423 -- TOC entry 1463 (class 1255 OID 146566136)
42424 -- Dependencies: 2678 4536 8
42425 -- Name: financialreport(integer, integer[], character, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
42426 --
42427
42428 CREATE FUNCTION financialreport(integer, integer[], character, boolean, integer) RETURNS SETOF fltrenditem
42429     LANGUAGE plpgsql
42430     AS $_$
42431 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42432 -- See www.xtuple.com/CPAL for the full text of the software license.
42433 DECLARE
42434   pFlheadId ALIAS FOR $1;
42435   pPeriodIds ALIAS FOR $2;
42436   pInterval ALIAS FOR $3;
42437   pShowNumbers ALIAS FOR $4;
42438   pPrjid ALIAS FOR $5;
42439   _row fltrenditem%ROWTYPE;
42440   _type CHAR;
42441   _p RECORD;
42442   _count INTEGER;
42443   _n NUMERIC;
42444   _fld NUMERIC[];
42445   _grndttl NUMERIC;
42446   _i INTEGER;
42447   _first BOOLEAN;
42448   _prevlevel INTEGER;
42449   _subgrp INTEGER;
42450
42451 BEGIN
42452         _first := true;
42453         _subgrp := 0;
42454
42455         IF ARRAY_UPPER(pPeriodIds,1) <= 12 THEN
42456                 _count := ARRAY_UPPER(pPeriodIds,1);
42457         ELSE
42458                 _count := 12;
42459         END IF;
42460
42461         --Get Type
42462         SELECT flhead_type FROM flhead INTO _type WHERE flhead_id=pFlheadId;
42463
42464         --Build Financial Data
42465         FOR _i IN 1.._count
42466         LOOP
42467                 PERFORM financialreport(pFlheadId,pPeriodIds[_i],pInterval,pPrjid);
42468         END LOOP;
42469
42470         --Get Row Data
42471         FOR _p IN
42472         SELECT flrpt_flhead_id,
42473                 flrpt_username,
42474                 flrpt_order,
42475                 flrpt_level,
42476                 flrpt_type,
42477                 flrpt_type_id,
42478                 flrpt_parent_id,
42479                 flrpt_accnt_id,
42480                 formatindent(flgrp.flgrp_name,flrpt.flrpt_level) AS flrpt_name,
42481                 CASE
42482                         WHEN (flgrp_summarize AND (_type IN ('I','C'))) THEN
42483                                 (COALESCE(flrpt_diff,0))
42484                         WHEN (flgrp_summarize AND (_type = 'B')) THEN
42485                                 (COALESCE(flrpt_ending,0))
42486                         ELSE NULL
42487                 END AS f_fld1,
42488                 flgrp_summarize AS display
42489         FROM flrpt,flgrp
42490         WHERE ((flrpt_flhead_id=pFlheadId)
42491         AND (flgrp_id=flrpt_type_id)
42492         AND (flrpt_type='G')
42493         AND (flrpt_period_id=pPeriodIds[1])
42494         AND (flrpt_interval=pInterval)
42495         AND (flrpt_username=getEffectiveXtUser()))
42496         UNION
42497         SELECT flrpt_flhead_id,
42498                 flrpt_username,
42499                 flrpt_order,
42500                 flrpt_level,
42501                 flrpt_type,
42502                 flrpt_type_id,
42503                 flrpt_parent_id,
42504                 flrpt_accnt_id,
42505                 formatindent(accnt_descrip,flrpt.flrpt_level) AS flrpt_name,
42506                 CASE
42507                         WHEN (_type IN ('I','C')) THEN
42508                                 (COALESCE(flrpt_diff,0))
42509                         WHEN (_type = 'B') THEN
42510                                 (COALESCE(flrpt_ending,0))
42511                         ELSE NULL
42512                 END AS f_fld1,
42513                 true AS display
42514         FROM flrpt,flitem,accnt
42515         WHERE ((flrpt_flhead_id=pFlheadId)
42516         AND (flrpt_accnt_id=accnt_id)
42517         AND (flitem_id=flrpt_type_id)
42518         AND (flrpt_type='I')
42519         AND (flrpt_period_id=pPeriodIds[1])
42520         AND (flrpt_interval=pInterval)
42521         AND (flrpt_username=getEffectiveXtUser()))
42522         UNION
42523         SELECT flrpt_flhead_id,
42524                 flrpt_username,
42525                 flrpt_order,
42526                 flrpt_level,
42527                 flrpt_type,
42528                 flrpt_type_id,
42529                 flrpt_parent_id,
42530                 flrpt_accnt_id,
42531                 CASE
42532                         WHEN (flrpt.flrpt_type='T' AND flrpt.flrpt_level=0) THEN
42533                                 COALESCE(flrpt.flrpt_altname, 'Total')
42534                         WHEN (flrpt.flrpt_type='T') THEN
42535                                 formatindent(COALESCE(flrpt.flrpt_altname, 'Subtotal') ,flrpt.flrpt_level) 
42536
42537                         ELSE
42538                                 formatindent(('Type ' || flrpt.flrpt_type || ' ' || text(flrpt.flrpt_type_id)), flrpt.flrpt_level)
42539                 END AS flstmtitem_name,
42540                 CASE
42541                         WHEN (_type IN ('I','C')) THEN
42542                                 (COALESCE(flrpt_diff,0))
42543                         WHEN (_type = 'B') THEN
42544                                 (COALESCE(flrpt_ending,0))
42545                         ELSE NULL
42546                 END AS f_fld1,
42547                 true AS display
42548         FROM flrpt
42549         WHERE ((flrpt_flhead_id=pFlheadId)
42550         AND (flrpt_type NOT IN ('I','S','G'))
42551         AND (flrpt_period_id=pPeriodIds[1])
42552         AND (flrpt_interval=pInterval)
42553         AND (flrpt_username=getEffectiveXtUser()))
42554         ORDER BY flrpt_order
42555         LOOP
42556
42557                 IF _type IN ('I','C') THEN
42558                         _grndttl := _p.f_fld1;
42559                 END IF;
42560
42561                 --Loop through and calculate period column values
42562                 IF (_p.display) THEN
42563                         FOR _i IN 2.._count
42564                         LOOP
42565                                 SELECT
42566                                 CASE
42567                                         WHEN (_type IN ('I','C')) THEN
42568                                                 COALESCE(flrpt_diff,0)
42569                                         WHEN (_type = 'B') THEN
42570                                                 COALESCE(flrpt_ending,0)
42571                                         ELSE NULL
42572                                 END INTO _n
42573                                 FROM flrpt
42574                                 WHERE ((flrpt_flhead_id=pFlheadId)
42575                                 AND (flrpt_period_id=pPeriodIds[_i])
42576                                 AND (flrpt_interval=pInterval)
42577                                 AND (flrpt_username=getEffectiveXtUser())
42578                                 AND (flrpt_order=_p.flrpt_order));
42579                                 _fld[_i-1] := _n;
42580                                 IF _type IN ('I','C') THEN
42581                                         _grndttl := _grndttl+_n;
42582                                 END IF;
42583                         END LOOP;
42584                 END IF;
42585
42586                 --Send it all back to the caller
42587                 IF _prevlevel > _p.flrpt_level THEN
42588                         _subgrp := _subgrp+1;
42589                 END IF;
42590                 _prevlevel:=_p.flrpt_level;
42591                 _row.fltrenditem_subgrp := _subgrp;
42592
42593                 IF NOT _first THEN
42594                         RETURN NEXT _row;
42595                 END IF;
42596
42597                 _first := FALSE;
42598
42599                 _row.fltrenditem_flhead_id := _p.flrpt_flhead_id;
42600                 _row.fltrenditem_username := _p.flrpt_username;
42601                 _row.fltrenditem_order := _p.flrpt_order;
42602                 _row.fltrenditem_level := _p.flrpt_level;
42603                 _row.fltrenditem_type := _p.flrpt_type;
42604                 _row.fltrenditem_type_id := _p.flrpt_type_id;
42605                 _row.fltrenditem_parent_id := _p.flrpt_parent_id;
42606                 _row.fltrenditem_accnt_id := _p.flrpt_accnt_id;
42607                 _row.fltrenditem_name := _p.flrpt_name;
42608                 IF (_p.display) THEN
42609                         _row.fltrenditem_fld1 := (_p.f_fld1);
42610                         _row.fltrenditem_fld2 := (_fld[1]);
42611                         _row.fltrenditem_fld3 := (_fld[2]);
42612                         _row.fltrenditem_fld4 := (_fld[3]);
42613                         _row.fltrenditem_fld5 := (_fld[4]);
42614                         _row.fltrenditem_fld6 := (_fld[5]);
42615                         _row.fltrenditem_fld7 := (_fld[6]);
42616                         _row.fltrenditem_fld8 := (_fld[7]);
42617                         _row.fltrenditem_fld9 := (_fld[8]);
42618                         _row.fltrenditem_fld10 := (_fld[9]);
42619                         _row.fltrenditem_fld11 := (_fld[10]);
42620                         _row.fltrenditem_fld12 := (_fld[11]);
42621                         _row.fltrenditem_grndttl := (_grndttl);
42622                 ELSE
42623                         _row.fltrenditem_fld1 := NULL;
42624                         _row.fltrenditem_fld2 := NULL;
42625                         _row.fltrenditem_fld3 := NULL;
42626                         _row.fltrenditem_fld4 := NULL;
42627                         _row.fltrenditem_fld5 := NULL;
42628                         _row.fltrenditem_fld6 := NULL;
42629                         _row.fltrenditem_fld7 := NULL;
42630                         _row.fltrenditem_fld8 := NULL;
42631                         _row.fltrenditem_fld9 := NULL;
42632                         _row.fltrenditem_fld10 := NULL;
42633                         _row.fltrenditem_fld11 := NULL;
42634                         _row.fltrenditem_fld12 := NULL;
42635                         _row.fltrenditem_grndttl := NULL;
42636                 END IF;
42637
42638         END LOOP;
42639
42640         _row.fltrenditem_subgrp := _subgrp + 1;
42641         RETURN NEXT _row;
42642
42643 END;
42644 $_$;
42645
42646
42647 ALTER FUNCTION public.financialreport(integer, integer[], character, boolean, integer) OWNER TO admin;
42648
42649 --
42650 -- TOC entry 1478 (class 1255 OID 146566138)
42651 -- Dependencies: 2672 4536 8
42652 -- Name: financialreport(integer, integer, boolean, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
42653 --
42654
42655 CREATE FUNCTION financialreport(integer, integer, boolean, boolean, integer) RETURNS SETOF flstmtitem
42656     LANGUAGE plpgsql
42657     AS $_$
42658 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
42659 -- See www.xtuple.com/CPAL for the full text of the software license.
42660 DECLARE
42661   pFlcolid ALIAS FOR $1;
42662   pPeriodid ALIAS FOR $2;
42663   pShowNumbers ALIAS FOR $3;
42664   pIndentName ALIAS FOR $4;
42665   pPrjid ALIAS FOR $5;
42666   _row flstmtitem%ROWTYPE;
42667   _p RECORD;
42668   _x RECORD;
42669   _priorMoPeriodId INTEGER;
42670   _priorQtPeriodId INTEGER;
42671   _priorYrPeriodId INTEGER;
42672   _first BOOLEAN;
42673   _prevlevel INTEGER;
42674   _subgrp INTEGER;
42675   _qtrInterval TEXT;
42676   _yrInterval TEXT;
42677
42678 BEGIN
42679
42680   _priorMoPeriodId := -1;
42681   _priorQtPeriodId := -1;
42682   _priorYrPeriodId := -1;
42683   _first := TRUE;
42684   _prevlevel :=0;
42685   _subgrp := 0;
42686
42687 --Get Layout Data
42688   SELECT flhead_id,flhead_type,
42689         flcol_month,flcol_quarter,flcol_year,flcol_priortype,
42690         flcol_priormonth,flcol_priorquarter,flcol_prioryear,
42691         flcol_priordiff,flcol_priordiffprcnt,flcol_priorprcnt,
42692         flcol_budget,flcol_budgetdiff,flcol_budgetdiffprcnt,
42693         flcol_budgetprcnt INTO _p
42694   FROM flhead,flcol
42695   WHERE ((flcol_id=pFlcolid)
42696   AND (flhead_id=flcol_flhead_id));
42697
42698   IF (_p.flhead_type='B') THEN
42699     _qtrInterval := 'M';
42700     _yrInterval := 'M';
42701   ELSE
42702     _qtrInterval := 'Q';
42703     _yrInterval := 'Y';
42704   END IF;
42705
42706 --Delete old data from all periods
42707   DELETE FROM flrpt
42708   WHERE ((flrpt_username=getEffectiveXtUser())
42709   AND (flrpt_flhead_id=_p.flhead_id));
42710
42711 --Populate report data...
42712 --...for Month
42713         IF (_p.flcol_month) THEN
42714
42715         PERFORM financialreport(_p.flhead_id,pPeriodid,'M',pPrjid);
42716
42717                 IF ((_p.flcol_priortype = 'P') AND (_p.flcol_priormonth)) THEN
42718
42719                         SELECT COALESCE(pp.period_id,-1) INTO _priorMoPeriodId
42720                         FROM period cp, period pp
42721                         WHERE ((cp.period_id=pPeriodId)
42722                         AND (cp.period_start > pp.period_start))
42723                         ORDER BY pp.period_start DESC LIMIT 1;
42724
42725                         IF (_priorMoPeriodId IS NOT NULL) THEN
42726                                 PERFORM financialreport(_p.flhead_id,_priorMoPeriodId,'M',pPrjid);
42727                         END IF;
42728
42729                         ELSE IF ((_p.flcol_priortype='Y')AND (_p.flcol_priormonth)) THEN
42730
42731                                 SELECT COALESCE(pp.period_id,-1) INTO _priorMoPeriodId
42732                                 FROM period cp, period pp
42733                                 WHERE ((cp.period_id=pPeriodId)
42734                                 AND (cp.period_id != pp.period_id)
42735                                 AND (cp.period_start > pp.period_start)
42736                                 AND (cp.period_number = pp.period_number))
42737                                 ORDER BY pp.period_start DESC LIMIT 1;
42738
42739                                 IF (_priorMoPeriodId IS NOT NULL) THEN
42740                                         PERFORM financialreport(_p.flhead_id,_priorMoPeriodId,'M',pPrjid);
42741                                 END IF;
42742
42743                         END IF;
42744
42745                 END IF;
42746         END IF;
42747
42748 --...for Quarter
42749         IF (_p.flcol_quarter) THEN
42750
42751         PERFORM financialreport(_p.flhead_id,pPeriodid,'Q',pPrjid);
42752
42753         END IF;
42754
42755         IF ((_p.flcol_priortype='P') AND (_p.flcol_priorquarter)) THEN
42756
42757                 SELECT COALESCE(pp.period_id,-1) INTO _priorQtPeriodId
42758                 FROM period cp, period pp
42759                 WHERE ((cp.period_id=pPeriodId)
42760                 AND (cp.period_start > pp.period_start)
42761                 AND (pp.period_quarter=
42762                         CASE WHEN cp.period_quarter > 1 THEN
42763                                 cp.period_quarter - 1
42764                         ELSE 4 END)
42765                 AND (pp.period_start >= cp.period_start - interval '1 year'))
42766                 ORDER BY pp.period_start DESC LIMIT 1;
42767
42768                 IF (_priorQtPeriodId IS NOT NULL) THEN
42769                         PERFORM financialreport(_p.flhead_id,_priorQtPeriodId,'Q',pPrjid);
42770                 END IF;
42771
42772                 ELSE IF ((_p.flcol_priortype='Y')AND (_p.flcol_priorquarter)) THEN
42773
42774                         SELECT pp.period_id INTO _priorQtPeriodId
42775                         FROM period cp, period pp, yearperiod cy, yearperiod py
42776                         WHERE ((cp.period_id=pPeriodId)
42777                         AND (cp.period_yearperiod_id=cy.yearperiod_id)
42778                         AND (pp.period_yearperiod_id=py.yearperiod_id)
42779                         AND (cp.period_quarter=pp.period_quarter)
42780                         AND (cy.yearperiod_start > py.yearperiod_start))
42781                         ORDER BY py.yearperiod_start DESC, pp.period_start DESC LIMIT 1;
42782
42783                         IF (_priorQtPeriodId IS NOT NULL) THEN
42784                                 PERFORM financialreport(_p.flhead_id,_priorQtPeriodId,'Q',pPrjid);
42785                         END IF;
42786
42787                 END IF;
42788         END IF;
42789
42790 --...for Year
42791         IF (_p.flcol_year) THEN
42792
42793                 PERFORM financialreport(_p.flhead_id,pPeriodid,'Y',pPrjid);
42794
42795         END IF;
42796
42797         IF (_p.flcol_prioryear='D') THEN
42798
42799                 SELECT COALESCE(pp.period_id,-1) INTO _priorYrPeriodId
42800                 FROM period cp, period pp
42801                 WHERE ((cp.period_id = pPeriodId)
42802                 AND (cp.period_number = pp.period_number)
42803                 AND (cp.period_start > pp.period_start))
42804                 ORDER BY pp.period_start DESC LIMIT 1;
42805
42806                 IF (_priorYrPeriodId IS NOT NULL) THEN
42807                         PERFORM financialreport(_p.flhead_id,_priorYrPeriodId,'Y',pPrjid);
42808                 END IF;
42809
42810                 ELSE IF (_p.flcol_prioryear='F') THEN
42811
42812                         SELECT pp.period_id INTO _priorYrPeriodId
42813                         FROM period cp, period pp, yearperiod cy, yearperiod py
42814                         WHERE ((cp.period_id=pPeriodId)
42815                         AND (cp.period_yearperiod_id=cy.yearperiod_id)
42816                         AND (pp.period_yearperiod_id=py.yearperiod_id)
42817                         AND (cy.yearperiod_start > py.yearperiod_start))
42818                         ORDER BY pp.period_start DESC LIMIT 1;
42819
42820                         IF (_priorYrPeriodId IS NOT NULL) THEN
42821                                 PERFORM financialreport(_p.flhead_id,_priorYrPeriodId,'Y',pPrjid);
42822                         END IF;
42823
42824                 END IF;
42825         END IF;
42826
42827 --Return the data
42828   FOR _x IN
42829         SELECT
42830         flrpt.flrpt_flhead_id AS flstmtitem_flhead_id,
42831         flrpt.flrpt_period_id AS flstmtitem_period_id,
42832         flrpt.flrpt_username AS flstmtitem_username,
42833         flrpt.flrpt_order AS flstmtitem_order,
42834         flrpt.flrpt_level AS flstmtitem_level,
42835         flrpt.flrpt_type AS flstmtitem_type,
42836         flrpt.flrpt_type_id AS flstmtitem_type_id,
42837         flrpt.flrpt_parent_id AS flstmtitem_parent_id,
42838         NULL AS flstmtitem_accnt_id,
42839         CASE
42840                 WHEN (pIndentName) THEN
42841                         formatindent(flgrp.flgrp_name,flrpt.flrpt_level)
42842                 ELSE flgrp.flgrp_name
42843         END AS flstmtitem_name,
42844         CASE
42845                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C'))) THEN
42846                         (COALESCE(flrptmo.flrpt_diff,0))
42847                 WHEN (flgrp_summarize AND (flhead_type = 'B')) THEN
42848                         (COALESCE(flrptmo.flrpt_ending,0))
42849                 ELSE NULL
42850         END AS flstmtitem_month,
42851         CASE
42852                 WHEN (flgrp_summarize) THEN
42853                         (COALESCE(flrptmo.flrpt_debits,0))
42854                 ELSE NULL
42855         END AS flstmtitem_monthdb,
42856         CASE
42857                 WHEN (flgrp_summarize) THEN
42858                         (COALESCE(flrptmo.flrpt_credits,0))
42859                 ELSE NULL
42860         END AS flstmtitem_monthcr,
42861         CASE
42862                 WHEN (flgrp_summarize AND flgrp_showdiffprcnt) THEN
42863                         (COALESCE(flrptmo.flrpt_diffprcnt,0))
42864                 WHEN (flgrp_summarize AND flgrp_showendprcnt) THEN
42865                         (COALESCE(flrptmo.flrpt_endingprcnt,0))
42866                 ELSE NULL
42867         END AS flstmtitem_monthprcnt,
42868         CASE
42869                 WHEN (flgrp_summarize) THEN
42870                         (flrptmo.flrpt_budget)
42871                 ELSE NULL
42872         END AS flstmtitem_monthbudget,
42873         CASE
42874                 WHEN (flgrp_summarize) THEN
42875                         (flrptmo.flrpt_budgetprcnt)
42876                 ELSE NULL
42877         END AS flstmtitem_monthbudgetprcnt,
42878         CASE
42879                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
42880                         (COALESCE((flrptmo.flrpt_diff-flrptmo.flrpt_budget),0))
42881                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
42882                         (COALESCE((flrptmo.flrpt_ending-flrptmo.flrpt_budget),0))
42883                 ELSE NULL
42884         END AS flstmtitem_monthbudgetdiff,
42885         CASE
42886                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C')) AND (flrptmo.flrpt_budget > 0)) THEN
42887                         (COALESCE(((flrptmo.flrpt_diff-flrptmo.flrpt_budget)/flrptmo.flrpt_budget),0))
42888                 WHEN (flgrp_summarize AND (flhead_type='B') AND (flrptmo.flrpt_budget > 0)) THEN
42889                         (COALESCE(((flrptmo.flrpt_ending-flrptmo.flrpt_budget)/flrptmo.flrpt_budget),0))
42890                 WHEN (flgrp_summarize AND (flrptmo.flrpt_budget = 0)) THEN
42891                         NULL
42892                 ELSE NULL
42893         END AS flstmtitem_monthbudgetdiffprcnt,
42894         CASE
42895                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
42896                         (COALESCE(flrptqt.flrpt_diff,0))
42897                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
42898                         (COALESCE(flrptqt.flrpt_ending,0))
42899                 ELSE NULL
42900         END AS flstmtitem_qtr,
42901         CASE
42902                 WHEN (flgrp_summarize) THEN
42903                         (COALESCE(flrptqt.flrpt_debits,0))
42904                 ELSE NULL
42905         END AS flstmtitem_qtrdb,
42906         CASE
42907                 WHEN (flgrp_summarize) THEN
42908                         (COALESCE(flrptqt.flrpt_credits,0))
42909                 ELSE NULL
42910         END AS flstmtitem_qtrcr,
42911         CASE
42912                 WHEN (flgrp_summarize AND flgrp_showdiffprcnt) THEN
42913                         (flrptqt.flrpt_diffprcnt)
42914                 WHEN (flgrp_summarize AND flgrp_showendprcnt) THEN
42915                         (flrptqt.flrpt_endingprcnt)
42916                 ELSE NULL
42917         END AS flstmtitem_qtrprcnt,
42918         CASE
42919                 WHEN (flgrp_summarize) THEN
42920                         (COALESCE(flrptqt.flrpt_budget,0))
42921                 ELSE NULL
42922         END AS flstmtitem_qtrbudget,
42923         CASE
42924                 WHEN (flgrp_summarize) THEN
42925                         (flrptqt.flrpt_budgetprcnt)
42926                 ELSE NULL
42927         END AS flstmtitem_qtrbudgetprcnt,
42928         CASE
42929                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
42930                         (COALESCE((flrptqt.flrpt_diff-flrptqt.flrpt_budget),0))
42931                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
42932                         (COALESCE((flrptqt.flrpt_ending-flrptqt.flrpt_budget),0))
42933                 ELSE NULL
42934         END AS flstmtitem_qtrbudgetdiff,
42935         CASE
42936                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C')) AND (flrptqt.flrpt_budget > 0)) THEN
42937                         (COALESCE(((flrptqt.flrpt_diff-flrptqt.flrpt_budget)/flrptqt.flrpt_budget),0))
42938                 WHEN (flgrp_summarize AND (flhead_type='B') AND (flrptqt.flrpt_budget > 0)) THEN
42939                         (COALESCE(((flrptqt.flrpt_ending-flrptqt.flrpt_budget)/flrptqt.flrpt_budget),0))
42940                 ELSE NULL
42941         END AS flstmtitem_qtrbudgetdiffprcnt,
42942         CASE
42943                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
42944                         (COALESCE(flrptyr.flrpt_diff,0))
42945                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
42946                         (COALESCE(flrptyr.flrpt_ending,0))
42947                 ELSE NULL
42948         END AS flstmtitem_year,
42949         CASE
42950                 WHEN (flgrp_summarize) THEN
42951                         (COALESCE(flrptyr.flrpt_debits,0))
42952                 ELSE NULL
42953         END AS flstmtitem_yeardb,
42954         CASE
42955                 WHEN (flgrp_summarize) THEN
42956                         (COALESCE(flrptyr.flrpt_credits,0))
42957                 ELSE NULL
42958         END AS flstmtitem_yearcr,
42959         CASE
42960                 WHEN (flgrp_summarize AND flgrp_showdiffprcnt) THEN
42961                         (COALESCE(flrptyr.flrpt_diffprcnt,0))
42962                 WHEN (flgrp_summarize AND flgrp_showendprcnt) THEN
42963                         (COALESCE(flrptyr.flrpt_endingprcnt,0))
42964                 ELSE NULL
42965         END AS flstmtitem_yearprcnt,
42966         CASE
42967                 WHEN (flgrp_summarize) THEN
42968                         (flrptyr.flrpt_budget)
42969                 ELSE NULL
42970         END AS  flstmtitem_yearbudget,
42971         CASE
42972                 WHEN (flgrp_summarize) THEN
42973                         (flrptyr.flrpt_budgetprcnt)
42974                 ELSE NULL
42975         END AS flstmtitem_yearbudgetprcnt,
42976         CASE
42977                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
42978                         (COALESCE((flrptyr.flrpt_diff-flrptyr.flrpt_budget),0))
42979                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
42980                         (COALESCE((flrptyr.flrpt_ending-flrptyr.flrpt_budget),0))
42981                 ELSE NULL
42982         END AS flstmtitem_yearbudgetdiff,
42983         CASE
42984                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C')) AND (flrptyr.flrpt_budget > 0)) THEN
42985                         (COALESCE(((flrptyr.flrpt_diff-flrptyr.flrpt_budget)/flrptyr.flrpt_budget),0))
42986                 WHEN (flgrp_summarize AND (flhead_type = 'B') AND (flrptyr.flrpt_budget > 0)) THEN
42987                         (COALESCE(((flrptyr.flrpt_ending-flrptyr.flrpt_budget)/flrptyr.flrpt_budget),0))
42988                 WHEN (flgrp_summarize AND (flrptyr.flrpt_budget = 0)) THEN
42989                         NULL
42990                 ELSE NULL
42991         END AS flstmtitem_yearbudgetdiffprcnt,
42992         CASE
42993                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
42994                         (COALESCE(flrptprmo.flrpt_diff,0))
42995                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
42996                         (COALESCE(flrptprmo.flrpt_ending,0))
42997                 ELSE NULL
42998         END AS flstmtitem_prmonth,
42999         CASE
43000                 WHEN (flgrp_summarize AND flgrp_showdiffprcnt) THEN
43001                         (flrptprmo.flrpt_diffprcnt)
43002                 WHEN (flgrp_summarize AND flgrp_showendprcnt) THEN
43003                         (flrptprmo.flrpt_endingprcnt)
43004                 ELSE NULL
43005         END AS flstmtitem_prmonthprcnt,
43006         CASE
43007                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
43008                         (COALESCE(flrptmo.flrpt_diff-flrptprmo.flrpt_diff,0))
43009                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
43010                         (COALESCE(flrptmo.flrpt_ending-flrptprmo.flrpt_ending,0))
43011                 ELSE NULL
43012         END AS flstmtitem_prmonthdiff,
43013         CASE
43014                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C')) AND (flrptprmo.flrpt_diff > 0)) THEN
43015                         (COALESCE((flrptmo.flrpt_diff-flrptprmo.flrpt_diff)/flrptprmo.flrpt_diff,0))
43016                 WHEN (flgrp_summarize AND (flhead_type = 'B') AND (flrptprmo.flrpt_ending > 0)) THEN
43017                         (COALESCE((flrptmo.flrpt_ending-flrptprmo.flrpt_ending)/flrptprmo.flrpt_ending,0))
43018                 WHEN (flgrp_summarize AND (flrptprmo.flrpt_ending = 0)) THEN
43019                         NULL
43020                 ELSE NULL
43021         END AS flstmtitem_prmonthdiffprcnt,
43022         CASE
43023                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
43024                         (COALESCE(flrptprqt.flrpt_diff,0))
43025                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
43026                         (COALESCE(flrptprqt.flrpt_ending,0))
43027                 ELSE NULL
43028         END AS flstmtitem_prqtr,
43029         CASE
43030                 WHEN (flgrp_summarize AND flgrp_showdiffprcnt) THEN
43031                         (flrptprqt.flrpt_diffprcnt)
43032                 WHEN (flgrp_summarize AND flgrp_showendprcnt) THEN
43033                         (flrptprqt.flrpt_endingprcnt)
43034                 ELSE NULL
43035         END AS flstmtitem_prqtrprcnt,
43036         CASE
43037                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
43038                         (COALESCE(flrptqt.flrpt_diff-flrptprqt.flrpt_diff,0))
43039                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
43040                         (COALESCE(flrptqt.flrpt_ending-flrptprqt.flrpt_ending,0))
43041                 ELSE NULL
43042         END AS flstmtitem_prqtrdiff,
43043         CASE
43044                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C')) AND (flrptprqt.flrpt_diff > 0)) THEN
43045                         (COALESCE((flrptqt.flrpt_diff-flrptprqt.flrpt_diff)/flrptprqt.flrpt_diff,0))
43046                 WHEN (flgrp_summarize AND (flhead_type = 'B') AND (flrptprqt.flrpt_ending > 0)) THEN
43047                         (COALESCE((flrptqt.flrpt_ending-flrptprqt.flrpt_ending)/flrptprqt.flrpt_ending,0))
43048                 WHEN (flgrp_summarize AND (flrptprqt.flrpt_ending = 0)) THEN
43049                         NULL
43050                 ELSE NULL
43051         END AS flstmtitem_prqtrdiffprcnt,
43052         CASE
43053                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
43054                         (COALESCE(flrptpryr.flrpt_diff,0))
43055                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
43056                         (COALESCE(flrptpryr.flrpt_ending,0))
43057                 ELSE NULL
43058         END AS flstmtitem_pryear,
43059         CASE
43060                 WHEN (flgrp_summarize AND flgrp_showdiffprcnt) THEN
43061                         (flrptpryr.flrpt_diffprcnt)
43062                 WHEN (flgrp_summarize AND flgrp_showendprcnt) THEN
43063                         (flrptpryr.flrpt_endingprcnt)
43064                 ELSE NULL
43065         END AS flstmtitem_pryearprcnt,
43066         CASE
43067                 WHEN (flgrp_summarize AND flhead_type IN ('I','C')) THEN
43068                         (COALESCE(flrptyr.flrpt_diff-flrptpryr.flrpt_diff,0))
43069                 WHEN (flgrp_summarize AND flhead_type = 'B') THEN
43070                         (COALESCE(flrptyr.flrpt_ending-flrptpryr.flrpt_ending,0))
43071                 ELSE NULL
43072         END AS flstmtitem_pryeardiff,
43073         CASE
43074                 WHEN (flgrp_summarize AND (flhead_type IN ('I','C')) AND (flrptpryr.flrpt_diff > 0)) THEN
43075                         (COALESCE((flrptyr.flrpt_diff-flrptpryr.flrpt_diff)/flrptpryr.flrpt_diff,0))
43076                 WHEN (flgrp_summarize AND (flhead_type = 'B' ) AND (flrptpryr.flrpt_ending > 0)) THEN
43077                         (COALESCE((flrptyr.flrpt_ending-flrptpryr.flrpt_ending)/flrptpryr.flrpt_ending,0))
43078                 WHEN (flgrp_summarize AND (flrptpryr.flrpt_ending = 0)) THEN
43079                         NULL
43080                 ELSE NULL
43081         END AS flstmtitem_pryeardiffprcnt
43082         FROM flgrp,flhead,
43083                 (SELECT DISTINCT
43084                         flrpt_flhead_id,
43085                         flrpt_period_id,
43086                         flrpt_username,
43087                         flrpt_order,
43088                         flrpt_level,
43089                         flrpt_type,
43090                         flrpt_type_id,
43091                         flrpt_parent_id
43092                 FROM flrpt
43093                 WHERE ((flrpt_type='G')
43094                 AND (flrpt_flhead_id=_p.flhead_id)
43095                 AND (flrpt_period_id=pPeriodId)
43096                 AND (flrpt_username=getEffectiveXtUser()))) AS flrpt
43097                         LEFT OUTER JOIN flrpt flrptmo
43098                                 ON ((flrptmo.flrpt_type=flrpt.flrpt_type)
43099                                 AND (flrptmo.flrpt_type_id=flrpt.flrpt_type_id)
43100                                 AND (flrptmo.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43101                                 AND (flrptmo.flrpt_period_id=flrpt.flrpt_period_id)
43102                                 AND (flrptmo.flrpt_interval='M')
43103                                 AND (flrptmo.flrpt_username=flrpt.flrpt_username)
43104                                 AND (flrptmo.flrpt_order=flrpt.flrpt_order))
43105                         LEFT OUTER JOIN flrpt flrptqt
43106                                 ON ((flrptqt.flrpt_type=flrpt.flrpt_type)
43107                                 AND (flrptqt.flrpt_type_id=flrpt.flrpt_type_id)
43108                                 AND (flrptqt.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43109                                 AND (flrptqt.flrpt_period_id=flrpt.flrpt_period_id)
43110                                 AND (flrptqt.flrpt_interval=_qtrInterval)
43111                                 AND (flrptqt.flrpt_username=flrpt.flrpt_username)
43112                                 AND (flrptqt.flrpt_order=flrpt.flrpt_order))
43113                         LEFT OUTER JOIN flrpt flrptyr
43114                                 ON ((flrptyr.flrpt_type=flrpt.flrpt_type)
43115                                 AND (flrptyr.flrpt_type_id=flrpt.flrpt_type_id)
43116                                 AND (flrptyr.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43117                                 AND (flrptyr.flrpt_period_id=flrpt.flrpt_period_id)
43118                                 AND (flrptyr.flrpt_interval=_yrInterval)
43119                                 AND (flrptyr.flrpt_username=flrpt.flrpt_username)
43120                                 AND (flrptyr.flrpt_order=flrpt.flrpt_order))
43121                         LEFT OUTER JOIN flrpt flrptprmo
43122                                 ON ((flrptprmo.flrpt_type=flrpt.flrpt_type)
43123                                 AND (flrptprmo.flrpt_type_id=flrpt.flrpt_type_id)
43124                                 AND (flrptprmo.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43125                                 AND (flrptprmo.flrpt_period_id=_priorMoPeriodId)
43126                                 AND (flrptprmo.flrpt_interval='M')
43127                                 AND (flrptprmo.flrpt_username=flrpt.flrpt_username)
43128                                 AND (flrptprmo.flrpt_order=flrpt.flrpt_order))
43129                         LEFT OUTER JOIN flrpt flrptprqt
43130                                 ON ((flrptprqt.flrpt_type=flrpt.flrpt_type)
43131                                 AND (flrptprqt.flrpt_type_id=flrpt.flrpt_type_id)
43132                                 AND (flrptprqt.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43133                                 AND (flrptprqt.flrpt_period_id=_priorQtPeriodId)
43134                                 AND (flrptprqt.flrpt_interval='Q')
43135                                 AND (flrptprqt.flrpt_username=flrpt.flrpt_username)
43136                                 AND (flrptprqt.flrpt_order=flrpt.flrpt_order))
43137                         LEFT OUTER JOIN flrpt flrptpryr
43138                                 ON ((flrptpryr.flrpt_type=flrpt.flrpt_type)
43139                                 AND (flrptpryr.flrpt_type_id=flrpt.flrpt_type_id)
43140                                 AND (flrptpryr.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43141                                 AND (flrptpryr.flrpt_period_id=_priorYrPeriodId)
43142                                 AND (flrptpryr.flrpt_interval='Y')
43143                                 AND (flrptpryr.flrpt_username=flrpt.flrpt_username)
43144                                 AND (flrptpryr.flrpt_order=flrpt.flrpt_order))
43145         WHERE ((flgrp_id = flrpt.flrpt_type_id)
43146         AND (flhead_id = flgrp_flhead_id))
43147         UNION
43148         SELECT
43149         flrpt.flrpt_flhead_id AS flstmtitem_flhead_id,
43150         flrpt.flrpt_period_id AS flstmtitem_period_id,
43151         flrpt.flrpt_username AS flstmtitem_username,
43152         flrpt.flrpt_order AS flstmtitem_order,
43153         flrpt.flrpt_level AS flstmtitem_level,
43154         flrpt.flrpt_type AS flstmtitem_type,
43155         flrpt.flrpt_type_id AS flstmtitem_type_id,
43156         flrpt.flrpt_parent_id AS flstmtitem_parent_id,
43157         flrpt.flrpt_accnt_id AS flstmtitem_accnt_id,
43158         CASE
43159                 WHEN (pIndentName) THEN
43160                         formatindent(flrpt.flrpt_name,flrpt.flrpt_level)
43161                 ELSE flrpt.flrpt_name
43162         END AS flstmtitem_name,
43163         CASE
43164                 WHEN (flhead_type IN ('I','C')) THEN
43165                         (COALESCE(flrptmo.flrpt_diff,0))
43166                 ELSE (COALESCE(flrptmo.flrpt_ending,0))
43167         END AS flstmtitem_month,
43168         (COALESCE(flrptmo.flrpt_debits,0)) AS flstmtitem_monthdb,
43169         (COALESCE(flrptmo.flrpt_credits,0)) AS flstmtitem_monthcr,
43170         CASE
43171                 WHEN (flitem_showdiffprcnt) THEN
43172                         (flrptmo.flrpt_diffprcnt)
43173                 WHEN (flitem_showendprcnt) THEN
43174                         (flrptmo.flrpt_endingprcnt)
43175                 ELSE NULL
43176         END AS flstmtitem_monthprcnt,
43177         (COALESCE(flrptmo.flrpt_budget,0)) AS flstmtitem_monthbudget,
43178         (flrptmo.flrpt_budgetprcnt) AS flstmtitem_monthbudgetprcnt,
43179         CASE
43180                 WHEN (flhead_type IN ('I','C')) THEN
43181                         (COALESCE((flrptmo.flrpt_diff-flrptmo.flrpt_budget),0))
43182                 ELSE (COALESCE((flrptmo.flrpt_ending-flrptmo.flrpt_budget),0))
43183         END AS flstmtitem_monthbudgetdiff,
43184         CASE
43185                 WHEN ((flhead_type IN ('I','C')) AND (flrptmo.flrpt_budget > 0)) THEN
43186                         (COALESCE(((flrptmo.flrpt_diff-flrptmo.flrpt_budget)/flrptmo.flrpt_budget),0))
43187                 WHEN ((flhead_type='B') AND (flrptmo.flrpt_budget > 0)) THEN
43188                         (COALESCE(((flrptmo.flrpt_ending-flrptmo.flrpt_budget)/flrptmo.flrpt_budget),0))
43189                 ELSE NULL
43190         END AS flstmtitem_monthbudgetdiffprcnt,
43191         CASE
43192                 WHEN (flhead_type IN ('I','C')) THEN
43193                         (COALESCE(flrptqt.flrpt_diff,0))
43194                 ELSE (COALESCE(flrptqt.flrpt_ending,0))
43195         END AS flstmtitem_qtr,
43196         (COALESCE(flrptqt.flrpt_debits,0)) AS flstmtitem_qtrdb,
43197         (COALESCE(flrptqt.flrpt_credits,0)) AS flstmtitem_qtrcr,
43198         CASE
43199                 WHEN (flitem_showdiffprcnt) THEN
43200                         (COALESCE(flrptqt.flrpt_diffprcnt,0))
43201                 WHEN (flitem_showendprcnt) THEN
43202                         (COALESCE(flrptqt.flrpt_endingprcnt,0))
43203                 ELSE NULL
43204         END AS flstmtitem_qtrprcnt,
43205         (COALESCE(flrptqt.flrpt_budget,0)) AS flstmtitem_qtrbudget,
43206         (flrptqt.flrpt_budgetprcnt) AS flstmtitem_qtrbudgetprcnt,
43207         CASE
43208                 WHEN (flhead_type IN ('I','C')) THEN
43209                         (COALESCE((flrptqt.flrpt_diff-flrptqt.flrpt_budget),0))
43210                 ELSE (COALESCE((flrptqt.flrpt_ending-flrptqt.flrpt_budget),0))
43211         END AS flstmtitem_qtrbudgetdiff,
43212         CASE
43213                 WHEN ((flhead_type IN ('I','C')) AND (flrptqt.flrpt_budget > 0)) THEN
43214                         (COALESCE(((flrptqt.flrpt_diff-flrptqt.flrpt_budget)/flrptqt.flrpt_budget),0))
43215                 WHEN ((flhead_type='B') AND (flrptqt.flrpt_budget > 0)) THEN
43216                         (COALESCE(((flrptqt.flrpt_ending-flrptqt.flrpt_budget)/flrptqt.flrpt_budget),0))
43217                 ELSE NULL
43218         END AS flstmtitem_qtrbudgetdiffprcnt,
43219         CASE
43220                 WHEN (flhead_type IN ('I','C')) THEN
43221                         (COALESCE(flrptyr.flrpt_diff,0))
43222                 ELSE (COALESCE(flrptyr.flrpt_ending,0))
43223         END AS flstmtitem_year,
43224         (COALESCE(flrptyr.flrpt_debits,0)) AS flstmtitem_yeardb,
43225         (COALESCE(flrptyr.flrpt_credits,0)) AS flstmtitem_yearcr,
43226         CASE
43227                 WHEN (flitem_showdiffprcnt) THEN
43228                         (flrptyr.flrpt_diffprcnt)
43229                 WHEN (flitem_showendprcnt) THEN
43230                         (flrptyr.flrpt_endingprcnt)
43231                 ELSE NULL
43232         END AS flstmtitem_yearprcnt,
43233         (COALESCE(flrptyr.flrpt_budget,0)) AS  flstmtitem_yearbudget,
43234         (flrptyr.flrpt_budgetprcnt) AS flstmtitem_yearbudgetprcnt,
43235         CASE
43236                 WHEN (flhead_type IN ('I','C')) THEN
43237                         (COALESCE((flrptyr.flrpt_diff-flrptyr.flrpt_budget),0))
43238                 ELSE (COALESCE((flrptyr.flrpt_ending-flrptyr.flrpt_budget),0))
43239         END AS flstmtitem_yearbudgetdiff,
43240         CASE
43241                 WHEN ((flhead_type IN ('I','C')) AND (flrptyr.flrpt_budget > 0)) THEN
43242                         (COALESCE(((flrptyr.flrpt_diff-flrptyr.flrpt_budget)/flrptyr.flrpt_budget),0))
43243                 WHEN ((flhead_type = 'B') AND (flrptyr.flrpt_budget > 0)) THEN
43244                         (COALESCE(((flrptyr.flrpt_ending-flrptyr.flrpt_budget)/flrptyr.flrpt_budget),0))
43245                 ELSE NULL
43246         END AS flstmtitem_yearbudgetdiffprcnt,
43247         CASE
43248                 WHEN (flhead_type IN ('I','C')) THEN
43249                         (COALESCE(flrptprmo.flrpt_diff,0))
43250                 ELSE (COALESCE(flrptprmo.flrpt_ending,0))
43251         END AS flstmtitem_prmonth,
43252         CASE
43253                 WHEN (flitem_showdiffprcnt) THEN
43254                         (flrptprmo.flrpt_diffprcnt)
43255                 WHEN (flitem_showendprcnt) THEN
43256                         (flrptprmo.flrpt_endingprcnt)
43257                 ELSE NULL
43258         END AS flstmtitem_prmonthprcnt,
43259         CASE
43260                 WHEN (flhead_type IN ('I','C')) THEN
43261                         (COALESCE(flrptmo.flrpt_diff-flrptprmo.flrpt_diff,0))
43262                 ELSE (COALESCE(flrptmo.flrpt_ending-flrptprmo.flrpt_ending,0))
43263         END AS flstmtitem_prmonthdiff,
43264         CASE
43265                 WHEN ((flhead_type IN ('I','C')) AND (flrptprmo.flrpt_diff > 0)) THEN
43266                         (COALESCE((flrptmo.flrpt_diff-flrptprmo.flrpt_diff)/flrptprmo.flrpt_diff,0))
43267                 WHEN ((flhead_type = 'B') AND (flrptprmo.flrpt_ending > 0)) THEN
43268                         (COALESCE((flrptmo.flrpt_ending-flrptprmo.flrpt_ending)/flrptprmo.flrpt_ending,0))
43269                 ELSE NULL
43270         END AS flstmtitem_prmonthdiffprcnt,
43271         CASE
43272                 WHEN (flhead_type IN ('I','C')) THEN
43273                         (COALESCE(flrptprqt.flrpt_diff,0))
43274                 ELSE (COALESCE(flrptprqt.flrpt_ending,0))
43275         END AS flstmtitem_prqtr,
43276         CASE
43277                 WHEN (flitem_showdiffprcnt) THEN
43278                         (flrptprqt.flrpt_diffprcnt)
43279                 WHEN (flitem_showendprcnt) THEN
43280                         (flrptprqt.flrpt_endingprcnt)
43281                 ELSE NULL
43282         END AS flstmtitem_prqtrprcnt,
43283         CASE
43284                 WHEN (flhead_type IN ('I','C')) THEN
43285                         (COALESCE(flrptqt.flrpt_diff-flrptprqt.flrpt_diff,0))
43286                 ELSE (COALESCE(flrptqt.flrpt_ending-flrptprqt.flrpt_ending,0))
43287         END AS flstmtitem_prqtrdiff,
43288         CASE
43289                 WHEN ((flhead_type IN ('I','C')) AND (flrptprqt.flrpt_diff > 0)) THEN
43290                         (COALESCE((flrptqt.flrpt_diff-flrptprqt.flrpt_diff)/flrptprqt.flrpt_diff,0))
43291                 WHEN ((flhead_type = 'B') AND (flrptprqt.flrpt_ending > 0)) THEN
43292                         (COALESCE((flrptqt.flrpt_ending-flrptprqt.flrpt_ending)/flrptprqt.flrpt_ending,0))
43293                 ELSE NULL
43294         END AS flstmtitem_prqtrdiffprcnt,
43295         CASE
43296                 WHEN (flhead_type IN ('I','C')) THEN
43297                         (COALESCE(flrptpryr.flrpt_diff,0))
43298                 ELSE (COALESCE(flrptpryr.flrpt_ending,0))
43299         END AS flstmtitem_pryear,
43300         CASE
43301                 WHEN (flitem_showdiffprcnt) THEN
43302                         (flrptpryr.flrpt_diffprcnt)
43303                 WHEN (flitem_showendprcnt) THEN
43304                         (flrptpryr.flrpt_endingprcnt)
43305                 ELSE NULL
43306         END AS flstmtitem_pryearprcnt,
43307         CASE
43308                 WHEN (flhead_type IN ('I','C')) THEN
43309                         (COALESCE((flrptyr.flrpt_diff-flrptpryr.flrpt_diff),0))
43310                 ELSE (COALESCE((flrptyr.flrpt_ending-flrptpryr.flrpt_ending),0))
43311         END AS flstmtitem_pryeardiff,
43312         CASE
43313                 WHEN ((flhead_type IN ('I','C')) AND (flrptpryr.flrpt_diff > 0)) THEN
43314                         (COALESCE((flrptyr.flrpt_diff-flrptpryr.flrpt_diff)/flrptpryr.flrpt_diff,0))
43315                 WHEN ((flhead_type = 'B' ) AND (flrptpryr.flrpt_ending > 0)) THEN
43316                         (COALESCE((flrptyr.flrpt_ending-flrptpryr.flrpt_ending)/flrptpryr.flrpt_ending,0))
43317                 ELSE NULL
43318         END AS flstmtitem_pryeardiffprcnt
43319         FROM flitem,flhead,
43320                 (SELECT DISTINCT
43321                         flrpt_flhead_id,
43322                         flrpt_period_id,
43323                         flrpt_username,
43324                         flrpt_order,
43325                         flrpt_level,
43326                         flrpt_type,
43327                         flrpt_type_id,
43328                         flrpt_parent_id,
43329                         accnt_id AS flrpt_accnt_id,
43330                         CASE WHEN (pShowNumbers) THEN
43331                                 (formatGLAccount(accnt_id) || '-' || accnt_descrip)
43332                         ELSE accnt_descrip END AS flrpt_name
43333                 FROM flrpt,accnt
43334                 WHERE ((flrpt_type='I')
43335                 AND (flrpt_flhead_id=_p.flhead_id)
43336                 AND (flrpt_period_id=pPeriodid)
43337                 AND (flrpt_username=getEffectiveXtUser())
43338                 AND (accnt_id=flrpt_accnt_id))) AS flrpt
43339                         LEFT OUTER JOIN flrpt flrptmo
43340                                 ON ((flrptmo.flrpt_type=flrpt.flrpt_type)
43341                                 AND (flrptmo.flrpt_type_id=flrpt.flrpt_type_id)
43342                                 AND (flrptmo.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43343                                 AND (flrptmo.flrpt_period_id=flrpt.flrpt_period_id)
43344                                 AND (flrptmo.flrpt_interval='M')
43345                                 AND (flrptmo.flrpt_username=flrpt.flrpt_username)
43346                                 AND (flrptmo.flrpt_order=flrpt.flrpt_order))
43347                         LEFT OUTER JOIN flrpt flrptqt
43348                                 ON ((flrptqt.flrpt_type=flrpt.flrpt_type)
43349                                 AND (flrptqt.flrpt_type_id=flrpt.flrpt_type_id)
43350                                 AND (flrptqt.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43351                                 AND (flrptqt.flrpt_period_id=flrpt.flrpt_period_id)
43352                                 AND (flrptqt.flrpt_interval=_qtrInterval)
43353                                 AND (flrptqt.flrpt_username=flrpt.flrpt_username)
43354                                 AND (flrptqt.flrpt_order=flrpt.flrpt_order))
43355                         LEFT OUTER JOIN flrpt flrptyr
43356                                 ON ((flrptyr.flrpt_type=flrpt.flrpt_type)
43357                                 AND (flrptyr.flrpt_type_id=flrpt.flrpt_type_id)
43358                                 AND (flrptyr.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43359                                 AND (flrptyr.flrpt_period_id=flrpt.flrpt_period_id)
43360                                 AND (flrptyr.flrpt_interval=_yrInterval)
43361                                 AND (flrptyr.flrpt_username=flrpt.flrpt_username)
43362                                 AND (flrptyr.flrpt_order=flrpt.flrpt_order))
43363                         LEFT OUTER JOIN flrpt flrptprmo
43364                                 ON ((flrptprmo.flrpt_type=flrpt.flrpt_type)
43365                                 AND (flrptprmo.flrpt_type_id=flrpt.flrpt_type_id)
43366                                 AND (flrptprmo.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43367                                 AND (flrptprmo.flrpt_period_id=_priorMoPeriodId)
43368                                 AND (flrptprmo.flrpt_interval='M')
43369                                 AND (flrptprmo.flrpt_username=flrpt.flrpt_username)
43370                                 AND (flrptprmo.flrpt_order=flrpt.flrpt_order))
43371                         LEFT OUTER JOIN flrpt flrptprqt
43372                                 ON ((flrptprqt.flrpt_type=flrpt.flrpt_type)
43373                                 AND (flrptprqt.flrpt_type_id=flrpt.flrpt_type_id)
43374                                 AND (flrptprqt.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43375                                 AND (flrptprqt.flrpt_period_id=_priorQtPeriodId)
43376                                 AND (flrptprqt.flrpt_interval='Q')
43377                                 AND (flrptprqt.flrpt_username=flrpt.flrpt_username)
43378                                 AND (flrptprqt.flrpt_order=flrpt.flrpt_order))
43379                         LEFT OUTER JOIN flrpt flrptpryr
43380                                 ON ((flrptpryr.flrpt_type=flrpt.flrpt_type)
43381                                 AND (flrptpryr.flrpt_type_id=flrpt.flrpt_type_id)
43382                                 AND (flrptpryr.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43383                                 AND (flrptpryr.flrpt_period_id=_priorYrPeriodId)
43384                                 AND (flrptpryr.flrpt_interval='Y')
43385                                 AND (flrptpryr.flrpt_username=flrpt.flrpt_username)
43386                                 AND (flrptpryr.flrpt_order=flrpt.flrpt_order) )
43387         WHERE ((flitem_id = flrpt.flrpt_type_id)
43388         AND (flhead_id = flitem_flhead_id))
43389         UNION
43390         SELECT
43391         flrpt.flrpt_flhead_id AS flstmtitem_flhead_id,
43392         flrpt.flrpt_period_id AS flstmtitem_period_id,
43393         flrpt.flrpt_username AS flstmtitem_username,
43394         flrpt.flrpt_order AS flstmtitem_order,
43395         flrpt.flrpt_level AS flstmtitem_level,
43396         flrpt.flrpt_type AS flstmtitem_type,
43397         flrpt.flrpt_type_id AS flstmtitem_type_id,
43398         flrpt.flrpt_parent_id AS flstmtitem_parent_id,
43399         NULL AS flstmtitem_accnt_id,
43400         CASE WHEN(flrpt.flrpt_type='T' AND flrpt.flrpt_level=0) THEN
43401                         COALESCE(flrpt.flrpt_altname, 'Total')
43402                 WHEN(flrpt.flrpt_type='T') THEN
43403                         formatindent(COALESCE(flrpt.flrpt_altname, 'Subtotal') ,
43404                         (CASE WHEN pIndentName THEN flrpt.flrpt_level ELSE 0 END))
43405                 ELSE formatindent(('Type ' || flrpt.flrpt_type || ' ' || text(flrpt.flrpt_type_id)),
43406                         (CASE WHEN pIndentName THEN flrpt.flrpt_level ELSE 0 END))
43407                 END AS flstmtitem_name,
43408         CASE
43409                 WHEN (flhead_type IN ('I','C')) THEN
43410                         (COALESCE(flrptmo.flrpt_diff,0))
43411                 ELSE (COALESCE(flrptmo.flrpt_ending,0))
43412         END AS flstmtitem_month,
43413         (COALESCE(flrptmo.flrpt_debits,0)) AS flstmtitem_monthdb,
43414         (COALESCE(flrptmo.flrpt_credits,0)) AS flstmtitem_monthcr,
43415         CASE
43416                 WHEN (flhead_type IN ('I','C')) THEN
43417                         (flrptmo.flrpt_diffprcnt)
43418                 ELSE (flrptmo.flrpt_endingprcnt)
43419         END AS flstmtitem_monthprcnt,
43420         (COALESCE(flrptmo.flrpt_budget,0)) AS flstmtitem_monthbudget,
43421         (flrptmo.flrpt_budgetprcnt) AS flstmtitem_monthbudgetprcnt,
43422         CASE
43423                 WHEN (flhead_type IN ('I','C')) THEN
43424                         (COALESCE((flrptmo.flrpt_diff-flrptmo.flrpt_budget),0))
43425                 ELSE (COALESCE((flrptmo.flrpt_ending-flrptmo.flrpt_budget),0))
43426         END AS flstmtitem_monthbudgetdiff,
43427         CASE
43428                 WHEN ((flhead_type IN ('I','C')) AND (flrptmo.flrpt_budget > 0)) THEN
43429                         (COALESCE(((flrptmo.flrpt_diff-flrptmo.flrpt_budget)/flrptmo.flrpt_budget),0))
43430                 WHEN ((flhead_type='B') AND (flrptmo.flrpt_budget > 0)) THEN
43431                         (COALESCE(((flrptmo.flrpt_ending-flrptmo.flrpt_budget)/flrptmo.flrpt_budget),0))
43432                 ELSE NULL
43433         END AS flstmtitem_monthbudgetdiffprcnt,
43434         CASE
43435                 WHEN (flhead_type IN ('I','C')) THEN
43436                         (COALESCE(flrptqt.flrpt_diff,0))
43437                 ELSE (COALESCE(flrptqt.flrpt_ending,0))
43438         END AS flstmtitem_qtr,
43439         (COALESCE(flrptqt.flrpt_debits,0)) AS flstmtitem_qtrdb,
43440         (COALESCE(flrptqt.flrpt_credits,0)) AS flstmtitem_qtrcr,
43441         CASE
43442                 WHEN (flhead_type IN ('I','C')) THEN
43443                         (flrptqt.flrpt_diffprcnt)
43444                 ELSE (flrptqt.flrpt_endingprcnt)
43445         END AS flstmtitem_qtrprcnt,
43446         (COALESCE(flrptqt.flrpt_budget,0)) AS flstmtitem_qtrbudget,
43447         (flrptqt.flrpt_budgetprcnt) AS flstmtitem_qtrbudgetprcnt,
43448         CASE
43449                 WHEN (flhead_type IN ('I','C')) THEN
43450                         (COALESCE((flrptqt.flrpt_diff-flrptqt.flrpt_budget),0))
43451                 ELSE (COALESCE((flrptqt.flrpt_ending-flrptqt.flrpt_budget),0))
43452         END AS flstmtitem_qtrbudgetdiff,
43453         CASE
43454                 WHEN ((flhead_type IN ('I','C')) AND (flrptqt.flrpt_budget > 0)) THEN
43455                         (COALESCE(((flrptqt.flrpt_diff-flrptqt.flrpt_budget)/flrptqt.flrpt_budget),0))
43456                 WHEN ((flhead_type='B') AND (flrptqt.flrpt_budget > 0)) THEN
43457                         (COALESCE(((flrptqt.flrpt_ending-flrptqt.flrpt_budget)/flrptqt.flrpt_budget),0))
43458                 ELSE NULL
43459         END AS flstmtitem_qtrbudgetdiffprcnt,
43460         CASE
43461                 WHEN (flhead_type IN ('I','C')) THEN
43462                         (COALESCE(flrptyr.flrpt_diff,0))
43463                 ELSE (COALESCE(flrptyr.flrpt_ending,0))
43464         END AS flstmtitem_year,
43465         (COALESCE(flrptyr.flrpt_debits,0)) AS flstmtitem_yeardb,
43466         (COALESCE(flrptyr.flrpt_credits,0)) AS flstmtitem_yearcr,
43467         CASE
43468                 WHEN (flhead_type IN ('I','C')) THEN
43469                         (flrptyr.flrpt_diffprcnt)
43470                 ELSE (flrptyr.flrpt_endingprcnt)
43471         END AS flstmtitem_yearprcnt,
43472         (COALESCE(flrptyr.flrpt_budget,0)) AS  flstmtitem_yearbudget,
43473         (flrptyr.flrpt_budgetprcnt) AS flstmtitem_yearbudgetprcnt,
43474         CASE
43475                 WHEN (flhead_type IN ('I','C')) THEN
43476                         (COALESCE((flrptyr.flrpt_diff-flrptyr.flrpt_budget),0))
43477                 ELSE (COALESCE((flrptyr.flrpt_ending-flrptyr.flrpt_budget),0))
43478         END AS flstmtitem_yearbudgetdiff,
43479         CASE
43480                 WHEN ((flhead_type IN ('I','C')) AND (flrptyr.flrpt_budget > 0)) THEN
43481                         (COALESCE(((flrptyr.flrpt_diff-flrptyr.flrpt_budget)/flrptyr.flrpt_budget),0))
43482                 WHEN ((flhead_type = 'B') AND (flrptyr.flrpt_budget > 0)) THEN
43483                         (COALESCE(((flrptyr.flrpt_ending-flrptyr.flrpt_budget)/flrptyr.flrpt_budget),0))
43484                 ELSE NULL
43485         END AS flstmtitem_yearbudgetdiffprcnt,
43486         CASE
43487                 WHEN (flhead_type IN ('I','C')) THEN
43488                         (COALESCE(flrptprmo.flrpt_diff,0))
43489                 ELSE (COALESCE(flrptprmo.flrpt_ending,0))
43490         END AS flstmtitem_prmonth,
43491         CASE
43492                 WHEN (flhead_type IN ('I','C')) THEN
43493                         (flrptprmo.flrpt_diffprcnt)
43494                 ELSE (flrptprmo.flrpt_endingprcnt)
43495         END AS flstmtitem_prmonthprcnt,
43496         CASE
43497                 WHEN (flhead_type IN ('I','C')) THEN
43498                         (COALESCE(flrptmo.flrpt_diff-flrptprmo.flrpt_diff,0))
43499                 ELSE (COALESCE(flrptmo.flrpt_ending-flrptprmo.flrpt_ending,0))
43500         END AS flstmtitem_prmonthdiff,
43501         CASE
43502                 WHEN ((flhead_type IN ('I','C')) AND (flrptprmo.flrpt_diff > 0)) THEN
43503                         (COALESCE((flrptmo.flrpt_diff-flrptprmo.flrpt_diff)/flrptprmo.flrpt_diff,0))
43504                 WHEN ((flhead_type = 'B') AND (flrptprmo.flrpt_ending > 0)) THEN
43505                         (COALESCE((flrptmo.flrpt_ending-flrptprmo.flrpt_ending)/flrptprmo.flrpt_ending,0))
43506                 ELSE NULL
43507         END AS flstmtitem_prmonthdiffprcnt,
43508         CASE
43509                 WHEN (flhead_type IN ('I','C')) THEN
43510                         (COALESCE(flrptprqt.flrpt_diff,0))
43511                 ELSE (COALESCE(flrptprqt.flrpt_ending,0))
43512         END AS flstmtitem_prqtr,
43513         CASE
43514                 WHEN (flhead_type IN ('I','C')) THEN
43515                         (flrptprqt.flrpt_diffprcnt)
43516                 ELSE (flrptprqt.flrpt_endingprcnt)
43517         END AS flstmtitem_prqtrprcnt,
43518         CASE
43519                 WHEN (flhead_type IN ('I','C')) THEN
43520                         (COALESCE(flrptqt.flrpt_diff-flrptprqt.flrpt_diff,0))
43521                 ELSE (COALESCE(flrptqt.flrpt_ending-flrptprqt.flrpt_ending,0))
43522         END AS flstmtitem_prqtrdiff,
43523         CASE
43524                 WHEN ((flhead_type IN ('I','C')) AND (flrptprqt.flrpt_diff > 0)) THEN
43525                         (COALESCE((flrptqt.flrpt_diff-flrptprqt.flrpt_diff)/flrptprqt.flrpt_diff,0))
43526                 WHEN ((flhead_type = 'B') AND (flrptprqt.flrpt_ending > 0)) THEN
43527                         (COALESCE((flrptqt.flrpt_ending-flrptprqt.flrpt_ending)/flrptprqt.flrpt_ending,0))
43528                 ELSE NULL
43529         END AS flstmtitem_prqtrdiffprcnt,
43530         CASE
43531                 WHEN (flhead_type IN ('I','C')) THEN
43532                         (COALESCE(flrptpryr.flrpt_diff,0))
43533                 ELSE (COALESCE(flrptpryr.flrpt_ending,0))
43534         END AS flstmtitem_pryear,
43535         CASE
43536                 WHEN (flhead_type IN ('I','C')) THEN
43537                         (flrptpryr.flrpt_diffprcnt)
43538                 ELSE (flrptpryr.flrpt_endingprcnt)
43539         END AS flstmtitem_pryearprcnt,
43540         CASE
43541                 WHEN (flhead_type IN ('I','C')) THEN
43542                         (COALESCE(flrptyr.flrpt_diff-flrptpryr.flrpt_diff,0))
43543                 ELSE (COALESCE(flrptyr.flrpt_ending-flrptpryr.flrpt_ending,0))
43544         END AS flstmtitem_pryeardiff,
43545         CASE
43546                 WHEN ((flhead_type IN ('I','C')) AND (flrptpryr.flrpt_diff > 0)) THEN
43547                         (COALESCE((flrptyr.flrpt_diff-flrptpryr.flrpt_diff)/flrptpryr.flrpt_diff,0))
43548                 WHEN ((flhead_type = 'B' ) AND (flrptpryr.flrpt_ending > 0)) THEN
43549                         (COALESCE((flrptyr.flrpt_ending-flrptpryr.flrpt_ending)/flrptpryr.flrpt_ending,0))
43550                 ELSE NULL
43551         END AS flstmtitem_pryeardiffprcnt
43552         FROM flhead CROSS JOIN (SELECT DISTINCT
43553                         flrpt_flhead_id,
43554                         flrpt_period_id,
43555                         flrpt_username,
43556                         flrpt_order,
43557                         flrpt_level,
43558                         flrpt_type,
43559                         flrpt_type_id,
43560                         flrpt_parent_id,
43561                         flrpt_altname
43562                 FROM flrpt
43563                 WHERE ((NOT (flrpt_type IN ('G','I','S')))
43564                 AND (flrpt_flhead_id=_p.flhead_id)
43565                 AND (flrpt_period_id=pPeriodId)
43566                 AND (flrpt_username=getEffectiveXtUser()))) AS flrpt
43567                         LEFT OUTER JOIN flrpt flrptmo
43568                                 ON ((flrptmo.flrpt_type=flrpt.flrpt_type)
43569                                 AND (flrptmo.flrpt_order=flrpt.flrpt_order)
43570                                 AND (flrptmo.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43571                                 AND (flrptmo.flrpt_period_id=flrpt.flrpt_period_id)
43572                                 AND (flrptmo.flrpt_interval='M')
43573                                 AND (flrptmo.flrpt_username=flrpt.flrpt_username))
43574                         LEFT OUTER JOIN flrpt flrptqt
43575                                 ON ((flrptqt.flrpt_type=flrpt.flrpt_type)
43576                                 AND (flrptqt.flrpt_order=flrpt.flrpt_order)
43577                                 AND (flrptqt.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43578                                 AND (flrptqt.flrpt_period_id=flrpt.flrpt_period_id)
43579                                 AND (flrptqt.flrpt_interval=_qtrInterval)
43580                                 AND (flrptqt.flrpt_username=flrpt.flrpt_username))
43581                         LEFT OUTER JOIN flrpt flrptyr
43582                                 ON ((flrptyr.flrpt_type=flrpt.flrpt_type)
43583                                 AND (flrptyr.flrpt_order=flrpt.flrpt_order)
43584                                 AND (flrptyr.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43585                                 AND (flrptyr.flrpt_period_id=flrpt.flrpt_period_id)
43586                                 AND (flrptyr.flrpt_interval=_yrInterval)
43587                                 AND (flrptyr.flrpt_username=flrpt.flrpt_username))
43588                         LEFT OUTER JOIN flrpt flrptprmo
43589                                 ON ((flrptprmo.flrpt_type=flrpt.flrpt_type)
43590                                 AND (flrptprmo.flrpt_order=flrpt.flrpt_order)
43591                                 AND (flrptprmo.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43592                                 AND (flrptprmo.flrpt_period_id=_priorMoPeriodId)
43593                                 AND (flrptprmo.flrpt_interval='M')
43594                                 AND (flrptprmo.flrpt_username=flrpt.flrpt_username))
43595                         LEFT OUTER JOIN flrpt flrptprqt
43596                                 ON ((flrptprqt.flrpt_type=flrpt.flrpt_type)
43597                                 AND (flrptprqt.flrpt_order=flrpt.flrpt_order)
43598                                 AND (flrptprqt.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43599                                 AND (flrptprqt.flrpt_period_id=_priorQtPeriodId)
43600                                 AND (flrptprqt.flrpt_interval='Q')
43601                                 AND (flrptprqt.flrpt_username=flrpt.flrpt_username))
43602                         LEFT OUTER JOIN flrpt flrptpryr
43603                                 ON ((flrptpryr.flrpt_type=flrpt.flrpt_type)
43604                                 AND (flrptpryr.flrpt_order=flrpt.flrpt_order)
43605                                 AND (flrptpryr.flrpt_flhead_id=flrpt.flrpt_flhead_id)
43606                                 AND (flrptpryr.flrpt_period_id=_priorYrPeriodId)
43607                                 AND (flrptpryr.flrpt_interval='Y')
43608                                 AND (flrptpryr.flrpt_username=flrpt.flrpt_username))
43609         WHERE (flhead_id=flrpt.flrpt_flhead_id)
43610         ORDER BY flstmtitem_order
43611         LOOP
43612                 IF _prevlevel > _x.flstmtitem_level THEN
43613                         _subgrp := _subgrp+1;
43614                 END IF;
43615                 _prevlevel:=_x.flstmtitem_level;
43616                 _row.flstmtitem_subgrp := _subgrp;
43617
43618                 IF NOT _first THEN
43619                         RETURN NEXT _row;
43620                 END IF;
43621
43622                 _first := FALSE;
43623
43624                 _row.flstmtitem_flhead_id := _x.flstmtitem_flhead_id;
43625                 _row.flstmtitem_period_id := _x.flstmtitem_period_id;
43626                 _row.flstmtitem_username := _x.flstmtitem_username;
43627                 _row.flstmtitem_order := _x.flstmtitem_order;
43628                 _row.flstmtitem_level := _x.flstmtitem_level;
43629                 _row.flstmtitem_type := _x.flstmtitem_type;
43630                 _row.flstmtitem_type_id := _x.flstmtitem_type_id;
43631                 _row.flstmtitem_parent_id := _x.flstmtitem_parent_id;
43632                 _row.flstmtitem_accnt_id := _x.flstmtitem_accnt_id;
43633                 _row.flstmtitem_name := _x.flstmtitem_name;
43634                 _row.flstmtitem_month := _x.flstmtitem_month;
43635                 _row.flstmtitem_monthdb := _x.flstmtitem_monthdb;
43636                 _row.flstmtitem_monthcr := _x.flstmtitem_monthcr;
43637                 _row.flstmtitem_monthprcnt := _x.flstmtitem_monthprcnt;
43638                 _row.flstmtitem_monthbudget := _x.flstmtitem_monthbudget;
43639                 _row.flstmtitem_monthbudgetprcnt := _x.flstmtitem_monthbudgetprcnt;
43640                 _row.flstmtitem_monthbudgetdiff := _x.flstmtitem_monthbudgetdiff;
43641                 _row.flstmtitem_monthbudgetdiffprcnt := _x.flstmtitem_monthbudgetdiffprcnt;
43642                 _row.flstmtitem_qtr := _x.flstmtitem_qtr;
43643                 _row.flstmtitem_qtrdb := _x.flstmtitem_qtrdb;
43644                 _row.flstmtitem_qtrcr := _x.flstmtitem_qtrcr;
43645                 _row.flstmtitem_qtrprcnt := _x.flstmtitem_qtrprcnt;
43646                 _row.flstmtitem_qtrbudget := _x.flstmtitem_qtrbudget;
43647                 _row.flstmtitem_qtrbudgetprcnt := _x.flstmtitem_qtrbudgetprcnt;
43648                 _row.flstmtitem_qtrbudgetdiff := _x.flstmtitem_qtrbudgetdiff;
43649                 _row.flstmtitem_qtrbudgetdiffprcnt := _x.flstmtitem_qtrbudgetdiffprcnt;
43650                 _row.flstmtitem_year := _x.flstmtitem_year;
43651                 _row.flstmtitem_yeardb := _x.flstmtitem_yeardb;
43652                 _row.flstmtitem_yearcr := _x.flstmtitem_yearcr;
43653                 _row.flstmtitem_yearprcnt := _x.flstmtitem_yearprcnt;
43654                 _row.flstmtitem_yearbudget := _x.flstmtitem_yearbudget;
43655                 _row.flstmtitem_yearbudgetprcnt := _x.flstmtitem_yearbudgetprcnt;
43656                 _row.flstmtitem_yearbudgetdiff := _x.flstmtitem_yearbudgetdiff;
43657                 _row.flstmtitem_yearbudgetdiffprcnt := _x.flstmtitem_yearbudgetdiffprcnt;
43658                 _row.flstmtitem_prmonth := _x.flstmtitem_prmonth;
43659                 _row.flstmtitem_prmonthprcnt := _x.flstmtitem_prmonthprcnt;
43660                 _row.flstmtitem_prmonthdiff := _x.flstmtitem_prmonthdiff;
43661                 _row.flstmtitem_prmonthdiffprcnt := _x.flstmtitem_prmonthdiffprcnt;
43662                 _row.flstmtitem_prqtr := _x.flstmtitem_prqtr;
43663                 _row.flstmtitem_prqtrprcnt := _x.flstmtitem_prqtrprcnt;
43664                 _row.flstmtitem_prqtrdiff := _x.flstmtitem_prqtrdiff;
43665                 _row.flstmtitem_prqtrdiffprcnt := _x.flstmtitem_prqtrdiffprcnt;
43666                 _row.flstmtitem_pryear := _x.flstmtitem_pryear;
43667                 _row.flstmtitem_pryearprcnt := _x.flstmtitem_pryearprcnt;
43668                 _row.flstmtitem_pryeardiff := _x.flstmtitem_pryeardiff;
43669                 _row.flstmtitem_pryeardiffprcnt := _x.flstmtitem_pryeardiffprcnt;
43670
43671         END LOOP;
43672
43673         _row.flstmtitem_subgrp := _subgrp + 1;
43674         RETURN NEXT _row;
43675 END;
43676 $_$;
43677
43678
43679 ALTER FUNCTION public.financialreport(integer, integer, boolean, boolean, integer) OWNER TO admin;
43680
43681 --
43682 -- TOC entry 1562 (class 1255 OID 146566140)
43683 -- Dependencies: 4536 8
43684 -- Name: findapaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
43685 --
43686
43687 CREATE FUNCTION findapaccount(integer) RETURNS integer
43688     LANGUAGE plpgsql STABLE
43689     AS $_$
43690 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43691 -- See www.xtuple.com/CPAL for the full text of the software license.
43692 DECLARE
43693   pVendid ALIAS FOR $1;
43694   _accntid INTEGER;
43695
43696 BEGIN
43697
43698   IF (NOT fetchMetricBool('InterfaceAPToGL')) THEN
43699     RETURN 0;
43700   END IF;
43701
43702   SELECT apaccnt_ap_accnt_id INTO _accntid
43703     FROM apaccnt
43704     JOIN vendinfo ON (apaccnt_vendtype_id=vend_vendtype_id)
43705   WHERE (vend_id=pVendid);
43706   IF (FOUND) THEN
43707     RETURN _accntid;
43708   END IF;
43709
43710   SELECT apaccnt_ap_accnt_id INTO _accntid
43711     FROM apaccnt
43712     JOIN vendtype ON (vendtype_code ~ apaccnt_vendtype)
43713     JOIN vendinfo ON (vend_vendtype_id=vendtype_id)
43714   WHERE ((apaccnt_vendtype_id=-1)
43715      AND (vend_id=pVendid));
43716   IF (FOUND) THEN
43717     RETURN _accntid;
43718   END IF;
43719
43720   RETURN -1;
43721
43722 END;
43723 $_$;
43724
43725
43726 ALTER FUNCTION public.findapaccount(integer) OWNER TO admin;
43727
43728 --
43729 -- TOC entry 1563 (class 1255 OID 146566141)
43730 -- Dependencies: 4536 8
43731 -- Name: findapdiscountaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
43732 --
43733
43734 CREATE FUNCTION findapdiscountaccount(integer) RETURNS integer
43735     LANGUAGE plpgsql
43736     AS $_$
43737 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43738 -- See www.xtuple.com/CPAL for the full text of the software license.
43739 DECLARE
43740   pVendid ALIAS FOR $1;
43741   _accntid INTEGER;
43742
43743 BEGIN
43744
43745   IF (NOT fetchMetricBool('InterfaceAPToGL')) THEN
43746     RETURN 0;
43747   END IF;
43748
43749   SELECT apaccnt_discount_accnt_id INTO _accntid
43750     FROM apaccnt
43751     JOIN vendinfo ON (apaccnt_vendtype_id=vend_vendtype_id)
43752   WHERE (vend_id=pVendid);
43753   IF (FOUND) THEN
43754     RETURN _accntid;
43755   END IF;
43756
43757   SELECT apaccnt_discount_accnt_id INTO _accntid
43758     FROM apaccnt
43759     JOIN vendtype ON (vendtype_code ~ apaccnt_vendtype)
43760     JOIN vendinfo ON (vend_vendtype_id=vendtype_id)
43761   WHERE ((apaccnt_vendtype_id=-1)
43762      AND (vend_id=pVendid));
43763   IF (FOUND) THEN
43764     RETURN _accntid;
43765   END IF;
43766
43767   RETURN -1;
43768
43769 END;
43770 $_$;
43771
43772
43773 ALTER FUNCTION public.findapdiscountaccount(integer) OWNER TO admin;
43774
43775 --
43776 -- TOC entry 1564 (class 1255 OID 146566142)
43777 -- Dependencies: 4536 8
43778 -- Name: findapprepaidaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
43779 --
43780
43781 CREATE FUNCTION findapprepaidaccount(integer) RETURNS integer
43782     LANGUAGE plpgsql
43783     AS $_$
43784 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43785 -- See www.xtuple.com/CPAL for the full text of the software license.
43786 DECLARE
43787   pVendid ALIAS FOR $1;
43788   _accntid INTEGER;
43789
43790 BEGIN
43791
43792   IF (NOT fetchMetricBool('InterfaceAPToGL')) THEN
43793     RETURN 0;
43794   END IF;
43795
43796 --  Check for a Vendor Type specific Account
43797   SELECT apaccnt_prepaid_accnt_id INTO _accntid
43798     FROM apaccnt
43799     JOIN vendinfo ON (apaccnt_vendtype_id=vend_vendtype_id)
43800   WHERE (vend_id=pVendid);
43801   IF (FOUND) THEN
43802     RETURN _accntid;
43803   END IF;
43804
43805 --  Check for a Vendor Type pattern
43806   SELECT apaccnt_prepaid_accnt_id INTO _accntid
43807     FROM apaccnt
43808     JOIN vendtype ON (vendtype_code ~ apaccnt_vendtype)
43809     JOIN vendinfo ON (vend_vendtype_id=vendtype_id)
43810   WHERE ((apaccnt_vendtype_id=-1)
43811      AND (vend_id=pVendid));
43812   IF (FOUND) THEN
43813     RETURN _accntid;
43814   END IF;
43815
43816   RETURN -1;
43817
43818 END;
43819 $_$;
43820
43821
43822 ALTER FUNCTION public.findapprepaidaccount(integer) OWNER TO admin;
43823
43824 --
43825 -- TOC entry 1565 (class 1255 OID 146566143)
43826 -- Dependencies: 4536 8
43827 -- Name: findaraccount(integer); Type: FUNCTION; Schema: public; Owner: admin
43828 --
43829
43830 CREATE FUNCTION findaraccount(integer) RETURNS integer
43831     LANGUAGE plpgsql STABLE
43832     AS $_$
43833 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43834 -- See www.xtuple.com/CPAL for the full text of the software license.
43835 DECLARE
43836   pCustid ALIAS FOR $1;
43837   _accntid INTEGER;
43838
43839 BEGIN
43840
43841   IF (NOT fetchMetricBool('InterfaceARToGL')) THEN
43842     RETURN 0;
43843   END IF;
43844
43845 --  Check for a Customer Type specific Account
43846   SELECT araccnt_ar_accnt_id INTO _accntid
43847   FROM araccnt, custinfo
43848   WHERE ( (araccnt_custtype_id=cust_custtype_id)
43849    AND (cust_id=pCustid) );
43850   IF (FOUND) THEN
43851     RETURN _accntid;
43852   END IF;
43853
43854 --  Check for a Customer Type pattern
43855   SELECT araccnt_ar_accnt_id INTO _accntid
43856   FROM araccnt, custinfo, custtype
43857   WHERE ( (custtype_code ~ araccnt_custtype)
43858    AND (araccnt_custtype_id=-1)
43859    AND (cust_custtype_id=custtype_id)
43860    AND (cust_id=pCustid) );
43861   IF (FOUND) THEN
43862     RETURN _accntid;
43863   END IF;
43864
43865   RETURN -1;
43866
43867 END;
43868 $_$;
43869
43870
43871 ALTER FUNCTION public.findaraccount(integer) OWNER TO admin;
43872
43873 --
43874 -- TOC entry 1566 (class 1255 OID 146566144)
43875 -- Dependencies: 4536 8
43876 -- Name: findardiscountaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
43877 --
43878
43879 CREATE FUNCTION findardiscountaccount(integer) RETURNS integer
43880     LANGUAGE plpgsql
43881     AS $_$
43882 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43883 -- See www.xtuple.com/CPAL for the full text of the software license.
43884 DECLARE
43885   pCustid ALIAS FOR $1;
43886   _accntid INTEGER;
43887
43888 BEGIN
43889
43890   IF (NOT fetchMetricBool('InterfaceARToGL')) THEN
43891     RETURN 0;
43892   END IF;
43893
43894 --  Check for a Customer Type specific Account
43895   SELECT araccnt_discount_accnt_id INTO _accntid
43896   FROM araccnt, custinfo
43897   WHERE ( (araccnt_custtype_id=cust_custtype_id)
43898    AND (cust_id=pCustid) );
43899   IF (FOUND) THEN
43900     RETURN _accntid;
43901   END IF;
43902
43903 --  Check for a Customer Type pattern
43904   SELECT araccnt_discount_accnt_id INTO _accntid
43905   FROM araccnt, custinfo, custtype
43906   WHERE ( (custtype_code ~ araccnt_custtype)
43907    AND (cust_custtype_id=custtype_id)
43908    AND (araccnt_custtype_id=-1)
43909    AND (cust_id=pCustid) );
43910   IF (FOUND) THEN
43911     RETURN _accntid;
43912   END IF;
43913
43914   RETURN -1;
43915
43916 END;
43917 $_$;
43918
43919
43920 ALTER FUNCTION public.findardiscountaccount(integer) OWNER TO admin;
43921
43922 --
43923 -- TOC entry 1567 (class 1255 OID 146566145)
43924 -- Dependencies: 4536 8
43925 -- Name: findcalendarorigin(integer); Type: FUNCTION; Schema: public; Owner: admin
43926 --
43927
43928 CREATE FUNCTION findcalendarorigin(integer) RETURNS date
43929     LANGUAGE plpgsql
43930     AS $_$
43931 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43932 -- See www.xtuple.com/CPAL for the full text of the software license.
43933 DECLARE
43934   pCalheadid ALIAS FOR $1;
43935   _originType CHAR(1);
43936   _origin DATE;
43937
43938 BEGIN
43939
43940   SELECT calhead_origin INTO _originType
43941   FROM calhead
43942   WHERE (calhead_id=pCalheadid);
43943
43944   IF (NOT FOUND) THEN
43945     _origin := NULL;
43946
43947   ELSIF (_originType = 'D') THEN
43948     _origin := CURRENT_DATE;
43949
43950   ELSIF (_originType = 'E') THEN
43951     _origin := (CURRENT_DATE + 1);
43952
43953   ELSIF (_originType = 'W') THEN
43954     _origin := (CURRENT_DATE - EXTRACT(DOW FROM CURRENT_DATE)::INTEGER);
43955
43956   ELSIF (_originType = 'X') THEN
43957     _origin := ((CURRENT_DATE - EXTRACT(DOW FROM CURRENT_DATE)::INTEGER) + INTERVAL '1 week');
43958
43959   ELSIF (_originType = 'M') THEN
43960     _origin := date_trunc('month', CURRENT_DATE);
43961
43962   ELSIF (_originType = 'N') THEN
43963     _origin := (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month');
43964
43965   ELSIF (_originType = 'L') THEN
43966     _origin := (date_trunc('year', CURRENT_DATE) - INTERVAL '1 year');
43967
43968   ELSIF (_originType = 'Y') THEN
43969     _origin := date_trunc('year', CURRENT_DATE);
43970
43971   ELSIF (_originType = 'Z') THEN
43972     _origin := (date_trunc('year', CURRENT_DATE) + INTERVAL '1 year');
43973
43974   ELSE
43975     _origin := NULL;
43976   END IF;
43977
43978   RETURN _origin;
43979
43980   END;
43981 $_$;
43982
43983
43984 ALTER FUNCTION public.findcalendarorigin(integer) OWNER TO admin;
43985
43986 --
43987 -- TOC entry 1568 (class 1255 OID 146566146)
43988 -- Dependencies: 4536 8
43989 -- Name: findcustomerform(integer, character); Type: FUNCTION; Schema: public; Owner: admin
43990 --
43991
43992 CREATE FUNCTION findcustomerform(integer, character) RETURNS text
43993     LANGUAGE plpgsql
43994     AS $_$
43995 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
43996 -- See www.xtuple.com/CPAL for the full text of the software license.
43997 DECLARE
43998   pCustid ALIAS FOR $1;
43999   pFormtype ALIAS FOR $2;
44000   _f RECORD;
44001   _found BOOLEAN;
44002
44003 BEGIN
44004
44005 --  Check for a Customer Type specific Form
44006   SELECT custform.* INTO _f
44007     FROM custform
44008     JOIN custinfo ON (custform_custtype_id=cust_custtype_id)
44009   WHERE (cust_id=pCustid);
44010
44011   IF (FOUND) THEN
44012     _found := TRUE;
44013   ELSE
44014 --  Check for a Customer Type pattern
44015     SELECT custform.* INTO _f
44016       FROM custform
44017       JOIN custtype ON (custtype_code ~ custform_custtype)
44018       JOIN custinfo ON (cust_custtype_id=custtype_id)
44019     WHERE ((custform_custtype_id=-1)
44020        AND (cust_id=pCustid));
44021
44022     IF (FOUND) THEN
44023       _found := TRUE;
44024     ELSE
44025       _found := FALSE;
44026     END IF;
44027   END IF;
44028
44029   IF (_found) THEN
44030     IF ( (pFormType = 'I') AND (_f.custform_invoice_report_name IS NOT NULL) ) THEN
44031       RETURN _f.custform_invoice_report_name;
44032
44033     ELSIF ( (pFormType = 'C') AND (_f.custform_creditmemo_report_name IS NOT NULL) ) THEN
44034       RETURN _f.custform_creditmemo_report_name;
44035
44036     ELSIF ( (pFormType = 'S') AND (_f.custform_statement_report_name IS NOT NULL) ) THEN
44037       RETURN _f.custform_statement_report_name;
44038
44039     ELSIF ( (pFormType = 'Q') AND (_f.custform_quote_report_name IS NOT NULL) ) THEN
44040       RETURN _f.custform_quote_report_name;
44041
44042     ELSIF ( (pFormType = 'P') AND (_f.custform_packinglist_report_name IS NOT NULL) ) THEN
44043       RETURN _f.custform_packinglist_report_name;
44044
44045     ELSIF ( (pFormType = 'L') AND (_f.custform_sopicklist_report_name IS NOT NULL) ) THEN
44046       RETURN _f.custform_sopicklist_report_name;
44047     END IF;
44048
44049   END IF;
44050
44051   IF (pFormType = 'I') THEN
44052     RETURN 'Invoice';
44053   ELSIF (pFormType = 'C') THEN
44054     RETURN 'CreditMemo';
44055   ELSIF (pFormType = 'S') THEN
44056     RETURN 'Statement';
44057   ELSIF (pFormType = 'Q') THEN
44058     RETURN 'Quote';
44059   ELSIF (pFormType = 'P') THEN
44060     RETURN 'PackingList-Shipment';
44061   ELSIF (pFormType = 'L') THEN
44062     RETURN 'PackingList';
44063   END IF;
44064
44065 END;
44066 $_$;
44067
44068
44069 ALTER FUNCTION public.findcustomerform(integer, character) OWNER TO admin;
44070
44071 --
44072 -- TOC entry 1570 (class 1255 OID 146566147)
44073 -- Dependencies: 4536 8
44074 -- Name: finddeferredaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
44075 --
44076
44077 CREATE FUNCTION finddeferredaccount(integer) RETURNS integer
44078     LANGUAGE plpgsql STABLE
44079     AS $_$
44080 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44081 -- See www.xtuple.com/CPAL for the full text of the software license.
44082 DECLARE
44083   pCustid ALIAS FOR $1;
44084   _accntid INTEGER;
44085
44086 BEGIN
44087
44088   IF (NOT fetchMetricBool('InterfaceARToGL')) THEN
44089     RETURN 0;
44090   END IF;
44091
44092 --  Check for a Customer Type specific Account
44093   SELECT araccnt_deferred_accnt_id INTO _accntid
44094     FROM araccnt
44095     JOIN custinfo ON (araccnt_custtype_id=cust_custtype_id)
44096   WHERE (cust_id=pCustid);
44097   IF (FOUND) THEN
44098     RETURN _accntid;
44099   END IF;
44100
44101 --  Check for a Customer Type pattern
44102   SELECT araccnt_deferred_accnt_id INTO _accntid
44103     FROM araccnt
44104     JOIN custtype ON (custtype_code ~ araccnt_custtype)
44105     JOIN custinfo ON (cust_custtype_id=custtype_id)
44106   WHERE ((araccnt_custtype_id=-1)
44107      AND (cust_id=pCustid));
44108   IF (FOUND) THEN
44109     RETURN _accntid;
44110   END IF;
44111
44112   RETURN -1;
44113
44114 END;
44115 $_$;
44116
44117
44118 ALTER FUNCTION public.finddeferredaccount(integer) OWNER TO admin;
44119
44120 --
44121 -- TOC entry 1571 (class 1255 OID 146566148)
44122 -- Dependencies: 4536 8
44123 -- Name: findfreightaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
44124 --
44125
44126 CREATE FUNCTION findfreightaccount(integer) RETURNS integer
44127     LANGUAGE plpgsql
44128     AS $_$
44129 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44130 -- See www.xtuple.com/CPAL for the full text of the software license.
44131 DECLARE
44132   pCustid ALIAS FOR $1;
44133   _accntid INTEGER;
44134
44135 BEGIN
44136
44137   IF (NOT fetchMetricBool('InterfaceARToGL')) THEN
44138     RETURN 0;
44139   END IF;
44140
44141 --  Check for a Customer Type specific Account
44142   SELECT araccnt_freight_accnt_id INTO _accntid
44143   FROM araccnt, custinfo
44144   WHERE ( (araccnt_custtype_id=cust_custtype_id)
44145    AND (cust_id=pCustid) );
44146   IF (FOUND) THEN
44147     RETURN _accntid;
44148   END IF;
44149
44150 --  Check for a Customer Type pattern
44151   SELECT araccnt_freight_accnt_id INTO _accntid
44152   FROM araccnt, custinfo, custtype
44153   WHERE ( (custtype_code ~ araccnt_custtype)
44154    AND (cust_custtype_id=custtype_id)
44155    AND (araccnt_custtype_id=-1)
44156    AND (cust_id=pCustid) );
44157   IF (FOUND) THEN
44158     RETURN _accntid;
44159   END IF;
44160
44161 --  Find the default
44162   SELECT metric_value::INTEGER INTO _accntid
44163   FROM metric
44164   WHERE (metric_name='FreightAccount');
44165   IF (FOUND) THEN
44166     RETURN _accntid;
44167   END IF;
44168
44169   RETURN -1;
44170
44171 END;
44172 $_$;
44173
44174
44175 ALTER FUNCTION public.findfreightaccount(integer) OWNER TO admin;
44176
44177 --
44178 -- TOC entry 1572 (class 1255 OID 146566149)
44179 -- Dependencies: 4536 8
44180 -- Name: findperiodend(integer); Type: FUNCTION; Schema: public; Owner: admin
44181 --
44182
44183 CREATE FUNCTION findperiodend(integer) RETURNS date
44184     LANGUAGE plpgsql STABLE
44185     AS $_$
44186 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44187 -- See www.xtuple.com/CPAL for the full text of the software license.
44188 DECLARE
44189   pCalitemid ALIAS FOR $1;
44190   _calType CHAR(1);
44191   _calItem RECORD;
44192   _start DATE;
44193   _loop INTEGER;
44194
44195 BEGIN
44196
44197   SELECT calhead_type INTO _calType
44198   FROM calhead, acalitem
44199   WHERE ((acalitem_calhead_id=calhead_id)
44200    AND (acalitem_id=pCalitemid));
44201
44202   IF (NOT FOUND) THEN
44203     SELECT calhead_type INTO _calType
44204     FROM calhead, rcalitem
44205     WHERE ((rcalitem_calhead_id=calhead_id)
44206      AND (rcalitem_id=pCalitemid));
44207
44208     IF (NOT FOUND) THEN
44209       RETURN NULL;
44210     END IF;
44211   END IF;
44212
44213   IF (_calType = 'A') THEN
44214     RETURN ( SELECT (findPeriodStart(acalitem_id) + acalitem_periodlength - 1)
44215              FROM acalitem
44216              WHERE (acalitem_id=pCalitemid) );
44217
44218   ELSIF (_calType = 'R') THEN
44219
44220 --  Grab the relative calitem's particulars
44221     SELECT rcalitem_periodtype, rcalitem_periodcount INTO _calitem
44222     FROM rcalitem
44223     WHERE (rcalitem_id=pCalitemid);
44224
44225     IF (NOT FOUND) THEN
44226       RETURN NULL;
44227     END If;
44228
44229 --  Grab the origin of the calitem
44230     SELECT findPeriodStart(pCalitemid) INTO _start;
44231
44232     IF (_start IS NULL) THEN
44233
44234 --  If days...
44235     ELSIF (_calitem.rcalitem_periodtype = 'D') THEN
44236       _start := (_start + _calitem.rcalitem_periodcount - 1);
44237
44238 --  If weeks... (gotta be a better way)
44239     ELSIF (_calitem.rcalitem_periodtype = 'W') THEN
44240       _loop := _calitem.rcalitem_periodcount;
44241
44242       WHILE (_loop > 0) LOOP
44243         _start := (_start + INTERVAL '1 week');
44244         _loop := (_loop - 1);
44245       END LOOP;
44246
44247       _start := (_start - 1);
44248
44249 --  If months... (gotta be a better way)
44250     ELSIF (_calitem.rcalitem_periodtype = 'M') THEN
44251       _loop := _calitem.rcalitem_periodcount;
44252
44253       WHILE (_loop > 0) LOOP
44254         _start := (_start + INTERVAL '1 month');
44255         _loop := (_loop - 1);
44256       END LOOP;
44257
44258       _start := (_start - 1);
44259
44260 --  If years... (gotta be a better way)
44261     ELSIF (_calitem.rcalitem_periodtype = 'Y') THEN
44262       _loop := _calitem.rcalitem_periodcount;
44263
44264       WHILE (_loop > 0) LOOP
44265         _start := (_start + INTERVAL '1 year');
44266         _loop := (_loop - 1);
44267       END LOOP;
44268
44269       _start := (_start - 1);
44270
44271     ELSE
44272       _start := NULL;
44273     END IF;
44274
44275   ELSE
44276     _start := NULL;
44277   END IF;
44278
44279   RETURN _start;
44280
44281 END;
44282 $_$;
44283
44284
44285 ALTER FUNCTION public.findperiodend(integer) OWNER TO admin;
44286
44287 --
44288 -- TOC entry 1573 (class 1255 OID 146566150)
44289 -- Dependencies: 4536 8
44290 -- Name: findperiodstart(integer); Type: FUNCTION; Schema: public; Owner: admin
44291 --
44292
44293 CREATE FUNCTION findperiodstart(integer) RETURNS date
44294     LANGUAGE plpgsql STABLE
44295     AS $_$
44296 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44297 -- See www.xtuple.com/CPAL for the full text of the software license.
44298 DECLARE
44299   pCalitemid ALIAS FOR $1;
44300   _calType CHAR(1);
44301   _calItem RECORD;
44302   _start DATE;
44303   _loop INTEGER;
44304
44305 BEGIN
44306
44307   SELECT calhead_type INTO _calType
44308   FROM calhead, acalitem
44309   WHERE ((acalitem_calhead_id=calhead_id)
44310    AND (acalitem_id=pCalitemid));
44311
44312   IF (NOT FOUND) THEN
44313     SELECT calhead_type INTO _calType
44314     FROM calhead, rcalitem
44315     WHERE ((rcalitem_calhead_id=calhead_id)
44316      AND (rcalitem_id=pCalitemid));
44317
44318     IF (NOT FOUND) THEN
44319       RETURN NULL;
44320     END IF;
44321   END IF;
44322
44323   IF (_calType = 'A') THEN
44324     RETURN ( SELECT acalitem_periodstart
44325              FROM acalitem
44326              WHERE (acalitem_id=pCalitemid) );
44327
44328   ELSIF (_calType = 'R') THEN
44329
44330 --  Grab the relative calitem's particulars
44331     SELECT rcalitem_offsettype, rcalitem_offsetcount INTO _calitem
44332     FROM rcalitem
44333     WHERE (rcalitem_id=pCalitemid);
44334
44335     IF (NOT FOUND) THEN
44336       RETURN NULL;
44337     END If;
44338
44339 --  Grab the origin of the calitem's parend calhead
44340     SELECT findCalendarOrigin(calhead_id) INTO _start
44341     FROM calhead, rcalitem
44342     WHERE ((rcalitem_calhead_id=calhead_id)
44343      AND (rcalitem_id=pCalitemid));
44344
44345 --  If days...
44346     IF (_calitem.rcalitem_offsettype = 'D') THEN
44347       _start := (_start + _calitem.rcalitem_offsetcount);
44348
44349 --  If weeks...
44350     ELSIF (_calitem.rcalitem_offsettype = 'W') THEN
44351       _start := (_start + (_calitem.rcalitem_offsetcount * 7));
44352
44353 --  If months... (gotta be a better way)
44354     ELSIF (_calitem.rcalitem_offsettype = 'M') THEN
44355       _loop := _calitem.rcalitem_offsetcount;
44356
44357       IF (_loop > 0) THEN
44358         WHILE (_loop > 0) LOOP
44359           _start := (_start + INTERVAL '1 month');
44360           _loop := _loop - 1;
44361         END LOOP;
44362       ELSE
44363         WHILE (_loop < 0) LOOP
44364           _start := (_start - INTERVAL '1 month');
44365           _loop := _loop + 1;
44366         END LOOP;
44367       END IF;
44368
44369 --  If years... (gotta be a better way)
44370     ELSIF (_calitem.rcalitem_offsettype = 'Y') THEN
44371       _loop := _calitem.rcalitem_offsetcount;
44372
44373       IF (_loop > 0) THEN
44374         WHILE (_loop > 0) LOOP
44375           _start := (_start + INTERVAL '1 year');
44376           _loop := _loop - 1;
44377         END LOOP;
44378       ELSE
44379         WHILE (_loop < 0) LOOP
44380           _start := (_start - INTERVAL '1 year');
44381           _loop := _loop + 1;
44382         END LOOP;
44383       END IF;
44384
44385     ELSE
44386       _start := NULL;
44387     END IF;
44388
44389   ELSE
44390     _start := NULL;
44391   END IF;
44392
44393   RETURN _start;
44394
44395 END;
44396 $_$;
44397
44398
44399 ALTER FUNCTION public.findperiodstart(integer) OWNER TO admin;
44400
44401 --
44402 -- TOC entry 1574 (class 1255 OID 146566151)
44403 -- Dependencies: 4536 8
44404 -- Name: findprepaidaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
44405 --
44406
44407 CREATE FUNCTION findprepaidaccount(integer) RETURNS integer
44408     LANGUAGE plpgsql
44409     AS $_$
44410 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44411 -- See www.xtuple.com/CPAL for the full text of the software license.
44412 DECLARE
44413   pCustid ALIAS FOR $1;
44414   _accntid INTEGER;
44415
44416 BEGIN
44417
44418   IF (NOT fetchMetricBool('InterfaceARToGL')) THEN
44419     RETURN 0;
44420   END IF;
44421
44422 --  Check for a Customer Type specific Account
44423   SELECT araccnt_prepaid_accnt_id INTO _accntid
44424     FROM araccnt
44425     JOIN custinfo ON (araccnt_custtype_id=cust_custtype_id)
44426   WHERE (cust_id=pCustid);
44427   IF (FOUND) THEN
44428     RETURN _accntid;
44429   END IF;
44430
44431 --  Check for a Customer Type pattern
44432   SELECT araccnt_prepaid_accnt_id INTO _accntid
44433     FROM araccnt
44434     JOIN custtype ON (custtype_code ~ araccnt_custtype)
44435     JOIN custinfo ON (cust_custtype_id=custtype_id)
44436   WHERE ((araccnt_custtype_id=-1)
44437      AND (cust_id=pCustid) );
44438   IF (FOUND) THEN
44439     RETURN _accntid;
44440   END IF;
44441
44442   RETURN -1;
44443
44444 END;
44445 $_$;
44446
44447
44448 ALTER FUNCTION public.findprepaidaccount(integer) OWNER TO admin;
44449
44450 --
44451 -- TOC entry 1575 (class 1255 OID 146566152)
44452 -- Dependencies: 4536 8
44453 -- Name: findsalesaccnt(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
44454 --
44455
44456 CREATE FUNCTION findsalesaccnt(integer, integer) RETURNS integer
44457     LANGUAGE plpgsql
44458     AS $_$
44459 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44460 -- See www.xtuple.com/CPAL for the full text of the software license.
44461 BEGIN
44462   RETURN findSalesAccnt($1, 'IS', $2, NULL, NULL);
44463 END;
44464 $_$;
44465
44466
44467 ALTER FUNCTION public.findsalesaccnt(integer, integer) OWNER TO admin;
44468
44469 --
44470 -- TOC entry 1576 (class 1255 OID 146566153)
44471 -- Dependencies: 4536 8
44472 -- Name: findsalesaccnt(integer, text, integer); Type: FUNCTION; Schema: public; Owner: admin
44473 --
44474
44475 CREATE FUNCTION findsalesaccnt(integer, text, integer) RETURNS integer
44476     LANGUAGE plpgsql
44477     AS $_$
44478 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44479 -- See www.xtuple.com/CPAL for the full text of the software license.
44480 BEGIN
44481   RETURN findSalesAccnt($1, $2, $3, NULL, NULL);
44482 END;
44483 $_$;
44484
44485
44486 ALTER FUNCTION public.findsalesaccnt(integer, text, integer) OWNER TO admin;
44487
44488 --
44489 -- TOC entry 1577 (class 1255 OID 146566154)
44490 -- Dependencies: 4536 8
44491 -- Name: findsalesaccnt(integer, text, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
44492 --
44493
44494 CREATE FUNCTION findsalesaccnt(pid integer, pidtype text, pcustid integer, psaletypeid integer, pshipzoneid integer) RETURNS integer
44495     LANGUAGE plpgsql
44496     AS $$
44497 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44498 -- See www.xtuple.com/CPAL for the full text of the software license.
44499 DECLARE
44500   _s RECORD;
44501
44502 BEGIN
44503
44504   IF (pidType = 'I') THEN
44505     --  Check for a custtype specific rule
44506     SELECT salesaccnt_id,
44507            CASE WHEN (salesaccnt_warehous_id<>-1) THEN 1 ELSE 0 END +
44508            CASE WHEN (salesaccnt_custtype_id<>-1) THEN 2 ELSE 0 END +
44509            CASE WHEN (salesaccnt_prodcat_id<>-1) THEN 3 ELSE 0 END +
44510            CASE WHEN (salesaccnt_shipzone_id<>-1) THEN 4 ELSE 0 END +
44511            CASE WHEN (salesaccnt_saletype_id<>-1) THEN 5 ELSE 0 END AS orderby
44512     INTO _s
44513     FROM salesaccnt, item, prodcat, custinfo, custtype
44514     WHERE ( (salesaccnt_warehous_id=-1)
44515       AND  (item_prodcat_id=prodcat_id)
44516       AND  (cust_custtype_id=custtype_id)
44517       AND  ( (salesaccnt_prodcat='.*') OR
44518             ( (salesaccnt_prodcat_id=-1) AND
44519               (salesaccnt_prodcat<>'') AND
44520               (prodcat_code ~ salesaccnt_prodcat) ) OR
44521             ( (salesaccnt_prodcat_id=prodcat_id) ) )
44522       AND  ( (salesaccnt_custtype='.*') OR
44523             ( (salesaccnt_custtype_id=-1) AND
44524               (salesaccnt_custtype<>'') AND
44525               (custtype_code ~ salesaccnt_custtype) ) OR
44526             ( (salesaccnt_custtype_id=custtype_id) ) )
44527       AND  ( (salesaccnt_shipzone_id=-1) OR
44528              (salesaccnt_shipzone_id=pShipzoneid) )
44529       AND  ( (salesaccnt_saletype_id=-1) OR
44530              (salesaccnt_saletype_id=pSaletypeid) )
44531       AND (item_id=pid)
44532       AND (cust_id=pCustid) )
44533     ORDER BY orderby DESC, salesaccnt_custtype DESC, salesaccnt_prodcat DESC,
44534              salesaccnt_saletype_id DESC, salesaccnt_shipzone_id DESC
44535      LIMIT 1;
44536
44537   ELSIF (pidType = 'IS') THEN
44538     --  Check for a custtype specific rule
44539     SELECT salesaccnt_id,
44540            CASE WHEN (salesaccnt_warehous_id<>-1) THEN 1 ELSE 0 END +
44541            CASE WHEN (salesaccnt_custtype_id<>-1) THEN 2 ELSE 0 END +
44542            CASE WHEN (salesaccnt_prodcat_id<>-1) THEN 3 ELSE 0 END +
44543            CASE WHEN (salesaccnt_shipzone_id<>-1) THEN 4 ELSE 0 END +
44544            CASE WHEN (salesaccnt_saletype_id<>-1) THEN 5 ELSE 0 END AS orderby
44545     INTO _s
44546     FROM salesaccnt, itemsite, item, prodcat, custinfo, custtype
44547     WHERE ( ( (salesaccnt_warehous_id=-1) OR
44548               (salesaccnt_warehous_id=itemsite_warehous_id) )
44549      AND (itemsite_item_id=item_id)
44550      AND (item_prodcat_id=prodcat_id)
44551      AND (cust_custtype_id=custtype_id)
44552      AND ( (salesaccnt_prodcat='.*') OR
44553            ( (salesaccnt_prodcat_id=-1) AND
44554              (salesaccnt_prodcat<>'') AND
44555              (prodcat_code ~ salesaccnt_prodcat) ) OR
44556            ( (salesaccnt_prodcat_id=prodcat_id) ) )
44557      AND ( (salesaccnt_custtype='.*') OR
44558            ( (salesaccnt_custtype_id=-1) AND
44559              (salesaccnt_custtype<>'') AND
44560              (custtype_code ~ salesaccnt_custtype) ) OR
44561            ( (salesaccnt_custtype_id=custtype_id) ) )
44562      AND  ( (salesaccnt_shipzone_id=-1) OR
44563             (salesaccnt_shipzone_id=pShipzoneid) )
44564      AND  ( (salesaccnt_saletype_id=-1) OR
44565             (salesaccnt_saletype_id=pSaletypeid) )
44566      AND (itemsite_id=pid)
44567      AND (cust_id=pCustid) ) 
44568     ORDER BY orderby DESC, salesaccnt_custtype DESC, salesaccnt_prodcat DESC, salesaccnt_warehous_id DESC,
44569              salesaccnt_saletype_id DESC, salesaccnt_shipzone_id DESC
44570     LIMIT 1;
44571
44572   ELSE
44573     RETURN -2;  -- invalid pidType
44574   END IF;
44575
44576   IF (FOUND) THEN
44577     RETURN _s.salesaccnt_id;
44578   END IF;
44579
44580   RETURN -1;
44581
44582 END;
44583 $$;
44584
44585
44586 ALTER FUNCTION public.findsalesaccnt(pid integer, pidtype text, pcustid integer, psaletypeid integer, pshipzoneid integer) OWNER TO admin;
44587
44588 --
44589 -- TOC entry 1579 (class 1255 OID 146566155)
44590 -- Dependencies: 4536 8
44591 -- Name: findspecialfinancial(text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
44592 --
44593
44594 CREATE FUNCTION findspecialfinancial(text, text, integer) RETURNS numeric
44595     LANGUAGE plpgsql
44596     AS $_$
44597 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44598 -- See www.xtuple.com/CPAL for the full text of the software license.
44599 DECLARE
44600   pUnit ALIAS FOR $1;
44601   pType ALIAS FOR $2;
44602   pPeriodid ALIAS FOR $3;
44603
44604   _value NUMERIC;
44605 BEGIN
44606
44607   _value := 0.00;
44608
44609   IF ('OpenAR' = pType) THEN
44610     IF ( pUnit IN ('D','E') ) THEN
44611       SELECT SUM( CASE WHEN (aropen_doctype IN ('C', 'R')) THEN ((aropen_amount - aropen_paid) * -1)
44612                        ELSE (aropen_amount - aropen_paid) END ) INTO _value
44613         FROM aropen, period
44614        WHERE ((aropen_open)
44615          AND  (aropen_duedate BETWEEN period_start AND period_end)
44616          AND  (period_id=pPeriodid));
44617
44618       IF ('E' = pUnit) THEN
44619         _value := 0.00 - _value;
44620       END IF;
44621     END IF;
44622   END IF;
44623
44624   IF ('OpenAP' = pType) THEN
44625     IF ( pUnit IN ('C','E') ) THEN
44626       SELECT SUM( CASE WHEN (apopen_doctype='C') THEN ((apopen_amount - apopen_paid) * -1)
44627                        ELSE (apopen_amount - apopen_paid) END ) INTO _value
44628         FROM apopen, period
44629        WHERE ((apopen_open)
44630          AND  (apopen_duedate BETWEEN period_start AND period_end)
44631          AND  (period_id=pPeriodid));
44632     END IF;
44633   END IF;
44634
44635   RETURN _value;
44636
44637 END;
44638 $_$;
44639
44640
44641 ALTER FUNCTION public.findspecialfinancial(text, text, integer) OWNER TO admin;
44642
44643 --
44644 -- TOC entry 1580 (class 1255 OID 146566156)
44645 -- Dependencies: 4536 8
44646 -- Name: findxt(); Type: FUNCTION; Schema: public; Owner: admin
44647 --
44648
44649 CREATE FUNCTION findxt() RETURNS void
44650     LANGUAGE plpgsql
44651     AS $$
44652 BEGIN
44653   IF EXISTS (select relname from pg_class where relname = 'ext')
44654 THEN
44655 PERFORM xt.js_init();
44656 END IF;
44657 END;
44658 $$;
44659
44660
44661 ALTER FUNCTION public.findxt() OWNER TO admin;
44662
44663 --
44664 -- TOC entry 1581 (class 1255 OID 146566157)
44665 -- Dependencies: 8
44666 -- Name: first_agg(anyelement, anyelement); Type: FUNCTION; Schema: public; Owner: admin
44667 --
44668
44669 CREATE FUNCTION first_agg(anyelement, anyelement) RETURNS anyelement
44670     LANGUAGE sql STABLE
44671     AS $_$
44672   SELECT CASE WHEN $1 IS NULL THEN $2 ELSE $1 END;
44673 $_$;
44674
44675
44676 ALTER FUNCTION public.first_agg(anyelement, anyelement) OWNER TO admin;
44677
44678 --
44679 -- TOC entry 1582 (class 1255 OID 146566158)
44680 -- Dependencies: 4536 8
44681 -- Name: firstline(text); Type: FUNCTION; Schema: public; Owner: admin
44682 --
44683
44684 CREATE FUNCTION firstline(text) RETURNS text
44685     LANGUAGE plpgsql IMMUTABLE
44686     AS $_$
44687 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44688 -- See www.xtuple.com/CPAL for the full text of the software license.
44689 DECLARE
44690   pSource ALIAS FOR $1;
44691   _result TEXT := '';
44692
44693 BEGIN
44694   SELECT regexp_replace(pSource, E'^(\r?\n)*([^\r\n]*)\r?\n.*', E'\\2') INTO _result;
44695   RETURN _result;
44696 END;
44697 $_$;
44698
44699
44700 ALTER FUNCTION public.firstline(text) OWNER TO admin;
44701
44702 --
44703 -- TOC entry 1583 (class 1255 OID 146566159)
44704 -- Dependencies: 4536 8
44705 -- Name: fixacl(); Type: FUNCTION; Schema: public; Owner: admin
44706 --
44707
44708 CREATE FUNCTION fixacl() RETURNS integer
44709     LANGUAGE plpgsql
44710     AS $$
44711 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44712 -- See www.xtuple.com/CPAL for the full text of the software license.
44713 DECLARE
44714   _r        RECORD;
44715   _count    INTEGER := 0;
44716   _oldgrp   BOOLEAN := false;
44717   _objtype  TEXT;
44718   _table    TEXT;
44719   _schema   TEXT;
44720
44721 BEGIN
44722   IF EXISTS(SELECT 1 FROM pg_group WHERE groname = 'openmfg') THEN
44723     _oldgrp := true;
44724   END IF;
44725   
44726   FOR _r IN SELECT relname, nspname, relkind,
44727                    CASE relkind WHEN 'r' THEN 1
44728                                 WHEN 'v' THEN 2
44729                                 WHEN 'S' THEN 3
44730                                 ELSE 4
44731                    END AS seq
44732             FROM pg_catalog.pg_class c, pg_namespace n
44733             WHERE ((n.oid=c.relnamespace)
44734               AND  (nspname in ('public', 'api') OR
44735                     nspname in (SELECT pkghead_name FROM pkghead))
44736               AND  (relkind in ('S', 'r', 'v')))
44737             ORDER BY seq
44738   LOOP
44739     _schema := quote_ident(_r.nspname);
44740     _table  := quote_ident(_r.relname);
44741
44742     RAISE DEBUG '%.%', _schema, _table;
44743     
44744     IF (_oldgrp) THEN
44745       EXECUTE 'REVOKE ALL ON ' || _schema || '.' || _table || ' FROM openmfg;';
44746     END IF;
44747     EXECUTE 'REVOKE ALL ON ' || _schema || '.' || _table || ' FROM PUBLIC;';
44748     EXECUTE 'GRANT ALL ON '  || _schema || '.' || _table || ' TO GROUP xtrole;';
44749     _count := _count + 1;
44750
44751     _objtype := CASE _r.relkind WHEN 'S' THEN 'SEQUENCE'
44752                                 WHEN 'r' THEN 'TABLE'
44753                                 WHEN 'v' THEN 'VIEW'
44754                                 ELSE NULL
44755                 END;
44756     IF (_objtype IS NOT NULL) THEN
44757       BEGIN
44758         EXECUTE 'ALTER ' || _objtype || ' ' ||
44759                 _schema || '.' || _table || ' OWNER TO admin;';
44760       EXCEPTION WHEN OTHERS THEN
44761         RAISE WARNING 'Could not change ownership of %.% to admin',
44762                       _schema, _table;
44763       END;
44764     END IF;
44765
44766   END LOOP;
44767
44768   RETURN _count;
44769 END;
44770 $$;
44771
44772
44773 ALTER FUNCTION public.fixacl() OWNER TO admin;
44774
44775 --
44776 -- TOC entry 1584 (class 1255 OID 146566160)
44777 -- Dependencies: 2648 4536 8
44778 -- Name: formatabachecks(integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
44779 --
44780
44781 CREATE FUNCTION formatabachecks(integer, integer, text) RETURNS SETOF achline
44782     LANGUAGE plpgsql
44783     AS $_$
44784 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
44785 -- See www.xtuple.com/CPAL for the full text of the software license.
44786 DECLARE
44787   pbankaccntid     ALIAS FOR $1;   -- all unprinted checks for this bankaccnt
44788   pcheckheadid     ALIAS FOR $2;   -- but if 2nd arg not null then just 1 check
44789   penckey          ALIAS FOR $3;
44790   _bank            RECORD;
44791   _batchcount      INTEGER := 0;
44792   _batchdate       DATE;
44793   _check           RECORD;
44794   _vendnumber      TEXT;
44795   _vendname        TEXT;
44796   _filenum         TEXT;
44797   _prevsec         TEXT;
44798   _row             achline%ROWTYPE;
44799   _totalcr         NUMERIC := 0;
44800   _totaldb         NUMERIC := 0;
44801   _detailcount     INTEGER := 0;     -- count of type 1 entries
44802   _vendbsb         TEXT;
44803
44804 BEGIN
44805   -- General notes:
44806   -- Numeric values are formatted using RPAD(TO_CHAR(#, '0..0SG', #)).
44807   --    TO_CHAR(#, ...) (at least in the default server locale) puts a space at
44808   --    the beginning of the string for numbers >= 0 and '-' for numbers < 0.
44809   --    'SG' pushes the sign char to the end, then RPAD cuts it off.
44810   -- This whole thing is for Australian bank transactions only, and generates entries for an ABA file.
44811   -- Currently restricted to checks to Vendor; there's no support for checks to
44812   --    customers or tax authorities, or for debits or corrections.
44813   -- This function has been adapted from the US-centric ACH formatACHChecks function.
44814
44815   IF (NOT fetchMetricBool('ACHEnabled')) THEN
44816     RAISE EXCEPTION 'Cannot format the ABA file because the system is not configured for ABA file generation.';
44817   END IF;
44818   IF (LENGTH(COALESCE(penckey, '')) <= 0) THEN
44819     RAISE EXCEPTION 'Cannot format the ABA file because there is no encryption key.';
44820   END IF;
44821
44822   SELECT * INTO _bank
44823   FROM bankaccnt
44824   WHERE (bankaccnt_id=pbankaccntid);
44825
44826   IF (NOT FOUND) THEN
44827     RAISE EXCEPTION 'Could not find the bank information to create the ABA file.';
44828   ELSIF (NOT _bank.bankaccnt_ach_enabled) THEN
44829     RAISE EXCEPTION 'Cannot format the ABA file because the Bank Account % is not configured for ABA transactions.',
44830       _bank.bankaccnt_name;
44831   ELSIF (LENGTH(COALESCE(_bank.bankaccnt_routing, '')) <= 0) THEN 
44832     RAISE EXCEPTION 'Cannot format the ABA file because the Bank Account % has no BSB number.', _bank.bankaccnt_name;
44833   END IF;
44834
44835   -- Check the BSB number is in the right format and then re-format for output.
44836   -- Valid format is \d{3}-\d{3}|\d{6}000
44837   IF (_bank.bankaccnt_routing ~ E'^(\\d{3})(?:-(?=\\d{3}$)|(?=\\d{3}0{3}$))(\\d{3})(0{3})?$') THEN
44838     _bank.bankaccnt_routing := regexp_replace(
44839       _bank.bankaccnt_routing,
44840       E'^(\\d{3})(?:-(?=\\d{3}$)|(?=\\d{3}0{3}$))(\\d{3})(0{3})?$', E'\\1-\\2'
44841     );
44842   ELSE RAISE EXCEPTION 'Cannot format the ABA file because the Bank Account % has an invalid BSB number.',
44843     _bank.bankaccnt_name;
44844   END IF;
44845
44846
44847   _filenum := LPAD(fetchNextNumber('ACHBatch'), 8, '0');
44848
44849   IF (COALESCE(_bank.bankaccnt_ach_lastdate,startOfTime()) < CURRENT_DATE
44850     OR _bank.bankaccnt_ach_lastfileid IS NULL) THEN
44851     _bank.bankaccnt_ach_lastfileid = '0';
44852   ELSIF (_bank.bankaccnt_ach_lastfileid = '9') THEN
44853     _bank.bankaccnt_ach_lastfileid = 'A';
44854   ELSIF (_bank.bankaccnt_ach_lastfileid = 'Z') THEN
44855     RAISE EXCEPTION 'Cannot write % check % to an ABA file because too many files have been written for this bank already today.',
44856       _bank.bankaccnt_name, _check.checkhead_number;
44857   ELSE
44858     _bank.bankaccnt_ach_lastfileid = CHR(ASCII(_bank.bankaccnt_ach_lastfileid) + 1);
44859   END IF;
44860   
44861
44862   _row.achline_checkhead_id := NULL;
44863   _row.achline_batch := _filenum;
44864   _row.achline_type := 'HEADER';
44865   _row.achline_value := RPAD(
44866     RPAD('0',18)                                    -- Record Type 0 blank filled with 17 spaces
44867     || '01'                                         -- Reel sequence number 
44868     || RPAD(_bank.bankaccnt_bankname,3)             -- Approved financial instition abbreviation.
44869     || RPAD('',7)                                   -- blank filled
44870     || RPAD(fetchMetricText('ACHCompanyName'), 26)  -- Name of user supplying ABA file
44871     || LPAD(fetchMetricText('ACHCompanyId'),6)      -- User identification number APCA issued
44872     || RPAD('PAYMENT',12)                           -- description of entries on file
44873                                                     --  currently only use payment description
44874     || TO_CHAR(CURRENT_DATE,      'DDMMYY'),        -- date to be processed
44875     120                                             -- blank filled to 120 characters
44876   );
44877   RETURN NEXT _row;
44878
44879   FOR _check IN SELECT *
44880     FROM checkhead
44881     JOIN vendinfo ON (checkhead_recip_type='V'
44882       AND checkhead_recip_id=vend_id
44883       AND vend_ach_enabled)
44884     JOIN curr_symbol ON (checkhead_curr_id=curr_id)
44885     LEFT OUTER JOIN crmacct ON (crmacct_vend_id=vend_id)
44886     WHERE ((checkhead_bankaccnt_id=pbankaccntid)
44887       AND (checkhead_amount > 0)
44888       AND (checkhead_id=pcheckheadid OR pcheckheadid IS NULL)
44889       AND NOT checkhead_posted
44890       AND NOT checkhead_replaced
44891       AND NOT checkhead_deleted
44892       AND NOT checkhead_void
44893       AND NOT checkhead_printed
44894       AND (LENGTH(COALESCE(checkhead_ach_batch,'')) <= 0)
44895       AND (curr_abbr='AUD'))
44896     ORDER BY checkhead_checkdate, vend_name LOOP
44897
44898     IF (COALESCE(_check.checkhead_number, -1) <= 0
44899       AND _bank.bankaccnt_ach_genchecknum) THEN
44900         _check.checkhead_number := fetchNextCheckNumber(_check.checkhead_bankaccnt_id);
44901     END IF;
44902
44903     -- Although a crmacct record is not required for used in this function
44904     -- this code is retained for consistancy with the original formatachchecks function.
44905     IF (_check.crmacct_id IS NULL) THEN
44906       RAISE NOTICE 'Vendor % does not have a corresponding crmacct record.',
44907         _check.checkhead_recip_id;
44908     ELSIF (_check.crmacct_type IS NULL) THEN
44909       RAISE NOTICE 'crmacct for vendor % does not have a valid crmacct_type.',
44910          _check.checkhead_recip_id;
44911     END IF;
44912
44913     _vendnumber := CASE WHEN _check.vend_ach_use_vendinfo THEN _check.vend_number
44914       ELSE _check.vend_ach_indiv_number
44915       END;
44916     _vendname := CASE WHEN _check.vend_ach_use_vendinfo THEN _check.vend_name
44917       ELSE _check.vend_ach_indiv_name
44918       END;
44919
44920     IF (COALESCE(_check.vend_ach_routingnumber, '') = '') THEN
44921       RAISE EXCEPTION 'Cannot write % check % to an ABA file because the BSB number for % has not been supplied.',
44922         _bank.bankaccnt_name, _check.checkhead_number, _vendnumber;
44923     ELSIF (COALESCE(_check.vend_ach_accntnumber, '') = '') THEN
44924       RAISE EXCEPTION 'Cannot write % check % to an ABA file because the account number for % has not been supplied.',
44925         _bank.bankaccnt_name, _check.checkhead_number, _vendnumber;
44926     END IF;
44927     _check.vend_ach_routingnumber := decrypt(setbytea(_check.vend_ach_routingnumber),
44928       setbytea(penckey), 'bf');
44929     _check.vend_ach_accntnumber   := decrypt(setbytea(_check.vend_ach_accntnumber),
44930       setbytea(penckey), 'bf');
44931     
44932     -- Check the BSB number is in the right format and then re-format for output.
44933     -- Valid format is \d{3}-\d{3}|\d{6}000
44934     IF (formatbytea(_check.vend_ach_routingnumber) ~ E'^(\\d{3})(?:-(?=\\d{3}$)|(?=\\d{3}0{3}$))(\\d{3})(0{3})?$') THEN
44935       _vendbsb := regexp_replace(
44936         formatbytea(_check.vend_ach_routingnumber),
44937         E'^(\\d{3})(?:-(?=\\d{3}$)|(?=\\d{3}0{3}$))(\\d{3})(0{3})?$', E'\\1-\\2'
44938       );
44939     ELSE RAISE EXCEPTION 'Cannot write % check % to an ABA file because the BSB number for % is not valid.',
44940       _bank.bankaccnt_name, _check.checkhead_number, _vendnumber;
44941     END IF;
44942
44943     _row.achline_checkhead_id := _check.checkhead_id;
44944     _row.achline_batch        := _filenum;
44945     _row.achline_type         := 'DETAIL';
44946
44947     _totaldb      := _totaldb + _check.checkhead_amount;                -- Total debits for balancing entry
44948     _detailcount  := _detailcount + 1;                                  -- Detail record counter (type 1)
44949     _totalcr      := _totalcr + _check.checkhead_amount;                -- Total credits from payments
44950                                                                         
44951     _row.achline_value := RPAD('1'                                      -- record type 1
44952       || _vendbsb                                                       -- vendor BSB #
44953       || LPAD(formatbytea(_check.vend_ach_accntnumber), 9)              -- vendor account no.
44954       ||' '                                                             -- withholding tax indicator
44955       ||'50'                                                            -- transaction code, this should be calculated.
44956       || LPAD(to_char(_check.checkhead_amount,'FM99999999V99'),10,'0')  -- amount
44957       || RPAD(_vendname,   32)                                          -- vendor name
44958       || RPAD('Deposit',8) || RPAD('#'  , 2) || LPAD (_filenum,8,' ')   -- Lodgement Reference
44959       || _bank.bankaccnt_routing                                        -- BSB #
44960       || RPAD(_bank.bankaccnt_accntnumber, 9)                           -- company account number
44961       || RPAD(fetchMetricText('ACHCompanyName'), 16)                    -- company account name
44962       || LPAD('', 8, '0'),                                              -- Witholding Tax Amount
44963       120                                                               -- line width
44964     );
44965     RETURN NEXT _row;
44966
44967     UPDATE checkhead
44968     SET checkhead_ach_batch=_filenum,
44969       checkhead_number=_check.checkhead_number
44970     WHERE (checkhead_id=_check.checkhead_id);
44971
44972   END LOOP;
44973
44974   IF (NOT FOUND) THEN
44975     RAISE EXCEPTION 'Cannot write an ABA file for % because there are no checks pending in AUD for EFT-enabled Vendors.',
44976       _bank.bankaccnt_name;
44977   END IF;
44978
44979   -- Place a final balancing detail record.
44980   -- Check that the balancing record actually balances.
44981   IF (_totalcr != _totaldb) THEN
44982     RAISE EXCEPTION 'Cannot write an ABA file for % because the total credits: % does not equal the total debits: %, file will not balance.',
44983     _bank.bankaccnt_name, _totalcr, _totaldb;
44984   END IF;
44985   
44986
44987   _detailcount := _detailcount + 1;
44988   _row.achline_checkhead_id := NULL;
44989   _row.achline_batch := _filenum;
44990   _row.achline_type := 'BALANCING';
44991   -- keep in sync with the other batchcontrol record format above
44992   -- THE FOLLOWING IS THE DEBIT BALANCING RECORD
44993   _row.achline_value := RPAD('1'                          -- record type 1
44994     || _bank.bankaccnt_routing                            -- Austalian BSB #
44995     || LPAD(_bank.bankaccnt_accntnumber, 9)               -- company account no.
44996     || ' '                                                -- withholding tax indicator
44997     || '13'                                               -- transaction code
44998     || to_char(_totaldb,'FM09999999V99')                  -- the balancing amount
44999     || RPAD(fetchMetricText('ACHCompanyName'),   32)      -- company name
45000     || RPAD('DIRECT DEPOSIT',18)                          
45001     || _bank.bankaccnt_routing                            -- Austalian BSB #
45002     || RPAD(_bank.bankaccnt_accntnumber, 9)               -- company account number
45003     || RPAD(fetchMetricText('ACHCompanyName'), 16)        -- company account name
45004     || LPAD('', 8, '0'),                                  -- Witholding Tax Amount
45005     120                                                   -- line width
45006   );
45007   RETURN NEXT _row;
45008
45009   RAISE DEBUG 'formatABAChecks building TRAILER with _totaldb %, _totalcr %, _detailcount %',
45010                _totaldb, _totalcr, _detailcount;
45011   -- file control record
45012   _row.achline_checkhead_id := NULL;
45013   _row.achline_batch := _filenum;
45014   _row.achline_type := 'TRAILER';
45015   _row.achline_value := RPAD('7'                                    -- record type 7
45016     || RPAD('999-999',   7)                                         -- BSB format filler
45017     || RPAD('' , 12)                                                -- blank
45018     || LPAD(to_char((_totaldb - _totalcr),'FM09999999V99'),10,'0')  -- net total amount
45019     || LPAD(to_char(_totalcr, 'FM09999999V99'),10,'0')              -- total credit amount
45020     || LPAD(to_char(_totaldb, 'FM09999999V99'),10,'0')              -- total debit amount
45021     || RPAD('', 24)                                                 -- blank
45022     || RPAD(to_char(_detailcount, 'FM000000'), 6,'0'),              -- count of type 1 records
45023     120                                                             -- blank fill
45024   );
45025
45026   RETURN NEXT _row;
45027
45028
45029   UPDATE bankaccnt
45030   SET bankaccnt_ach_lastdate=CURRENT_DATE,
45031     bankaccnt_ach_lastfileid=_bank.bankaccnt_ach_lastfileid
45032   WHERE (bankaccnt_id=_bank.bankaccnt_id);
45033
45034   RETURN;
45035
45036 END;
45037 $_$;
45038
45039
45040 ALTER FUNCTION public.formatabachecks(integer, integer, text) OWNER TO admin;
45041
45042 --
45043 -- TOC entry 1585 (class 1255 OID 146566162)
45044 -- Dependencies: 2648 4536 8
45045 -- Name: formatachchecks(integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
45046 --
45047
45048 CREATE FUNCTION formatachchecks(integer, integer, text) RETURNS SETOF achline
45049     LANGUAGE plpgsql
45050     AS $_$
45051 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45052 -- See www.xtuple.com/CPAL for the full text of the software license.
45053 DECLARE
45054   pbankaccntid     ALIAS FOR $1;   -- all unprinted checks for this bankaccnt
45055   pcheckheadid     ALIAS FOR $2;   -- but if 2nd arg not null then just 1 check
45056   penckey          ALIAS FOR $3;
45057   _bank            RECORD;
45058   _batchcount      INTEGER := 0;
45059   _batchcr         NUMERIC := 0;
45060   _batchdate       DATE;
45061   _batchdb         NUMERIC := 0;
45062   _batchhash       INTEGER := 0;
45063   _check           RECORD;
45064   _ccdnumber       TEXT;
45065   _ccdname         TEXT;
45066   _entrycount      INTEGER := 0;
45067   _filenum         TEXT;
45068   _prevsec         TEXT;
45069   _row             achline%ROWTYPE;
45070   _rowcount        INTEGER := 0;
45071   _sec             TEXT;
45072   _serviceclass    TEXT := '200';    -- 220 = credits, 225 = debits, 200 = mixed
45073   _totalcr         NUMERIC := 0;
45074   _totaldb         NUMERIC := 0;
45075   _totalentrycnt   INTEGER := 0;
45076   _totalhash       INTEGER := 0;
45077   _transactionprefix TEXT;
45078
45079 BEGIN
45080   -- General notes:
45081   -- Numeric values are formatted using RPAD(TO_CHAR(#, '0..0SG', #)).
45082   --    TO_CHAR(#, ...) (at least in the default server locale) puts a space at
45083   --    the beginning of the string for numbers >= 0 and '-' for numbers < 0.
45084   --    'SG' pushes the sign char to the end, then RPAD cuts it off.
45085   -- This whole thing is US-centric, as that's where the NACHA is.
45086   -- Currently restricted to checks to Vendor; there's no support for checks to
45087   --    customers or tax authorities, or for debits or corrections.
45088
45089   IF (NOT fetchMetricBool('ACHEnabled')) THEN
45090     RAISE EXCEPTION 'Cannot format the ACH file because the system is not configured for ACH file generation.';
45091   END IF;
45092   IF (LENGTH(COALESCE(penckey, '')) <= 0) THEN
45093     RAISE EXCEPTION 'Cannot format the ACH file because there is no encryption key.';
45094   END IF;
45095
45096   SELECT * INTO _bank
45097   FROM bankaccnt
45098   WHERE (bankaccnt_id=pbankaccntid);
45099
45100   IF (NOT FOUND) THEN
45101     RAISE EXCEPTION 'Could not find the bank information to create the ACH file.';
45102   ELSIF (NOT _bank.bankaccnt_ach_enabled) THEN
45103     RAISE EXCEPTION 'Cannot format the ACH file because the Bank Account % is not configured for ACH transactions.',
45104       _bank.bankaccnt_name;
45105   ELSIF (LENGTH(COALESCE(_bank.bankaccnt_routing, '')) <= 0) THEN 
45106     RAISE EXCEPTION 'Cannot format the ACH file because the Bank Account % has no routing number.',
45107       _bank.bankaccnt_name;
45108   END IF;
45109
45110   _filenum := LPAD(fetchNextNumber('ACHBatch'), 8, '0');
45111
45112   IF (COALESCE(_bank.bankaccnt_ach_lastdate,startOfTime()) < CURRENT_DATE
45113       OR _bank.bankaccnt_ach_lastfileid IS NULL) THEN
45114     _bank.bankaccnt_ach_lastfileid = '0';
45115   ELSIF (_bank.bankaccnt_ach_lastfileid = '9') THEN
45116     _bank.bankaccnt_ach_lastfileid = 'A';
45117   ELSIF (_bank.bankaccnt_ach_lastfileid = 'Z') THEN
45118     RAISE EXCEPTION 'Cannot write % check % to an ACH file because too many files have been written for this bank already today.',
45119                   _bank.bankaccnt_name, _check.checkhead_number;
45120   ELSE
45121     _bank.bankaccnt_ach_lastfileid = CHR(ASCII(_bank.bankaccnt_ach_lastfileid) + 1);
45122   END IF;
45123
45124   _rowcount := _rowcount + 1;
45125   _row.achline_checkhead_id := NULL;
45126   _row.achline_batch := _filenum;
45127   _row.achline_type := 'FILEHEADER';
45128   _row.achline_value := RPAD('1'
45129                           || '01'
45130                           || RPAD(CASE WHEN _bank.bankaccnt_ach_desttype = 'B' THEN ' ' || _bank.bankaccnt_routing
45131                                        WHEN _bank.bankaccnt_ach_desttype = 'F' THEN ' ' || _bank.bankaccnt_ach_fed_dest
45132                                        ELSE _bank.bankaccnt_ach_dest END, 10)
45133                           || RPAD(CASE WHEN _bank.bankaccnt_ach_origintype = 'B' THEN ' ' || _bank.bankaccnt_routing
45134                                        WHEN _bank.bankaccnt_ach_origintype = 'I' THEN formatAchCompanyId()
45135                                        ELSE _bank.bankaccnt_ach_origin END, 10)
45136                           || TO_CHAR(CURRENT_DATE,      'YYMMDD')
45137                           || TO_CHAR(CURRENT_TIMESTAMP, 'HH24MM')
45138                           || UPPER(_bank.bankaccnt_ach_lastfileid)
45139                           || '094'
45140                           || '10'
45141                           || '1'
45142                           || RPAD(CASE WHEN _bank.bankaccnt_ach_desttype = 'B' THEN _bank.bankaccnt_bankname
45143                                        WHEN _bank.bankaccnt_ach_desttype = 'F' THEN 'Federal Reserve'
45144                                        ELSE _bank.bankaccnt_ach_destname END, 23)
45145                           || RPAD(CASE WHEN _bank.bankaccnt_ach_origintype = 'B' THEN ' ' || _bank.bankaccnt_bankname
45146                                        WHEN _bank.bankaccnt_ach_origintype = 'I' THEN fetchMetricText('ACHCompanyName')
45147                                        ELSE _bank.bankaccnt_ach_originname END, 23)
45148                           || RPAD(_filenum, 8),
45149                           94);
45150   RETURN NEXT _row;
45151
45152   FOR _check IN SELECT *
45153                 FROM checkhead
45154                 JOIN vendinfo ON (checkhead_recip_type='V'
45155                               AND checkhead_recip_id=vend_id
45156                               AND vend_ach_enabled)
45157                 JOIN curr_symbol ON (checkhead_curr_id=curr_id)
45158                 LEFT OUTER JOIN crmacct ON (crmacct_vend_id=vend_id)
45159                 WHERE ((checkhead_bankaccnt_id=pbankaccntid)
45160                    AND (checkhead_amount > 0)
45161                    AND (checkhead_id=pcheckheadid OR pcheckheadid IS NULL)
45162                    AND NOT checkhead_posted
45163                    AND NOT checkhead_replaced
45164                    AND NOT checkhead_deleted
45165                    AND NOT checkhead_void
45166                    AND NOT checkhead_printed
45167                    AND (LENGTH(COALESCE(checkhead_ach_batch,'')) <= 0)
45168                    AND (curr_abbr='USD'))
45169                 ORDER BY checkhead_checkdate, vend_name LOOP
45170
45171     IF (COALESCE(_check.checkhead_number, -1) <= 0
45172         AND _bank.bankaccnt_ach_genchecknum) THEN
45173       _check.checkhead_number := fetchNextCheckNumber(_check.checkhead_bankaccnt_id);
45174     END IF;
45175
45176     _prevsec := _sec;
45177
45178     IF (_check.crmacct_type = 'I') THEN
45179       _sec := 'PPD';
45180     ELSE
45181       _sec := 'CCD';
45182       IF (_check.crmacct_id IS NULL) THEN
45183         RAISE NOTICE 'Vendor % does not have a corresponding crmacct record.',
45184                      _check.checkhead_recip_id;
45185       ELSIF (_check.crmacct_type IS NULL) THEN
45186         RAISE NOTICE 'crmacct for vendor % does not have a valid crmacct_type.',
45187                      _check.checkhead_recip_id;
45188       END IF;
45189     END IF;
45190
45191     _ccdnumber := CASE WHEN _check.vend_ach_use_vendinfo THEN _check.vend_number
45192                        ELSE _check.vend_ach_indiv_number
45193                   END;
45194     _ccdname := CASE WHEN _check.vend_ach_use_vendinfo THEN _check.vend_name
45195                      ELSE _check.vend_ach_indiv_name
45196                 END;
45197
45198     IF (COALESCE(_check.vend_ach_routingnumber, '') = '') THEN
45199       RAISE EXCEPTION 'Cannot write % check % to an ACH file because the routing number for % has not been supplied.',
45200                   _bank.bankaccnt_name, _check.checkhead_number, _ccdnumber;
45201     ELSIF (COALESCE(_check.vend_ach_accntnumber, '') = '') THEN
45202       RAISE EXCEPTION 'Cannot write % check % to an ACH file because the account number for % has not been supplied.',
45203                   _bank.bankaccnt_name, _check.checkhead_number, _ccdnumber;
45204     END IF;
45205     _check.vend_ach_routingnumber := decrypt(setbytea(_check.vend_ach_routingnumber),
45206                                          setbytea(penckey), 'bf');
45207     _check.vend_ach_accntnumber   := decrypt(setbytea(_check.vend_ach_accntnumber),
45208                                          setbytea(penckey), 'bf');
45209     _transactionprefix := CASE WHEN (_check.vend_ach_accnttype = 'K') THEN '2'
45210                                WHEN (_check.vend_ach_accnttype = 'C') THEN '3'
45211                           END;
45212
45213     -- create separate batches for each check date and for PPD vs CCD
45214     IF (COALESCE(_batchdate, startOfTime()) != _check.checkhead_checkdate
45215         OR (_prevsec != _sec)) THEN
45216       IF (_batchcount > 0) THEN
45217         _rowcount := _rowcount + 1;
45218         _row.achline_checkhead_id := NULL;
45219         _row.achline_batch := _filenum;
45220         _row.achline_type := 'BATCHCONTROL';
45221         -- keep in sync with the other batchcontrol record format below
45222         _row.achline_value := RPAD('8'
45223                                 || _serviceclass
45224                                 || RPAD(TO_CHAR(_entrycount, '000000SG'), 6)
45225                                 || RPAD(TO_CHAR(_batchhash % 10000000000,
45226                                                 '0000000000SG'), 10)
45227                                 || RPAD(TO_CHAR(_batchdb, '0000000000V99SG'), 12)
45228                                 || RPAD(TO_CHAR(_batchcr, '0000000000V99SG'), 12)
45229                                 || RPAD(formatAchCompanyId(), 10)
45230                                 || RPAD(' ', 19)
45231                                 || RPAD(' ',  6)
45232                                 || RPAD(_bank.bankaccnt_routing, 8)
45233                                 || RPAD(TO_CHAR(_batchcount, '0000000SG'), 7),
45234                                 94);
45235         RETURN NEXT _row;
45236       END IF;
45237
45238       _batchhash     := 0;
45239       _batchcr       := 0;
45240       _batchdb       := 0;
45241       _batchdate     := _check.checkhead_checkdate;
45242       _entrycount    := 0;
45243       _rowcount      := _rowcount + 1;
45244       _batchcount    := _batchcount + 1;
45245       _row.achline_checkhead_id := NULL;
45246       _row.achline_batch := _filenum;
45247       _row.achline_type := 'BATCHHEADER';
45248
45249       -- effective entry date = 1 or 2 banking days after the banking day
45250       -- of processing (the following accounts for weekends but not holidays)
45251
45252       _row.achline_value := RPAD('5'
45253                               || _serviceclass
45254                               || RPAD(fetchMetricText('ACHCompanyName'), 16)
45255                               || RPAD('', 20)   -- TODO: find a use
45256                               || RPAD(formatAchCompanyId(), 10)
45257                               || _sec
45258                               || RPAD('xTuple ERP', 10)
45259                               || TO_CHAR(_check.checkhead_checkdate, 'YYMMDD')
45260                               || TO_CHAR(CURRENT_DATE +
45261                                          COALESCE(_bank.bankaccnt_ach_leadtime,1) +
45262                                          CASE WHEN EXTRACT(DOW FROM CURRENT_DATE) = 5 THEN 2
45263                                               WHEN EXTRACT(DOW FROM CURRENT_DATE) = 6 THEN 1
45264                                               ELSE 0 END,
45265                                          'YYMMDD')
45266                               || RPAD('', 3)
45267                               || '1'
45268                               || RPAD(_bank.bankaccnt_routing, 8)
45269                               || RPAD(TO_CHAR(_batchcount, '0000000SG'), 7),
45270                               94);
45271       RETURN NEXT _row;
45272     END IF;
45273
45274     _row.achline_checkhead_id := _check.checkhead_id;
45275     _row.achline_batch        := _filenum;
45276     _row.achline_type         := _sec;
45277
45278     IF (_sec = 'CCD' OR _sec = 'PPD') THEN
45279       _rowcount      := _rowcount + 1;
45280       _entrycount    := _entrycount + 1;
45281       _totalentrycnt := _totalentrycnt + 1;
45282       _batchhash     := _batchhash + CAST(SUBSTRING(_bank.bankaccnt_routing FOR 8) AS INTEGER);
45283       _totalhash     := _totalhash + CAST(SUBSTRING(_bank.bankaccnt_routing FOR 8) AS INTEGER);
45284       _batchdb       := _batchdb + _check.checkhead_amount;
45285       _totaldb       := _totaldb + _check.checkhead_amount;
45286
45287       _row.achline_value := RPAD('6'
45288                               || _transactionprefix || '7'              -- debit
45289                               || RPAD(_bank.bankaccnt_routing,      9)  -- 2 fields
45290                               || RPAD(_bank.bankaccnt_accntnumber, 17)
45291                               || RPAD(TO_CHAR(_check.checkhead_amount,
45292                                               '00000000V99SG'), 10)
45293                               || RPAD(fetchMetricText('ACHCompanyId'),   15)
45294                               || RPAD(fetchMetricText('ACHCompanyName'), 22)
45295                               || RPAD(TO_CHAR(_check.checkhead_id % 100, '00SG'),
45296                                       2)        -- last 2 digits of checkhead_id
45297                               || '0'
45298                               || RPAD(_bank.bankaccnt_routing, 9)  -- split field
45299                               || RPAD(TO_CHAR(_entrycount, '000000SG'), 15-9),
45300                               94);
45301       RETURN NEXT _row;
45302
45303       _rowcount      := _rowcount + 1;
45304       _entrycount    := _entrycount + 1;
45305       _totalentrycnt := _totalentrycnt + 1;
45306       _batchhash     := _batchhash + CAST(SUBSTRING(formatbytea(_check.vend_ach_routingnumber) FOR 8) AS INTEGER);
45307       _totalhash     := _totalhash + CAST(SUBSTRING(formatbytea(_check.vend_ach_routingnumber) FOR 8) AS INTEGER);
45308       _totalcr       := _totalcr + _check.checkhead_amount;
45309       _batchcr       := _batchcr + _check.checkhead_amount;
45310       _row.achline_value := RPAD('6'
45311                               || _transactionprefix || '2'              -- credit
45312                               || RPAD(formatbytea(_check.vend_ach_routingnumber), 9)   -- 2 fields
45313                               || RPAD(formatbytea(_check.vend_ach_accntnumber), 17)
45314                               || RPAD(TO_CHAR(_check.checkhead_amount,
45315                                               '00000000V99SG'), 10)
45316                               || RPAD(_ccdnumber, 15)
45317                               || RPAD(_ccdname,   22)
45318                               || RPAD(TO_CHAR(_check.checkhead_id % 100, '00SG'),
45319                                       2)        -- last 2 digits of checkhead_id
45320                               || '0'
45321                               || RPAD(_bank.bankaccnt_routing, 9)  -- split field
45322                               || RPAD(TO_CHAR(_entrycount, '000000SG'), 15-9),
45323                               94);
45324       RETURN NEXT _row;
45325
45326     ELSE
45327       RAISE EXCEPTION 'Cannot write % check % to an ACH file because % is not a supported SEC code.',
45328                     _bank.bankaccnt_name, _check.checkhead_number, _sec;
45329     END IF;
45330
45331     UPDATE checkhead
45332     SET checkhead_ach_batch=_filenum,
45333         checkhead_number=_check.checkhead_number
45334     WHERE (checkhead_id=_check.checkhead_id);
45335
45336   END LOOP;
45337
45338   IF (NOT FOUND) THEN
45339     RAISE EXCEPTION 'Cannot write an ACH file for % because there are no checks pending in USD for ACH-enabled Vendors.',
45340                     _bank.bankaccnt_name;
45341   END IF;
45342
45343   -- place a final batch control record
45344   IF (_batchcount > 0) THEN
45345     _rowcount := _rowcount + 1;
45346     _row.achline_checkhead_id := NULL;
45347     _row.achline_batch := _filenum;
45348     _row.achline_type := 'BATCHCONTROL';
45349     -- keep in sync with the other batchcontrol record format above
45350     _row.achline_value := RPAD('8'
45351                             || _serviceclass
45352                             || RPAD(TO_CHAR(_entrycount, '000000SG'), 6)
45353                             || RPAD(TO_CHAR(_batchhash % 10000000000,
45354                                             '0000000000SG'), 10)
45355                             || RPAD(TO_CHAR(_batchdb, '0000000000V99SG'), 12)
45356                             || RPAD(TO_CHAR(_batchcr, '0000000000V99SG'), 12)
45357                             || RPAD(formatAchCompanyId(), 10)
45358                             || RPAD(' ', 19)
45359                             || RPAD(' ',  6)
45360                             || RPAD(_bank.bankaccnt_routing, 8)
45361                             || RPAD(TO_CHAR(_batchcount, '0000000SG'), 7),
45362                             94);
45363     RETURN NEXT _row;
45364   END IF;
45365
45366   -- and end with a file control record
45367   _rowcount := _rowcount + 1;
45368   _row.achline_checkhead_id := NULL;
45369   _row.achline_batch := _filenum;
45370   _row.achline_type := 'FILECONTROL';
45371   _row.achline_value := RPAD('9'
45372                           || RPAD(TO_CHAR(_batchcount,    '000000SG'),   6)
45373                           || RPAD(TO_CHAR(_rowcount,      '000000SG'),   6)
45374                           || RPAD(TO_CHAR(_totalentrycnt, '00000000SG'), 8)
45375                           || RPAD(TO_CHAR(_totalhash % 10000000000,
45376                                           '0000000000SG'), 10)
45377                           || RPAD(TO_CHAR(_totaldb, '0000000000V99SG'), 12)
45378                           || RPAD(TO_CHAR(_totalcr, '0000000000V99SG'), 12)
45379                           || RPAD('', 39),
45380                           94);
45381
45382   RETURN NEXT _row;
45383
45384   -- file must be a multiple of 10 lines long
45385   _row.achline_checkhead_id := NULL;
45386   _row.achline_batch := _filenum;
45387   _row.achline_type := 'BLOCKFILL';
45388   WHILE (_rowcount % 10 > 0) LOOP
45389     _rowcount := _rowcount + 1;
45390     _row.achline_value := RPAD('99999999999999999999'
45391                             || '99999999999999999999'
45392                             || '99999999999999999999'
45393                             || '99999999999999999999'
45394                             || '99999999999999999999', 94);
45395     RETURN NEXT _row;
45396   END LOOP;
45397
45398   UPDATE bankaccnt
45399   SET bankaccnt_ach_lastdate=CURRENT_DATE,
45400       bankaccnt_ach_lastfileid=_bank.bankaccnt_ach_lastfileid
45401   WHERE (bankaccnt_id=_bank.bankaccnt_id);
45402
45403   RETURN;
45404
45405 END;
45406 $_$;
45407
45408
45409 ALTER FUNCTION public.formatachchecks(integer, integer, text) OWNER TO admin;
45410
45411 --
45412 -- TOC entry 1586 (class 1255 OID 146566164)
45413 -- Dependencies: 4536 8
45414 -- Name: formatachcompanyid(); Type: FUNCTION; Schema: public; Owner: admin
45415 --
45416
45417 CREATE FUNCTION formatachcompanyid() RETURNS text
45418     LANGUAGE plpgsql
45419     AS $$
45420 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45421 -- See www.xtuple.com/CPAL for the full text of the software license.
45422 BEGIN
45423   RETURN CASE WHEN fetchMetricText('ACHCompanyIdType') = 'D' THEN '3'
45424               WHEN fetchMetricText('ACHCompanyIdType') = 'E' THEN '1'
45425               WHEN fetchMetricText('ACHCompanyIdType') = 'O' THEN '9'
45426          END ||
45427          CASE WHEN fetchMetricText('ACHCompanyIdType') = 'D' OR
45428                    fetchMetricText('ACHCompanyIdType') = 'E' THEN
45429                  REPLACE(fetchMetricText('ACHCompanyId'), '-', '')
45430               ELSE fetchMetricText('ACHCompanyId')
45431          END;
45432 END;
45433 $$;
45434
45435
45436 ALTER FUNCTION public.formatachcompanyid() OWNER TO admin;
45437
45438 --
45439 -- TOC entry 1569 (class 1255 OID 146566168)
45440 -- Dependencies: 4536 8
45441 -- Name: formataddr(integer); Type: FUNCTION; Schema: public; Owner: admin
45442 --
45443
45444 CREATE FUNCTION formataddr(integer) RETURNS text
45445     LANGUAGE plpgsql
45446     AS $_$
45447 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45448 -- See www.xtuple.com/CPAL for the full text of the software license.
45449 DECLARE
45450   pAddrId       ALIAS FOR $1;
45451   _return       TEXT;
45452
45453 BEGIN
45454   -- US conventions
45455   SELECT formatAddr(addr_line1, addr_line2, addr_line3,
45456                     addr_city || ', ' || addr_state || ' ' || addr_postalcode,
45457                     addr_country) INTO _return
45458   FROM addr
45459   WHERE (addr_id=pAddrId);
45460
45461   RETURN _return;
45462 END;
45463 $_$;
45464
45465
45466 ALTER FUNCTION public.formataddr(integer) OWNER TO admin;
45467
45468 --
45469 -- TOC entry 1587 (class 1255 OID 146566165)
45470 -- Dependencies: 4536 8
45471 -- Name: formataddr(text, text, text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
45472 --
45473
45474 CREATE FUNCTION formataddr(text, text, text, text, integer) RETURNS text
45475     LANGUAGE plpgsql
45476     AS $_$
45477 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45478 -- See www.xtuple.com/CPAL for the full text of the software license.
45479 DECLARE
45480   f_addr1 ALIAS FOR $1;
45481   f_addr2 ALIAS FOR $2;
45482   f_addr3 ALIAS FOR $3;
45483   csz     ALIAS FOR $4;
45484   line    ALIAS FOR $5;
45485
45486 BEGIN
45487   RETURN formatAddr(f_addr1, f_addr2, f_addr3, csz, '', line);
45488 END;
45489 $_$;
45490
45491
45492 ALTER FUNCTION public.formataddr(text, text, text, text, integer) OWNER TO admin;
45493
45494 --
45495 -- TOC entry 1589 (class 1255 OID 146566167)
45496 -- Dependencies: 4536 8
45497 -- Name: formataddr(text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
45498 --
45499
45500 CREATE FUNCTION formataddr(text, text, text, text, text) RETURNS text
45501     LANGUAGE plpgsql
45502     AS $_$
45503 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45504 -- See www.xtuple.com/CPAL for the full text of the software license.
45505 DECLARE
45506   f_addr1 ALIAS FOR $1;
45507   f_addr2 ALIAS FOR $2;
45508   f_addr3 ALIAS FOR $3;
45509   csz     ALIAS FOR $4;
45510   country ALIAS FOR $5;
45511   addr TEXT:='';
45512
45513 BEGIN
45514
45515   IF (LENGTH(TRIM(both from f_addr1)) > 0) THEN
45516     addr:=f_addr1;
45517   END IF;
45518
45519   IF (LENGTH(TRIM(both from f_addr2)) > 0)  THEN
45520         IF (LENGTH(TRIM(both from addr)) > 0) THEN
45521                 addr:=addr || E'\n';
45522         END IF;
45523     addr:=addr || f_addr2;
45524   END IF;
45525
45526   IF (LENGTH(TRIM(both from f_addr3)) > 0)  THEN
45527         IF (LENGTH(TRIM(both from addr)) > 0) THEN
45528                 addr:=addr || E'\n';
45529         END IF;
45530     addr:=addr || f_addr3;
45531   END IF;
45532
45533   IF (LENGTH(TRIM(both from csz)) > 0)  THEN
45534         IF (LENGTH(TRIM(both from addr)) > 0) THEN
45535                 addr:=addr || E'\n';
45536         END IF;
45537     addr:=addr || csz;
45538   END IF;
45539
45540   IF (LENGTH(TRIM(both from country)) > 0)  THEN
45541         IF (LENGTH(TRIM(both from addr)) > 0) THEN
45542                 addr:=addr || E'\n';
45543         END IF;
45544     addr:=addr || country;
45545   END IF;
45546
45547   RETURN addr;
45548
45549 END;
45550 $_$;
45551
45552
45553 ALTER FUNCTION public.formataddr(text, text, text, text, text) OWNER TO admin;
45554
45555 --
45556 -- TOC entry 1588 (class 1255 OID 146566166)
45557 -- Dependencies: 4536 8
45558 -- Name: formataddr(text, text, text, text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
45559 --
45560
45561 CREATE FUNCTION formataddr(text, text, text, text, text, integer) RETURNS text
45562     LANGUAGE plpgsql
45563     AS $_$ 
45564 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45565 -- See www.xtuple.com/CPAL for the full text of the software license.
45566 DECLARE
45567   f_addr1 ALIAS FOR $1;
45568   f_addr2 ALIAS FOR $2;
45569   f_addr3 ALIAS FOR $3;
45570   csz     ALIAS FOR $4;
45571   country ALIAS FOR $5;
45572   line    ALIAS FOR $6;
45573
45574   i int:=0;
45575
45576 BEGIN
45577
45578   IF (LENGTH(TRIM(both from f_addr1)) > 0) THEN
45579     i:=i+1;
45580   END IF;
45581
45582   IF (i=line) THEN
45583     RETURN f_addr1;
45584   END IF;
45585
45586   IF (LENGTH(TRIM(both from f_addr2)) > 0)  THEN
45587     i:=i+1;
45588   END IF;
45589
45590   IF (i=line) THEN
45591     RETURN f_addr2;
45592   END IF;
45593
45594   IF (LENGTH(TRIM(both from f_addr3)) > 0) THEN
45595     i:=i+1;
45596   END IF;
45597
45598   IF (i=line) THEN
45599     RETURN f_addr3;
45600   END IF;
45601
45602   IF (LENGTH(TRIM(both from csz)) > 0) THEN
45603     i:=i+1;
45604   END IF;
45605
45606   IF (i=line) THEN
45607     RETURN csz;
45608   END IF;
45609
45610   IF (LENGTH(TRIM(both from country)) > 0) THEN
45611     i:=i+1;
45612   END IF;
45613
45614   IF (i=line) THEN
45615     RETURN country;
45616   END IF;
45617
45618   RETURN ' ';
45619
45620 END;
45621 $_$;
45622
45623
45624 ALTER FUNCTION public.formataddr(text, text, text, text, text, integer) OWNER TO admin;
45625
45626 --
45627 -- TOC entry 1578 (class 1255 OID 146566169)
45628 -- Dependencies: 4536 8
45629 -- Name: formatboolyn(boolean); Type: FUNCTION; Schema: public; Owner: admin
45630 --
45631
45632 CREATE FUNCTION formatboolyn(boolean) RETURNS text
45633     LANGUAGE plpgsql IMMUTABLE
45634     AS $_$
45635 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45636 -- See www.xtuple.com/CPAL for the full text of the software license.
45637 DECLARE pBool ALIAS FOR $1;
45638 BEGIN
45639   IF (pBool) THEN
45640     RETURN 'Yes';
45641   ELSE
45642     RETURN 'No';
45643   END IF;
45644 END;
45645 $_$;
45646
45647
45648 ALTER FUNCTION public.formatboolyn(boolean) OWNER TO admin;
45649
45650 --
45651 -- TOC entry 1591 (class 1255 OID 146566170)
45652 -- Dependencies: 4536 8
45653 -- Name: formatbooseq(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
45654 --
45655
45656 CREATE FUNCTION formatbooseq(integer, integer) RETURNS text
45657     LANGUAGE plpgsql
45658     AS $_$
45659 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45660 -- See www.xtuple.com/CPAL for the full text of the software license.
45661 DECLARE
45662   pItemid ALIAS FOR $1;
45663   pBooitemSeqId ALIAS FOR $2;
45664   _result TEXT;
45665   
45666 BEGIN
45667
45668   IF (fetchMetricBool('Routings')) THEN
45669     SELECT booitem_seqnumber::text INTO _result
45670     FROM xtmfg.booitem(pItemid)
45671     WHERE (booitem_seq_id=pBooitemSeqId);
45672
45673     RETURN _result;
45674   ELSE
45675     RETURN NULL;
45676   END IF;
45677
45678 END;
45679 $_$;
45680
45681
45682 ALTER FUNCTION public.formatbooseq(integer, integer) OWNER TO admin;
45683
45684 --
45685 -- TOC entry 1592 (class 1255 OID 146566171)
45686 -- Dependencies: 4536 8
45687 -- Name: formatbytea(bytea); Type: FUNCTION; Schema: public; Owner: admin
45688 --
45689
45690 CREATE FUNCTION formatbytea(bytea) RETURNS text
45691     LANGUAGE plpgsql
45692     AS $_$
45693 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45694 -- See www.xtuple.com/CPAL for the full text of the software license.
45695 DECLARE
45696   pField ALIAS FOR $1;
45697   output_field TEXT;
45698
45699 BEGIN
45700
45701   output_field := pField;
45702
45703   RETURN output_field;
45704
45705 END;
45706 $_$;
45707
45708
45709 ALTER FUNCTION public.formatbytea(bytea) OWNER TO admin;
45710
45711 --
45712 -- TOC entry 1593 (class 1255 OID 146566172)
45713 -- Dependencies: 4536 8
45714 -- Name: formatccdashes(text, text); Type: FUNCTION; Schema: public; Owner: admin
45715 --
45716
45717 CREATE FUNCTION formatccdashes(text, text) RETURNS text
45718     LANGUAGE plpgsql
45719     AS $_$
45720 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45721 -- See www.xtuple.com/CPAL for the full text of the software license.
45722 DECLARE
45723   pCCard ALIAS FOR $1;
45724   pCCardType ALIAS FOR $2;
45725   _returnCard text;
45726   card_length integer;
45727
45728 BEGIN
45729
45730   IF (pCCardType = 'A')  THEN
45731     _returnCard := pCCard;
45732     RETURN _returnCard;
45733   END IF;
45734
45735   card_length := length(pCcard);
45736
45737   if (card_length = 16) THEN
45738     _returnCard := substr(pCCard, 1, 4) || '-' || substr(pCCard, 5, 4) || '-' || substr(pCCard, 9, 4) || '-' || substr(pCCard, 13, 4);
45739   ELSE
45740     _returnCard := substr(pCCard, 1, 4) || '-' || substr(pCCard, 5, 4) || '-' || substr(pCCard, 9, 4) || '-' || substr(pCCard, 13, 1);
45741   END IF;
45742
45743   RETURN _returnCard;
45744
45745 END;
45746 $_$;
45747
45748
45749 ALTER FUNCTION public.formatccdashes(text, text) OWNER TO admin;
45750
45751 --
45752 -- TOC entry 1594 (class 1255 OID 146566173)
45753 -- Dependencies: 4536 8
45754 -- Name: formatccnumber(text); Type: FUNCTION; Schema: public; Owner: admin
45755 --
45756
45757 CREATE FUNCTION formatccnumber(text) RETURNS text
45758     LANGUAGE plpgsql
45759     AS $_$
45760 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45761 -- See www.xtuple.com/CPAL for the full text of the software license.
45762 DECLARE
45763   pCcardnum ALIAS FOR $1;
45764   card_length INTEGER;
45765   output_cardnum TEXT;
45766
45767 BEGIN
45768
45769   card_length := length(pCcardnum);
45770
45771   IF (card_length = 13) THEN
45772     output_cardnum := '*********' || substr(pCcardnum, 10, 4);  
45773   END IF;
45774
45775   IF (card_length = 14) THEN
45776     output_cardnum := '**********' || substr(pCcardnum, 11, 4);  
45777   END IF;
45778
45779   IF (card_length = 15) THEN
45780     output_cardnum := '***********' || substr(pCcardnum, 12, 4);  
45781   END IF;
45782
45783   IF (card_length = 16) THEN
45784     output_cardnum := '************' || substr(pCcardnum, 13, 4);  
45785   END IF;
45786
45787   RETURN output_cardnum;
45788
45789 END;
45790 $_$;
45791
45792
45793 ALTER FUNCTION public.formatccnumber(text) OWNER TO admin;
45794
45795 --
45796 -- TOC entry 1595 (class 1255 OID 146566174)
45797 -- Dependencies: 4536 8
45798 -- Name: formatccnumber(bytea); Type: FUNCTION; Schema: public; Owner: admin
45799 --
45800
45801 CREATE FUNCTION formatccnumber(bytea) RETURNS text
45802     LANGUAGE plpgsql
45803     AS $_$
45804 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45805 -- See www.xtuple.com/CPAL for the full text of the software license.
45806 DECLARE
45807   pCcardnum ALIAS FOR $1;
45808   card_length INTEGER;
45809   output_cardnum TEXT;
45810
45811 BEGIN
45812
45813   card_length := length(pCcardnum);
45814
45815   IF (card_length = 13) THEN
45816     output_cardnum := '*********' || substr(pCcardnum, 10, 4);  
45817   END IF;
45818
45819   IF (card_length = 14) THEN
45820     output_cardnum := '**********' || substr(pCcardnum, 11, 4);  
45821   END IF;
45822
45823   IF (card_length = 15) THEN
45824     output_cardnum := '***********' || substr(pCcardnum, 12, 4);  
45825   END IF;
45826
45827   IF (card_length = 16) THEN
45828     output_cardnum := '************' || substr(pCcardnum, 13, 4);  
45829   END IF;
45830
45831   RETURN output_cardnum;
45832
45833 END;
45834 $_$;
45835
45836
45837 ALTER FUNCTION public.formatccnumber(bytea) OWNER TO admin;
45838
45839 --
45840 -- TOC entry 1596 (class 1255 OID 146566175)
45841 -- Dependencies: 4536 8
45842 -- Name: formatcntctname(integer); Type: FUNCTION; Schema: public; Owner: admin
45843 --
45844
45845 CREATE FUNCTION formatcntctname(integer) RETURNS text
45846     LANGUAGE plpgsql
45847     AS $_$ 
45848 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45849 -- See www.xtuple.com/CPAL for the full text of the software license.
45850 DECLARE
45851   pCntctId ALIAS FOR $1;
45852   _r RECORD;
45853   _rows NUMERIC;
45854
45855 BEGIN
45856
45857   SELECT cntct_honorific, cntct_first_name, cntct_middle, 
45858     cntct_last_name, cntct_suffix INTO _r
45859   FROM cntct
45860   WHERE (cntct_id=pCntctId);
45861
45862   GET DIAGNOSTICS _rows = ROW_COUNT;
45863   IF (_rows = 0) THEN
45864     RETURN '';
45865   END IF;
45866
45867   RETURN formatCntctName(_r.cntct_honorific, _r.cntct_first_name, _r.cntct_middle, _r.cntct_last_name, _r.cntct_suffix);
45868
45869 END;
45870 $_$;
45871
45872
45873 ALTER FUNCTION public.formatcntctname(integer) OWNER TO admin;
45874
45875 --
45876 -- TOC entry 1597 (class 1255 OID 146566176)
45877 -- Dependencies: 4536 8
45878 -- Name: formatcntctname(text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
45879 --
45880
45881 CREATE FUNCTION formatcntctname(text, text, text, text, text) RETURNS text
45882     LANGUAGE plpgsql
45883     AS $_$ 
45884 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45885 -- See www.xtuple.com/CPAL for the full text of the software license.
45886 DECLARE
45887   pHonorific ALIAS FOR $1;
45888   pFirstName ALIAS FOR $2;
45889   pMiddle ALIAS FOR $3;
45890   pLastName ALIAS FOR $4;
45891   pSuffix ALIAS FOR $5;
45892   _name TEXT := '';
45893
45894 BEGIN
45895
45896   IF (LENGTH(TRIM(both from COALESCE(pHonorific,''))) > 0) THEN
45897     IF (POSITION('.' IN COALESCE(pHonorific, '')) > 0) THEN
45898       _name:= pHonorific;
45899     ELSE
45900       _name:= pHonorific || '.';
45901     END IF;
45902   END IF;
45903
45904   IF (LENGTH(TRIM(both from COALESCE(pFirstName,''))) > 0)  THEN
45905         IF (LENGTH(TRIM(both from _name)) > 0) THEN
45906                 _name:=_name || ' ';
45907         END IF;
45908     _name:=_name || pFirstName;
45909   END IF;
45910
45911   IF (LENGTH(TRIM(both from COALESCE(pMiddle,''))) > 0)  THEN
45912         IF (LENGTH(TRIM(both from _name)) > 0) THEN
45913                 _name:=_name || ' ';
45914         END IF;
45915     IF (POSITION('.' IN COALESCE(pHonorific, '')) > 0) THEN
45916       _name:=_name || pMiddle;
45917     ELSE
45918       _name:=_name || pMiddle || '.';
45919     END IF;
45920   END IF;
45921
45922   IF (LENGTH(TRIM(both from COALESCE(pLastName,''))) > 0)  THEN
45923         IF (LENGTH(TRIM(both from _name)) > 0) THEN
45924                 _name:=_name || ' ';
45925         END IF;
45926     _name:=_name || pLastName;
45927   END IF;
45928
45929   IF (LENGTH(TRIM(both from COALESCE(pSuffix,''))) > 0)  THEN
45930         IF (LENGTH(TRIM(both from _name)) > 0) THEN
45931                 _name:=_name || ' ';
45932         END IF;
45933     _name:=_name || pSuffix;
45934   END IF;
45935
45936   RETURN _name;
45937
45938 END;
45939 $_$;
45940
45941
45942 ALTER FUNCTION public.formatcntctname(text, text, text, text, text) OWNER TO admin;
45943
45944 --
45945 -- TOC entry 1598 (class 1255 OID 146566177)
45946 -- Dependencies: 4536 8
45947 -- Name: formatcost(numeric); Type: FUNCTION; Schema: public; Owner: admin
45948 --
45949
45950 CREATE FUNCTION formatcost(numeric) RETURNS text
45951     LANGUAGE plpgsql IMMUTABLE
45952     AS $_$
45953 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45954 -- See www.xtuple.com/CPAL for the full text of the software license.
45955 BEGIN
45956   RETURN formatNumeric($1, 'cost');
45957 END;$_$;
45958
45959
45960 ALTER FUNCTION public.formatcost(numeric) OWNER TO admin;
45961
45962 --
45963 -- TOC entry 1599 (class 1255 OID 146566178)
45964 -- Dependencies: 4536 8
45965 -- Name: formatcounttagbarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
45966 --
45967
45968 CREATE FUNCTION formatcounttagbarcode(integer) RETURNS text
45969     LANGUAGE plpgsql IMMUTABLE
45970     AS $_$
45971 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
45972 -- See www.xtuple.com/CPAL for the full text of the software license.
45973 DECLARE
45974   pCnttagid ALIAS FOR $1;
45975   _barcode TEXT;
45976 BEGIN
45977
45978   SELECT ( E'\138CTXX' ||
45979            LTRIM(TO_CHAR(LENGTH(invcnt_tagnumber), '00')) || invcnt_tagnumber ) INTO _barcode
45980   FROM invcnt
45981   WHERE (invcnt_id=pCnttagid);
45982
45983   RETURN _barcode;
45984
45985 END;
45986 $_$;
45987
45988
45989 ALTER FUNCTION public.formatcounttagbarcode(integer) OWNER TO admin;
45990
45991 --
45992 -- TOC entry 1600 (class 1255 OID 146566179)
45993 -- Dependencies: 4536 8
45994 -- Name: formatcreditmemonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
45995 --
45996
45997 CREATE FUNCTION formatcreditmemonumber(integer) RETURNS text
45998     LANGUAGE plpgsql IMMUTABLE
45999     AS $_$
46000 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46001 -- See www.xtuple.com/CPAL for the full text of the software license.
46002 DECLARE
46003   pCmheadid ALIAS FOR $1;
46004
46005 BEGIN
46006   RETURN ( SELECT COALESCE(cmhead_number::TEXT, '')
46007            FROM cmhead
46008            WHERE (cmhead_id=pCmheadid) );
46009 END;
46010 $_$;
46011
46012
46013 ALTER FUNCTION public.formatcreditmemonumber(integer) OWNER TO admin;
46014
46015 --
46016 -- TOC entry 1601 (class 1255 OID 146566180)
46017 -- Dependencies: 8
46018 -- Name: formatdate(date); Type: FUNCTION; Schema: public; Owner: admin
46019 --
46020
46021 CREATE FUNCTION formatdate(date) RETURNS text
46022     LANGUAGE sql IMMUTABLE
46023     AS $_$
46024 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46025 -- See www.xtuple.com/CPAL for the full text of the software license.
46026 SELECT TO_CHAR($1, COALESCE((SELECT locale_dateformat
46027                              FROM locale, usr
46028                              WHERE ((usr_locale_id=locale_id)
46029                               AND (usr_username=getEffectiveXtUser())) ),
46030                             'yyyy-mm-dd') ) AS result
46031 $_$;
46032
46033
46034 ALTER FUNCTION public.formatdate(date) OWNER TO admin;
46035
46036 --
46037 -- TOC entry 1603 (class 1255 OID 146566182)
46038 -- Dependencies: 8
46039 -- Name: formatdate(timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
46040 --
46041
46042 CREATE FUNCTION formatdate(timestamp with time zone) RETURNS text
46043     LANGUAGE sql IMMUTABLE
46044     AS $_$
46045 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46046 -- See www.xtuple.com/CPAL for the full text of the software license.
46047 SELECT TO_CHAR($1, COALESCE((SELECT locale_dateformat
46048                              FROM locale, usr
46049                              WHERE ((usr_locale_id=locale_id)
46050                               AND (usr_username=getEffectiveXtUser())) ),
46051                             'yyyy-mm-dd' )) AS result
46052 $_$;
46053
46054
46055 ALTER FUNCTION public.formatdate(timestamp with time zone) OWNER TO admin;
46056
46057 --
46058 -- TOC entry 1602 (class 1255 OID 146566181)
46059 -- Dependencies: 4536 8
46060 -- Name: formatdate(date, text); Type: FUNCTION; Schema: public; Owner: admin
46061 --
46062
46063 CREATE FUNCTION formatdate(date, text) RETURNS text
46064     LANGUAGE plpgsql IMMUTABLE
46065     AS $_$
46066 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46067 -- See www.xtuple.com/CPAL for the full text of the software license.
46068 DECLARE
46069   pDate ALIAS FOR $1;
46070   pString ALIAS FOR $2;
46071
46072 BEGIN
46073
46074   IF ( (pDate = startOfTime()) OR
46075        (pDate = endOfTime()) OR
46076        (pDate IS NULL) ) THEN
46077     RETURN pString;
46078   ELSE
46079     RETURN formatDate(pDate);
46080   END IF;
46081
46082 END;
46083 $_$;
46084
46085
46086 ALTER FUNCTION public.formatdate(date, text) OWNER TO admin;
46087
46088 --
46089 -- TOC entry 1604 (class 1255 OID 146566183)
46090 -- Dependencies: 8
46091 -- Name: formatdatetime(timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
46092 --
46093
46094 CREATE FUNCTION formatdatetime(timestamp with time zone) RETURNS text
46095     LANGUAGE sql IMMUTABLE
46096     AS $_$
46097 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46098 -- See www.xtuple.com/CPAL for the full text of the software license.
46099 SELECT TO_CHAR($1, COALESCE((SELECT locale_timestampformat
46100                              FROM locale, usr
46101                              WHERE ((usr_locale_id=locale_id)
46102                               AND (usr_username=getEffectiveXtUser())) ),
46103                             'yyyy-mm-dd HH24:MI:SS')) AS result
46104 $_$;
46105
46106
46107 ALTER FUNCTION public.formatdatetime(timestamp with time zone) OWNER TO admin;
46108
46109 --
46110 -- TOC entry 1605 (class 1255 OID 146566184)
46111 -- Dependencies: 8
46112 -- Name: formatdatetime(timestamp without time zone); Type: FUNCTION; Schema: public; Owner: admin
46113 --
46114
46115 CREATE FUNCTION formatdatetime(timestamp without time zone) RETURNS text
46116     LANGUAGE sql IMMUTABLE
46117     AS $_$
46118 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46119 -- See www.xtuple.com/CPAL for the full text of the software license.
46120 SELECT TO_CHAR($1, COALESCE((SELECT locale_timestampformat
46121                              FROM locale, usr
46122                              WHERE ((usr_locale_id=locale_id)
46123                               AND (usr_username=getEffectiveXtUser())) ),
46124                             'yyyy-mm-dd HH24:MI:SS')) AS result
46125 $_$;
46126
46127
46128 ALTER FUNCTION public.formatdatetime(timestamp without time zone) OWNER TO admin;
46129
46130 --
46131 -- TOC entry 1606 (class 1255 OID 146566185)
46132 -- Dependencies: 4536 8
46133 -- Name: formatextprice(numeric); Type: FUNCTION; Schema: public; Owner: admin
46134 --
46135
46136 CREATE FUNCTION formatextprice(numeric) RETURNS text
46137     LANGUAGE plpgsql IMMUTABLE
46138     AS $_$
46139 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46140 -- See www.xtuple.com/CPAL for the full text of the software license.
46141 BEGIN
46142   RETURN formatNumeric($1, 'extprice');
46143 END;$_$;
46144
46145
46146 ALTER FUNCTION public.formatextprice(numeric) OWNER TO admin;
46147
46148 --
46149 -- TOC entry 1607 (class 1255 OID 146566186)
46150 -- Dependencies: 4536 8
46151 -- Name: formatflitemdescrip(integer); Type: FUNCTION; Schema: public; Owner: admin
46152 --
46153
46154 CREATE FUNCTION formatflitemdescrip(integer) RETURNS text
46155     LANGUAGE plpgsql
46156     AS $_$
46157 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46158 -- See www.xtuple.com/CPAL for the full text of the software license.
46159 DECLARE
46160   pFlitemId ALIAS FOR $1;
46161   _x RECORD;
46162   _descrip TEXT;
46163
46164 BEGIN
46165   SELECT flitem_accnt_id, flitem_company, flitem_profit, flitem_number,
46166         flitem_sub, flitem_type, flitem_subaccnttype_code,
46167         accnt_id, accnt_descrip INTO _x
46168   FROM flitem LEFT OUTER JOIN accnt
46169         ON flitem_accnt_id=accnt_id
46170   WHERE flitem_id=pFlitemId;
46171
46172   IF _x.flitem_accnt_id > -1 THEN
46173
46174     SELECT (formatGLAccount(_x.accnt_id) || '-' || _x.accnt_descrip) INTO _descrip;
46175
46176   ELSE
46177
46178     _descrip:='';
46179
46180     IF _x.flitem_type = 'A' THEN
46181       _descrip:='Type=' || 'Asset';
46182       ELSE IF _x.flitem_type='L' THEN
46183         _descrip:='Type=' || 'Liability';
46184         ELSE IF _x.flitem_type='R' THEN
46185           _descrip:='Type=' || 'Revenue';
46186           ELSE IF _x.flitem_type='E' THEN
46187             _descrip:='Type=' || 'Expense';
46188             ELSE IF _x.flitem_type='Q' THEN
46189               _descrip:='Type=' || 'Equity';
46190             END IF;
46191           END IF;
46192         END IF;
46193       END IF;
46194     END IF;
46195
46196     IF _x.flitem_subaccnttype_code <> 'All' THEN
46197       IF (LENGTH(TRIM(both from _descrip)) > 0) THEN
46198         _descrip:=_descrip || ', ';
46199       END IF;
46200       _descrip:=_descrip || 'Sub Accnt Type=' || _x.flitem_subaccnttype_code;
46201     END IF;
46202
46203     IF _x.flitem_company <> 'All' THEN
46204       IF (LENGTH(TRIM(both from _descrip)) > 0) THEN
46205         _descrip:=_descrip || ', ';
46206       END IF;
46207       _descrip:=_descrip || 'Company=' || _x.flitem_company;
46208     END IF;
46209
46210     IF _x.flitem_profit <> 'All' THEN
46211       IF (LENGTH(TRIM(both from _descrip)) > 0) THEN
46212         _descrip:=_descrip || ', ';
46213       END IF;
46214       _descrip:=_descrip || 'Profit=' || _x.flitem_profit;
46215     END IF;
46216
46217     IF _x.flitem_number <> 'All' THEN
46218       IF (LENGTH(TRIM(both from _descrip)) > 0) THEN
46219         _descrip:=_descrip || ', ';
46220       END IF;
46221       _descrip:=_descrip || 'Number=' || _x.flitem_number;
46222     END IF;
46223
46224     IF _x.flitem_sub <> 'All' THEN
46225       IF (LENGTH(TRIM(both from _descrip)) > 0) THEN
46226         _descrip:=_descrip || ', ';
46227       END IF;
46228       _descrip:=_descrip || 'Sub Accnt=' || _x.flitem_sub;
46229     END IF;
46230   END IF;
46231
46232   RETURN _descrip;
46233
46234 END;
46235 $_$;
46236
46237
46238 ALTER FUNCTION public.formatflitemdescrip(integer) OWNER TO admin;
46239
46240 --
46241 -- TOC entry 1608 (class 1255 OID 146566187)
46242 -- Dependencies: 4536 8
46243 -- Name: formatglaccount(text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
46244 --
46245
46246 CREATE FUNCTION formatglaccount(text, text, text, text) RETURNS text
46247     LANGUAGE plpgsql IMMUTABLE
46248     AS $_$
46249 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46250 -- See www.xtuple.com/CPAL for the full text of the software license.
46251 DECLARE
46252   pCompany ALIAS FOR $1;
46253   pProfit ALIAS FOR $2;
46254   pNumber ALIAS FOR $3;
46255   pSub    ALIAS FOR $4;
46256   _number TEXT := '';
46257
46258 BEGIN
46259
46260   IF ( ( SELECT metric_value::INTEGER
46261          FROM metric
46262          WHERE (metric_name='GLCompanySize') ) > 0 ) THEN
46263     _number := pCompany || '-';
46264   END IF;
46265
46266   IF ( ( SELECT metric_value::INTEGER
46267          FROM metric
46268          WHERE (metric_name='GLProfitSize') ) > 0 ) THEN
46269     _number := _number || pProfit || '-';
46270   END IF;
46271
46272   _number := _number || pNumber;
46273
46274   IF ( ( SELECT metric_value::INTEGER
46275          FROM metric
46276          WHERE (metric_name='GLSubaccountSize') ) > 0 ) THEN
46277     _number := _number || '-' || pSub;
46278   END IF;
46279
46280   RETURN _number;
46281
46282 END;
46283 $_$;
46284
46285
46286 ALTER FUNCTION public.formatglaccount(text, text, text, text) OWNER TO admin;
46287
46288 --
46289 -- TOC entry 1609 (class 1255 OID 146566188)
46290 -- Dependencies: 4536 8
46291 -- Name: formatglaccountlong(integer); Type: FUNCTION; Schema: public; Owner: admin
46292 --
46293
46294 CREATE FUNCTION formatglaccountlong(integer) RETURNS text
46295     LANGUAGE plpgsql IMMUTABLE
46296     AS $_$
46297 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46298 -- See www.xtuple.com/CPAL for the full text of the software license.
46299 DECLARE
46300   pAccntid ALIAS FOR $1;
46301   _result TEXT;
46302
46303 BEGIN
46304
46305   SELECT (formatGLAccount(accnt_id) || '-' || accnt_descrip) INTO _result
46306   FROM accnt
46307   WHERE (accnt_id=pAccntid);
46308
46309   RETURN _result;
46310
46311 END;
46312 $_$;
46313
46314
46315 ALTER FUNCTION public.formatglaccountlong(integer) OWNER TO admin;
46316
46317 --
46318 -- TOC entry 1610 (class 1255 OID 146566189)
46319 -- Dependencies: 4536 8
46320 -- Name: formatindent(text, integer); Type: FUNCTION; Schema: public; Owner: admin
46321 --
46322
46323 CREATE FUNCTION formatindent(text, integer) RETURNS text
46324     LANGUAGE plpgsql
46325     AS $_$
46326 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46327 -- See www.xtuple.com/CPAL for the full text of the software license.
46328 DECLARE
46329   pText ALIAS FOR $1;
46330   pIndent ALIAS FOR $2;
46331   _i INTEGER;
46332   _result TEXT;
46333
46334 BEGIN
46335   _result := '';
46336   _i := 0;
46337
46338   WHILE _i < pIndent LOOP
46339     _result := _result || '  ';
46340     _i := _i + 1;
46341   END LOOP;
46342
46343   _result := _result || pText;
46344   RETURN _result;
46345 END;
46346 $_$;
46347
46348
46349 ALTER FUNCTION public.formatindent(text, integer) OWNER TO admin;
46350
46351 --
46352 -- TOC entry 1611 (class 1255 OID 146566190)
46353 -- Dependencies: 8
46354 -- Name: formatinterval(numeric); Type: FUNCTION; Schema: public; Owner: admin
46355 --
46356
46357 CREATE FUNCTION formatinterval(numeric) RETURNS text
46358     LANGUAGE sql IMMUTABLE
46359     AS $_$
46360 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46361 -- See www.xtuple.com/CPAL for the full text of the software license.
46362   SELECT TO_CHAR(('@ ' || trunc($1) || ' min ' ||
46363                              ($1 - trunc($1)) * 60 || ' sec')::INTERVAL,
46364                  ( SELECT locale_intervalformat
46365                        FROM locale, usr
46366                        WHERE ((usr_locale_id=locale_id)
46367                          AND  (usr_username=getEffectiveXtUser())) ) ) AS result
46368 $_$;
46369
46370
46371 ALTER FUNCTION public.formatinterval(numeric) OWNER TO admin;
46372
46373 --
46374 -- TOC entry 1612 (class 1255 OID 146566191)
46375 -- Dependencies: 8
46376 -- Name: formatinterval(interval); Type: FUNCTION; Schema: public; Owner: admin
46377 --
46378
46379 CREATE FUNCTION formatinterval(interval) RETURNS text
46380     LANGUAGE sql IMMUTABLE
46381     AS $_$
46382 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46383 -- See www.xtuple.com/CPAL for the full text of the software license.
46384   SELECT TO_CHAR($1, ( SELECT locale_intervalformat
46385                        FROM locale, usr
46386                        WHERE ((usr_locale_id=locale_id)
46387                          AND  (usr_username=getEffectiveXtUser())) ) ) AS result
46388 $_$;
46389
46390
46391 ALTER FUNCTION public.formatinterval(interval) OWNER TO admin;
46392
46393 --
46394 -- TOC entry 1613 (class 1255 OID 146566192)
46395 -- Dependencies: 4536 8
46396 -- Name: formatinvcnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
46397 --
46398
46399 CREATE FUNCTION formatinvcnumber(integer) RETURNS text
46400     LANGUAGE plpgsql IMMUTABLE
46401     AS $_$
46402 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46403 -- See www.xtuple.com/CPAL for the full text of the software license.
46404 DECLARE
46405   pCobmiscid ALIAS FOR $1;
46406
46407 BEGIN
46408   RETURN ( SELECT COALESCE(cobmisc_invcnumber::TEXT, '')
46409            FROM cobmisc
46410            WHERE (cobmisc_id=pCobmiscid) );
46411 END;
46412 $_$;
46413
46414
46415 ALTER FUNCTION public.formatinvcnumber(integer) OWNER TO admin;
46416
46417 --
46418 -- TOC entry 1614 (class 1255 OID 146566193)
46419 -- Dependencies: 4536 8
46420 -- Name: formatitemsitebarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
46421 --
46422
46423 CREATE FUNCTION formatitemsitebarcode(integer) RETURNS text
46424     LANGUAGE plpgsql IMMUTABLE
46425     AS $_$
46426 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46427 -- See www.xtuple.com/CPAL for the full text of the software license.
46428 DECLARE
46429   pItemsiteid ALIAS FOR $1;
46430   _barcode TEXT;
46431 BEGIN
46432
46433   SELECT ( E'\138ISXX' ||
46434            LTRIM(TO_CHAR(LENGTH(item_number), '00')) || LENGTH(warehous_code)::TEXT ||
46435            item_number || warehous_code ) INTO _barcode
46436   FROM itemsite, item, whsinfo
46437   WHERE ( (itemsite_item_id=item_id)
46438    AND (itemsite_warehous_id=warehous_id)
46439    AND (itemsite_id=pItemsiteid) );
46440
46441   RETURN _barcode;
46442
46443 END;
46444 $_$;
46445
46446
46447 ALTER FUNCTION public.formatitemsitebarcode(integer) OWNER TO admin;
46448
46449 --
46450 -- TOC entry 1615 (class 1255 OID 146566194)
46451 -- Dependencies: 4536 8
46452 -- Name: formatlocationbarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
46453 --
46454
46455 CREATE FUNCTION formatlocationbarcode(integer) RETURNS text
46456     LANGUAGE plpgsql IMMUTABLE
46457     AS $_$
46458 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46459 -- See www.xtuple.com/CPAL for the full text of the software license.
46460 DECLARE
46461   pLocationid ALIAS FOR $1;
46462   _barcode TEXT;
46463 BEGIN
46464
46465   SELECT ( E'\138LOXX' ||
46466            LENGTH(warehous_code)::TEXT || LTRIM(TO_CHAR(LENGTH(location_name::TEXT), '00')) ||
46467            warehous_code || location_name ) INTO _barcode
46468   FROM location, whsinfo
46469   WHERE ( (location_warehous_id=warehous_id)
46470    AND (location_id=pLocationid) );
46471
46472   RETURN _barcode;
46473
46474 END;
46475 $_$;
46476
46477
46478 ALTER FUNCTION public.formatlocationbarcode(integer) OWNER TO admin;
46479
46480 --
46481 -- TOC entry 1616 (class 1255 OID 146566195)
46482 -- Dependencies: 4536 8
46483 -- Name: formatlocationcontentsbarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
46484 --
46485
46486 CREATE FUNCTION formatlocationcontentsbarcode(integer) RETURNS text
46487     LANGUAGE plpgsql IMMUTABLE
46488     AS $_$
46489 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46490 -- See www.xtuple.com/CPAL for the full text of the software license.
46491 DECLARE
46492   pLocationid ALIAS FOR $1;
46493   _barcode TEXT;
46494 BEGIN
46495
46496   SELECT ( E'\138LOCN' ||
46497            LENGTH(warehous_code)::TEXT || LTRIM(TO_CHAR(LENGTH(location_name), '00')) ||
46498            warehous_code || location_name ) INTO _barcode
46499   FROM location, whsinfo
46500   WHERE ( (location_warehous_id=warehous_id)
46501    AND (location_id=pLocationid) );
46502
46503   RETURN _barcode;
46504
46505 END;
46506 $_$;
46507
46508
46509 ALTER FUNCTION public.formatlocationcontentsbarcode(integer) OWNER TO admin;
46510
46511 --
46512 -- TOC entry 1617 (class 1255 OID 146566196)
46513 -- Dependencies: 4536 8
46514 -- Name: formatlocationissuebarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
46515 --
46516
46517 CREATE FUNCTION formatlocationissuebarcode(integer) RETURNS text
46518     LANGUAGE plpgsql IMMUTABLE
46519     AS $_$
46520 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46521 -- See www.xtuple.com/CPAL for the full text of the software license.
46522 DECLARE
46523   pLocationid ALIAS FOR $1;
46524   _barcode TEXT;
46525 BEGIN
46526
46527   SELECT ( E'\138LOIS' ||
46528            LENGTH(warehous_code)::TEXT || LTRIM(TO_CHAR(LENGTH(location_name), '00')) ||
46529            warehous_code || location_name ) INTO _barcode
46530   FROM location, whsinfo
46531   WHERE ( (location_warehous_id=warehous_id)
46532    AND (location_id=pLocationid) );
46533
46534   RETURN _barcode;
46535
46536 END;
46537 $_$;
46538
46539
46540 ALTER FUNCTION public.formatlocationissuebarcode(integer) OWNER TO admin;
46541
46542 --
46543 -- TOC entry 1618 (class 1255 OID 146566197)
46544 -- Dependencies: 4536 8
46545 -- Name: formatlotserialnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
46546 --
46547
46548 CREATE FUNCTION formatlotserialnumber(integer) RETURNS text
46549     LANGUAGE plpgsql
46550     AS $_$
46551 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46552 -- See www.xtuple.com/CPAL for the full text of the software license.
46553 DECLARE
46554   pLotSerialId ALIAS FOR $1;
46555   _lotserial TEXT;
46556
46557 BEGIN
46558   --See if lot serial control turned on (Postbooks will not ever have this)
46559   IF (fetchmetricbool('LotSerialControl')) THEN
46560     SELECT ls_number INTO _lotserial
46561     FROM ls
46562     WHERE (ls_id=pLotSerialId);
46563   END IF;
46564
46565   RETURN COALESCE(_lotserial,'');
46566
46567 END;
46568 $_$;
46569
46570
46571 ALTER FUNCTION public.formatlotserialnumber(integer) OWNER TO admin;
46572
46573 --
46574 -- TOC entry 1619 (class 1255 OID 146566198)
46575 -- Dependencies: 4536 8
46576 -- Name: formatmoney(numeric); Type: FUNCTION; Schema: public; Owner: admin
46577 --
46578
46579 CREATE FUNCTION formatmoney(numeric) RETURNS text
46580     LANGUAGE plpgsql IMMUTABLE
46581     AS $_$
46582 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46583 -- See www.xtuple.com/CPAL for the full text of the software license.
46584 BEGIN
46585   RETURN formatNumeric($1, 'curr');
46586 END;$_$;
46587
46588
46589 ALTER FUNCTION public.formatmoney(numeric) OWNER TO admin;
46590
46591 --
46592 -- TOC entry 1620 (class 1255 OID 146566199)
46593 -- Dependencies: 4536 8
46594 -- Name: formatnumeric(numeric, text); Type: FUNCTION; Schema: public; Owner: admin
46595 --
46596
46597 CREATE FUNCTION formatnumeric(numeric, text) RETURNS text
46598     LANGUAGE plpgsql IMMUTABLE
46599     AS $_$
46600 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46601 -- See www.xtuple.com/CPAL for the full text of the software license.
46602 DECLARE
46603   _value        NUMERIC := $1;
46604   _type         TEXT    := LOWER(COALESCE($2, 'curr'));
46605   _abs          NUMERIC;
46606   _magnitudecnt NUMERIC(1000);
46607   _wholefmt     TEXT    := '0';
46608   _scale        INTEGER;
46609   _neg          TEXT;
46610   _decimal      TEXT;
46611   _group        TEXT;
46612   _string       TEXT;
46613   _debug        BOOL := false;
46614   _r            RECORD;
46615
46616 BEGIN
46617   -- If the value passed in is NULL then we want to pass back an empty string
46618   IF(_value IS NULL) THEN
46619     RETURN '';
46620   END IF;
46621
46622   SELECT * INTO _r
46623   FROM locale
46624   WHERE (locale_id=getUsrLocaleId());
46625
46626   _decimal := COALESCE(SUBSTRING(_r.locale_qtyformat FROM 1 FOR 1), '.');
46627   _neg     := COALESCE(SUBSTRING(_r.locale_qtyformat FROM 2 FOR 1), '-');
46628   _group   := COALESCE(SUBSTRING(_r.locale_qtyformat FROM 3 FOR 1), ',');
46629
46630   _scale   := CASE WHEN _type = 'cost'       THEN _r.locale_cost_scale
46631                    WHEN _type = 'extprice'   THEN _r.locale_extprice_scale
46632                    WHEN _type = 'percent'    THEN _r.locale_percent_scale
46633                    WHEN _type = 'purchprice' THEN _r.locale_purchprice_scale
46634                    WHEN _type = 'qty'        THEN _r.locale_qty_scale
46635                    WHEN _type = 'qtyper'     THEN _r.locale_qtyper_scale
46636                    WHEN _type = 'salesprice' THEN _r.locale_salesprice_scale
46637                    WHEN _type = 'uomratio'   THEN _r.locale_uomratio_scale
46638                    WHEN _type = 'weight'     THEN _r.locale_weight_scale
46639                    WHEN SUBSTRING(_type FOR 4) = 'curr' THEN _r.locale_curr_scale
46640                    ELSE 2
46641               END;
46642
46643   _value        := round(_value, _scale);
46644   _abs          := ABS(_value);
46645   _magnitudecnt := TRUNC(_abs / 10);
46646
46647   IF (_debug) THEN
46648     RAISE NOTICE '_value % _abs % _scale % _neg % _decimal % _group % ',
46649                  _value, _abs, _scale, _decimal, _group, _scale;
46650   END IF;
46651
46652   IF (_value < 0) THEN
46653     _string := _neg;
46654   ELSE
46655     _string := '';
46656   END IF;
46657
46658   WHILE (_magnitudecnt >= 1) LOOP
46659     _magnitudecnt := TRUNC(_magnitudecnt / 10);
46660     IF (LENGTH(_wholefmt) % 3 = 0) THEN
46661       _wholefmt := '"' || _group || '"' || _wholefmt;
46662     END IF;
46663     _wholefmt := '9' || _wholefmt;
46664   END LOOP;
46665
46666   IF (_scale > 0) THEN
46667     _abs := (_abs * (10 ^ _scale));
46668     _abs := TRUNC(_abs);
46669     _wholefmt := _wholefmt || '"' || _decimal || '"' || REPEAT('0', _scale);
46670   END IF;
46671
46672   _wholefmt := 'FM' || _wholefmt;
46673   _string := _string || to_char(_abs, _wholefmt);
46674
46675   RETURN _string;
46676 END;$_$;
46677
46678
46679 ALTER FUNCTION public.formatnumeric(numeric, text) OWNER TO admin;
46680
46681 --
46682 -- TOC entry 1621 (class 1255 OID 146566200)
46683 -- Dependencies: 4536 8
46684 -- Name: formatperiodname(integer, character); Type: FUNCTION; Schema: public; Owner: admin
46685 --
46686
46687 CREATE FUNCTION formatperiodname(integer, character) RETURNS text
46688     LANGUAGE plpgsql
46689     AS $_$
46690 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46691 -- See www.xtuple.com/CPAL for the full text of the software license.
46692 DECLARE
46693   pPeriodId ALIAS FOR $1;
46694   pInterval ALIAS FOR $2;
46695   _result TEXT;
46696
46697 BEGIN
46698
46699 --...for Month
46700
46701    IF (pInterval='M') THEN
46702         SELECT
46703           (CASE
46704                       WHEN period_name='' THEN
46705                         formatdate(period_start) || '-' || formatdate(period_end)
46706                       ELSE period_name
46707           END) INTO _result
46708         FROM period
46709         WHERE (period_id=pPeriodId);
46710
46711         RETURN _result;
46712
46713 --...for Quarter
46714
46715         ELSE IF (pInterval='Q') THEN
46716                 SELECT
46717                         ('Q' || period_quarter || '-' || EXTRACT(year from yearperiod_end)) INTO _result
46718                 FROM period, yearperiod
46719                 WHERE ((period_id=pPeriodId)
46720                 AND (period_yearperiod_id=yearperiod_id));
46721
46722                 RETURN _result;
46723 --...for Year
46724         ELSE
46725                 SELECT
46726                         EXTRACT(year FROM yearperiod_end) INTO _result
46727                 FROM period,yearperiod
46728                 WHERE ((period_id=pPeriodId)
46729                 AND (period_yearperiod_id=yearperiod_id));
46730
46731                 RETURN _result;
46732         END IF;
46733    END IF;
46734
46735    RETURN 'Err';
46736
46737 END;
46738 $_$;
46739
46740
46741 ALTER FUNCTION public.formatperiodname(integer, character) OWNER TO admin;
46742
46743 --
46744 -- TOC entry 1622 (class 1255 OID 146566201)
46745 -- Dependencies: 4536 8
46746 -- Name: formatplonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
46747 --
46748
46749 CREATE FUNCTION formatplonumber(integer) RETURNS text
46750     LANGUAGE plpgsql IMMUTABLE
46751     AS $_$
46752 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46753 -- See www.xtuple.com/CPAL for the full text of the software license.
46754 DECLARE
46755   pPlanordid ALIAS FOR $1;
46756   _result TEXT;
46757
46758 BEGIN
46759
46760   SELECT (TEXT(planord_number) || '-' || TEXT(planord_subnumber)) INTO _result
46761   FROM planord
46762   WHERE (planord_id=pPlanordid);
46763
46764   RETURN _result;
46765
46766 END;
46767 $_$;
46768
46769
46770 ALTER FUNCTION public.formatplonumber(integer) OWNER TO admin;
46771
46772 --
46773 -- TOC entry 1623 (class 1255 OID 146566202)
46774 -- Dependencies: 8
46775 -- Name: formatprcnt(numeric); Type: FUNCTION; Schema: public; Owner: admin
46776 --
46777
46778 CREATE FUNCTION formatprcnt(numeric) RETURNS text
46779     LANGUAGE sql IMMUTABLE
46780     AS $_$
46781 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
46782 -- See www.xtuple.com/CPAL for the full text of the software license.
46783 SELECT formatNumeric($1 * 100, 'percent')  AS result
46784 $_$;
46785
46786
46787 ALTER FUNCTION public.formatprcnt(numeric) OWNER TO admin;
46788
46789 --
46790 -- TOC entry 1624 (class 1255 OID 146566203)
46791 -- Dependencies: 8
46792 -- Name: formatprice(numeric); Type: FUNCTION; Schema: public; Owner: admin
46793 --
46794
46795 CREATE FUNCTION formatprice(numeric) RETURNS text
46796     LANGUAGE sql IMMUTABLE
46797     AS $_$
46798 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
46799 -- See www.xtuple.com/CPAL for the full text of the software license.
46800   SELECT formatNumeric($1, 'salesprice') AS result;
46801 $_$;
46802
46803
46804 ALTER FUNCTION public.formatprice(numeric) OWNER TO admin;
46805
46806 --
46807 -- TOC entry 1625 (class 1255 OID 146566204)
46808 -- Dependencies: 4536 8
46809 -- Name: formatpurchprice(numeric); Type: FUNCTION; Schema: public; Owner: admin
46810 --
46811
46812 CREATE FUNCTION formatpurchprice(numeric) RETURNS text
46813     LANGUAGE plpgsql IMMUTABLE
46814     AS $_$
46815 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46816 -- See www.xtuple.com/CPAL for the full text of the software license.
46817 BEGIN
46818   RETURN formatNumeric($1, 'purchprice');
46819 END;$_$;
46820
46821
46822 ALTER FUNCTION public.formatpurchprice(numeric) OWNER TO admin;
46823
46824 --
46825 -- TOC entry 1626 (class 1255 OID 146566205)
46826 -- Dependencies: 4536 8
46827 -- Name: formatqty(numeric); Type: FUNCTION; Schema: public; Owner: admin
46828 --
46829
46830 CREATE FUNCTION formatqty(numeric) RETURNS text
46831     LANGUAGE plpgsql IMMUTABLE
46832     AS $_$
46833 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46834 -- See www.xtuple.com/CPAL for the full text of the software license.
46835 BEGIN
46836   RETURN formatNumeric($1, 'qty');
46837 END;$_$;
46838
46839
46840 ALTER FUNCTION public.formatqty(numeric) OWNER TO admin;
46841
46842 --
46843 -- TOC entry 1627 (class 1255 OID 146566206)
46844 -- Dependencies: 4536 8
46845 -- Name: formatqtyper(numeric); Type: FUNCTION; Schema: public; Owner: admin
46846 --
46847
46848 CREATE FUNCTION formatqtyper(numeric) RETURNS text
46849     LANGUAGE plpgsql IMMUTABLE
46850     AS $_$
46851 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46852 -- See www.xtuple.com/CPAL for the full text of the software license.
46853 BEGIN
46854   RETURN formatNumeric($1, 'qtyper');
46855 END;$_$;
46856
46857
46858 ALTER FUNCTION public.formatqtyper(numeric) OWNER TO admin;
46859
46860 --
46861 -- TOC entry 1590 (class 1255 OID 146566207)
46862 -- Dependencies: 8
46863 -- Name: formatratio(numeric); Type: FUNCTION; Schema: public; Owner: admin
46864 --
46865
46866 CREATE FUNCTION formatratio(numeric) RETURNS text
46867     LANGUAGE sql IMMUTABLE
46868     AS $_$
46869 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
46870 -- See www.xtuple.com/CPAL for the full text of the software license.
46871   SELECT formatNumeric($1, 'uomratio');
46872 $_$;
46873
46874
46875 ALTER FUNCTION public.formatratio(numeric) OWNER TO admin;
46876
46877 --
46878 -- TOC entry 1628 (class 1255 OID 146566208)
46879 -- Dependencies: 4536 8
46880 -- Name: formatrevnumber(text, integer); Type: FUNCTION; Schema: public; Owner: admin
46881 --
46882
46883 CREATE FUNCTION formatrevnumber(text, integer) RETURNS text
46884     LANGUAGE plpgsql
46885     AS $_$
46886 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46887 -- See www.xtuple.com/CPAL for the full text of the software license.
46888 DECLARE
46889   pRevType      ALIAS FOR $1;
46890   pRevId        ALIAS FOR $2;
46891   _revision     TEXT;
46892
46893 BEGIN
46894   --See if revision control turned on (Postbooks will not ever have this)
46895   IF (fetchmetricbool('RevControl')) THEN
46896     SELECT rev_number INTO _revision
46897     FROM rev
46898     WHERE ((rev_target_type=pRevType)
46899     AND (rev_id=pRevId));
46900   END IF;
46901
46902   RETURN COALESCE(_revision,'');
46903
46904 END;
46905 $_$;
46906
46907
46908 ALTER FUNCTION public.formatrevnumber(text, integer) OWNER TO admin;
46909
46910 --
46911 -- TOC entry 1629 (class 1255 OID 146566209)
46912 -- Dependencies: 4536 8
46913 -- Name: formatsalesprice(numeric); Type: FUNCTION; Schema: public; Owner: admin
46914 --
46915
46916 CREATE FUNCTION formatsalesprice(numeric) RETURNS text
46917     LANGUAGE plpgsql IMMUTABLE
46918     AS $_$
46919 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46920 -- See www.xtuple.com/CPAL for the full text of the software license.
46921 BEGIN
46922   RETURN formatNumeric($1, 'salesprice');
46923 END;$_$;
46924
46925
46926 ALTER FUNCTION public.formatsalesprice(numeric) OWNER TO admin;
46927
46928 --
46929 -- TOC entry 1630 (class 1255 OID 146566210)
46930 -- Dependencies: 8
46931 -- Name: formatscrap(numeric); Type: FUNCTION; Schema: public; Owner: admin
46932 --
46933
46934 CREATE FUNCTION formatscrap(numeric) RETURNS text
46935     LANGUAGE sql IMMUTABLE
46936     AS $_$
46937 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
46938 -- See www.xtuple.com/CPAL for the full text of the software license.
46939   SELECT formatNumeric(($1 * 100), 'percent') AS result
46940 $_$;
46941
46942
46943 ALTER FUNCTION public.formatscrap(numeric) OWNER TO admin;
46944
46945 --
46946 -- TOC entry 1631 (class 1255 OID 146566211)
46947 -- Dependencies: 4536 8
46948 -- Name: formatshipmentnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
46949 --
46950
46951 CREATE FUNCTION formatshipmentnumber(integer) RETURNS text
46952     LANGUAGE plpgsql IMMUTABLE
46953     AS $_$
46954 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46955 -- See www.xtuple.com/CPAL for the full text of the software license.
46956 DECLARE
46957   pshipheadid    ALIAS FOR $1;
46958 BEGIN
46959   RETURN ( SELECT COALESCE(shiphead_number::TEXT, '')
46960            FROM shiphead
46961            WHERE (shiphead_id=pshipheadid) );
46962 END;
46963 $_$;
46964
46965
46966 ALTER FUNCTION public.formatshipmentnumber(integer) OWNER TO admin;
46967
46968 --
46969 -- TOC entry 1632 (class 1255 OID 146566212)
46970 -- Dependencies: 4536 8
46971 -- Name: formatsobarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
46972 --
46973
46974 CREATE FUNCTION formatsobarcode(integer) RETURNS text
46975     LANGUAGE plpgsql IMMUTABLE
46976     AS $_$
46977 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
46978 -- See www.xtuple.com/CPAL for the full text of the software license.
46979 DECLARE
46980   pSoheadid ALIAS FOR $1;
46981   _barcode TEXT;
46982 BEGIN
46983
46984   SELECT ( E'\138SOXX' ||
46985            LENGTH(TEXT(cohead_number)) || TEXT(cohead_number) ) INTO _barcode
46986   FROM cohead
46987   WHERE (cohead_id=pSoheadid);
46988
46989   RETURN _barcode;
46990
46991 END;
46992 $_$;
46993
46994
46995 ALTER FUNCTION public.formatsobarcode(integer) OWNER TO admin;
46996
46997 --
46998 -- TOC entry 1633 (class 1255 OID 146566213)
46999 -- Dependencies: 4536 8
47000 -- Name: formatsoitembarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
47001 --
47002
47003 CREATE FUNCTION formatsoitembarcode(integer) RETURNS text
47004     LANGUAGE plpgsql IMMUTABLE
47005     AS $_$
47006 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47007 -- See www.xtuple.com/CPAL for the full text of the software license.
47008 DECLARE
47009   pSoitemid ALIAS FOR $1;
47010   _barcode TEXT;
47011 BEGIN
47012
47013   SELECT ( E'\138SOLI' ||
47014            LENGTH(TEXT(cohead_number)) || LENGTH(formatsolinenumber(coitem_id)) ||
47015            TEXT(cohead_number) || formatsolinenumber(coitem_id) ) INTO _barcode
47016   FROM cohead, coitem
47017   WHERE ( (coitem_cohead_id=cohead_id)
47018    AND (coitem_id=pSoitemid) );
47019
47020   RETURN _barcode;
47021
47022 END;
47023 $_$;
47024
47025
47026 ALTER FUNCTION public.formatsoitembarcode(integer) OWNER TO admin;
47027
47028 --
47029 -- TOC entry 1634 (class 1255 OID 146566214)
47030 -- Dependencies: 4536 8
47031 -- Name: formatsoitemnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
47032 --
47033
47034 CREATE FUNCTION formatsoitemnumber(integer) RETURNS text
47035     LANGUAGE plpgsql
47036     AS $_$
47037 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47038 -- See www.xtuple.com/CPAL for the full text of the software license.
47039 DECLARE
47040   targetSoitemid ALIAS FOR $1;
47041 BEGIN
47042   RETURN ( SELECT (cohead_number::TEXT || '-' || formatsolinenumber(coitem_id))
47043            FROM cohead, coitem
47044            WHERE ((coitem_cohead_id=cohead_id)
47045             AND (coitem_id=targetSoitemid)) );
47046 END;
47047 $_$;
47048
47049
47050 ALTER FUNCTION public.formatsoitemnumber(integer) OWNER TO admin;
47051
47052 --
47053 -- TOC entry 1635 (class 1255 OID 146566215)
47054 -- Dependencies: 8
47055 -- Name: formatsonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
47056 --
47057
47058 CREATE FUNCTION formatsonumber(integer) RETURNS text
47059     LANGUAGE sql STABLE
47060     AS $_$
47061 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
47062 -- See www.xtuple.com/CPAL for the full text of the software license.
47063 SELECT COALESCE((SELECT (text(cohead_number) || '-' || formatSoLineNumber(coitem_id))
47064                    FROM coitem JOIN cohead ON (coitem_cohead_id=cohead_id)
47065                   WHERE (coitem_id=($1))),'DELETED');
47066 $_$;
47067
47068
47069 ALTER FUNCTION public.formatsonumber(integer) OWNER TO admin;
47070
47071 --
47072 -- TOC entry 1636 (class 1255 OID 146566216)
47073 -- Dependencies: 8
47074 -- Name: formattime(timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
47075 --
47076
47077 CREATE FUNCTION formattime(timestamp with time zone) RETURNS text
47078     LANGUAGE sql IMMUTABLE
47079     AS $_$
47080 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47081 -- See www.xtuple.com/CPAL for the full text of the software license.
47082   SELECT TO_CHAR($1, ( SELECT locale_timeformat
47083                        FROM locale, usr
47084                        WHERE ((usr_locale_id=locale_id)
47085                         AND (usr_username=getEffectiveXtUser())) ) ) AS result
47086 $_$;
47087
47088
47089 ALTER FUNCTION public.formattime(timestamp with time zone) OWNER TO admin;
47090
47091 --
47092 -- TOC entry 1637 (class 1255 OID 146566217)
47093 -- Dependencies: 8
47094 -- Name: formattime(numeric); Type: FUNCTION; Schema: public; Owner: admin
47095 --
47096
47097 CREATE FUNCTION formattime(numeric) RETURNS text
47098     LANGUAGE sql IMMUTABLE
47099     AS $_$
47100 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47101 -- See www.xtuple.com/CPAL for the full text of the software license.
47102   SELECT LTRIM(TO_CHAR(COALESCE($1, 0), '999999990.0'));
47103 $_$;
47104
47105
47106 ALTER FUNCTION public.formattime(numeric) OWNER TO admin;
47107
47108 --
47109 -- TOC entry 1638 (class 1255 OID 146566218)
47110 -- Dependencies: 4536 8
47111 -- Name: formatuomratio(numeric); Type: FUNCTION; Schema: public; Owner: admin
47112 --
47113
47114 CREATE FUNCTION formatuomratio(numeric) RETURNS text
47115     LANGUAGE plpgsql IMMUTABLE
47116     AS $_$
47117 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47118 -- See www.xtuple.com/CPAL for the full text of the software license.
47119 BEGIN
47120   RETURN formatNumeric($1, 'uomratio');
47121 END;$_$;
47122
47123
47124 ALTER FUNCTION public.formatuomratio(numeric) OWNER TO admin;
47125
47126 --
47127 -- TOC entry 1639 (class 1255 OID 146566219)
47128 -- Dependencies: 4536 8
47129 -- Name: formatuserbarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
47130 --
47131
47132 CREATE FUNCTION formatuserbarcode(integer) RETURNS text
47133     LANGUAGE plpgsql IMMUTABLE
47134     AS $_$
47135 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47136 -- See www.xtuple.com/CPAL for the full text of the software license.
47137 DECLARE
47138   pUserid ALIAS FOR $1;
47139   _barcode TEXT;
47140 BEGIN
47141
47142   SELECT formatUserBarcode(usr_username) INTO _barcode
47143     FROM usr
47144    WHERE(usr_id=pUserid);
47145
47146   RETURN _barcode;
47147
47148 END;
47149 $_$;
47150
47151
47152 ALTER FUNCTION public.formatuserbarcode(integer) OWNER TO admin;
47153
47154 --
47155 -- TOC entry 1640 (class 1255 OID 146566220)
47156 -- Dependencies: 4536 8
47157 -- Name: formatuserbarcode(text); Type: FUNCTION; Schema: public; Owner: admin
47158 --
47159
47160 CREATE FUNCTION formatuserbarcode(text) RETURNS text
47161     LANGUAGE plpgsql IMMUTABLE
47162     AS $_$
47163 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47164 -- See www.xtuple.com/CPAL for the full text of the software license.
47165 DECLARE
47166   pUsername ALIAS FOR $1;
47167   _barcode TEXT;
47168 BEGIN
47169
47170   _barcode := ( E'\138USER' || LENGTH(pUsername)::TEXT || pUsername );
47171
47172   RETURN _barcode;
47173
47174 END;
47175 $_$;
47176
47177
47178 ALTER FUNCTION public.formatuserbarcode(text) OWNER TO admin;
47179
47180 --
47181 -- TOC entry 1641 (class 1255 OID 146566221)
47182 -- Dependencies: 8
47183 -- Name: formatweight(numeric); Type: FUNCTION; Schema: public; Owner: admin
47184 --
47185
47186 CREATE FUNCTION formatweight(numeric) RETURNS text
47187     LANGUAGE sql IMMUTABLE
47188     AS $_$
47189 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
47190 -- See www.xtuple.com/CPAL for the full text of the software license.
47191 SELECT formatNumeric($1, 'weight') AS result
47192 $_$;
47193
47194
47195 ALTER FUNCTION public.formatweight(numeric) OWNER TO admin;
47196
47197 --
47198 -- TOC entry 1642 (class 1255 OID 146566222)
47199 -- Dependencies: 4536 8
47200 -- Name: formatwobarcode(integer); Type: FUNCTION; Schema: public; Owner: admin
47201 --
47202
47203 CREATE FUNCTION formatwobarcode(integer) RETURNS text
47204     LANGUAGE plpgsql IMMUTABLE
47205     AS $_$
47206 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47207 -- See www.xtuple.com/CPAL for the full text of the software license.
47208 DECLARE
47209   pWoid ALIAS FOR $1;
47210   _barcode TEXT;
47211 BEGIN
47212
47213   SELECT ( E'\138WOXX' ||
47214            LENGTH(wo_number::TEXT) || LENGTH(wo_subnumber::TEXT) ||
47215            wo_number::TEXT || wo_subnumber::TEXT ) INTO _barcode
47216   FROM wo
47217   WHERE (wo_id=pWoid);
47218
47219   RETURN _barcode;
47220
47221 END;
47222 $_$;
47223
47224
47225 ALTER FUNCTION public.formatwobarcode(integer) OWNER TO admin;
47226
47227 --
47228 -- TOC entry 1643 (class 1255 OID 146566223)
47229 -- Dependencies: 4536 8
47230 -- Name: formatwonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
47231 --
47232
47233 CREATE FUNCTION formatwonumber(integer) RETURNS text
47234     LANGUAGE plpgsql IMMUTABLE
47235     AS $_$
47236 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47237 -- See www.xtuple.com/CPAL for the full text of the software license.
47238 DECLARE
47239   pWoid ALIAS FOR $1;
47240
47241 BEGIN
47242
47243   RETURN ( SELECT (wo_number::TEXT || '-' || wo_subnumber::TEXT)
47244            FROM wo
47245            WHERE (wo_id=pWoid) );
47246
47247 END;
47248 $_$;
47249
47250
47251 ALTER FUNCTION public.formatwonumber(integer) OWNER TO admin;
47252
47253 --
47254 -- TOC entry 1644 (class 1255 OID 146566224)
47255 -- Dependencies: 4536 8
47256 -- Name: formatwooperseq(integer); Type: FUNCTION; Schema: public; Owner: admin
47257 --
47258
47259 CREATE FUNCTION formatwooperseq(integer) RETURNS text
47260     LANGUAGE plpgsql
47261     AS $_$
47262 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47263 -- See www.xtuple.com/CPAL for the full text of the software license.
47264 DECLARE
47265   pWooperId  ALIAS FOR $1;
47266   _result    TEXT;
47267
47268 BEGIN
47269
47270   IF pWooperId = -1 THEN
47271     RETURN '';
47272   ELSE
47273     SELECT wooper_seqnumber INTO _result
47274     FROM xtmfg.wooper
47275     WHERE (wooper_id=pWooperId);
47276   END IF;
47277
47278   RETURN _result;
47279 END;
47280 $_$;
47281
47282
47283 ALTER FUNCTION public.formatwooperseq(integer) OWNER TO admin;
47284
47285 --
47286 -- TOC entry 1645 (class 1255 OID 146566225)
47287 -- Dependencies: 4536 8
47288 -- Name: forwardupdateaccount(integer); Type: FUNCTION; Schema: public; Owner: admin
47289 --
47290
47291 CREATE FUNCTION forwardupdateaccount(integer) RETURNS integer
47292     LANGUAGE plpgsql
47293     AS $_$
47294 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47295 -- See www.xtuple.com/CPAL for the full text of the software license.
47296 DECLARE
47297   pAccntid ALIAS FOR $1;
47298   _r RECORD;
47299   _trialbalid INTEGER;
47300
47301 BEGIN
47302   SELECT trialbal_id, trialbal_dirty,
47303          CASE WHEN (trialbal_dirty) THEN 0
47304               ELSE 1
47305          END AS dirty_seq INTO _r
47306     FROM trialbal, period
47307    WHERE ((trialbal_period_id=period_id)
47308      AND  (trialbal_accnt_id=pAccntid))
47309    ORDER BY dirty_seq, period_start
47310    LIMIT 1;
47311   IF (FOUND) THEN
47312     IF (_r.trialbal_dirty) THEN
47313       RETURN forwardUpdateTrialBalance(_r.trialbal_id);
47314     ELSE
47315       RETURN _r.trialbal_id;
47316     END IF;
47317   ELSE
47318       _trialbalid := nextval('trialbal_trialbal_id_seq');
47319       
47320       INSERT INTO trialbal
47321       ( trialbal_id,
47322         trialbal_period_id, trialbal_accnt_id,
47323         trialbal_beginning, trialbal_ending,
47324         trialbal_debits, trialbal_credits, trialbal_dirty )
47325       SELECT
47326         _trialbalid,
47327         period_id, pAccntid,
47328         0, 0,
47329         0, 0, FALSE
47330       FROM period
47331       ORDER BY period_start LIMIT 1;
47332
47333       RETURN forwardUpdateTrialBalance(_trialbalid);
47334   END IF;
47335
47336   RETURN -1;
47337 END;
47338 $_$;
47339
47340
47341 ALTER FUNCTION public.forwardupdateaccount(integer) OWNER TO admin;
47342
47343 --
47344 -- TOC entry 1646 (class 1255 OID 146566226)
47345 -- Dependencies: 4536 8
47346 -- Name: forwardupdateinvbalance(integer); Type: FUNCTION; Schema: public; Owner: admin
47347 --
47348
47349 CREATE FUNCTION forwardupdateinvbalance(integer) RETURNS integer
47350     LANGUAGE plpgsql
47351     AS $_$
47352 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47353 -- See www.xtuple.com/CPAL for the full text of the software license.
47354 DECLARE
47355   pInvbalid ALIAS FOR $1;
47356   _p RECORD;
47357   _r RECORD;
47358   _qohEnding NUMERIC;
47359   _valueEnding NUMERIC;
47360   _nnEnding NUMERIC;
47361   _nnvalEnding NUMERIC;
47362
47363 BEGIN
47364
47365   SELECT invbal_itemsite_id, 
47366          invbal_qoh_ending,
47367          invbal_value_ending,
47368          invbal_nn_ending,
47369          invbal_nnval_ending,
47370          period_end INTO _p
47371   FROM invbal
47372     JOIN period ON (invbal_period_id=period_id)
47373     JOIN itemsite ON (invbal_itemsite_id=itemsite_id)
47374   WHERE (invbal_id=pInvbalid);
47375
47376   _qohEnding = _p.invbal_qoh_ending;
47377   _valueEnding = _p.invbal_value_ending;
47378   _nnEnding = _p.invbal_nn_ending;
47379   _nnvalEnding = _p.invbal_nnval_ending;
47380
47381 --  Find all of the subsequent periods and their inventory balance, if they exist
47382   FOR _r IN SELECT period_id, period_end,
47383                    invbal_id, 
47384                    invbal_qty_in, invbal_qty_out,
47385                    invbal_value_in, invbal_value_out,
47386                    invbal_nn_in, invbal_nn_out,
47387                    invbal_nnval_in, invbal_nnval_out
47388             FROM period 
47389               LEFT OUTER JOIN invbal
47390                  ON ( (invbal_period_id=period_id) AND (invbal_itemsite_id=_p.invbal_itemsite_id) )
47391             WHERE (period_start > _p.period_end)
47392             ORDER BY period_start LOOP
47393
47394     IF (_r.invbal_id IS NULL) THEN
47395
47396       INSERT INTO invbal
47397       ( invbal_period_id, invbal_itemsite_id,
47398         invbal_qoh_beginning, invbal_qoh_ending,
47399         invbal_qty_in, invbal_qty_out,
47400         invbal_value_beginning, invbal_value_ending,
47401         invbal_value_in, invbal_value_out, 
47402         invbal_nn_beginning, invbal_nn_ending,
47403         invbal_nn_in, invbal_nn_out,
47404         invbal_nnval_beginning, invbal_nnval_ending,
47405         invbal_nnval_in, invbal_nnval_out, 
47406         invbal_dirty )
47407       VALUES
47408       ( _r.period_id, _p.invbal_itemsite_id,
47409         _qohEnding, _qohEnding,
47410         0, 0, 
47411         _valueEnding, _valueEnding,
47412         0, 0,
47413         _nnEnding, _nnEnding,
47414         0, 0, 
47415         _nnvalEnding, _nnvalEnding,
47416         0, 0,
47417         FALSE );
47418     ELSE
47419       UPDATE invbal
47420       SET invbal_qoh_beginning = (_qohEnding),
47421           invbal_qoh_ending = (_qohEnding + _r.invbal_qty_in - _r.invbal_qty_out),
47422           invbal_value_beginning = (_valueEnding),
47423           invbal_value_ending = (_valueEnding + _r.invbal_value_in - _r.invbal_value_out),
47424           invbal_nn_beginning = (_nnEnding),
47425           invbal_nn_ending = (_nnEnding + _r.invbal_nn_in - _r.invbal_nn_out),
47426           invbal_nnval_beginning = (_nnvalEnding),
47427           invbal_nnval_ending = (_nnvalEnding + _r.invbal_nnval_in - _r.invbal_nnval_out),
47428           invbal_dirty = FALSE
47429       WHERE (invbal_id=_r.invbal_id);
47430
47431       _qohEnding = (_qohEnding + _r.invbal_qty_in - _r.invbal_qty_out);
47432       _valueEnding = (_valueEnding + _r.invbal_value_in - _r.invbal_value_out);
47433       _nnEnding = (_nnEnding + _r.invbal_nn_in - _r.invbal_nn_out);
47434       _nnvalEnding = (_nnvalEnding + _r.invbal_nnval_in - _r.invbal_nnval_out);
47435     END IF;
47436   END LOOP;
47437
47438   UPDATE invbal
47439   SET invbal_dirty = false
47440   WHERE (invbal_id=pInvbalid);
47441
47442   RETURN pInvbalid;
47443
47444 END;
47445 $_$;
47446
47447
47448 ALTER FUNCTION public.forwardupdateinvbalance(integer) OWNER TO admin;
47449
47450 --
47451 -- TOC entry 1647 (class 1255 OID 146566227)
47452 -- Dependencies: 4536 8
47453 -- Name: forwardupdateitemsite(integer); Type: FUNCTION; Schema: public; Owner: admin
47454 --
47455
47456 CREATE FUNCTION forwardupdateitemsite(integer) RETURNS integer
47457     LANGUAGE plpgsql
47458     AS $_$
47459 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47460 -- See www.xtuple.com/CPAL for the full text of the software license.
47461 DECLARE
47462   pItemsiteId ALIAS FOR $1;
47463   _r RECORD;
47464   _invbalid INTEGER;
47465
47466 BEGIN
47467   SELECT invbal_id INTO _r
47468   FROM invbal
47469       JOIN period ON (invbal_period_id=period_id)
47470   WHERE (invbal_itemsite_id=pItemsiteid)
47471   ORDER BY period_start
47472   LIMIT 1;
47473
47474   IF (FOUND) THEN
47475     RETURN forwardUpdateInvbalance(_r.invbal_id);
47476   ELSE
47477       _invbalid := nextval('invbal_invbal_id_seq');
47478       
47479       INSERT INTO invbal
47480       ( invbal_id,
47481         invbal_period_id, invbal_itemsite_id,
47482         invbal_qoh_beginning, invbal_qoh_ending,
47483         invbal_qty_in, invbal_qty_out,
47484         invbal_value_beginning, invbal_value_ending,
47485         invbal_value_in, invbal_value_out,
47486         invbal_nn_beginning, invbal_nn_ending,
47487         invbal_nn_in, invbal_nn_out,
47488         invbal_nnval_beginning, invbal_nnval_ending,
47489         invbal_nnval_in, invbal_nnval_out,
47490         invbal_dirty )
47491       SELECT
47492         _invbalid,
47493         period_id, pItemsiteid,
47494         0, 0, 0, 0, 0, 0, 0, 0,
47495         0, 0, 0, 0, 0, 0, 0, 0,
47496         false
47497       FROM period
47498       ORDER BY period_start LIMIT 1;
47499
47500       RETURN forwardUpdateInvbalance(_invbalid);
47501   END IF;
47502
47503   RETURN -1;
47504 END;
47505 $_$;
47506
47507
47508 ALTER FUNCTION public.forwardupdateitemsite(integer) OWNER TO admin;
47509
47510 --
47511 -- TOC entry 1648 (class 1255 OID 146566228)
47512 -- Dependencies: 4536 8
47513 -- Name: forwardupdatetrialbalance(integer); Type: FUNCTION; Schema: public; Owner: admin
47514 --
47515
47516 CREATE FUNCTION forwardupdatetrialbalance(integer) RETURNS integer
47517     LANGUAGE plpgsql
47518     AS $_$
47519 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47520 -- See www.xtuple.com/CPAL for the full text of the software license.
47521 DECLARE
47522   pTrialbalid ALIAS FOR $1;
47523   _p RECORD;
47524   _r RECORD;
47525   _ending NUMERIC;
47526   _prevYear INTEGER;
47527   _currYear INTEGER;
47528   _prevYearClosed BOOLEAN;
47529   _currYearClosed BOOLEAN;
47530   _result INTEGER;
47531
47532 BEGIN
47533
47534   SELECT trialbal_accnt_id, trialbal_ending,
47535          yearperiod_id, yearperiod_closed,
47536          period_end, accnt_type IN ('E', 'R') AS revexp INTO _p
47537   FROM trialbal, period, yearperiod, accnt
47538   WHERE ( (trialbal_period_id=period_id)
47539    AND (yearperiod_id=period_yearperiod_id)
47540    AND (trialbal_accnt_id=accnt_id)
47541    AND (trialbal_id=pTrialbalid) );
47542
47543   _ending = _p.trialbal_ending;
47544
47545   SELECT yearperiod_id, yearperiod_closed INTO _prevYear, _prevYearClosed
47546     FROM yearperiod
47547    WHERE (_p.period_end BETWEEN yearperiod_start AND yearperiod_end);
47548   IF (NOT FOUND) THEN
47549     _prevYear := -1;
47550     _prevYearClosed := false;
47551   END IF;
47552
47553 --  Find all of the subsequent periods and their trialbal, if they exist
47554   FOR _r IN SELECT period_id, period_end,
47555                    trialbal_id, trialbal_debits, trialbal_credits,
47556                    trialbal_yearend
47557             FROM period LEFT OUTER JOIN trialbal
47558                  ON ( (trialbal_period_id=period_id) AND (trialbal_accnt_id=_p.trialbal_accnt_id) )
47559             WHERE (period_start > _p.period_end)
47560             ORDER BY period_start LOOP
47561
47562     SELECT yearperiod_id, yearperiod_closed INTO _currYear, _currYearClosed
47563       FROM yearperiod
47564      WHERE (_r.period_end BETWEEN yearperiod_start AND yearperiod_end);
47565     IF (NOT FOUND) THEN
47566       _currYear := -1;
47567       _currYearClosed := false;
47568     END IF;
47569
47570     IF (_p.revexp AND _currYear != _prevYear) THEN
47571       _ending := 0;
47572       IF (_prevYearClosed) THEN
47573         SELECT updateRetainedEarnings(_prevYear) INTO _result;
47574         IF (_result < 0) THEN
47575           RETURN _result;
47576         END IF;
47577       END IF;
47578     END IF;
47579
47580     _prevYear := _currYear;
47581     _prevYearClosed := _currYearClosed;
47582
47583     IF (_r.trialbal_id IS NULL) THEN
47584       -- SELECT SUM(gltrans_amount) INTO _glAmount
47585        -- FROM gltrans
47586        -- WHERE ( (gltrans_date BETWEEN _r.period_start and _r.period_end )
47587          -- AND   (gltrans_accnt_id=_p.trialbal_accnt_id)
47588          -- AND   (gltrans_posted) );
47589         -- and change 2nd and 3rd VALUES line of INSERT to read
47590         --      _ending, _ending + _glAmount,
47591         --      noneg(0 - _glAmount), noneg(_glAmount), FALSE );
47592
47593       INSERT INTO trialbal
47594       ( trialbal_period_id, trialbal_accnt_id,
47595         trialbal_beginning, trialbal_ending,
47596         trialbal_debits, trialbal_credits, trialbal_dirty )
47597       VALUES
47598       ( _r.period_id, _p.trialbal_accnt_id,
47599         _ending, _ending,
47600         0, 0, FALSE );
47601     ELSE
47602       UPDATE trialbal
47603       SET trialbal_beginning = (_ending + trialbal_yearend),
47604           trialbal_ending = (_ending + trialbal_yearend - _r.trialbal_debits + _r.trialbal_credits),
47605           trialbal_dirty = FALSE
47606       WHERE (trialbal_id=_r.trialbal_id);
47607
47608       _ending = (_ending + _r.trialbal_yearend - _r.trialbal_debits + _r.trialbal_credits);
47609     END IF;
47610   END LOOP;
47611
47612   UPDATE trialbal
47613   SET trialbal_dirty = FALSE
47614   WHERE (trialbal_id=pTrialbalid);
47615
47616   RETURN pTrialbalid;
47617
47618 END;
47619 $_$;
47620
47621
47622 ALTER FUNCTION public.forwardupdatetrialbalance(integer) OWNER TO admin;
47623
47624 --
47625 -- TOC entry 1649 (class 1255 OID 146566229)
47626 -- Dependencies: 4536 8
47627 -- Name: freezeaccountingperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
47628 --
47629
47630 CREATE FUNCTION freezeaccountingperiod(integer) RETURNS integer
47631     LANGUAGE plpgsql
47632     AS $_$
47633 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
47634 -- See www.xtuple.com/CPAL for the full text of the software license.
47635 DECLARE
47636   pPeriodid ALIAS FOR $1;
47637
47638 BEGIN
47639
47640 --  Check to make use that the period is not already frozen
47641   IF ( ( SELECT period_freeze
47642          FROM period
47643          WHERE (period_id=pPeriodid) ) ) THEN
47644     RETURN -2;
47645   END IF;
47646
47647 --  Set the period_freeze flag
47648   UPDATE period
47649   SET period_freeze=TRUE
47650   WHERE (period_id=pPeriodid);
47651
47652   RETURN pPeriodid;
47653
47654 END;
47655 $_$;
47656
47657
47658 ALTER FUNCTION public.freezeaccountingperiod(integer) OWNER TO admin;
47659
47660 --
47661 -- TOC entry 1652 (class 1255 OID 146566230)
47662 -- Dependencies: 2681 4536 8
47663 -- Name: freightdetail(text, integer, integer, integer, date, text, integer); Type: FUNCTION; Schema: public; Owner: admin
47664 --
47665
47666 CREATE FUNCTION freightdetail(text, integer, integer, integer, date, text, integer) RETURNS SETOF freightdata
47667     LANGUAGE plpgsql
47668     AS $_$
47669 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
47670 -- See www.xtuple.com/CPAL for the full text of the software license.
47671 DECLARE
47672   pOrderType ALIAS FOR $1;
47673   pOrderId ALIAS FOR $2;
47674   pCustId ALIAS FOR $3;
47675   pShiptoId ALIAS FOR $4;
47676   pOrderDate ALIAS FOR $5;
47677   pShipVia ALIAS FOR $6;
47678   pCurrId ALIAS FOR $7;
47679
47680   _row freightData%ROWTYPE;
47681   _order RECORD;
47682   _weights RECORD;
47683   _includepkgweight BOOLEAN := FALSE;
47684   _qry TEXT;
47685   _debug BOOLEAN := FALSE;
47686
47687 BEGIN
47688   IF (_debug) THEN
47689     RAISE NOTICE 'pOrderType = %', pOrderType;
47690     RAISE NOTICE 'pOrderId = %', pOrderId;
47691     RAISE NOTICE 'pCustId = %', pCustId;
47692     RAISE NOTICE 'pShiptoId = %', pShiptoId;
47693     RAISE NOTICE 'pOrderDate = %', pOrderDate;
47694     RAISE NOTICE 'pShipVia = %', pShipVia;
47695     RAISE NOTICE 'pCurrId = %', pCurrId;
47696   END IF;
47697
47698   SELECT fetchMetricBool('IncludePackageWeight') INTO _includepkgweight;
47699
47700   --Get the order header information need to match
47701   --against price schedules
47702   IF (pOrderType = 'SO') THEN
47703     SELECT
47704       cust_id AS cust_id,
47705       custtype_id,
47706       custtype_code,
47707       COALESCE(shipto_id, -1) AS shipto_id,
47708       COALESCE(shipto_num, '') AS shipto_num,
47709       COALESCE(pOrderDate, cohead_orderdate) AS orderdate,
47710       COALESCE(pShipVia, cohead_shipvia) AS shipvia,
47711       shipto_shipzone_id AS shipzone_id,
47712       COALESCE(pCurrId, cohead_curr_id) AS curr_id,
47713       currConcat(COALESCE(pCurrId, cohead_curr_id)) AS currAbbr
47714     INTO _order
47715       FROM cohead
47716       JOIN custinfo ON (cust_id=COALESCE(pCustId, cohead_cust_id))
47717       JOIN custtype ON (custtype_id=cust_custtype_id)
47718       LEFT OUTER JOIN shiptoinfo ON (shipto_id=COALESCE(pShiptoId, cohead_shipto_id))
47719     WHERE (cohead_id=pOrderId);
47720
47721   ELSIF (pOrderType = 'QU') THEN
47722     SELECT
47723       quhead_cust_id AS cust_id,
47724       custtype_id,
47725       custtype_code,
47726       COALESCE(shipto_id, -1) AS shipto_id,
47727       COALESCE(shipto_num, '') AS shipto_num,
47728       quhead_quotedate AS orderdate,
47729       quhead_shipvia AS shipvia,
47730       shipto_shipzone_id AS shipzone_id,
47731       quhead_curr_id AS curr_id,
47732       currConcat(quhead_curr_id) AS currAbbr
47733     INTO _order
47734       FROM quhead
47735       JOIN custinfo ON (cust_id=quhead_cust_id)
47736       JOIN custtype ON (custtype_id=cust_custtype_id)
47737       LEFT OUTER JOIN shiptoinfo ON (shipto_id=quhead_shipto_id)
47738     WHERE (quhead_id=pOrderId);
47739
47740   ELSIF (pOrderType = 'RA') THEN
47741     SELECT
47742       cust_id AS cust_id,
47743       custtype_id,
47744       custtype_code,
47745       COALESCE(shipto_id, -1) AS shipto_id,
47746       COALESCE(shipto_num, '') AS shipto_num,
47747       COALESCE(pOrderDate, rahead_authdate) AS orderdate,
47748       ''::text AS shipvia,
47749       shipto_shipzone_id AS shipzone_id,
47750       COALESCE(pCurrId, rahead_curr_id) AS curr_id,
47751       currConcat(COALESCE(pCurrId, rahead_curr_id)) AS currAbbr
47752     INTO _order
47753       FROM rahead
47754       JOIN custinfo ON (cust_id=COALESCE(pCustId, rahead_cust_id))
47755       JOIN custtype ON (custtype_id=cust_custtype_id)
47756       LEFT OUTER JOIN shiptoinfo ON (shipto_id=COALESCE(pShiptoId, rahead_shipto_id))
47757     WHERE (rahead_id=pOrderId);
47758
47759   ELSE
47760     RAISE EXCEPTION 'Invalid order type.';
47761   END IF;
47762
47763   IF (_debug) THEN
47764     RAISE NOTICE 'cust_id = %', _order.cust_id;
47765     RAISE NOTICE 'custtype_id = %', _order.custtype_id;
47766     RAISE NOTICE 'shipto_id = %', _order.shipto_id;
47767     RAISE NOTICE 'shipto_num = %', _order.shipto_num;
47768     RAISE NOTICE 'orderdate = %', _order.orderdate;
47769     RAISE NOTICE 'shipvia = %', _order.shipvia;
47770     RAISE NOTICE 'shipzone_id = %', _order.shipzone_id;
47771     RAISE NOTICE 'curr_id = %', _order.curr_id;
47772     RAISE NOTICE 'currAbbr = %', _order.currAbbr;
47773   END IF;
47774
47775   --Get a list of aggregated weights from sites and
47776   --freight classes used on order lines
47777
47778   IF (_includePkgWeight) THEN
47779     _qry := 'SELECT SUM(orderitem_qty_ordered * orderitem_qty_invuomratio * (item_prodweight + item_packweight)) AS weight, ';
47780   ELSE
47781     _qry := 'SELECT SUM(orderitem_qty_ordered * orderitem_qty_invuomratio * item_prodweight) AS weight, ';
47782   END IF;
47783
47784   _qry := _qry || 'itemsite_warehous_id, COALESCE(item_freightclass_id, -1) AS item_freightclass_id
47785     FROM orderitem
47786     JOIN itemsite ON (itemsite_id=orderitem_itemsite_id)
47787     JOIN item ON (item_id=itemsite_item_id) ';
47788
47789   IF (pOrderType = 'RA') THEN
47790     _qry := _qry || 'JOIN raitem ON ((orderitem_id=raitem_id)
47791     AND (raitem_disposition IN (''C'',''R'',''P''))) ';
47792   END IF;
47793
47794   _qry := _qry || '
47795     WHERE ( (orderitem_orderhead_type=' || quote_literal(pOrderType) || ')
47796       AND (orderitem_orderhead_id=' || quote_literal(pOrderId) || ')
47797       AND (orderitem_status <> ''X'') )
47798     GROUP BY itemsite_warehous_id, item_freightclass_id;';
47799
47800   FOR _weights IN
47801     EXECUTE _qry LOOP
47802
47803     _row := calculateFreightDetail(
47804       _order.cust_id, --pCustId
47805       _order.custtype_id, --pCustTypeId
47806       _order.custtype_code, --pCustTypeCode
47807       _order.shipto_id, --pShiptoId
47808       _order.shipzone_id, --pShipZoneId
47809       _order.shipto_num, --pShiptoNum
47810       _order.orderdate, --pOrderDate
47811       _order.shipvia, --pShipVia
47812       _order.curr_id, --pCurrId
47813       _order.currAbbr, --pCurrAbbr
47814       _weights.itemsite_warehous_id, --pItemSiteWhsId
47815       _weights.item_freightclass_id, --pItemFreightclassId
47816       _weights.weight --pWeight
47817       );
47818
47819     RETURN NEXT _row;
47820
47821   END LOOP;
47822   RETURN;
47823 END;
47824 $_$;
47825
47826
47827 ALTER FUNCTION public.freightdetail(text, integer, integer, integer, date, text, integer) OWNER TO admin;
47828
47829 --
47830 -- TOC entry 1653 (class 1255 OID 146566231)
47831 -- Dependencies: 2681 4536 8
47832 -- Name: freightdetailquote(integer, text, integer, text, date, text, text, text[]); Type: FUNCTION; Schema: public; Owner: admin
47833 --
47834
47835 CREATE FUNCTION freightdetailquote(integer, text, integer, text, date, text, text, text[]) RETURNS SETOF freightdata
47836     LANGUAGE plpgsql
47837     AS $_$
47838 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
47839 -- See www.xtuple.com/CPAL for the full text of the software license.
47840 DECLARE
47841   pCustId ALIAS FOR $1;
47842   pCustNumber ALIAS FOR $2;
47843   pShiptoId ALIAS FOR $3;
47844   pShiptoNum ALIAS FOR $4;
47845   pOrderDate ALIAS FOR $5;
47846   pShipVia ALIAS FOR $6;
47847   pItemArrayType ALIAS FOR $7;
47848   pItemQty ALIAS FOR $8;
47849     -- Array item_id format = ARRAY[['300','3'],['310','50']]
47850     -- Array item_number format = ARRAY[['YTRUCK1','3'],['RTRUCK1','50']]
47851     -- Array itemsite_id format = ARRAY[['293','3'],['302','50']]
47852
47853   _cust RECORD;
47854   _shipto RECORD;
47855   _curr RECORD;
47856   _includepkgweight BOOLEAN := FALSE;
47857   _order_date DATE;
47858   _ship_via TEXT;
47859   _item_num RECORD;
47860   _item_id RECORD;
47861   _weights RECORD;
47862   _row freightData%ROWTYPE;
47863   _debug BOOLEAN := FALSE;
47864
47865 BEGIN
47866 -- Parameters are setup to allow this function to be called multiple ways.
47867 -- Check parameters and lookup what is NULL.
47868
47869   -- Check pCustId and pCustNumber.
47870   IF (pCustId IS NULL AND (pCustNumber IS NULL OR pCustNumber = '')) THEN
47871     RAISE EXCEPTION 'You must specify a Customer ID or Number to get a freight quote.';
47872   ELSIF (pCustId IS NULL AND pCustNumber IS NOT NULL) THEN
47873     -- Get customer info using pCustNumber.
47874     SELECT
47875       cust_id,
47876       cust_number,
47877       custtype_id,
47878       custtype_code,
47879       cust_curr_id,
47880       cust_shipvia
47881     INTO _cust
47882     FROM custinfo
47883     LEFT JOIN custtype ON cust_custtype_id = custtype_id
47884     WHERE 1=1
47885       AND cust_number = pCustNumber;
47886   ELSE
47887     -- Get customer info using pCustId.
47888     SELECT
47889       cust_id,
47890       cust_number,
47891       custtype_id,
47892       custtype_code,
47893       cust_curr_id,
47894       cust_shipvia
47895     INTO _cust
47896     FROM custinfo
47897     LEFT JOIN custtype ON cust_custtype_id = custtype_id
47898     WHERE 1=1
47899       AND cust_id = pCustId;
47900   END IF;
47901
47902   IF(NOT FOUND) THEN
47903     RAISE EXCEPTION 'Invalid Customer specified when trying to get a freight quote.';
47904   END IF;
47905
47906   -- Check pShiptoId and pShiptoNum.
47907   IF (pShiptoId IS NULL AND (pShiptoNum IS NULL OR pShiptoNum = '')) THEN
47908     -- Get Customer's default shipto.
47909     SELECT
47910       shipto_id,
47911       shipto_name,
47912       shipto_shipzone_id,
47913       shipto_shipvia,
47914       shipto_num
47915     INTO _shipto
47916     FROM shiptoinfo
47917     WHERE 1=1
47918       AND shipto_cust_id = _cust.cust_id
47919       AND shipto_default;
47920   ELSIF (pShiptoId IS NULL AND pShiptoNum IS NOT NULL) THEN
47921     -- Get shipto info using pShiptoNum.
47922     SELECT
47923       shipto_id,
47924       shipto_name,
47925       shipto_shipzone_id,
47926       shipto_shipvia,
47927       shipto_num
47928     INTO _shipto
47929     FROM shiptoinfo
47930     WHERE 1=1
47931       AND shipto_cust_id = _cust.cust_id
47932       AND shipto_num = pShiptoNum;
47933   ELSE
47934     -- Get shipto info using pShiptoId.
47935     SELECT
47936       shipto_id,
47937       shipto_name,
47938       shipto_shipzone_id,
47939       shipto_shipvia,
47940       shipto_num
47941     INTO _shipto
47942     FROM shiptoinfo
47943     WHERE 1=1
47944       AND shipto_cust_id = _cust.cust_id
47945       AND shipto_id = pShiptoId;
47946   END IF;
47947
47948   IF(NOT FOUND) THEN
47949     RAISE EXCEPTION 'Invalid Ship-to specified when trying to get a freight quote.';
47950   END IF;
47951
47952   -- Get curr info.
47953   SELECT
47954     curr_id,
47955     curr_abbr
47956   INTO _curr
47957   FROM curr_symbol
47958   WHERE 1=1
47959     AND curr_id = _cust.cust_curr_id;
47960
47961   IF(NOT FOUND) THEN
47962     RAISE EXCEPTION 'Could not find currency when trying to get a freight quote.';
47963   END IF;
47964
47965   -- Check pOrderDate.
47966   IF (pOrderDate IS NULL) THEN
47967     _order_date := CURRENT_DATE;
47968   ELSE
47969     _order_date := pOrderDate;
47970   END IF;
47971
47972   -- Check pShipVia.
47973   IF (pShipVia IS NULL OR pShipVia = '') THEN
47974     IF (_shipto.shipto_shipvia IS NULL OR _shipto.shipto_shipvia = '') THEN
47975       _ship_via := _cust.cust_shipvia;
47976     ELSE
47977       _ship_via := _shipto.shipto_shipvia;
47978     END IF;
47979   ELSE
47980     _ship_via := pShipVia;
47981   END IF;
47982
47983   -- Determine if package weight should be included in freight calculation.
47984   SELECT fetchMetricBool('IncludePackageWeight') INTO _includepkgweight;
47985
47986   -- Check pItemQty.
47987   IF (pItemQty IS NULL OR array_upper(pItemQty,1) IS NULL) THEN
47988     -- Item Array is NULL.
47989     RAISE EXCEPTION 'You must specify an Item ID, Item Number or Itemsite ID to get a freight quote.';
47990   ELSIF (pItemArrayType = 'item_number' AND (array_upper(pItemQty,1) > 0)) THEN
47991     -- Using item_number.
47992     FOR _weights IN
47993       -- Get a list of aggregated weights from sites and freight classes for items.
47994       SELECT
47995         CASE WHEN _includepkgweight THEN
47996           SUM(qty * (item_prodweight + item_packweight))
47997         ELSE
47998           SUM(qty * (item_prodweight))
47999         END AS weight,
48000         itemsite_warehous_id,
48001         COALESCE(item_freightclass_id, -1) AS item_freightclass_id
48002       FROM
48003         -- Create item_number -> qty record from array.
48004         (SELECT
48005           unnest((SELECT pItemQty[1:array_upper(pItemQty,1)][1])) AS item_number,
48006           unnest((SELECT pItemQty[1:array_upper(pItemQty,1)][2:array_ndims(pItemQty)]))::numeric AS qty
48007         ) AS itemnum_qty
48008         JOIN item USING (item_number)
48009         JOIN itemsite ON item_id=itemsite_item_id
48010       WHERE 1=1
48011         AND itemsite_warehous_id = fetchprefwarehousid()
48012       GROUP BY
48013         itemsite_warehous_id,
48014         item_freightclass_id
48015     LOOP
48016       -- Calculate the freight detail for these item weights.
48017       _row := calculateFreightDetail(
48018         _cust.cust_id, --pCustId
48019         _cust.custtype_id, --pCustTypeId
48020         _cust.custtype_code, --pCustTypeCode
48021         _shipto.shipto_id, --pShiptoId
48022         _shipto.shipto_shipzone_id, --pShipZoneId
48023         _shipto.shipto_num, --pShiptoNum
48024         _order_date, --pOrderDate
48025         _ship_via, --pShipVia
48026         _curr.curr_id, --pCurrId
48027         _curr.curr_abbr, --pCurrAbbr
48028         _weights.itemsite_warehous_id, --pItemSiteWhsId
48029         _weights.item_freightclass_id, --pItemFreightclassId
48030         _weights.weight --pWeight
48031         );
48032
48033       RETURN NEXT _row;
48034     END LOOP;
48035
48036   ELSIF (pItemArrayType = 'item_id' AND (array_upper(pItemQty,1) > 0)) THEN
48037     -- Using item_id.
48038     FOR _weights IN
48039       -- Get a list of aggregated weights from sites and freight classes for items.
48040       SELECT
48041         CASE WHEN _includepkgweight THEN
48042           SUM(qty * (item_prodweight + item_packweight))
48043         ELSE
48044           SUM(qty * (item_prodweight))
48045         END AS weight,
48046         itemsite_warehous_id,
48047         COALESCE(item_freightclass_id, -1) AS item_freightclass_id
48048       FROM
48049         -- Create item_id -> qty record from array.
48050         (SELECT
48051           unnest((SELECT pItemQty[1:array_upper(pItemQty,1)][1]))::integer AS item_id,
48052           unnest((SELECT pItemQty[1:array_upper(pItemQty,1)][2:array_ndims(pItemQty)]))::numeric AS qty
48053         ) AS itemid_qty
48054         JOIN item USING (item_id)
48055         JOIN itemsite ON item_id=itemsite_item_id
48056       WHERE 1=1
48057         AND itemsite_warehous_id = fetchprefwarehousid()
48058       GROUP BY
48059         itemsite_warehous_id,
48060         item_freightclass_id
48061     LOOP
48062       -- Calculate the freight detail for these item weights.
48063       _row := calculateFreightDetail(
48064         _cust.cust_id, --pCustId
48065         _cust.custtype_id, --pCustTypeId
48066         _cust.custtype_code, --pCustTypeCode
48067         _shipto.shipto_id, --pShiptoId
48068         _shipto.shipto_shipzone_id, --pShipZoneId
48069         _shipto.shipto_num, --pShiptoNum
48070         _order_date, --pOrderDate
48071         _ship_via, --pShipVia
48072         _curr.curr_id, --pCurrId
48073         _curr.curr_abbr, --pCurrAbbr
48074         _weights.itemsite_warehous_id, --pItemSiteWhsId
48075         _weights.item_freightclass_id, --pItemFreightclassId
48076         _weights.weight --pWeight
48077         );
48078
48079       RETURN NEXT _row;
48080     END LOOP;
48081   ELSIF (pItemArrayType = 'itemsite_id' AND (array_upper(pItemQty,1) > 0)) THEN
48082     -- Using itemsite_id.
48083     FOR _weights IN
48084       -- Get a list of aggregated weights from sites and freight classes for items.
48085       SELECT
48086         CASE WHEN _includepkgweight THEN
48087           SUM(qty * (item_prodweight + item_packweight))
48088         ELSE
48089           SUM(qty * (item_prodweight))
48090         END AS weight,
48091         itemsite_warehous_id,
48092         COALESCE(item_freightclass_id, -1) AS item_freightclass_id
48093       FROM
48094         -- Create itemsite_id -> qty record from array.
48095         (SELECT
48096           unnest((SELECT pItemQty[1:array_upper(pItemQty,1)][1]))::integer AS itemsite_id,
48097           unnest((SELECT pItemQty[1:array_upper(pItemQty,1)][2:array_ndims(pItemQty)]))::numeric AS qty
48098         ) AS itemsiteid_qty
48099         JOIN itemsite USING (itemsite_id)
48100         JOIN item ON item_id=itemsite_item_id
48101       WHERE 1=1
48102       GROUP BY
48103         itemsite_warehous_id,
48104         item_freightclass_id
48105     LOOP
48106       -- Calculate the freight detail for these item weights.
48107       _row := calculateFreightDetail(
48108         _cust.cust_id, --pCustId
48109         _cust.custtype_id, --pCustTypeId
48110         _cust.custtype_code, --pCustTypeCode
48111         _shipto.shipto_id, --pShiptoId
48112         _shipto.shipto_shipzone_id, --pShipZoneId
48113         _shipto.shipto_num, --pShiptoNum
48114         _order_date, --pOrderDate
48115         _ship_via, --pShipVia
48116         _curr.curr_id, --pCurrId
48117         _curr.curr_abbr, --pCurrAbbr
48118         _weights.itemsite_warehous_id, --pItemSiteWhsId
48119         _weights.item_freightclass_id, --pItemFreightclassId
48120         _weights.weight --pWeight
48121         );
48122
48123       RETURN NEXT _row;
48124     END LOOP;
48125   ELSE -- The item array provided is invalid.
48126     RAISE EXCEPTION 'The Item/Itemsite array provided when trying to get a freight quote is invalid.';
48127   END IF;
48128
48129   IF(NOT FOUND) THEN
48130     RAISE EXCEPTION 'Error trying to aggregated weights when getting a freight quote.';
48131   END IF;
48132
48133   -- Print debug.
48134   IF (_debug) THEN
48135     RAISE NOTICE 'pCustId = %', _cust.cust_id;
48136     RAISE NOTICE 'pCustTypeId = %', _cust.custtype_id;
48137     RAISE NOTICE 'pCustTypeCode = %', _cust.custtype_code;
48138     RAISE NOTICE 'pShiptoId = %', _shipto.shipto_id;
48139     RAISE NOTICE 'pShipZoneId = %', _shipto.shipto_shipzone_id;
48140     RAISE NOTICE 'pShiptoNum = %', _shipto.shipto_num;
48141     RAISE NOTICE 'pOrderDate = %', _order_date;
48142     RAISE NOTICE 'pShipVia = %', _ship_via;
48143     RAISE NOTICE 'pCurrId = %', _curr.curr_id;
48144     RAISE NOTICE 'pCurrAbbr = %', _curr.curr_abbr;
48145   END IF;
48146
48147   RETURN;
48148 END;
48149 $_$;
48150
48151
48152 ALTER FUNCTION public.freightdetailquote(integer, text, integer, text, date, text, text, text[]) OWNER TO admin;
48153
48154 --
48155 -- TOC entry 1654 (class 1255 OID 146566233)
48156 -- Dependencies: 4536 8
48157 -- Name: freightforrecv(text, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
48158 --
48159
48160 CREATE FUNCTION freightforrecv(text, integer, boolean) RETURNS numeric
48161     LANGUAGE plpgsql
48162     AS $_$
48163 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48164 -- See www.xtuple.com/CPAL for the full text of the software license.
48165 DECLARE
48166   pordertype    ALIAS FOR $1;
48167   porderitemid  ALIAS FOR $2;
48168   pposted       ALIAS FOR $3;
48169   _freight      NUMERIC;
48170
48171 BEGIN
48172   IF (pordertype = 'TO' AND NOT fetchMetricBool('MultiWhs')) THEN
48173     RETURN 0;
48174   ELSIF (pordertype = 'RA' AND NOT fetchMetricBool('EnableReturnAuth')) THEN
48175     RETURN 0;
48176   END IF;
48177
48178   SELECT SUM(COALESCE(recv_freight, 0)) INTO _freight
48179   FROM recv
48180   WHERE ((recv_orderitem_id=porderitemid)
48181     AND  (recv_posted = pposted)
48182     AND  (recv_order_type=pordertype));
48183
48184   RETURN COALESCE(_freight, 0.0);
48185
48186 END;
48187 $_$;
48188
48189
48190 ALTER FUNCTION public.freightforrecv(text, integer, boolean) OWNER TO admin;
48191
48192 --
48193 -- TOC entry 1655 (class 1255 OID 146566234)
48194 -- Dependencies: 8
48195 -- Name: gen_salt(text); Type: FUNCTION; Schema: public; Owner: admin
48196 --
48197
48198 CREATE FUNCTION gen_salt(text) RETURNS text
48199     LANGUAGE c STRICT
48200     AS '$libdir/pgcrypto', 'pg_gen_salt';
48201
48202
48203 ALTER FUNCTION public.gen_salt(text) OWNER TO admin;
48204
48205 --
48206 -- TOC entry 1656 (class 1255 OID 146566235)
48207 -- Dependencies: 8
48208 -- Name: gen_salt(text, integer); Type: FUNCTION; Schema: public; Owner: admin
48209 --
48210
48211 CREATE FUNCTION gen_salt(text, integer) RETURNS text
48212     LANGUAGE c STRICT
48213     AS '$libdir/pgcrypto', 'pg_gen_salt_rounds';
48214
48215
48216 ALTER FUNCTION public.gen_salt(text, integer) OWNER TO admin;
48217
48218 --
48219 -- TOC entry 1657 (class 1255 OID 146566236)
48220 -- Dependencies: 4536 8
48221 -- Name: getactiverevid(text, integer); Type: FUNCTION; Schema: public; Owner: admin
48222 --
48223
48224 CREATE FUNCTION getactiverevid(text, integer) RETURNS integer
48225     LANGUAGE plpgsql STABLE
48226     AS $_$
48227 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48228 -- See www.xtuple.com/CPAL for the full text of the software license.
48229 DECLARE
48230   pTargetType ALIAS FOR $1;
48231   pTargetid ALIAS FOR $2;
48232   _revid INTEGER;
48233
48234 BEGIN
48235   --See if revcontrol turned on
48236   IF (fetchmetricbool('RevControl')) THEN
48237
48238     IF (pTargetType='BOM') THEN
48239       SELECT rev_id INTO _revid
48240       FROM rev
48241       WHERE ((rev_target_type='BOM')
48242       AND (rev_target_id=pTargetid)
48243       AND (rev_status='A'));
48244       IF (NOT FOUND) THEN
48245         _revid:=-1;
48246       END IF;
48247
48248       ELSE IF (pTargetType='BOO') THEN
48249       SELECT rev_id INTO _revid
48250       FROM rev
48251       WHERE ((rev_target_type='BOO')
48252       AND (rev_target_id=pTargetid)
48253       AND (rev_status='A'));
48254       IF (NOT FOUND) THEN
48255         _revid:=-1;
48256       END IF;
48257
48258       ELSE
48259         RAISE EXCEPTION 'Invalid Revision Type';
48260       END IF;
48261     END IF;
48262
48263   ELSE
48264     _revid:=-1;
48265   END IF;
48266
48267   RETURN _revid;
48268
48269 END;
48270 $_$;
48271
48272
48273 ALTER FUNCTION public.getactiverevid(text, integer) OWNER TO admin;
48274
48275 --
48276 -- TOC entry 1658 (class 1255 OID 146566237)
48277 -- Dependencies: 4536 8
48278 -- Name: getaddrid(text); Type: FUNCTION; Schema: public; Owner: admin
48279 --
48280
48281 CREATE FUNCTION getaddrid(paddressnumber text) RETURNS integer
48282     LANGUAGE plpgsql STABLE
48283     AS $$
48284 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48285 -- See www.xtuple.com/CPAL for the full text of the software license.
48286 DECLARE
48287   _returnVal INTEGER;
48288 BEGIN
48289   IF (pAddressNumber IS NULL OR pAddressNumber = '') THEN
48290     RETURN NULL;
48291   END IF;
48292
48293   SELECT addr_id INTO _returnVal
48294   FROM addr
48295   WHERE (addr_number=pAddressNumber);
48296
48297   IF (_returnVal IS NULL) THEN
48298         RAISE EXCEPTION 'Address Number % not found.', pAddressNumber;
48299   END IF;
48300
48301   RETURN _returnVal;
48302 END;
48303 $$;
48304
48305
48306 ALTER FUNCTION public.getaddrid(paddressnumber text) OWNER TO admin;
48307
48308 --
48309 -- TOC entry 1659 (class 1255 OID 146566238)
48310 -- Dependencies: 4536 8
48311 -- Name: getadjustmenttaxtypeid(); Type: FUNCTION; Schema: public; Owner: admin
48312 --
48313
48314 CREATE FUNCTION getadjustmenttaxtypeid() RETURNS integer
48315     LANGUAGE plpgsql IMMUTABLE
48316     AS $$
48317 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48318 -- See www.xtuple.com/CPAL for the full text of the software license.
48319 DECLARE
48320   _taxtypeid INTEGER;
48321 BEGIN
48322   SELECT taxtype_id
48323     INTO _taxtypeid
48324   FROM taxtype
48325   WHERE (taxtype_name='Adjustment');
48326
48327   RETURN _taxtypeid;
48328 END;
48329 $$;
48330
48331
48332 ALTER FUNCTION public.getadjustmenttaxtypeid() OWNER TO admin;
48333
48334 --
48335 -- TOC entry 1660 (class 1255 OID 146566239)
48336 -- Dependencies: 4536 8
48337 -- Name: getaropenid(text, character, text); Type: FUNCTION; Schema: public; Owner: admin
48338 --
48339
48340 CREATE FUNCTION getaropenid(text, character, text) RETURNS integer
48341     LANGUAGE plpgsql
48342     AS $_$
48343 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48344 -- See www.xtuple.com/CPAL for the full text of the software license.
48345 DECLARE
48346   pCustNumber ALIAS FOR $1;
48347   pDocType ALIAS FOR $2;
48348   pDocNumber ALIAS FOR $3;
48349   _returnVal INTEGER;
48350 BEGIN
48351   IF ((pCustNumber IS NULL) OR (pDocType IS NULL) OR (pDocNumber IS NULL)) THEN
48352         RETURN NULL;
48353   END IF;
48354
48355   SELECT aropen_id INTO _returnVal
48356   FROM aropen
48357   WHERE ((aropen_cust_id=getCustId(pCustNumber,true))
48358     AND  (UPPER(aropen_doctype)=UPPER(pDocType))
48359     AND  (UPPER(aropen_docnumber)=UPPER(pDocNumber)));
48360
48361   IF (_returnVal IS NULL) THEN
48362         RAISE EXCEPTION 'AR Open Item % not found.', pDocNumber;
48363   END IF;
48364
48365   RETURN _returnVal;
48366 END;
48367 $_$;
48368
48369
48370 ALTER FUNCTION public.getaropenid(text, character, text) OWNER TO admin;
48371
48372 --
48373 -- TOC entry 1661 (class 1255 OID 146566240)
48374 -- Dependencies: 4536 8
48375 -- Name: getbankaccntid(text); Type: FUNCTION; Schema: public; Owner: admin
48376 --
48377
48378 CREATE FUNCTION getbankaccntid(text) RETURNS integer
48379     LANGUAGE plpgsql
48380     AS $_$
48381 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48382 -- See www.xtuple.com/CPAL for the full text of the software license.
48383 DECLARE
48384   pBankAccntName ALIAS FOR $1;
48385   _returnVal INTEGER;
48386 BEGIN
48387   IF (pBankAccntName IS NULL) THEN
48388         RETURN NULL;
48389   END IF;
48390
48391   SELECT bankaccnt_id INTO _returnVal
48392   FROM bankaccnt
48393   WHERE (UPPER(bankaccnt_name)=UPPER(pBankAccntName));
48394
48395   IF (_returnVal IS NULL) THEN
48396         RAISE EXCEPTION 'Bank Account % not found.', pBankAccntName;
48397   END IF;
48398
48399   RETURN _returnVal;
48400 END;
48401 $_$;
48402
48403
48404 ALTER FUNCTION public.getbankaccntid(text) OWNER TO admin;
48405
48406 --
48407 -- TOC entry 1662 (class 1255 OID 146566241)
48408 -- Dependencies: 4536 8
48409 -- Name: getbomitemid(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
48410 --
48411
48412 CREATE FUNCTION getbomitemid(text, text, text) RETURNS integer
48413     LANGUAGE plpgsql
48414     AS $_$
48415 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48416 -- See www.xtuple.com/CPAL for the full text of the software license.
48417 DECLARE
48418   pItemNumber ALIAS FOR $1;
48419   pRevision ALIAS FOR $2;
48420   pSeqNumber ALIAS FOR $3;
48421   _returnVal INTEGER;
48422   
48423 BEGIN
48424   IF ((pItemNumber IS NULL) OR (pSeqNumber IS NULL) OR (pItemNumber = '') OR (pSeqNumber = '') ) THEN
48425     RETURN NULL;
48426   END IF;
48427
48428   SELECT bomitem_id INTO _returnVal
48429   FROM bomitem(getItemId(pItemNumber),COALESCE(getRevId('BOM',pItemNumber,pRevision)))
48430   WHERE (bomitem_seqnumber=pSeqNumber);
48431     
48432   IF (_returnVal IS NULL) THEN
48433     RAISE EXCEPTION 'Sequence % on Bill of Material % Revision % not found.', pSeqNumber, pItemNumber, pRevision;
48434   END IF;
48435
48436   RETURN _returnVal;
48437 END;
48438 $_$;
48439
48440
48441 ALTER FUNCTION public.getbomitemid(text, text, text) OWNER TO admin;
48442
48443 --
48444 -- TOC entry 1650 (class 1255 OID 146566242)
48445 -- Dependencies: 4536 8
48446 -- Name: getbooitemseqid(text, text); Type: FUNCTION; Schema: public; Owner: admin
48447 --
48448
48449 CREATE FUNCTION getbooitemseqid(text, text) RETURNS integer
48450     LANGUAGE plpgsql
48451     AS $_$
48452 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48453 -- See www.xtuple.com/CPAL for the full text of the software license.
48454 DECLARE
48455   pItemNumber ALIAS FOR $1;
48456   pSeqNumber ALIAS FOR $2;
48457   _revid INTEGER;
48458   _returnVal INTEGER;
48459   
48460 BEGIN
48461   IF ((pItemNumber IS NULL) OR (pSeqNumber IS NULL)) THEN
48462     RETURN NULL;
48463   END IF;
48464
48465   IF (NOT fetchMetricBool('Routings')) THEN
48466     RETURN -1;
48467   ELSE
48468     SELECT booitem_seq_id INTO _returnVal
48469     FROM booitem(getItemId(pItemNumber))
48470     WHERE (booitem_seqnumber=CAST(pSeqNumber AS integer));
48471   END IF;
48472     
48473   IF (_returnVal IS NULL) THEN
48474     RAISE EXCEPTION 'Boo Sequence % for Item % not found.', pSeqNumber, pItemNumber;
48475   END IF;
48476
48477   RETURN _returnVal;
48478 END;
48479 $_$;
48480
48481
48482 ALTER FUNCTION public.getbooitemseqid(text, text) OWNER TO admin;
48483
48484 --
48485 -- TOC entry 1663 (class 1255 OID 146566243)
48486 -- Dependencies: 4536 8
48487 -- Name: getbudgheadid(text); Type: FUNCTION; Schema: public; Owner: admin
48488 --
48489
48490 CREATE FUNCTION getbudgheadid(text) RETURNS integer
48491     LANGUAGE plpgsql
48492     AS $_$
48493 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48494 -- See www.xtuple.com/CPAL for the full text of the software license.
48495 DECLARE
48496   pBudghead ALIAS FOR $1;
48497   _returnVal INTEGER;
48498 BEGIN
48499   IF (pBudghead IS NULL) THEN
48500         RETURN NULL;
48501   END IF;
48502
48503   SELECT budghead_id INTO _returnVal
48504   FROM budghead
48505   WHERE (budghead_name=(pBudghead));
48506
48507   IF (_returnVal IS NULL) THEN
48508     RAISE EXCEPTION 'Budget % not found.', pBudghead;
48509   END IF;
48510
48511   RETURN _returnVal;
48512 END;
48513 $_$;
48514
48515
48516 ALTER FUNCTION public.getbudgheadid(text) OWNER TO admin;
48517
48518 --
48519 -- TOC entry 1664 (class 1255 OID 146566244)
48520 -- Dependencies: 4536 8
48521 -- Name: getcashrcptid(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
48522 --
48523
48524 CREATE FUNCTION getcashrcptid(text, text, text) RETURNS integer
48525     LANGUAGE plpgsql
48526     AS $_$
48527 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48528 -- See www.xtuple.com/CPAL for the full text of the software license.
48529 DECLARE
48530   pCustNumber ALIAS FOR $1;
48531   pFundsType ALIAS FOR $2;
48532   pDocNumber ALIAS FOR $3;
48533   _returnVal INTEGER;
48534 BEGIN
48535   IF ((pCustNumber IS NULL) OR (pFundsType IS NULL) OR (pDocNumber IS NULL)) THEN
48536         RETURN NULL;
48537   END IF;
48538
48539   SELECT cashrcpt_id INTO _returnVal
48540   FROM cashrcpt
48541   WHERE ((cashrcpt_cust_id=getCustId(pCustNumber,true))
48542     AND  (UPPER(cashrcpt_fundstype)=UPPER(pFundsType))
48543     AND  (UPPER(cashrcpt_docnumber)=UPPER(pDocNumber)));
48544
48545   IF (_returnVal IS NULL) THEN
48546         RAISE EXCEPTION 'Cash Receipt % not found.', pDocNumber;
48547   END IF;
48548
48549   RETURN _returnVal;
48550 END;
48551 $_$;
48552
48553
48554 ALTER FUNCTION public.getcashrcptid(text, text, text) OWNER TO admin;
48555
48556 --
48557 -- TOC entry 1665 (class 1255 OID 146566245)
48558 -- Dependencies: 4536 8
48559 -- Name: getcharid(text, text); Type: FUNCTION; Schema: public; Owner: admin
48560 --
48561
48562 CREATE FUNCTION getcharid(pchar text, ptype text) RETURNS integer
48563     LANGUAGE plpgsql STABLE
48564     AS $$
48565 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48566 -- See www.xtuple.com/CPAL for the full text of the software license.
48567 DECLARE
48568   _returnVal INTEGER;
48569 BEGIN
48570   IF (COALESCE(pChar, '') = '') THEN
48571     RETURN NULL;
48572   END IF;
48573
48574   SELECT char_id INTO _returnVal
48575   FROM char
48576   WHERE ((char_name=pChar)
48577   AND ((pType IN ('C','CT') AND char_customers)
48578     OR (pType IN ('I','SI','QI','W','PI','TI') AND char_items)
48579     OR (pType='CRMACCT' AND char_crmaccounts)
48580     OR (pType='ADDR' AND char_addresses)
48581     OR (pType='CNTCT' AND char_contacts)
48582     OR (pType='LS' AND char_lotserial)
48583     OR (pType='EMP' AND char_employees)
48584     OR (pType='INCDT' AND char_incidents)
48585     )) LIMIT 1;
48586
48587   IF (_returnVal IS NULL) THEN
48588         RAISE EXCEPTION 'Characteristic % not found.', pChar;
48589   END IF;
48590
48591   RETURN _returnVal;
48592 END;
48593 $$;
48594
48595
48596 ALTER FUNCTION public.getcharid(pchar text, ptype text) OWNER TO admin;
48597
48598 --
48599 -- TOC entry 1666 (class 1255 OID 146566246)
48600 -- Dependencies: 4536 8
48601 -- Name: getclasscodeid(text); Type: FUNCTION; Schema: public; Owner: admin
48602 --
48603
48604 CREATE FUNCTION getclasscodeid(text) RETURNS integer
48605     LANGUAGE plpgsql
48606     AS $_$
48607 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48608 -- See www.xtuple.com/CPAL for the full text of the software license.
48609 DECLARE
48610   pClassCode ALIAS FOR $1;
48611   _returnVal INTEGER;
48612 BEGIN
48613   IF (pClassCode IS NULL) THEN
48614     RETURN NULL;
48615   END IF;
48616
48617   SELECT classcode_id INTO _returnVal
48618   FROM classcode
48619   WHERE (classcode_code=pClassCode);
48620
48621   IF (_returnVal IS NULL) THEN
48622         RAISE EXCEPTION 'Class Code % not found.', pClassCode;
48623   END IF;
48624
48625   RETURN _returnVal;
48626 END;
48627 $_$;
48628
48629
48630 ALTER FUNCTION public.getclasscodeid(text) OWNER TO admin;
48631
48632 --
48633 -- TOC entry 1667 (class 1255 OID 146566247)
48634 -- Dependencies: 4536 8
48635 -- Name: getcmheadid(text); Type: FUNCTION; Schema: public; Owner: admin
48636 --
48637
48638 CREATE FUNCTION getcmheadid(text) RETURNS integer
48639     LANGUAGE plpgsql
48640     AS $_$
48641 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48642 -- See www.xtuple.com/CPAL for the full text of the software license.
48643 DECLARE
48644   pCreditMemoNumber ALIAS FOR $1;
48645 BEGIN
48646   RETURN getCmheadId(pCreditMemoNumber, NULL);
48647 END;
48648 $_$;
48649
48650
48651 ALTER FUNCTION public.getcmheadid(text) OWNER TO admin;
48652
48653 --
48654 -- TOC entry 1668 (class 1255 OID 146566248)
48655 -- Dependencies: 4536 8
48656 -- Name: getcmheadid(text, boolean); Type: FUNCTION; Schema: public; Owner: admin
48657 --
48658
48659 CREATE FUNCTION getcmheadid(text, boolean) RETURNS integer
48660     LANGUAGE plpgsql
48661     AS $_$
48662 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48663 -- See www.xtuple.com/CPAL for the full text of the software license.
48664 DECLARE
48665   pCreditMemoNumber ALIAS FOR $1;
48666   pPosted ALIAS FOR $2;
48667   _returnVal INTEGER;
48668 BEGIN
48669   IF (pCreditMemoNumber IS NULL) THEN
48670     RETURN NULL;
48671   END IF;
48672
48673   SELECT cmhead_id INTO _returnVal
48674   FROM cmhead
48675   WHERE (UPPER(cmhead_number)=UPPER(pCreditMemoNumber))
48676     AND ((pPosted IS NULL) OR (cmhead_posted=pPosted));
48677
48678   IF (_returnVal IS NULL) THEN
48679         RAISE EXCEPTION 'Credit Memo % not found.', pCreditMemoNumber;
48680   END IF;
48681
48682   RETURN _returnVal;
48683 END;
48684 $_$;
48685
48686
48687 ALTER FUNCTION public.getcmheadid(text, boolean) OWNER TO admin;
48688
48689 --
48690 -- TOC entry 1669 (class 1255 OID 146566249)
48691 -- Dependencies: 4536 8
48692 -- Name: getcmnttypeid(text); Type: FUNCTION; Schema: public; Owner: admin
48693 --
48694
48695 CREATE FUNCTION getcmnttypeid(text) RETURNS integer
48696     LANGUAGE plpgsql
48697     AS $_$
48698 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48699 -- See www.xtuple.com/CPAL for the full text of the software license.
48700 DECLARE
48701   pCmntType ALIAS FOR $1;
48702   _returnVal INTEGER;
48703 BEGIN
48704   IF (COALESCE(TRIM(pCmntType), '') = '') THEN
48705     RETURN NULL;
48706   END IF;
48707
48708   SELECT cmnttype_id INTO _returnVal
48709   FROM cmnttype
48710   WHERE (cmnttype_name=pCmntType) LIMIT 1;
48711
48712   IF (_returnVal IS NULL) THEN
48713         RAISE EXCEPTION 'Comment Type % not found.', pCmntType;
48714   END IF;
48715
48716   RETURN _returnVal;
48717 END;
48718 $_$;
48719
48720
48721 ALTER FUNCTION public.getcmnttypeid(text) OWNER TO admin;
48722
48723 --
48724 -- TOC entry 1670 (class 1255 OID 146566250)
48725 -- Dependencies: 4536 8
48726 -- Name: getcntctid(text); Type: FUNCTION; Schema: public; Owner: admin
48727 --
48728
48729 CREATE FUNCTION getcntctid(pcontactnumber text) RETURNS integer
48730     LANGUAGE plpgsql STABLE
48731     AS $$
48732 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48733 -- See www.xtuple.com/CPAL for the full text of the software license.
48734 DECLARE
48735   _returnVal INTEGER;
48736 BEGIN
48737   SELECT getCntctId(pContactNumber,true) INTO _returnVal;
48738
48739   RETURN _returnVal;
48740 END;
48741 $$;
48742
48743
48744 ALTER FUNCTION public.getcntctid(pcontactnumber text) OWNER TO admin;
48745
48746 --
48747 -- TOC entry 1671 (class 1255 OID 146566251)
48748 -- Dependencies: 4536 8
48749 -- Name: getcntctid(text, boolean); Type: FUNCTION; Schema: public; Owner: admin
48750 --
48751
48752 CREATE FUNCTION getcntctid(pcontactnumber text, pnotfounderr boolean) RETURNS integer
48753     LANGUAGE plpgsql STABLE
48754     AS $$
48755 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48756 -- See www.xtuple.com/CPAL for the full text of the software license.
48757 DECLARE
48758   _returnVal INTEGER;
48759 BEGIN
48760   IF (COALESCE(TRIM(pContactNumber), '') = '') THEN
48761     RETURN NULL;
48762   END IF;
48763
48764   SELECT cntct_id INTO _returnVal
48765   FROM cntct
48766   WHERE (cntct_number=pContactNumber);
48767
48768   IF (_returnVal IS NULL AND pNotFoundErr) THEN
48769     RAISE EXCEPTION 'Contact Number % not found.', pContactNumber;
48770   ELSIF (_returnVal IS NULL) THEN
48771     RETURN NULL;
48772   END IF;
48773
48774   RETURN _returnVal;
48775 END;
48776 $$;
48777
48778
48779 ALTER FUNCTION public.getcntctid(pcontactnumber text, pnotfounderr boolean) OWNER TO admin;
48780
48781 --
48782 -- TOC entry 1672 (class 1255 OID 146566252)
48783 -- Dependencies: 4536 8
48784 -- Name: getcoheadid(text); Type: FUNCTION; Schema: public; Owner: admin
48785 --
48786
48787 CREATE FUNCTION getcoheadid(text) RETURNS integer
48788     LANGUAGE plpgsql
48789     AS $_$
48790 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48791 -- See www.xtuple.com/CPAL for the full text of the software license.
48792 DECLARE
48793   pSalesOrderNumber ALIAS FOR $1;
48794   _returnVal INTEGER;
48795 BEGIN
48796   IF (pSalesOrderNumber IS NULL) THEN
48797     RETURN NULL;
48798   END IF;
48799
48800   SELECT cohead_id INTO _returnVal
48801   FROM cohead
48802   WHERE (cohead_number=pSalesOrderNumber);
48803
48804   IF (_returnVal IS NULL) THEN
48805         RAISE EXCEPTION 'Sales Order % not found.', pSalesOrderNumber;
48806   END IF;
48807
48808   RETURN _returnVal;
48809 END;
48810 $_$;
48811
48812
48813 ALTER FUNCTION public.getcoheadid(text) OWNER TO admin;
48814
48815 --
48816 -- TOC entry 1674 (class 1255 OID 146566253)
48817 -- Dependencies: 4536 8
48818 -- Name: getcoitemid(text, text); Type: FUNCTION; Schema: public; Owner: admin
48819 --
48820
48821 CREATE FUNCTION getcoitemid(text, text) RETURNS integer
48822     LANGUAGE plpgsql
48823     AS $_$
48824 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48825 -- See www.xtuple.com/CPAL for the full text of the software license.
48826 DECLARE
48827   pSalesOrderNumber     ALIAS FOR $1;
48828   pLineNumber           ALIAS FOR $2;
48829   _linenumber           INTEGER;
48830   _subnumber            INTEGER;
48831   _returnVal            INTEGER;
48832 BEGIN
48833   IF (pSalesOrderNumber IS NULL OR pLineNumber IS NULL) THEN
48834     RETURN NULL;
48835   END IF;
48836
48837   --Parse Line Number
48838   IF (position('.' in pLineNumber) > 0) THEN
48839     _linenumber := CAST(substring(pLineNumber from 1 for position('.' in pLineNumber)-1) AS INTEGER);
48840     _subnumber  := CAST(substring(pLineNumber from position('.' in pLineNumber)+1 for length(pLineNumber)) AS INTEGER);
48841   ELSE
48842     _linenumber := CAST(pLineNumber AS INTEGER);
48843     _subnumber  := 0;
48844   END IF;
48845
48846   SELECT coitem_id INTO _returnVal
48847   FROM cohead, coitem
48848   WHERE ((cohead_number=pSalesOrderNumber)
48849   AND (coitem_cohead_id=cohead_id)
48850   AND (coitem_linenumber=_linenumber)
48851   AND (coitem_subnumber=_subnumber));
48852
48853   IF (_returnVal IS NULL) THEN
48854         RAISE EXCEPTION 'Sales Order % not found.', pSalesOrderNumber;
48855   END IF;
48856
48857   RETURN _returnVal;
48858 END;
48859 $_$;
48860
48861
48862 ALTER FUNCTION public.getcoitemid(text, text) OWNER TO admin;
48863
48864 --
48865 -- TOC entry 1675 (class 1255 OID 146566254)
48866 -- Dependencies: 4536 8
48867 -- Name: getcontrcteffective(text); Type: FUNCTION; Schema: public; Owner: admin
48868 --
48869
48870 CREATE FUNCTION getcontrcteffective(pcontrctnumber text) RETURNS date
48871     LANGUAGE plpgsql
48872     AS $$
48873 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48874 -- See www.xtuple.com/CPAL for the full text of the software license.
48875 DECLARE
48876   _returnVal DATE;
48877 BEGIN
48878   IF (pContrctNumber IS NULL) THEN
48879     RETURN NULL;
48880   END IF;
48881
48882   SELECT contrct_effective INTO _returnVal
48883   FROM contrct
48884   WHERE (contrct_number=pContrctNumber);
48885
48886   IF (_returnVal IS NULL) THEN
48887         RAISE EXCEPTION 'Contract Number % not found.', pContrctNumber;
48888   END IF;
48889
48890   RETURN _returnVal;
48891 END;
48892 $$;
48893
48894
48895 ALTER FUNCTION public.getcontrcteffective(pcontrctnumber text) OWNER TO admin;
48896
48897 --
48898 -- TOC entry 1676 (class 1255 OID 146566255)
48899 -- Dependencies: 4536 8
48900 -- Name: getcontrctexpires(text); Type: FUNCTION; Schema: public; Owner: admin
48901 --
48902
48903 CREATE FUNCTION getcontrctexpires(pcontrctnumber text) RETURNS date
48904     LANGUAGE plpgsql
48905     AS $$
48906 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48907 -- See www.xtuple.com/CPAL for the full text of the software license.
48908 DECLARE
48909   _returnVal DATE;
48910 BEGIN
48911   IF (pContrctNumber IS NULL) THEN
48912     RETURN NULL;
48913   END IF;
48914
48915   SELECT contrct_expires INTO _returnVal
48916   FROM contrct
48917   WHERE (contrct_number=pContrctNumber);
48918
48919   IF (_returnVal IS NULL) THEN
48920         RAISE EXCEPTION 'Contract Number % not found.', pContrctNumber;
48921   END IF;
48922
48923   RETURN _returnVal;
48924 END;
48925 $$;
48926
48927
48928 ALTER FUNCTION public.getcontrctexpires(pcontrctnumber text) OWNER TO admin;
48929
48930 --
48931 -- TOC entry 1677 (class 1255 OID 146566256)
48932 -- Dependencies: 4536 8
48933 -- Name: getcontrctid(text); Type: FUNCTION; Schema: public; Owner: admin
48934 --
48935
48936 CREATE FUNCTION getcontrctid(pcontrctnumber text) RETURNS integer
48937     LANGUAGE plpgsql
48938     AS $$
48939 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48940 -- See www.xtuple.com/CPAL for the full text of the software license.
48941 DECLARE
48942   _returnVal INTEGER;
48943 BEGIN
48944   IF (pContrctNumber IS NULL) THEN
48945     RETURN NULL;
48946   END IF;
48947
48948   SELECT contrct_id INTO _returnVal
48949   FROM contrct
48950   WHERE (contrct_number=pContrctNumber);
48951
48952   IF (_returnVal IS NULL) THEN
48953         RAISE EXCEPTION 'Contract Number % not found.', pContrctNumber;
48954   END IF;
48955
48956   RETURN _returnVal;
48957 END;
48958 $$;
48959
48960
48961 ALTER FUNCTION public.getcontrctid(pcontrctnumber text) OWNER TO admin;
48962
48963 --
48964 -- TOC entry 1678 (class 1255 OID 146566257)
48965 -- Dependencies: 4536 8
48966 -- Name: getcostcatid(text); Type: FUNCTION; Schema: public; Owner: admin
48967 --
48968
48969 CREATE FUNCTION getcostcatid(text) RETURNS integer
48970     LANGUAGE plpgsql
48971     AS $_$
48972 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
48973 -- See www.xtuple.com/CPAL for the full text of the software license.
48974 DECLARE
48975   pCostCat ALIAS FOR $1;
48976   _returnVal INTEGER;
48977 BEGIN
48978   IF (pCostCat IS NULL) THEN
48979         RETURN NULL;
48980   END IF;
48981
48982   SELECT costcat_id INTO _returnVal
48983   FROM costcat
48984   WHERE (costcat_code=pCostCat);
48985
48986   IF (_returnVal IS NULL) THEN
48987         RAISE EXCEPTION 'Cost Category Code % not found.', pCostCat;
48988   END IF;
48989
48990   RETURN _returnVal;
48991 END;
48992 $_$;
48993
48994
48995 ALTER FUNCTION public.getcostcatid(text) OWNER TO admin;
48996
48997 --
48998 -- TOC entry 1679 (class 1255 OID 146566258)
48999 -- Dependencies: 4536 8
49000 -- Name: getcostelemid(text); Type: FUNCTION; Schema: public; Owner: admin
49001 --
49002
49003 CREATE FUNCTION getcostelemid(text) RETURNS integer
49004     LANGUAGE plpgsql
49005     AS $_$
49006 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49007 -- See www.xtuple.com/CPAL for the full text of the software license.
49008 DECLARE
49009   pCostElemType ALIAS FOR $1;
49010   _returnVal INTEGER;
49011 BEGIN
49012   IF (pCostElemType IS NULL) THEN
49013         RETURN NULL;
49014   END IF;
49015
49016   SELECT costelem_id INTO _returnVal
49017   FROM costelem
49018   WHERE (costelem_type=pCostElemType);
49019
49020   IF (_returnVal IS NULL) THEN
49021         RAISE EXCEPTION 'Cost Element % not found.', pCostElemType;
49022   END IF;
49023
49024   RETURN _returnVal;
49025 END;
49026 $_$;
49027
49028
49029 ALTER FUNCTION public.getcostelemid(text) OWNER TO admin;
49030
49031 --
49032 -- TOC entry 1680 (class 1255 OID 146566259)
49033 -- Dependencies: 4536 8
49034 -- Name: getcrmacctid(text); Type: FUNCTION; Schema: public; Owner: admin
49035 --
49036
49037 CREATE FUNCTION getcrmacctid(pacctnumber text) RETURNS integer
49038     LANGUAGE plpgsql STABLE
49039     AS $$
49040 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49041 -- See www.xtuple.com/CPAL for the full text of the software license.
49042 DECLARE
49043   _returnVal INTEGER;
49044 BEGIN
49045   
49046   IF (pAcctNumber IS NULL) THEN
49047     RETURN NULL;
49048   END IF;
49049
49050   SELECT crmacct_id INTO _returnVal
49051   FROM crmacct
49052   WHERE (UPPER(crmacct_number)=UPPER(pAcctNumber));
49053   
49054   IF (_returnVal IS NULL) THEN
49055       RAISE EXCEPTION 'CRM Account Number % not found.', pAcctNumber;
49056   END IF;
49057
49058   RETURN _returnVal;
49059 END;
49060 $$;
49061
49062
49063 ALTER FUNCTION public.getcrmacctid(pacctnumber text) OWNER TO admin;
49064
49065 --
49066 -- TOC entry 1681 (class 1255 OID 146566260)
49067 -- Dependencies: 4536 8
49068 -- Name: getcurrid(text); Type: FUNCTION; Schema: public; Owner: admin
49069 --
49070
49071 CREATE FUNCTION getcurrid(pcurrname text) RETURNS integer
49072     LANGUAGE plpgsql STABLE
49073     AS $$
49074 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49075 -- See www.xtuple.com/CPAL for the full text of the software license.
49076 DECLARE
49077   _returnVal INTEGER;
49078 BEGIN
49079   IF (pCurrName IS NULL) THEN
49080         RETURN NULL;
49081   END IF;
49082
49083   SELECT curr_id INTO _returnVal
49084   FROM curr_symbol
49085   WHERE (curr_abbr=pCurrName);
49086
49087   IF (_returnVal IS NULL) THEN
49088         RAISE EXCEPTION 'Currency % not found.', pCurrName;
49089   END IF;
49090
49091   RETURN _returnVal;
49092 END;
49093 $$;
49094
49095
49096 ALTER FUNCTION public.getcurrid(pcurrname text) OWNER TO admin;
49097
49098 --
49099 -- TOC entry 1682 (class 1255 OID 146566261)
49100 -- Dependencies: 4536 8
49101 -- Name: getcustid(text); Type: FUNCTION; Schema: public; Owner: admin
49102 --
49103
49104 CREATE FUNCTION getcustid(pcustnumber text) RETURNS integer
49105     LANGUAGE plpgsql STABLE
49106     AS $$
49107 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49108 -- See www.xtuple.com/CPAL for the full text of the software license.
49109 DECLARE
49110   _returnVal INTEGER;
49111 BEGIN
49112   
49113   SELECT getCustId(pCustNumber,false) INTO _returnVal;
49114
49115   RETURN _returnVal;
49116 END;
49117 $$;
49118
49119
49120 ALTER FUNCTION public.getcustid(pcustnumber text) OWNER TO admin;
49121
49122 --
49123 -- TOC entry 1683 (class 1255 OID 146566262)
49124 -- Dependencies: 4536 8
49125 -- Name: getcustid(text, boolean); Type: FUNCTION; Schema: public; Owner: admin
49126 --
49127
49128 CREATE FUNCTION getcustid(pcustnumber text, pinclprospects boolean) RETURNS integer
49129     LANGUAGE plpgsql STABLE
49130     AS $$
49131 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49132 -- See www.xtuple.com/CPAL for the full text of the software license.
49133 DECLARE
49134   _returnVal INTEGER;
49135 BEGIN
49136   IF (pCustNumber IS NULL) THEN
49137     RETURN NULL;
49138   END IF;
49139
49140   SELECT cust_id INTO _returnVal
49141   FROM custinfo
49142   WHERE (cust_number=UPPER(pCustNumber));
49143   
49144   IF (_returnVal IS NULL) THEN
49145     IF (pInclProspects) THEN
49146       SELECT prospect_id INTO _returnVal
49147       FROM prospect
49148       WHERE (UPPER(prospect_number)=UPPER(pCustNumber));
49149       IF (_returnVal IS NULL) THEN
49150         RAISE EXCEPTION 'Neither Customer nor Prospect Number % found.', pCustNumber;
49151       END IF;
49152     ELSE
49153       RAISE EXCEPTION 'Customer Number % not found.', pCustNumber;
49154     END IF;
49155   END IF;
49156
49157   RETURN _returnVal;
49158 END;
49159 $$;
49160
49161
49162 ALTER FUNCTION public.getcustid(pcustnumber text, pinclprospects boolean) OWNER TO admin;
49163
49164 --
49165 -- TOC entry 1673 (class 1255 OID 146566263)
49166 -- Dependencies: 4536 8
49167 -- Name: getcustnamefrominfo(text, text, text, text, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
49168 --
49169
49170 CREATE FUNCTION getcustnamefrominfo(text, text, text, text, text, boolean) RETURNS text
49171     LANGUAGE plpgsql
49172     AS $_$
49173 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49174 -- See www.xtuple.com/CPAL for the full text of the software license.
49175 DECLARE
49176   _email        TEXT    := COALESCE(UPPER($1), '');
49177   _company      TEXT    := COALESCE(UPPER($2), '');
49178   _first        TEXT    := COALESCE(UPPER($3), '');
49179   _last         TEXT    := COALESCE(UPPER($4), '');
49180   _fullname     TEXT    := COALESCE(UPPER($5), '');
49181   _generate     BOOLEAN := COALESCE($6, FALSE);
49182   _counter      INTEGER;
49183   _custcount    INTEGER := 0;
49184   _custname     TEXT;
49185   _candidate    RECORD;
49186   _r            RECORD;
49187 BEGIN
49188   IF (_email != '') THEN
49189     SELECT count(*), cust_name INTO _custcount, _custname
49190     FROM custinfo LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
49191     WHERE (UPPER(cntct_email)=_email)
49192     GROUP BY cust_name;
49193     IF (NOT FOUND) THEN
49194       _custcount := 0;
49195     ELSIF(_custcount = 1) THEN
49196       RETURN _custname;
49197     END IF;
49198   END IF;
49199
49200   IF (_company != '') THEN
49201     SELECT count(*), cust_name INTO _custcount, _custname
49202     FROM custinfo
49203     WHERE (UPPER(cust_name)=_company)
49204     GROUP BY cust_name;
49205     IF (NOT FOUND) THEN
49206       _custcount := 0;
49207     ELSIF(_custcount = 1) THEN
49208       RETURN _custname;
49209     END IF;
49210   END IF;
49211
49212   IF (_fullname = '' AND (_first != '' OR _last != '')) THEN
49213     _fullname := TRIM(_first || ' ' || _last);
49214   END IF;
49215
49216   IF (_custcount <= 0 AND _fullname != '') THEN
49217     SELECT count(*), cust_name INTO _custcount, _custname
49218     FROM custinfo
49219     WHERE (UPPER(cust_name)=_fullname)
49220     GROUP BY cust_name;
49221     IF (NOT FOUND) THEN
49222       _custcount := 0;
49223     ELSIF(_custcount = 1) THEN
49224       RETURN _custname;
49225     END IF;
49226   END IF;
49227
49228   IF (_custcount > 1) THEN
49229     RAISE EXCEPTION 'Found % possible Customers for % and % and %',
49230                     _custcount, _email, _company, _fullname;
49231   END IF;
49232
49233   IF (_custcount <= 0 AND _generate) THEN
49234     IF (_company != '') THEN
49235       RETURN _company;
49236     ELSIF (_email != '') THEN
49237       RETURN _email;
49238     ELSIF (_fullname != '') THEN
49239       RETURN _fullname;
49240     ELSE
49241       RAISE EXCEPTION 'Could not generate a new Customer Name without an email address or the name of a company or person';
49242     END IF;
49243   END IF;
49244
49245   IF (_custname IS NULL OR _custname = '') THEN
49246     RAISE EXCEPTION 'Could not find Customer Name for % and %',
49247                     _company, _fullname;
49248   END IF;
49249
49250   RETURN _custname;
49251 END;
49252 $_$;
49253
49254
49255 ALTER FUNCTION public.getcustnamefrominfo(text, text, text, text, text, boolean) OWNER TO admin;
49256
49257 --
49258 -- TOC entry 1685 (class 1255 OID 146566264)
49259 -- Dependencies: 4536 8
49260 -- Name: getcustnumberfrominfo(text, text, text, text, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
49261 --
49262
49263 CREATE FUNCTION getcustnumberfrominfo(text, text, text, text, text, boolean) RETURNS text
49264     LANGUAGE plpgsql
49265     AS $_$
49266 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
49267 -- See www.xtuple.com/CPAL for the full text of the software license.
49268 DECLARE
49269   _email        TEXT    := COALESCE(UPPER($1), '');
49270   _company      TEXT    := COALESCE(UPPER($2), '');
49271   _first        TEXT    := COALESCE(UPPER($3), '');
49272   _last         TEXT    := COALESCE(UPPER($4), '');
49273   _fullname     TEXT    := COALESCE(UPPER($5), TRIM(_first || ' ' || _last));
49274   _generate     BOOLEAN := COALESCE($6, FALSE);
49275   _counter      INTEGER;
49276   _custcount    INTEGER := 0;
49277   _custnumber   TEXT;
49278   _candidate    TEXT    := '';
49279   _loopmax      INTEGER := 0;
49280   _minlength    INTEGER := 5;
49281   _maxlength    INTEGER := 8;
49282   _numformat    TEXT    := '';
49283   _testme       TEXT;
49284 BEGIN
49285   IF (_email != '') THEN
49286     SELECT count(*), cust_number INTO _custcount, _custnumber
49287     FROM custinfo LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
49288     WHERE (UPPER(cntct_email)=_email)
49289     GROUP BY cust_number;
49290     IF (NOT FOUND) THEN
49291       _custcount := 0;
49292     ELSIF(_custcount = 1) THEN
49293       RETURN _custnumber;
49294     END IF;
49295   END IF;
49296
49297   IF (_company != '') THEN
49298     SELECT count(*), cust_number INTO _custcount, _custnumber
49299     FROM custinfo
49300     WHERE (UPPER(cust_name)=_company)
49301     GROUP BY cust_number;
49302     IF (NOT FOUND) THEN
49303       _custcount := 0;
49304     ELSIF(_custcount = 1) THEN
49305       RETURN _custnumber;
49306     END IF;
49307   END IF;
49308
49309   IF (_fullname = '' AND (_first != '' OR _last != '')) THEN
49310     _fullname := TRIM(_first || ' ' || _last);
49311   END IF;
49312
49313   IF (_custcount <= 0 AND _fullname != '') THEN
49314     SELECT count(*), cust_number INTO _custcount, _custnumber
49315     FROM custinfo
49316     WHERE (UPPER(cust_name)=_fullname)
49317     GROUP BY cust_number;
49318     IF (NOT FOUND) THEN
49319       _custcount := 0;
49320     ELSIF(_custcount = 1) THEN
49321       RETURN _custnumber;
49322     END IF;
49323   END IF;
49324
49325   IF (_custcount > 1) THEN
49326     RAISE EXCEPTION 'Found % possible Customers for % and % and %',
49327                     _custcount, _email, _company, _fullname;
49328   END IF;
49329
49330   IF (_custcount <= 0 AND _generate) THEN
49331     IF (_maxlength < _minlength) THEN
49332       RAISE EXCEPTION 'Fix getCustNumberFromInfo: max length < min length';
49333     END IF;
49334
49335     IF (_company != '') THEN
49336       _candidate := _company;
49337     ELSIF (_email != '') THEN
49338       _candidate := SUBSTRING(_email FOR POSITION('@' IN _email) - 1);
49339     ELSIF (_last != '') THEN
49340       _candidate := _last;
49341       IF (_first != '') THEN
49342         _candidate := _candidate || _first;
49343       END IF;
49344     ELSIF (_fullname != '' AND (POSITION(' ' IN _fullname) > 0)) THEN
49345       _candidate := SUBSTRING(_fullname FROM POSITION(' ' IN _fullname) + 1) ||
49346                     SUBSTRING(_fullname FOR  POSITION(' ' IN _fullname) - 1);
49347     END IF;
49348     WHILE (POSITION(' ' IN _candidate) > 0) LOOP
49349       _candidate := SUBSTRING(_candidate FOR  POSITION(' ' IN _candidate) - 1) ||
49350                     SUBSTRING(_candidate FROM POSITION(' ' IN _candidate) + 1);
49351     END LOOP;
49352     FOR _counter IN _minlength.._maxlength LOOP
49353       _testme := SUBSTRING(_candidate FOR _counter);
49354       IF (NOT EXISTS(SELECT cust_number
49355                      FROM custinfo
49356                      WHERE (cust_number=_testme))) THEN
49357         _custnumber := _testme;
49358         EXIT;
49359       END IF;
49360     END LOOP;
49361     IF (_custnumber IS NULL OR _custnumber = '') THEN
49362       IF (LENGTH(_candidate) < _minlength) THEN
49363         _minlength := LENGTH(_candidate);
49364       END IF;
49365       FOR _counter IN _minlength.._maxlength LOOP
49366         _loopmax := _loopmax * 10 + 9;
49367         _numformat := _numformat || '0';
49368       END LOOP;
49369       FOR _counter IN 1.._loopmax LOOP
49370         _testme := SUBSTRING(_candidate FOR _minlength) ||
49371                    TRIM(TO_CHAR(_counter, _numformat));
49372         IF (NOT EXISTS(SELECT cust_number
49373                        FROM custinfo
49374                        WHERE (cust_number=_testme))) THEN
49375           _custnumber := _testme;
49376           EXIT;
49377         END IF;
49378       END LOOP;
49379     END IF;
49380     IF (_custnumber IS NULL OR _custnumber = '') THEN
49381       RAISE EXCEPTION 'Could not generate a new Customer Number';
49382     END IF;
49383   END IF;
49384
49385   IF (_custnumber IS NULL OR _custnumber = '') THEN
49386     RAISE EXCEPTION 'Could not find Customer Number for % and % and %',
49387                     _email, _company, _fullname;
49388   END IF;
49389
49390   RETURN _custnumber;
49391 END;
49392 $_$;
49393
49394
49395 ALTER FUNCTION public.getcustnumberfrominfo(text, text, text, text, text, boolean) OWNER TO admin;
49396
49397 --
49398 -- TOC entry 1686 (class 1255 OID 146566265)
49399 -- Dependencies: 4536 8
49400 -- Name: getcusttypeid(text); Type: FUNCTION; Schema: public; Owner: admin
49401 --
49402
49403 CREATE FUNCTION getcusttypeid(text) RETURNS integer
49404     LANGUAGE plpgsql
49405     AS $_$
49406 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49407 -- See www.xtuple.com/CPAL for the full text of the software license.
49408 DECLARE
49409   pCustTypeCode ALIAS FOR $1;
49410   _returnVal INTEGER;
49411 BEGIN
49412   IF (pCustTypeCode IS NULL) THEN
49413     RETURN NULL;
49414   END IF;
49415
49416   SELECT custtype_id INTO _returnVal
49417   FROM custtype
49418   WHERE (custtype_code=pCustTypeCode);
49419
49420   IF (_returnVal IS NULL) THEN
49421         RAISE EXCEPTION 'Customer Type % not found.', pCustTypeCode;
49422   END IF;
49423
49424   RETURN _returnVal;
49425 END;
49426 $_$;
49427
49428
49429 ALTER FUNCTION public.getcusttypeid(text) OWNER TO admin;
49430
49431 --
49432 -- TOC entry 1687 (class 1255 OID 146566266)
49433 -- Dependencies: 4536 8
49434 -- Name: getdeptid(text); Type: FUNCTION; Schema: public; Owner: admin
49435 --
49436
49437 CREATE FUNCTION getdeptid(text) RETURNS integer
49438     LANGUAGE plpgsql
49439     AS $_$
49440 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49441 -- See www.xtuple.com/CPAL for the full text of the software license.
49442 DECLARE
49443   pDeptNumber ALIAS FOR $1;
49444   _returnVal INTEGER;
49445 BEGIN
49446   IF (COALESCE(TRIM(pDeptNumber), '') = '') THEN
49447     RETURN NULL;
49448   END IF;
49449
49450   SELECT dept_id INTO _returnVal
49451   FROM dept
49452   WHERE (UPPER(dept_number)=UPPER(pDeptNumber));
49453
49454   IF (_returnVal IS NULL) THEN
49455     RAISE EXCEPTION 'Department % not found.', pDeptNumber;
49456   END IF;
49457
49458   RETURN _returnVal;
49459 END;
49460 $_$;
49461
49462
49463 ALTER FUNCTION public.getdeptid(text) OWNER TO admin;
49464
49465 --
49466 -- TOC entry 1688 (class 1255 OID 146566267)
49467 -- Dependencies: 4536 8
49468 -- Name: getediprofileid(text); Type: FUNCTION; Schema: public; Owner: admin
49469 --
49470
49471 CREATE FUNCTION getediprofileid(text) RETURNS integer
49472     LANGUAGE plpgsql
49473     AS $_$
49474 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49475 -- See www.xtuple.com/CPAL for the full text of the software license.
49476 DECLARE
49477   pEdiProfileName ALIAS FOR $1;
49478   _returnVal INTEGER;
49479 BEGIN
49480   IF (pEdiProfileName IS NULL) THEN
49481         RETURN NULL;
49482   END IF;
49483
49484   SELECT pkghead_id INTO _returnVal
49485     FROM pkghead
49486    WHERE(pkghead_name='xtbatch');
49487   IF(NOT FOUND) THEN
49488     RETURN NULL;
49489   END IF;
49490
49491   SELECT ediprofile_id INTO _returnVal
49492   FROM xtbatch.ediprofile
49493   WHERE (ediprofile_name=pEdiProfileName);
49494
49495   IF (_returnVal IS NULL) THEN
49496     RAISE EXCEPTION 'EDI Profile % not found.', pEdiProfileName;
49497   END IF;
49498
49499   RETURN _returnVal;
49500 END;
49501 $_$;
49502
49503
49504 ALTER FUNCTION public.getediprofileid(text) OWNER TO admin;
49505
49506 --
49507 -- TOC entry 1689 (class 1255 OID 146566268)
49508 -- Dependencies: 4536 8
49509 -- Name: getediprofilename(integer); Type: FUNCTION; Schema: public; Owner: admin
49510 --
49511
49512 CREATE FUNCTION getediprofilename(integer) RETURNS text
49513     LANGUAGE plpgsql
49514     AS $_$
49515 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49516 -- See www.xtuple.com/CPAL for the full text of the software license.
49517 DECLARE
49518   pEdiProfileId ALIAS FOR $1;
49519   _returnVal TEXT;
49520 BEGIN
49521   IF (pEdiProfileId IS NULL) THEN
49522         RETURN NULL;
49523   END IF;
49524
49525   SELECT pkghead_name INTO _returnVal
49526     FROM pkghead
49527    WHERE(pkghead_name='xtbatch');
49528   IF(NOT FOUND) THEN
49529     RETURN NULL;
49530   END IF;
49531
49532   SELECT ediprofile_name INTO _returnVal
49533   FROM xtbatch.ediprofile
49534   WHERE (ediprofile_id=pEdiProfileId);
49535
49536   RETURN _returnVal;
49537 END;
49538 $_$;
49539
49540
49541 ALTER FUNCTION public.getediprofilename(integer) OWNER TO admin;
49542
49543 --
49544 -- TOC entry 1690 (class 1255 OID 146566269)
49545 -- Dependencies: 4536 8
49546 -- Name: getempid(text); Type: FUNCTION; Schema: public; Owner: admin
49547 --
49548
49549 CREATE FUNCTION getempid(text) RETURNS integer
49550     LANGUAGE plpgsql
49551     AS $_$
49552 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49553 -- See www.xtuple.com/CPAL for the full text of the software license.
49554 DECLARE
49555   pEmpCode ALIAS FOR $1;
49556   _returnVal INTEGER;
49557 BEGIN
49558   IF (COALESCE(TRIM(pEmpCode), '') = '') THEN
49559     RETURN NULL;
49560   END IF;
49561
49562   SELECT emp_id INTO _returnVal
49563   FROM emp
49564   WHERE (UPPER(emp_code)=UPPER(pEmpCode));
49565
49566   IF (_returnVal IS NULL) THEN
49567     RAISE EXCEPTION 'Employee % not found.', pEmpCode;
49568   END IF;
49569
49570   RETURN _returnVal;
49571 END;
49572 $_$;
49573
49574
49575 ALTER FUNCTION public.getempid(text) OWNER TO admin;
49576
49577 --
49578 -- TOC entry 1691 (class 1255 OID 146566270)
49579 -- Dependencies: 4536 8
49580 -- Name: getexpcatid(text); Type: FUNCTION; Schema: public; Owner: admin
49581 --
49582
49583 CREATE FUNCTION getexpcatid(text) RETURNS integer
49584     LANGUAGE plpgsql
49585     AS $_$
49586 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49587 -- See www.xtuple.com/CPAL for the full text of the software license.
49588 DECLARE
49589   pExpcatCode ALIAS FOR $1;
49590   _returnVal INTEGER;
49591 BEGIN
49592   IF (COALESCE(TRIM(pExpcatCode), '') = '') THEN
49593     RETURN NULL;
49594   END IF;
49595
49596   SELECT expcat_id INTO _returnVal
49597   FROM expcat
49598   WHERE (expcat_code=UPPER(pExpcatCode));
49599
49600   IF (_returnVal IS NULL) THEN
49601     RAISE EXCEPTION 'Expense Category % not found.', pExpcatCode;
49602   END IF;
49603
49604   RETURN _returnVal;
49605 END;
49606 $_$;
49607
49608
49609 ALTER FUNCTION public.getexpcatid(text) OWNER TO admin;
49610
49611 --
49612 -- TOC entry 1692 (class 1255 OID 146566271)
49613 -- Dependencies: 2666 4536 8
49614 -- Name: getflcoldata(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
49615 --
49616
49617 CREATE FUNCTION getflcoldata(integer, integer) RETURNS SETOF flcoldata
49618     LANGUAGE plpgsql
49619     AS $_$
49620 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49621 -- See www.xtuple.com/CPAL for the full text of the software license.
49622 DECLARE
49623   pFlcolid ALIAS FOR $1;
49624   pPeriodid ALIAS FOR $2;
49625   _row flcoldata%ROWTYPE;
49626   _r RECORD;
49627   _start DATE;
49628   _end DATE;
49629   _col INTEGER := 1;
49630   _mult INTEGER;
49631
49632 BEGIN
49633
49634 --Get Layout Data
49635   SELECT * INTO _r
49636   FROM flcol
49637   WHERE (flcol_id=pFlcolid);
49638
49639 -- Handle Month...
49640   IF (_r.flcol_month) THEN
49641     SELECT period_start, period_end INTO _start, _end
49642     FROM period
49643     WHERE (period_id=pPeriodid);
49644     
49645     IF (_r.flcol_showdb) THEN
49646       -- Debits Column
49647       _row.flcoldata_column := _col;
49648       _row.flcoldata_start := _start;
49649       _row.flcoldata_end := _end;
49650       RETURN NEXT _row;
49651       _col := _col + 1;
49652
49653       -- Credits Column
49654       _row.flcoldata_column := _col;
49655       _row.flcoldata_start := _start;
49656       _row.flcoldata_end := _end;
49657       RETURN NEXT _row;
49658       _col := _col + 1;
49659     END IF;
49660
49661     -- Month Column
49662     _row.flcoldata_column := _col;
49663     _row.flcoldata_start := _start;
49664     _row.flcoldata_end := _end;
49665     RETURN NEXT _row;
49666     _col := _col + 1;
49667
49668     -- These don't have drill down
49669     IF (_r.flcol_prcnt) THEN 
49670       _col := _col + 1;
49671     END IF;
49672     IF (_r.flcol_budget) THEN
49673       _col := _col + 1;
49674       IF (_r.flcol_budgetprcnt) THEN
49675         _col := _col + 1;
49676       END IF;
49677       IF (_r.flcol_budgetdiff) THEN
49678         _col := _col + 1;
49679       END IF;
49680       IF (_r.flcol_budgetdiffprcnt) THEN
49681         _col := _col + 1;
49682       END IF;
49683     END IF; 
49684   END IF;
49685
49686 -- Handle Quarter...
49687   IF (_r.flcol_quarter) THEN
49688     SELECT min(qtr.period_start), max(qtr.period_end) INTO _start, _end
49689     FROM period p
49690      JOIN period qtr ON (p.period_quarter=qtr.period_quarter)
49691                      AND (p.period_yearperiod_id=qtr.period_yearperiod_id)
49692     WHERE (p.period_id=pPeriodid);
49693     
49694     IF (_r.flcol_showdb) THEN
49695       -- Debits Column
49696       _row.flcoldata_column := _col;
49697       _row.flcoldata_start := _start;
49698       _row.flcoldata_end := _end;
49699       RETURN NEXT _row;
49700       _col := _col + 1;
49701
49702       -- Credits Column
49703       _row.flcoldata_column := _col;
49704       _row.flcoldata_start := _start;
49705       _row.flcoldata_end := _end;
49706       RETURN NEXT _row;
49707       _col := _col + 1;
49708     END IF;
49709
49710     -- Quarter Column
49711     _row.flcoldata_column := _col;
49712     _row.flcoldata_start := _start;
49713     _row.flcoldata_end := _end;
49714     RETURN NEXT _row;
49715     _col := _col + 1;
49716
49717     -- These don't have drill down
49718     IF (_r.flcol_prcnt) THEN 
49719       _col := _col + 1;
49720     END IF;
49721     IF (_r.flcol_budget) THEN
49722       _col := _col + 1;
49723       IF (_r.flcol_budgetprcnt) THEN
49724         _col := _col + 1;
49725       END IF;
49726       IF (_r.flcol_budgetdiff) THEN
49727         _col := _col + 1;
49728       END IF;
49729       IF (_r.flcol_budgetdiffprcnt) THEN
49730         _col := _col + 1;
49731       END IF;
49732     END IF; 
49733   END IF;
49734
49735 -- Handle Year...
49736   IF (_r.flcol_year) THEN
49737     SELECT yearperiod_start, period_end INTO _start, _end
49738     FROM period p
49739      JOIN yearperiod ON (period_yearperiod_id=yearperiod_id)
49740     WHERE (p.period_id=pPeriodid);
49741     
49742     IF (_r.flcol_showdb) THEN
49743       -- Debits Column
49744       _row.flcoldata_column := _col;
49745       _row.flcoldata_start := _start;
49746       _row.flcoldata_end := _end;
49747       RETURN NEXT _row;
49748       _col := _col + 1;
49749
49750       -- Credits Column
49751       _row.flcoldata_column := _col;
49752       _row.flcoldata_start := _start;
49753       _row.flcoldata_end := _end;
49754       RETURN NEXT _row;
49755       _col := _col + 1;
49756     END IF;
49757
49758     -- Year Column
49759     _row.flcoldata_column := _col;
49760     _row.flcoldata_start := _start;
49761     _row.flcoldata_end := _end;
49762     RETURN NEXT _row;
49763     _col := _col + 1;
49764
49765     -- These don't have drill down
49766     IF (_r.flcol_prcnt) THEN 
49767       _col := _col + 1;
49768     END IF;
49769     IF (_r.flcol_budget) THEN
49770       _col := _col + 1;
49771       IF (_r.flcol_budgetprcnt) THEN
49772         _col := _col + 1;
49773       END IF;
49774       IF (_r.flcol_budgetdiff) THEN
49775         _col := _col + 1;
49776       END IF;
49777       IF (_r.flcol_budgetdiffprcnt) THEN
49778         _col := _col + 1;
49779       END IF;
49780     END IF;
49781   END IF;
49782
49783   -- Handle Prior Month...
49784   IF (_r.flcol_priormonth) THEN
49785     SELECT prv.period_start, prv.period_end INTO _start, _end
49786     FROM period p
49787       JOIN period prv ON (prv.period_start < p.period_start)
49788     WHERE (p.period_id=pPeriodid)
49789     ORDER BY prv.period_start DESC
49790     LIMIT 1;
49791
49792     -- Prior Month Column
49793     _row.flcoldata_column := _col;
49794     _row.flcoldata_start := _start;
49795     _row.flcoldata_end := _end;
49796     RETURN NEXT _row;
49797     _col := _col + 1;
49798
49799     -- These don't have drill down
49800     IF (_r.flcol_priorprcnt) THEN 
49801       _col := _col + 1;
49802     END IF;
49803     IF (_r.flcol_priordiff) THEN 
49804       _col := _col + 1;
49805     END IF;
49806     IF (_r.flcol_priordiffprcnt) THEN 
49807       _col := _col + 1;
49808     END IF;
49809   END IF;
49810
49811 -- Handle Prior Quarter...
49812   IF (_r.flcol_priorquarter) THEN
49813     IF (_r.flcol_priortype = 'P') THEN
49814       -- Prior Quarter
49815       SELECT min(period_start), max(period_end)
49816       INTO _start, _end
49817       FROM (
49818         SELECT prv.period_start, prv.period_end, prv.period_quarter, prv.period_yearperiod_id
49819         FROM period p
49820           JOIN period prv ON (prv.period_start < p.period_start)
49821                           AND (prv.period_quarter != p.period_quarter)
49822         WHERE (p.period_id=pPeriodid)) data
49823       GROUP BY period_quarter, period_yearperiod_id
49824       ORDER BY min(period_start) DESC
49825       LIMIT 1;
49826     ELSE
49827       -- Prior Year Quarter
49828       SELECT min(period_start), max(period_end)
49829       INTO _start, _end
49830       FROM (
49831         SELECT prv.period_start, prv.period_end, prv.period_quarter, prv.period_yearperiod_id
49832         FROM period p
49833           JOIN period prv ON (prv.period_start < p.period_start)
49834                           AND (prv.period_yearperiod_id != p.period_yearperiod_id)
49835                           AND (prv.period_quarter = p.period_quarter)
49836         WHERE (p.period_id=pPeriodid)) data
49837       GROUP BY period_quarter, period_yearperiod_id
49838       ORDER BY min(period_start) DESC
49839       LIMIT 1;
49840     END IF;
49841
49842     -- Prior Quarter Column
49843     _row.flcoldata_column := _col;
49844     _row.flcoldata_start := _start;
49845     _row.flcoldata_end := _end;
49846     RETURN NEXT _row;
49847     _col := _col + 1;
49848
49849     -- These don't have drill down
49850     IF (_r.flcol_priorprcnt) THEN 
49851       _col := _col + 1;
49852     END IF;
49853     IF (_r.flcol_priordiff) THEN 
49854       _col := _col + 1;
49855     END IF;
49856     IF (_r.flcol_priordiffprcnt) THEN 
49857       _col := _col + 1;
49858     END IF;
49859   END IF;
49860
49861   -- Handle Prior Year...
49862   IF (_r.flcol_prioryear IN ('D','F')) THEN
49863     IF (_r.flcol_prioryear = 'D') THEN
49864       -- Prior Year to Date
49865       SELECT yearperiod_start, prv.period_end INTO _start, _end
49866       FROM period p
49867         JOIN period prv ON (prv.period_number = p.period_number)
49868                         AND (prv.period_yearperiod_id != p.period_yearperiod_id)
49869                         AND (prv.period_start < p.period_start)
49870         JOIN yearperiod ON (prv.period_yearperiod_id=yearperiod_id)   
49871       WHERE (p.period_id=pPeriodid)
49872       ORDER BY prv.period_start DESC
49873       LIMIT 1;
49874     ELSE
49875       -- Prior Full Year
49876       SELECT prv.yearperiod_start, prv.yearperiod_end INTO _start, _end
49877       FROM period p
49878         JOIN yearperiod cur ON (cur.yearperiod_id=p.period_yearperiod_id)
49879         JOIN yearperiod prv ON (prv.yearperiod_start < cur.yearperiod_start)
49880       WHERE (p.period_id=pPeriodid)
49881       ORDER BY prv.yearperiod_start DESC
49882       LIMIT 1;
49883     END IF;
49884
49885     -- Prior Year Column
49886     _row.flcoldata_column := _col;
49887     _row.flcoldata_start := _start;
49888     _row.flcoldata_end := _end;
49889     RETURN NEXT _row;
49890     _col := _col + 1;
49891
49892   END IF;
49893
49894   RETURN;
49895
49896 END;
49897 $_$;
49898
49899
49900 ALTER FUNCTION public.getflcoldata(integer, integer) OWNER TO admin;
49901
49902 --
49903 -- TOC entry 1694 (class 1255 OID 146566272)
49904 -- Dependencies: 2666 4536 8
49905 -- Name: getflcoldata(character, integer[], boolean); Type: FUNCTION; Schema: public; Owner: admin
49906 --
49907
49908 CREATE FUNCTION getflcoldata(character, integer[], boolean) RETURNS SETOF flcoldata
49909     LANGUAGE plpgsql
49910     AS $_$
49911 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49912 -- See www.xtuple.com/CPAL for the full text of the software license.
49913 DECLARE
49914   pInterval ALIAS FOR $1;
49915   pPeriodids ALIAS FOR $2;
49916   pBudgets ALIAS FOR $3;
49917   _row flcoldata%ROWTYPE;
49918   _r RECORD;
49919   _start DATE;
49920   _end DATE;
49921   _col INTEGER := 1;
49922   _count INTEGER;
49923   _i INTEGER := 1;
49924   _incr INTEGER := 1;
49925
49926 BEGIN
49927
49928   IF (pBudgets) THEN
49929     _col := 2;
49930     _incr := 2;
49931   END IF;
49932   
49933   _count := ARRAY_UPPER(pPeriodIds,1);
49934   
49935   IF (pInterval = 'M') THEN
49936     FOR _i IN 1.._count
49937     LOOP
49938       SELECT period_start, period_end INTO _start, _end
49939       FROM period
49940       WHERE (period_id=pPeriodids[_i]);
49941
49942       _row.flcoldata_column := _col;
49943       _row.flcoldata_start := _start;
49944       _row.flcoldata_end := _end;
49945       RETURN NEXT _row;
49946       _col := _col + _incr;
49947     END LOOP;
49948   ELSIF (pInterval = 'Q') THEN
49949     FOR _i IN 1.._count
49950     LOOP
49951       SELECT min(qtr.period_start), max(qtr.period_end) INTO _start, _end
49952       FROM period cur
49953         JOIN period qtr ON (cur.period_yearperiod_id=qtr.period_yearperiod_id)
49954                         AND (cur.period_quarter=qtr.period_quarter)
49955       WHERE (cur.period_id=pPeriodids[_i]);
49956
49957       _row.flcoldata_column := _col;
49958       _row.flcoldata_start := _start;
49959       _row.flcoldata_end := _end;
49960       RETURN NEXT _row;
49961       _col := _col + _incr;
49962     END LOOP;
49963   ELSE
49964     FOR _i IN 1.._count
49965     LOOP
49966       SELECT yearperiod_start, yearperiod_end INTO _start, _end
49967       FROM period
49968         JOIN yearperiod ON (period_yearperiod_id=yearperiod_id)
49969       WHERE (period_id=pPeriodids[_i]);
49970
49971       _row.flcoldata_column := _col;
49972       _row.flcoldata_start := _start;
49973       _row.flcoldata_end := _end;
49974       RETURN NEXT _row;
49975       _col := _col + _incr;
49976     END LOOP;
49977   END IF;
49978   RETURN;
49979
49980 END;
49981 $_$;
49982
49983
49984 ALTER FUNCTION public.getflcoldata(character, integer[], boolean) OWNER TO admin;
49985
49986 --
49987 -- TOC entry 1695 (class 1255 OID 146566273)
49988 -- Dependencies: 2669 4536 8
49989 -- Name: getflstmthead(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
49990 --
49991
49992 CREATE FUNCTION getflstmthead(integer, integer) RETURNS SETOF flstmthead
49993     LANGUAGE plpgsql
49994     AS $_$
49995 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
49996 -- See www.xtuple.com/CPAL for the full text of the software license.
49997 DECLARE
49998   pFlcolid ALIAS FOR $1;
49999   pPeriodid ALIAS FOR $2;
50000   _row flstmthead%ROWTYPE;
50001   _p RECORD;
50002   _month TEXT;
50003   _qtr TEXT;
50004   _year TEXT;
50005   _prmonth TEXT;
50006   _prqtr TEXT;
50007   _pryear TEXT;
50008   _err TEXT;
50009
50010 BEGIN
50011
50012   SELECT 'No Data' INTO _err;
50013
50014 --Get Layout Data
50015   SELECT flcol_priortype, flcol_prioryear INTO _p
50016   FROM flcol
50017   WHERE (flcol_id=pFlcolid);
50018
50019 --get data...
50020 --...for current Month
50021         SELECT
50022           (CASE
50023                       WHEN period_name='' THEN
50024                         formatdate(period_start) || '-' || formatdate(period_end)
50025                       ELSE period_name
50026           END) INTO _month
50027         FROM period
50028         WHERE (period_id=pPeriodId);
50029
50030         IF _month IS NULL THEN
50031           _month := _err;
50032         END IF;
50033
50034 --...for Quarter
50035         SELECT
50036           ('Q' || period_quarter || '-' || EXTRACT(year from yearperiod_end)) INTO _qtr
50037         FROM period, yearperiod
50038         WHERE ((period_id=pPeriodId)
50039         AND (period_yearperiod_id=yearperiod_id));
50040
50041         IF _qtr IS NULL THEN
50042           _qtr := _err;
50043         END IF;
50044
50045 --...for Year
50046         SELECT
50047           COALESCE((CASE WHEN period_name='' THEN
50048                 (formatdate(period_start) || '-' || formatdate(period_end) || ' YTD')
50049           ELSE (period_name || ' YTD')
50050           END),'No Data') INTO _year
50051         FROM period
50052         WHERE (period_id=pPeriodId);
50053
50054         IF _year IS NULL THEN
50055           _year := _err;
50056         END IF;
50057
50058 --...for prior month
50059
50060         IF (_p.flcol_priortype = 'P') THEN
50061
50062           SELECT
50063             (CASE WHEN pp.period_name='' THEN
50064               formatdate(pp.period_start) || '-' || formatdate(pp.period_end)
50065             ELSE pp.period_name END) INTO _prmonth
50066           FROM period cp, period pp
50067           WHERE ((cp.period_id=pPeriodId)
50068           AND (cp.period_start > pp.period_start))
50069           ORDER BY pp.period_start DESC LIMIT 1;
50070
50071         ELSE
50072
50073           SELECT
50074             (CASE WHEN pp.period_name='' THEN
50075               formatdate(pp.period_start) || '-' || formatdate(pp.period_end)
50076             ELSE pp.period_name END) INTO _prmonth
50077           FROM period cp, period pp
50078           WHERE ((cp.period_id=pPeriodId)
50079            AND (cp.period_id != pp.period_id)
50080            AND (cp.period_start > pp.period_start)
50081            AND (cp.period_number = pp.period_number))
50082           ORDER BY pp.period_start DESC LIMIT 1;
50083
50084         END IF;
50085
50086           IF _prmonth IS NULL THEN
50087             _prmonth := _err;
50088           END IF;
50089
50090
50091 --...for prior quarter
50092
50093         IF (_p.flcol_priortype='P') THEN
50094
50095           SELECT ('Q' || pp.period_quarter || '-' || EXTRACT(year from yearperiod_end)) INTO _prqtr
50096           FROM period cp, period pp, yearperiod
50097           WHERE ((cp.period_id=pPeriodId)
50098           AND (cp.period_start > pp.period_start)
50099           AND (pp.period_quarter=
50100             CASE WHEN cp.period_quarter > 1 THEN
50101               cp.period_quarter - 1
50102           ELSE 4 END)
50103           AND (pp.period_start >= cp.period_start - interval '1 year')
50104           AND (pp.period_yearperiod_id=yearperiod_id))
50105           ORDER BY pp.period_start DESC LIMIT 1;
50106
50107         ELSE
50108
50109           SELECT
50110             ('Q' || pp.period_quarter || '-' || EXTRACT(year from pp.period_start)) INTO _prqtr
50111           FROM period cp, period pp, yearperiod cy, yearperiod py
50112           WHERE ((cp.period_id=pPeriodId)
50113           AND (cp.period_yearperiod_id=cy.yearperiod_id)
50114           AND (pp.period_yearperiod_id=py.yearperiod_id)
50115           AND (cp.period_quarter=pp.period_quarter)
50116           AND (cy.yearperiod_start > py.yearperiod_start))
50117           ORDER BY py.yearperiod_start DESC, pp.period_start DESC LIMIT 1;
50118
50119         END IF;
50120
50121         IF _prqtr IS NULL THEN
50122           _prqtr := _err;
50123         END IF;
50124
50125 --...for prior year
50126
50127         IF (_p.flcol_prioryear='F') THEN
50128
50129           SELECT (EXTRACT(year from py.yearperiod_end)||'') INTO _pryear
50130           FROM period cp, yearperiod cy, yearperiod py
50131           WHERE ((cp.period_id=pPeriodId)
50132            AND (cp.period_yearperiod_id = cy.yearperiod_id)
50133            AND (cy.yearperiod_start > py.yearperiod_start))
50134           ORDER BY py.yearperiod_start DESC LIMIT 1;
50135
50136         ELSE
50137
50138           SELECT
50139           (CASE
50140                       WHEN pp.period_name='' THEN
50141                         formatdate(pp.period_start) || '-' || formatdate(pp.period_end) || ' YTD'
50142                       ELSE pp.period_name || ' YTD'
50143           END) INTO _pryear
50144           FROM period cp, period pp
50145           WHERE ((cp.period_id=pPeriodId)
50146             AND (cp.period_number = pp.period_number)
50147             AND (cp.period_start > pp.period_start))
50148           ORDER BY pp.period_start DESC LIMIT 1;
50149
50150         END IF;
50151
50152         IF _pryear IS NULL THEN
50153           _pryear := _err;
50154         END IF;
50155
50156 -- RETURN RESULTS
50157
50158         SELECT
50159                 flhead_id AS flstmthead_flhead_id,
50160                 flcol_id AS flstmthead_flcol_id,
50161                 pPeriodid AS flstmthead_period,
50162                 getEffectiveXtUser() AS flstmthead_username,
50163                 CASE
50164                         WHEN flhead_type = 'I' THEN 'Income Statement'
50165                         WHEN flhead_type = 'B' THEN 'Balance Sheet'
50166                         WHEN flhead_type = 'C' THEN 'Cash Flow Statement'
50167                         ELSE 'N/A'
50168                 END AS flstmthead_flhead_typedescrip1,
50169                 CASE
50170                         WHEN flhead_type = 'I' THEN 'Income'
50171                         WHEN flhead_type = 'B' THEN 'Balance'
50172                         WHEN flhead_type = 'C' THEN 'Cash'
50173                         ELSE 'N/A'
50174                 END AS flstmthead_flhead_typedescrip2,
50175                 flhead_name AS flstmthead_flhead_name,
50176                 flcol_name AS flstmthead_flcol_name,
50177                 _month AS flstmthead_month,
50178                 _qtr AS flstmthead_qtr,
50179                 _year AS flstmthead_year,
50180                 _prmonth AS flstmthead_prmonth,
50181                 _prqtr AS flstmthead_prqtr,
50182                 _pryear AS flstmthead_pryear INTO _p
50183         FROM flhead,flcol
50184         WHERE ((flcol_id=pFlcolid)
50185         AND (flhead_id=flcol_flhead_id));
50186
50187                 _row.flstmthead_flhead_id := _p.flstmthead_flhead_id;
50188                 _row.flstmthead_flcol_id := _p.flstmthead_flcol_id;
50189                 _row.flstmthead_period_id := _p.flstmthead_period;
50190                 _row.flstmthead_username := _p.flstmthead_username;
50191                 _row.flstmthead_typedescrip1 := _p.flstmthead_flhead_typedescrip1;
50192                 _row.flstmthead_typedescrip2 := _p.flstmthead_flhead_typedescrip2;
50193                 _row.flstmthead_flhead_name := _p.flstmthead_flhead_name;
50194                 _row.flstmthead_flcol_name := _p.flstmthead_flcol_name;
50195                 _row.flstmthead_month := _p.flstmthead_month;
50196                 _row.flstmthead_qtr := _p.flstmthead_qtr;
50197                 _row.flstmthead_year := _p.flstmthead_year;
50198                 _row.flstmthead_prmonth := _p.flstmthead_prmonth;
50199                 _row.flstmthead_prqtr := _p.flstmthead_prqtr;
50200                 _row.flstmthead_pryear := _p.flstmthead_pryear;
50201
50202         RETURN NEXT _row;
50203
50204 END;
50205 $_$;
50206
50207
50208 ALTER FUNCTION public.getflstmthead(integer, integer) OWNER TO admin;
50209
50210 --
50211 -- TOC entry 1696 (class 1255 OID 146566274)
50212 -- Dependencies: 2675 4536 8
50213 -- Name: getfltrendhead(integer, integer[], character); Type: FUNCTION; Schema: public; Owner: admin
50214 --
50215
50216 CREATE FUNCTION getfltrendhead(integer, integer[], character) RETURNS SETOF fltrendhead
50217     LANGUAGE plpgsql
50218     AS $_$
50219 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50220 -- See www.xtuple.com/CPAL for the full text of the software license.
50221 DECLARE
50222   pFlheadid ALIAS FOR $1;
50223   pPeriodids ALIAS FOR $2;
50224   pInterval ALIAS FOR $3;
50225   _row fltrendhead%ROWTYPE;
50226   _p RECORD;
50227   _count INTEGER;
50228   _i INTEGER;
50229   _t TEXT;
50230   _fld TEXT[];
50231   _type CHAR;
50232
50233 BEGIN
50234
50235 -- Validate Interval
50236    IF pInterval <> 'M' AND pInterval <> 'Q' AND pInterval <> 'Y' THEN
50237      RAISE EXCEPTION 'Invalid Interval --> %', pInterval;
50238    END IF;
50239
50240    IF ARRAY_UPPER(pPeriodIds,1) <= 12 THEN
50241         _count := ARRAY_UPPER(pPeriodIds,1);
50242    ELSE
50243         _count := 12;
50244    END IF;
50245
50246    SELECT flhead_type INTO _type FROM flhead WHERE flhead_id = pFlheadId;
50247
50248 --get data...
50249 --...for Month
50250         IF (pInterval = 'M') THEN
50251                 FOR _i IN 1.._count
50252                 LOOP
50253                         SELECT
50254                         (CASE
50255                                 WHEN period_name='' THEN
50256                                         formatdate(period_start) || '-' || formatdate(period_end)
50257                                 ELSE period_name
50258                         END) INTO _t
50259                         FROM period
50260                         WHERE (period_id=pPeriodIds[_i]);
50261
50262                         _fld[_i] := _t;
50263
50264                 END LOOP;
50265
50266 --...for Quarter
50267                 ELSE IF (pInterval = 'Q') THEN
50268                         FOR _i IN 1.._count
50269                         LOOP
50270                                 SELECT
50271                                         ('Q' || period_quarter || '-' || EXTRACT(year from yearperiod_end)) INTO _t
50272                                 FROM period, yearperiod
50273                                 WHERE ((period_id=pPeriodIds[_i])
50274                                 AND (period_yearperiod_id=yearperiod_id));
50275
50276                                         _fld[_i] := _t;
50277
50278                         END LOOP;
50279 --...for Year
50280                 ELSE
50281                         FOR _i IN 1.._count
50282                         LOOP
50283                                 SELECT (EXTRACT(year from yearperiod_end)||'') INTO _t
50284                                 FROM period, yearperiod
50285                                 WHERE ((period_id=pPeriodIds[_i])
50286                                 AND (period_yearperiod_id=yearperiod_id));
50287
50288                                 _fld[_i] := _t;
50289
50290                         END LOOP;
50291                 END IF;
50292         END IF;
50293
50294
50295 -- RETURN RESULTS
50296
50297         SELECT
50298                 flhead_id AS fltrendhead_flhead_id,
50299                 getEffectiveXtUser() AS fltrendhead_username,
50300                 CASE
50301                         WHEN flhead_type = 'I' THEN 'Income Statement'
50302                         WHEN flhead_type = 'B' THEN 'Balance Sheet'
50303                         WHEN flhead_type = 'C' THEN 'Cash Flow Statement'
50304                         ELSE 'Ad Hoc'
50305                 END AS fltrendhead_flhead_typedescrip,
50306                 flhead_name AS fltrendhead_flhead_name INTO _p
50307         FROM flhead
50308         WHERE (flhead_id=pFlheadId);
50309
50310                 _row.fltrendhead_flhead_id := _p.fltrendhead_flhead_id;
50311                 _row.fltrendhead_username := _p.fltrendhead_username;
50312                _row.fltrendhead_typedescrip := _p.fltrendhead_flhead_typedescrip;
50313                 _row.fltrendhead_flhead_name := _p.fltrendhead_flhead_name;
50314                 _row.fltrendhead_fld1 := _fld[1];
50315                 _row.fltrendhead_fld2 := _fld[2];
50316                 _row.fltrendhead_fld3 := _fld[3];
50317                 _row.fltrendhead_fld4 := _fld[4];
50318                 _row.fltrendhead_fld5 := _fld[5];
50319                 _row.fltrendhead_fld6 := _fld[6];
50320                 _row.fltrendhead_fld7 := _fld[7];
50321                 _row.fltrendhead_fld8 := _fld[8];
50322                 _row.fltrendhead_fld9 := _fld[9];
50323                 _row.fltrendhead_fld10 := _fld[10];
50324                 _row.fltrendhead_fld11 := _fld[11];
50325                 _row.fltrendhead_fld12 := _fld[12];
50326                 IF (_type IN ('I','C')) THEN
50327                         _row.fltrendhead_grndttl := 'Total';
50328                 END IF;
50329
50330         RETURN NEXT _row;
50331
50332 END;
50333 $_$;
50334
50335
50336 ALTER FUNCTION public.getfltrendhead(integer, integer[], character) OWNER TO admin;
50337
50338 --
50339 -- TOC entry 1697 (class 1255 OID 146566275)
50340 -- Dependencies: 4536 8
50341 -- Name: getfreightclassid(text); Type: FUNCTION; Schema: public; Owner: admin
50342 --
50343
50344 CREATE FUNCTION getfreightclassid(text) RETURNS integer
50345     LANGUAGE plpgsql
50346     AS $_$
50347 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50348 -- See www.xtuple.com/CPAL for the full text of the software license.
50349 DECLARE
50350   pFreightClassCode ALIAS FOR $1;
50351   _returnVal INTEGER;
50352 BEGIN
50353   IF (pFreightClassCode IS NULL) THEN
50354     RETURN NULL;
50355   END IF;
50356
50357   SELECT freightclass_id INTO _returnVal
50358   FROM freightclass
50359   WHERE (freightclass_code=pFreightClassCode);
50360
50361   IF (_returnVal IS NULL) THEN
50362         RAISE EXCEPTION 'Freight Class % not found.', pFreightClassCode;
50363   END IF;
50364
50365   RETURN _returnVal;
50366 END;
50367 $_$;
50368
50369
50370 ALTER FUNCTION public.getfreightclassid(text) OWNER TO admin;
50371
50372 --
50373 -- TOC entry 1698 (class 1255 OID 146566276)
50374 -- Dependencies: 4536 8
50375 -- Name: getfreighttaxtypeid(); Type: FUNCTION; Schema: public; Owner: admin
50376 --
50377
50378 CREATE FUNCTION getfreighttaxtypeid() RETURNS integer
50379     LANGUAGE plpgsql IMMUTABLE
50380     AS $$
50381 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50382 -- See www.xtuple.com/CPAL for the full text of the software license.
50383 DECLARE
50384   _taxtypeid INTEGER;
50385 BEGIN
50386   SELECT taxtype_id
50387     INTO _taxtypeid
50388     FROM taxtype
50389    WHERE (taxtype_name='Freight');
50390
50391   RETURN _taxtypeid;
50392 END;
50393 $$;
50394
50395
50396 ALTER FUNCTION public.getfreighttaxtypeid() OWNER TO admin;
50397
50398 --
50399 -- TOC entry 1699 (class 1255 OID 146566277)
50400 -- Dependencies: 4536 8
50401 -- Name: getgainlossaccntid(integer); Type: FUNCTION; Schema: public; Owner: admin
50402 --
50403
50404 CREATE FUNCTION getgainlossaccntid(integer) RETURNS integer
50405     LANGUAGE plpgsql STABLE
50406     AS $_$
50407 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50408 -- See www.xtuple.com/CPAL for the full text of the software license.
50409 DECLARE
50410   pAccntId ALIAS FOR $1;
50411   _returnVal INTEGER;
50412 BEGIN
50413   IF ( (pAccntId = 0) OR (pAccntId IS NULL) ) THEN
50414         RETURN 0;
50415   END IF;
50416
50417   IF (fetchMetricValue('GLCompanySize') = 0) THEN
50418     _returnVal := fetchMetricValue('CurrencyGainLossAccount')::integer;
50419   ELSE
50420     SELECT company_gainloss_accnt_id INTO _returnVal
50421     FROM company
50422       JOIN accnt ON (company_number=accnt_company)
50423     WHERE (accnt_id=pAccntId);
50424   END IF;
50425
50426   IF (_returnVal IS NULL) THEN
50427     RAISE EXCEPTION 'Currency Gain/Loss Account not found for %', formatGlAccountLong(pAccntId);
50428   END IF;
50429
50430   RETURN _returnVal;
50431 END;
50432 $_$;
50433
50434
50435 ALTER FUNCTION public.getgainlossaccntid(integer) OWNER TO admin;
50436
50437 --
50438 -- TOC entry 1700 (class 1255 OID 146566278)
50439 -- Dependencies: 4536 8
50440 -- Name: getglaccntid(text); Type: FUNCTION; Schema: public; Owner: admin
50441 --
50442
50443 CREATE FUNCTION getglaccntid(text) RETURNS integer
50444     LANGUAGE plpgsql
50445     AS $_$
50446 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50447 -- See www.xtuple.com/CPAL for the full text of the software license.
50448 DECLARE
50449   pGlAccnt ALIAS FOR $1;
50450   _returnVal INTEGER;
50451 BEGIN
50452   IF (pGlAccnt IS NULL) THEN
50453         RETURN NULL;
50454   END IF;
50455
50456   SELECT accnt_id INTO _returnVal
50457   FROM accnt
50458   WHERE (formatglaccount(accnt_id)=pGlAccnt);
50459
50460   IF (_returnVal IS NULL) THEN
50461         RAISE EXCEPTION 'Account Number % not found.', pGlAccnt;
50462   END IF;
50463
50464   RETURN _returnVal;
50465 END;
50466 $_$;
50467
50468
50469 ALTER FUNCTION public.getglaccntid(text) OWNER TO admin;
50470
50471 --
50472 -- TOC entry 1701 (class 1255 OID 146566279)
50473 -- Dependencies: 4536 8
50474 -- Name: getglaccntid(text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
50475 --
50476
50477 CREATE FUNCTION getglaccntid(text, text, text, text) RETURNS integer
50478     LANGUAGE plpgsql
50479     AS $_$
50480 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50481 -- See www.xtuple.com/CPAL for the full text of the software license.
50482 DECLARE
50483   pCompany ALIAS FOR $1;
50484   pProfit ALIAS FOR $2;
50485   pGlAccnt ALIAS FOR $3;
50486   pSub ALIAS FOR $4;
50487   _account TEXT;
50488   _returnVal INTEGER;
50489 BEGIN
50490   IF (pGlAccnt IS NULL) THEN
50491         RETURN NULL;
50492   END IF;
50493
50494   IF (pCompany is not null) THEN
50495     _account := pCompany || '-';
50496   END IF;
50497
50498   IF (pProfit is not null) THEN
50499     _account := _account || pProfit || '-';
50500   END IF;
50501   IF (pGlAccnt is not null) THEN
50502     if (_account is null) then
50503         _account := pGlAccnt;
50504     else
50505         _account := _account || pGlAccnt;
50506     end if;
50507   END IF;
50508
50509   IF (pSub is not null) THEN
50510     _account := _account || '-' || pSub;
50511   END IF;
50512
50513   SELECT accnt_id INTO _returnVal
50514   FROM accnt
50515   WHERE (formatglaccount(accnt_id)=_account);
50516
50517   IF (_returnVal IS NULL) THEN
50518         RAISE EXCEPTION 'Account Number % not found.', _account;
50519   END IF;
50520
50521   RETURN _returnVal;
50522 END;
50523 $_$;
50524
50525
50526 ALTER FUNCTION public.getglaccntid(text, text, text, text) OWNER TO admin;
50527
50528 --
50529 -- TOC entry 1702 (class 1255 OID 146566280)
50530 -- Dependencies: 4536 8
50531 -- Name: getimageid(text); Type: FUNCTION; Schema: public; Owner: admin
50532 --
50533
50534 CREATE FUNCTION getimageid(pimagename text) RETURNS integer
50535     LANGUAGE plpgsql STABLE
50536     AS $$
50537 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50538 -- See www.xtuple.com/CPAL for the full text of the software license.
50539 DECLARE
50540   _returnVal INTEGER;
50541 BEGIN
50542   IF (COALESCE(TRIM(pImageName), '') = '') THEN
50543     RETURN NULL;
50544   END IF;
50545
50546   SELECT image_id INTO _returnVal
50547   FROM image
50548   WHERE (image_name=pImageName);
50549
50550   IF (_returnVal IS NULL) THEN
50551     RAISE EXCEPTION 'Image % not found.', pImageName;
50552   END IF;
50553
50554   RETURN _returnVal;
50555 END;
50556 $$;
50557
50558
50559 ALTER FUNCTION public.getimageid(pimagename text) OWNER TO admin;
50560
50561 --
50562 -- TOC entry 1703 (class 1255 OID 146566281)
50563 -- Dependencies: 4536 8
50564 -- Name: getincdtcatid(text); Type: FUNCTION; Schema: public; Owner: admin
50565 --
50566
50567 CREATE FUNCTION getincdtcatid(pincdtcatname text) RETURNS integer
50568     LANGUAGE plpgsql STABLE
50569     AS $$
50570 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50571 -- See www.xtuple.com/CPAL for the full text of the software license.
50572 DECLARE
50573   _returnVal INTEGER;
50574 BEGIN
50575   IF (pIncdtCatName IS NULL) THEN
50576         RETURN NULL;
50577   END IF;
50578
50579   SELECT incdtcat_id INTO _returnVal
50580   FROM incdtcat
50581   WHERE (incdtcat_name=pIncdtCatName);
50582
50583   IF (_returnVal IS NULL) THEN
50584         RAISE EXCEPTION 'Incident Category Name % not found.', pIncdtCatName;
50585   END IF;
50586
50587   RETURN _returnVal;
50588 END;
50589 $$;
50590
50591
50592 ALTER FUNCTION public.getincdtcatid(pincdtcatname text) OWNER TO admin;
50593
50594 --
50595 -- TOC entry 1704 (class 1255 OID 146566282)
50596 -- Dependencies: 4536 8
50597 -- Name: getincdtcrmacctid(integer); Type: FUNCTION; Schema: public; Owner: admin
50598 --
50599
50600 CREATE FUNCTION getincdtcrmacctid(pincidentnumber integer) RETURNS integer
50601     LANGUAGE plpgsql STABLE
50602     AS $$
50603 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50604 -- See www.xtuple.com/CPAL for the full text of the software license.
50605 DECLARE
50606   _returnVal INTEGER;
50607 BEGIN
50608   IF (pIncidentNumber IS NULL) THEN
50609         RETURN NULL;
50610   END IF;
50611
50612   SELECT incdt_crmacct_id INTO _returnVal
50613   FROM incdt
50614   WHERE (incdt_number=pIncidentNumber);
50615
50616   IF (_returnVal IS NULL) THEN
50617         RAISE EXCEPTION 'Incident Number % not found.', pIncidentNumber;
50618   END IF;
50619
50620   RETURN _returnVal;
50621 END;
50622 $$;
50623
50624
50625 ALTER FUNCTION public.getincdtcrmacctid(pincidentnumber integer) OWNER TO admin;
50626
50627 --
50628 -- TOC entry 1705 (class 1255 OID 146566283)
50629 -- Dependencies: 4536 8
50630 -- Name: getincdtpriorityid(text); Type: FUNCTION; Schema: public; Owner: admin
50631 --
50632
50633 CREATE FUNCTION getincdtpriorityid(pincdtpriorityname text) RETURNS integer
50634     LANGUAGE plpgsql STABLE
50635     AS $$
50636 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50637 -- See www.xtuple.com/CPAL for the full text of the software license.
50638 DECLARE
50639   _returnVal INTEGER;
50640 BEGIN
50641   IF (pIncdtPriorityName IS NULL) THEN
50642         RETURN NULL;
50643   END IF;
50644
50645   SELECT incdtpriority_id INTO _returnVal
50646   FROM incdtpriority
50647   WHERE (incdtpriority_name=pIncdtPriorityName);
50648
50649   IF (_returnVal IS NULL) THEN
50650         RAISE EXCEPTION 'Incident Priority Name % not found.', pIncdtPriorityName;
50651   END IF;
50652
50653   RETURN _returnVal;
50654 END;
50655 $$;
50656
50657
50658 ALTER FUNCTION public.getincdtpriorityid(pincdtpriorityname text) OWNER TO admin;
50659
50660 --
50661 -- TOC entry 1706 (class 1255 OID 146566284)
50662 -- Dependencies: 4536 8
50663 -- Name: getincdtresolutionid(text); Type: FUNCTION; Schema: public; Owner: admin
50664 --
50665
50666 CREATE FUNCTION getincdtresolutionid(pincdtresolutionname text) RETURNS integer
50667     LANGUAGE plpgsql STABLE
50668     AS $$
50669 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50670 -- See www.xtuple.com/CPAL for the full text of the software license.
50671 DECLARE
50672   _returnVal INTEGER;
50673 BEGIN
50674   IF (pIncdtResolutionName IS NULL) THEN
50675         RETURN NULL;
50676   END IF;
50677
50678   SELECT incdtresolution_id INTO _returnVal
50679   FROM incdtresolution
50680   WHERE (incdtresolution_name=pIncdtResolutionName);
50681
50682   IF (_returnVal IS NULL) THEN
50683         RAISE EXCEPTION 'Incident Resolution Name % not found.', pIncdtResolutionName;
50684   END IF;
50685
50686   RETURN _returnVal;
50687 END;
50688 $$;
50689
50690
50691 ALTER FUNCTION public.getincdtresolutionid(pincdtresolutionname text) OWNER TO admin;
50692
50693 --
50694 -- TOC entry 1707 (class 1255 OID 146566285)
50695 -- Dependencies: 4536 8
50696 -- Name: getincdtseverityid(text); Type: FUNCTION; Schema: public; Owner: admin
50697 --
50698
50699 CREATE FUNCTION getincdtseverityid(pincdtseverityname text) RETURNS integer
50700     LANGUAGE plpgsql STABLE
50701     AS $$
50702 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50703 -- See www.xtuple.com/CPAL for the full text of the software license.
50704 DECLARE
50705   _returnVal INTEGER;
50706 BEGIN
50707   IF (pIncdtSeverityName IS NULL) THEN
50708         RETURN NULL;
50709   END IF;
50710
50711   SELECT incdtseverity_id INTO _returnVal
50712   FROM incdtseverity
50713   WHERE (incdtseverity_name=pIncdtSeverityName);
50714
50715   IF (_returnVal IS NULL) THEN
50716         RAISE EXCEPTION 'Incident Severity Name % not found.', pIncdtSeverityName;
50717   END IF;
50718
50719   RETURN _returnVal;
50720 END;
50721 $$;
50722
50723
50724 ALTER FUNCTION public.getincdtseverityid(pincdtseverityname text) OWNER TO admin;
50725
50726 --
50727 -- TOC entry 1708 (class 1255 OID 146566286)
50728 -- Dependencies: 4536 8
50729 -- Name: getincidentid(integer); Type: FUNCTION; Schema: public; Owner: admin
50730 --
50731
50732 CREATE FUNCTION getincidentid(pincidentnumber integer) RETURNS integer
50733     LANGUAGE plpgsql STABLE
50734     AS $$
50735 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50736 -- See www.xtuple.com/CPAL for the full text of the software license.
50737 DECLARE
50738   _returnVal INTEGER;
50739 BEGIN
50740   IF (pIncidentNumber IS NULL) THEN
50741         RETURN NULL;
50742   END IF;
50743
50744   SELECT incdt_id INTO _returnVal
50745   FROM incdt
50746   WHERE (incdt_number=pIncidentNumber);
50747
50748   IF (_returnVal IS NULL) THEN
50749         RAISE EXCEPTION 'Incident Number % not found.', pIncidentNumber;
50750   END IF;
50751
50752   RETURN _returnVal;
50753 END;
50754 $$;
50755
50756
50757 ALTER FUNCTION public.getincidentid(pincidentnumber integer) OWNER TO admin;
50758
50759 --
50760 -- TOC entry 1709 (class 1255 OID 146566287)
50761 -- Dependencies: 4536 8
50762 -- Name: getinvcheadid(text); Type: FUNCTION; Schema: public; Owner: admin
50763 --
50764
50765 CREATE FUNCTION getinvcheadid(text) RETURNS integer
50766     LANGUAGE plpgsql
50767     AS $_$
50768 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50769 -- See www.xtuple.com/CPAL for the full text of the software license.
50770 DECLARE
50771   pInvcNumber ALIAS FOR $1;
50772   _returnVal INTEGER;
50773 BEGIN
50774   IF (pInvcNumber IS NULL) THEN
50775         RETURN NULL;
50776   END IF;
50777
50778   SELECT invchead_id INTO _returnVal
50779   FROM invchead
50780   WHERE (UPPER(invchead_invcnumber)=UPPER(pInvcNumber));
50781
50782   IF (_returnVal IS NULL) THEN
50783         RAISE EXCEPTION 'Invoice % not found.', pInvcNumber;
50784   END IF;
50785
50786   RETURN _returnVal;
50787 END;
50788 $_$;
50789
50790
50791 ALTER FUNCTION public.getinvcheadid(text) OWNER TO admin;
50792
50793 --
50794 -- TOC entry 1710 (class 1255 OID 146566288)
50795 -- Dependencies: 4536 8
50796 -- Name: getinvcitemlotserial(integer); Type: FUNCTION; Schema: public; Owner: admin
50797 --
50798
50799 CREATE FUNCTION getinvcitemlotserial(integer) RETURNS text
50800     LANGUAGE plpgsql
50801     AS $_$
50802 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50803 -- See www.xtuple.com/CPAL for the full text of the software license.
50804 DECLARE
50805   pInvcitemid ALIAS FOR $1;
50806   _lotserial text;
50807   _r RECORD;
50808   _first BOOLEAN;
50809   _newMethod BOOLEAN;
50810 BEGIN
50811  
50812   --Test to see if Lot/Serial Enabled
50813   SELECT metric_value INTO _lotserial
50814   FROM metric
50815   WHERE ((metric_name='LotSerialControl')
50816   AND (metric_value ='t'));
50817
50818   IF (FOUND) THEN
50819     _lotserial := '';
50820     _first := true;
50821
50822 --  Two ways of doing this: old method and new method
50823 --  First, find out if new method employed.
50824 --  (new method is more accurate, but unfortunately no
50825 --  way to migrate or correct old data.  Have to keep
50826 --  old method in case someone reprints an old invoice.)
50827
50828     SELECT (COUNT(*) > 0) INTO _newMethod 
50829     FROM shipitem 
50830     WHERE ((shipitem_invcitem_id=pInvcitemid)
50831     AND (shipitem_invhist_id IS NOT NULL));
50832
50833     IF (_newMethod) THEN
50834
50835       FOR _r IN SELECT DISTINCT ls_number
50836                 FROM invdetail, invhist, shipitem, ls
50837                WHERE ((shipitem_invcitem_id=pInvcitemid)
50838                  AND  (shipitem_invhist_id=invhist_id)
50839                  AND  (invhist_id=invdetail_invhist_id)
50840                  AND  (invdetail_ls_id=ls_id)) LOOP
50841         IF (_first = false) THEN
50842           _lotserial := _lotserial || ', ';
50843         END IF;
50844         _lotserial := _lotserial || _r.ls_number;
50845         _first := false;
50846       END LOOP;
50847
50848       RETURN _lotserial;
50849     ELSE
50850       -- Handle it old way
50851       FOR _r IN SELECT DISTINCT ls_number
50852                 FROM ls, invdetail JOIN invhist ON (invdetail_invhist_id=invhist_id)
50853                WHERE ((invhist_transtype='SH')
50854                  AND  (invdetail_invcitem_id=pInvcitemid)
50855                  AND  (invdetail_ls_id=ls_id)) LOOP
50856         IF (_first = false) THEN
50857           _lotserial := _lotserial || ', ';
50858         END IF;
50859         _lotserial := _lotserial || _r.ls_number;
50860         _first := false;
50861       END LOOP;
50862
50863       RETURN _lotserial;
50864     END IF;
50865   ELSE
50866     RETURN '';
50867   END IF;
50868   
50869 END
50870 $_$;
50871
50872
50873 ALTER FUNCTION public.getinvcitemlotserial(integer) OWNER TO admin;
50874
50875 --
50876 -- TOC entry 1684 (class 1255 OID 146566289)
50877 -- Dependencies: 4536 8
50878 -- Name: getipsheadid(text); Type: FUNCTION; Schema: public; Owner: admin
50879 --
50880
50881 CREATE FUNCTION getipsheadid(pipsname text) RETURNS integer
50882     LANGUAGE plpgsql
50883     AS $$
50884 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50885 -- See www.xtuple.com/CPAL for the full text of the software license.
50886 DECLARE
50887   _returnVal INTEGER;
50888 BEGIN
50889   IF (pIpsName IS NULL) THEN
50890         RETURN NULL;
50891   END IF;
50892
50893   SELECT ipshead_id INTO _returnVal
50894   FROM ipshead
50895   WHERE (ipshead_name=pIpsName);
50896
50897   IF (_returnVal IS NULL) THEN
50898         RAISE EXCEPTION 'Pricing Schedule % not found.', pIpsName;
50899   END IF;
50900
50901   RETURN _returnVal;
50902 END;
50903 $$;
50904
50905
50906 ALTER FUNCTION public.getipsheadid(pipsname text) OWNER TO admin;
50907
50908 --
50909 -- TOC entry 1712 (class 1255 OID 146566290)
50910 -- Dependencies: 4536 8
50911 -- Name: getipsitemid(text, text, numeric, text, text); Type: FUNCTION; Schema: public; Owner: admin
50912 --
50913
50914 CREATE FUNCTION getipsitemid(pipsname text, pitemnumber text, pqtybreak numeric, pqtyuom text, ppriceuom text) RETURNS integer
50915     LANGUAGE plpgsql
50916     AS $$
50917 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50918 -- See www.xtuple.com/CPAL for the full text of the software license.
50919 DECLARE
50920   _returnVal INTEGER;
50921   
50922 BEGIN
50923   IF (pIpsName IS NULL AND pItemNumber IS NULL AND pQtyBreak IS NULL AND pQtyUom IS NULL AND pPriceUom IS NULL) THEN
50924         RETURN NULL;
50925   END IF;
50926
50927   SELECT ipsitem_id INTO _returnVal
50928   FROM ipsiteminfo
50929   WHERE ((ipsitem_ipshead_id=getIpsheadId(pIpsName))
50930   AND (ipsitem_item_id=getItemId(pItemNumber))
50931   AND (ipsitem_qtybreak=pQtyBreak)
50932   AND (ipsitem_qty_uom_id=getUomId(pQtyUom))
50933   AND (ipsitem_price_uom_id=getUomId(pPriceUom)));
50934
50935   IF (_returnVal IS NULL) THEN
50936         RAISE EXCEPTION 'Pricing Schedule Item for Schedule %, Item %,Qt Break %,Qty UOM %, Price UOM % not found.', 
50937         pIpsName, pItemNumber, pQtyBreak, pQtyUom, pPriceUom;
50938   END IF;
50939
50940   RETURN _returnVal;
50941 END;
50942 $$;
50943
50944
50945 ALTER FUNCTION public.getipsitemid(pipsname text, pitemnumber text, pqtybreak numeric, pqtyuom text, ppriceuom text) OWNER TO admin;
50946
50947 --
50948 -- TOC entry 1713 (class 1255 OID 146566291)
50949 -- Dependencies: 4536 8
50950 -- Name: getipsprodcatid(text, text, numeric); Type: FUNCTION; Schema: public; Owner: admin
50951 --
50952
50953 CREATE FUNCTION getipsprodcatid(pipsname text, pprodcat text, pqtybreak numeric) RETURNS integer
50954     LANGUAGE plpgsql
50955     AS $$
50956 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50957 -- See www.xtuple.com/CPAL for the full text of the software license.
50958 DECLARE
50959   _returnVal INTEGER;
50960   
50961 BEGIN
50962   IF (pIpsName IS NULL AND pProdCat IS NULL AND pQtyBreak IS NULL) THEN
50963         RETURN NULL;
50964   END IF;
50965
50966   SELECT ipsitem_id INTO _returnVal
50967   FROM ipsiteminfo
50968   WHERE ((ipsitem_ipshead_id=getIpsheadId(pIpsName))
50969   AND (ipsitem_prodcat_id=getProdcatId(pProdCat))
50970   AND (ipsitem_qtybreak=pQtyBreak));
50971
50972   IF (_returnVal IS NULL) THEN
50973         RAISE EXCEPTION 'Pricing Schedule Product Category for Schedule %, Product Category %,Qt Break % not found.', 
50974         pIpsName, pProdCat, pQtyBreak;
50975   END IF;
50976
50977   RETURN _returnVal;
50978 END;
50979 $$;
50980
50981
50982 ALTER FUNCTION public.getipsprodcatid(pipsname text, pprodcat text, pqtybreak numeric) OWNER TO admin;
50983
50984 --
50985 -- TOC entry 1714 (class 1255 OID 146566292)
50986 -- Dependencies: 4536 8
50987 -- Name: getitemid(text); Type: FUNCTION; Schema: public; Owner: admin
50988 --
50989
50990 CREATE FUNCTION getitemid(text) RETURNS integer
50991     LANGUAGE plpgsql IMMUTABLE
50992     AS $_$
50993 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
50994 -- See www.xtuple.com/CPAL for the full text of the software license.
50995 DECLARE
50996   pItemNumber ALIAS FOR $1;
50997   _returnVal INTEGER;
50998 BEGIN
50999   IF (pItemNumber IS NULL) THEN
51000         RETURN NULL;
51001   END IF;
51002
51003   SELECT item_id INTO _returnVal
51004   FROM item
51005   WHERE (item_number=UPPER(pItemNumber));
51006
51007   IF (_returnVal IS NULL) THEN
51008         RAISE EXCEPTION 'Item % not found.', pItemNumber;
51009   END IF;
51010
51011   RETURN _returnVal;
51012 END;
51013 $_$;
51014
51015
51016 ALTER FUNCTION public.getitemid(text) OWNER TO admin;
51017
51018 --
51019 -- TOC entry 1715 (class 1255 OID 146566293)
51020 -- Dependencies: 4536 8
51021 -- Name: getitemidfromupc(text); Type: FUNCTION; Schema: public; Owner: admin
51022 --
51023
51024 CREATE FUNCTION getitemidfromupc(text) RETURNS integer
51025     LANGUAGE plpgsql
51026     AS $_$
51027 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51028 -- See www.xtuple.com/CPAL for the full text of the software license.
51029 DECLARE
51030   pItemUPC ALIAS FOR $1;
51031   _returnVal INTEGER;
51032 BEGIN
51033   IF (pItemUPC IS NULL) THEN
51034         RETURN NULL;
51035   END IF;
51036
51037   SELECT item_id INTO _returnVal
51038   FROM item
51039   WHERE (item_upccode=UPPER(pItemUPC));
51040
51041   IF (_returnVal IS NULL) THEN
51042         RAISE EXCEPTION 'Item % not found.', pItemUPC;
51043   END IF;
51044
51045   RETURN _returnVal;
51046 END;
51047 $_$;
51048
51049
51050 ALTER FUNCTION public.getitemidfromupc(text) OWNER TO admin;
51051
51052 --
51053 -- TOC entry 1716 (class 1255 OID 146566294)
51054 -- Dependencies: 4536 8
51055 -- Name: getitemsiteid(text, text); Type: FUNCTION; Schema: public; Owner: admin
51056 --
51057
51058 CREATE FUNCTION getitemsiteid(text, text) RETURNS integer
51059     LANGUAGE plpgsql
51060     AS $_$
51061 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51062 -- See www.xtuple.com/CPAL for the full text of the software license.
51063 DECLARE
51064   pWarehouseCode ALIAS FOR $1;
51065   pItemNumber ALIAS FOR $2;
51066   _returnVal INTEGER;
51067 BEGIN
51068   SELECT getItemsiteId(pWarehouseCode,pItemNumber,'ALL') INTO _returnVal;
51069
51070   RETURN _returnVal;
51071 END;
51072 $_$;
51073
51074
51075 ALTER FUNCTION public.getitemsiteid(text, text) OWNER TO admin;
51076
51077 --
51078 -- TOC entry 1717 (class 1255 OID 146566295)
51079 -- Dependencies: 4536 8
51080 -- Name: getitemsiteid(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
51081 --
51082
51083 CREATE FUNCTION getitemsiteid(text, text, text) RETURNS integer
51084     LANGUAGE plpgsql
51085     AS $_$
51086 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51087 -- See www.xtuple.com/CPAL for the full text of the software license.
51088 DECLARE
51089   pWarehouseCode ALIAS FOR $1;
51090   pItemNumber ALIAS FOR $2;
51091   pType ALIAS FOR $3;
51092   _type TEXT;
51093   _p RECORD;
51094 BEGIN
51095   IF ((pWarehouseCode IS NULL) OR (pItemNumber IS NULL)) THEN
51096         RETURN NULL;
51097   END IF;
51098  
51099   IF UPPER(pType) NOT IN ('ALL','ACTIVE','SOLD') THEN
51100     RAISE EXCEPTION 'Invalid Type %. Valid Itemsite types are ALL and SOLD', pType;
51101   END IF;
51102
51103   SELECT * INTO _p
51104   FROM itemsite, item
51105   WHERE ((itemsite_item_id=item_id)
51106   AND (itemsite_warehous_id=getWarehousId(pWarehouseCode,'ALL'))
51107   AND (item_number=UPPER(pItemNumber)));
51108
51109   IF NOT (FOUND) THEN
51110     RAISE EXCEPTION 'Item % not found in Warehouse %', pItemNumber, pWarehouseCode;
51111   ELSIF ((UPPER(pType)='ACTIVE') OR (UPPER(pType)='SOLD')) THEN
51112     IF NOT (_p.item_active) THEN
51113       RAISE EXCEPTION 'Item % is inactive.', pItemNumber;
51114     ELSE
51115       IF NOT (_p.itemsite_active) THEN
51116         RAISE EXCEPTION 'Item % is inactive in Warehouse %', pItemNumber, pWarehouseCode;
51117       ELSE
51118         IF ((UPPER(pType)='SOLD') AND NOT _p.item_sold) THEN
51119           RAISE EXCEPTION 'Item % is not sold', pItemNumber;
51120         ELSE
51121           IF ((UPPER(pType)='SOLD') AND NOT _p.itemsite_sold) THEN
51122             RAISE EXCEPTION 'Item % is not sold from Warehouse %', pItemNumber, pWarehouseCode;
51123           END IF;
51124         END IF;
51125       END IF;
51126     END IF;
51127   END IF;
51128
51129   RETURN _p.itemsite_id;
51130 END;
51131 $_$;
51132
51133
51134 ALTER FUNCTION public.getitemsiteid(text, text, text) OWNER TO admin;
51135
51136 --
51137 -- TOC entry 1718 (class 1255 OID 146566296)
51138 -- Dependencies: 4536 8
51139 -- Name: getitemsrcid(text, text); Type: FUNCTION; Schema: public; Owner: admin
51140 --
51141
51142 CREATE FUNCTION getitemsrcid(text, text) RETURNS integer
51143     LANGUAGE plpgsql
51144     AS $_$
51145 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51146 -- See www.xtuple.com/CPAL for the full text of the software license.
51147 DECLARE
51148   pItemNumber ALIAS FOR $1;
51149   pVendNumber ALIAS FOR $2;
51150   _returnVal INTEGER;
51151 BEGIN
51152   IF ((pItemNumber IS NULL) OR (pVendNumber IS NULL)) THEN
51153     RETURN NULL;
51154   END IF;
51155
51156   SELECT itemsrc_id INTO _returnVal
51157   FROM itemsrc
51158   WHERE ((itemsrc_item_id=getItemId(pItemNumber))
51159   AND (itemsrc_vend_id=getVendId(pVendNumber)));
51160
51161   IF (_returnVal IS NULL) THEN
51162         RAISE EXCEPTION 'Item Source Item % Vendor % not found.', pItemNumber,pVendNumber;
51163   END IF;
51164
51165   RETURN _returnVal;
51166 END;
51167 $_$;
51168
51169
51170 ALTER FUNCTION public.getitemsrcid(text, text) OWNER TO admin;
51171
51172 --
51173 -- TOC entry 1719 (class 1255 OID 146566297)
51174 -- Dependencies: 4536 8
51175 -- Name: getlasttrialbalid(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51176 --
51177
51178 CREATE FUNCTION getlasttrialbalid(integer, integer) RETURNS integer
51179     LANGUAGE plpgsql STABLE
51180     AS $_$
51181 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51182 -- See www.xtuple.com/CPAL for the full text of the software license.
51183 DECLARE
51184   pAccntId ALIAS FOR $1;
51185   pPeriodId ALIAS FOR $2;
51186   _p RECORD;
51187   _accntType TEXT;
51188   _result NUMERIC;
51189
51190 BEGIN
51191
51192   SELECT period_end,period_yearperiod_id INTO _p
51193   FROM period
51194   WHERE period_id=pPeriodId;
51195
51196   SELECT accnt_type INTO _accntType
51197   FROM accnt
51198   WHERE accnt_id=pAccntId;
51199
51200   IF (_accntType IN ('R','E')) THEN
51201         SELECT trialbal_id INTO _result
51202         FROM trialbal
51203         WHERE ((trialbal_accnt_id=pAccntId)
51204         AND (trialbal_period_id=pPeriodId));
51205   ELSE
51206         SELECT trialbal_id INTO _result
51207         FROM (SELECT trialbal_id
51208                 FROM trialbal,period
51209                 WHERE ((trialbal_accnt_id=pAccntId)
51210                 AND (trialbal_period_id=period_id)
51211                 AND (period_end <= _p.period_end)
51212                 AND (period_yearperiod_id=_p.period_yearperiod_id))
51213                 ORDER BY period_end DESC) AS data;
51214   END IF;
51215
51216   RETURN _result;
51217
51218 END;
51219 $_$;
51220
51221
51222 ALTER FUNCTION public.getlasttrialbalid(integer, integer) OWNER TO admin;
51223
51224 --
51225 -- TOC entry 1693 (class 1255 OID 146566298)
51226 -- Dependencies: 4536 8
51227 -- Name: getlocationid(text, text); Type: FUNCTION; Schema: public; Owner: admin
51228 --
51229
51230 CREATE FUNCTION getlocationid(text, text) RETURNS integer
51231     LANGUAGE plpgsql
51232     AS $_$
51233 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51234 -- See www.xtuple.com/CPAL for the full text of the software license.
51235 DECLARE
51236   pWarehouse ALIAS FOR $1;
51237   pLocation ALIAS FOR $2;
51238   _returnVal INTEGER;
51239 BEGIN
51240   IF (pLocation IS NULL) THEN
51241         RETURN NULL;
51242   END IF;
51243
51244   SELECT location_id INTO _returnVal
51245   FROM location
51246   WHERE ((location_warehous_id=getWarehousId(pWarehouse,'ACTIVE'))
51247   AND (formatLocationname(location_id)=pLocation))
51248   LIMIT 1;
51249
51250   IF (_returnVal IS NULL) THEN
51251         RAISE EXCEPTION 'Location % not found in Warehouse %.', pLocation, pWarehouse;
51252   END IF;
51253
51254   RETURN _returnVal;
51255 END;
51256 $_$;
51257
51258
51259 ALTER FUNCTION public.getlocationid(text, text) OWNER TO admin;
51260
51261 --
51262 -- TOC entry 1721 (class 1255 OID 146566299)
51263 -- Dependencies: 4536 8
51264 -- Name: getlotserialid(text, text); Type: FUNCTION; Schema: public; Owner: admin
51265 --
51266
51267 CREATE FUNCTION getlotserialid(text, text) RETURNS integer
51268     LANGUAGE plpgsql
51269     AS $_$
51270 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51271 -- See www.xtuple.com/CPAL for the full text of the software license.
51272 DECLARE
51273   pItemNumber ALIAS FOR $1;
51274   pLotSerialNumber ALIAS FOR $2;
51275   _returnVal INTEGER;
51276 BEGIN
51277   IF ((pItemNumber IS NULL) OR (pLotSerialNumber IS NULL) OR (pLotSerialNumber='')) THEN
51278         RETURN NULL;
51279   END IF;
51280
51281   SELECT ls_id INTO _returnVal
51282   FROM ls
51283   WHERE ((ls_item_id=getItemId(pItemNumber))
51284   AND (UPPER(ls_number)=UPPER(pLotSerialNumber)));
51285
51286   IF (_returnVal IS NULL) THEN
51287         RAISE EXCEPTION 'LotSerial % not found.', pLotSerialNumber;
51288   END IF;
51289
51290   RETURN _returnVal;
51291 END;
51292 $_$;
51293
51294
51295 ALTER FUNCTION public.getlotserialid(text, text) OWNER TO admin;
51296
51297 --
51298 -- TOC entry 1722 (class 1255 OID 146566300)
51299 -- Dependencies: 4536 8
51300 -- Name: getopenshipment(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51301 --
51302
51303 CREATE FUNCTION getopenshipment(pordertype text, porderid integer, pwarehousid integer) RETURNS text
51304     LANGUAGE plpgsql STABLE
51305     AS $$
51306 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51307 -- See www.xtuple.com/CPAL for the full text of the software license.
51308 DECLARE
51309   _result TEXT := '';
51310
51311 BEGIN
51312
51313   IF (pOrderType = 'SO') THEN
51314     SELECT shiphead_number INTO _result
51315     FROM shiphead JOIN shipitem ON (shipitem_shiphead_id=shiphead_id)
51316                   JOIN coitem ON (coitem_id=shipitem_orderitem_id)
51317                   JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
51318     WHERE (shiphead_order_id=pOrderId)
51319       AND (shiphead_order_type='SO') 
51320       AND (NOT shiphead_shipped)
51321       AND (CASE WHEN (pWarehousId IS NULL) THEN TRUE
51322                 ELSE itemsite_warehous_id=pWarehousId END) 
51323     ORDER BY shiphead_number
51324     LIMIT 1; 
51325   ELSEIF (pOrderType = 'TO') THEN
51326     SELECT shiphead_number INTO _result
51327     FROM shiphead JOIN tohead ON (tohead_id=shiphead_order_id)
51328     WHERE (shiphead_order_id=pOrderId)
51329       AND (shiphead_order_type='TO') 
51330       AND (NOT shiphead_shipped)
51331       AND (CASE WHEN (pWarehousId IS NULL) THEN TRUE
51332                 ELSE tohead_src_warehous_id=pWarehousId END) 
51333     ORDER BY shiphead_number
51334     LIMIT 1; 
51335   END IF;
51336
51337   RETURN _result;
51338
51339 END;
51340 $$;
51341
51342
51343 ALTER FUNCTION public.getopenshipment(pordertype text, porderid integer, pwarehousid integer) OWNER TO admin;
51344
51345 --
51346 -- TOC entry 1723 (class 1255 OID 146566301)
51347 -- Dependencies: 4536 8
51348 -- Name: getopenshipmentid(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51349 --
51350
51351 CREATE FUNCTION getopenshipmentid(pordertype text, porderid integer, pwarehousid integer) RETURNS integer
51352     LANGUAGE plpgsql STABLE
51353     AS $$
51354 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51355 -- See www.xtuple.com/CPAL for the full text of the software license.
51356 DECLARE
51357   _result INTEGER := -1;
51358
51359 BEGIN
51360
51361   IF (pOrderType = 'SO') THEN
51362     SELECT shiphead_id INTO _result
51363     FROM shiphead JOIN shipitem ON (shipitem_shiphead_id=shiphead_id)
51364                   JOIN coitem ON (coitem_id=shipitem_orderitem_id)
51365                   JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
51366     WHERE (shiphead_order_id=pOrderId)
51367       AND (shiphead_order_type='SO') 
51368       AND (NOT shiphead_shipped)
51369       AND (CASE WHEN (pWarehousId IS NULL) THEN TRUE
51370                 ELSE itemsite_warehous_id=pWarehousId END) 
51371     ORDER BY shiphead_number
51372     LIMIT 1; 
51373   ELSEIF (pOrderType = 'TO') THEN
51374     SELECT shiphead_id INTO _result
51375     FROM shiphead JOIN tohead ON (tohead_id=shiphead_order_id)
51376     WHERE (shiphead_order_id=pOrderId)
51377       AND (shiphead_order_type='TO') 
51378       AND (NOT shiphead_shipped)
51379       AND (CASE WHEN (pWarehousId IS NULL) THEN TRUE
51380                 ELSE tohead_src_warehous_id=pWarehousId END) 
51381     ORDER BY shiphead_number
51382     LIMIT 1; 
51383   END IF;
51384
51385   RETURN _result;
51386
51387 END;
51388 $$;
51389
51390
51391 ALTER FUNCTION public.getopenshipmentid(pordertype text, porderid integer, pwarehousid integer) OWNER TO admin;
51392
51393 --
51394 -- TOC entry 1724 (class 1255 OID 146566302)
51395 -- Dependencies: 4536 8
51396 -- Name: getopheadid(text); Type: FUNCTION; Schema: public; Owner: admin
51397 --
51398
51399 CREATE FUNCTION getopheadid(text) RETURNS integer
51400     LANGUAGE plpgsql
51401     AS $_$
51402 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51403 -- See www.xtuple.com/CPAL for the full text of the software license.
51404 DECLARE
51405   pOpHeadName ALIAS FOR $1;
51406   _returnVal INTEGER;
51407 BEGIN
51408   
51409   IF (pOpHeadName IS NULL) THEN
51410     RETURN NULL;
51411   END IF;
51412
51413   SELECT ophead_id INTO _returnVal
51414   FROM ophead
51415   WHERE (UPPER(ophead_name)=UPPER(pOpHeadName));
51416   
51417   IF (_returnVal IS NULL) THEN
51418       RAISE EXCEPTION 'Opportunity % not found.', pOpHeadName;
51419   END IF;
51420
51421   RETURN _returnVal;
51422 END;
51423 $_$;
51424
51425
51426 ALTER FUNCTION public.getopheadid(text) OWNER TO admin;
51427
51428 --
51429 -- TOC entry 1725 (class 1255 OID 146566303)
51430 -- Dependencies: 4536 8
51431 -- Name: getpacklistcharname(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51432 --
51433
51434 CREATE FUNCTION getpacklistcharname(integer, integer) RETURNS text
51435     LANGUAGE plpgsql
51436     AS $_$
51437 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51438 -- See www.xtuple.com/CPAL for the full text of the software license.
51439 DECLARE
51440   pShipheadId ALIAS FOR $1;
51441   pOrderItemId ALIAS FOR $2;
51442   _charname text;
51443   _r RECORD;
51444   _first BOOLEAN;
51445   
51446 BEGIN
51447
51448 -- If transfer order, get out
51449   SELECT shiphead_order_type INTO _r
51450   FROM shiphead
51451   WHERE ((shiphead_id=pShipheadId)
51452   AND (shiphead_order_type='TO'));
51453   
51454   IF (FOUND) THEN
51455     RETURN '';
51456   END IF;
51457
51458   _charname := '';
51459   _first := true;
51460
51461   FOR _r IN SELECT char_name
51462             FROM char, charass
51463             WHERE ((char_id=charass_char_id)
51464             AND (charass_target_type='SI')
51465             AND (charass_target_id=pOrderItemId)) 
51466   LOOP
51467         IF (_first = false) THEN
51468           _charname := _charname || '
51469 ';
51470         END IF;
51471         _charname := _charname || _r.char_name;
51472         _first := false;
51473   END LOOP;
51474
51475   RETURN _charname;
51476   
51477 END
51478 $_$;
51479
51480
51481 ALTER FUNCTION public.getpacklistcharname(integer, integer) OWNER TO admin;
51482
51483 --
51484 -- TOC entry 1726 (class 1255 OID 146566304)
51485 -- Dependencies: 4536 8
51486 -- Name: getpacklistcharvalue(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51487 --
51488
51489 CREATE FUNCTION getpacklistcharvalue(integer, integer) RETURNS text
51490     LANGUAGE plpgsql
51491     AS $_$
51492 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51493 -- See www.xtuple.com/CPAL for the full text of the software license.
51494 DECLARE
51495   pShipheadId ALIAS FOR $1;
51496   pOrderItemId ALIAS FOR $2;
51497   _charval text;
51498   _r RECORD;
51499   _first BOOLEAN;
51500   
51501 BEGIN
51502
51503 -- If transfer order, get out
51504   SELECT shiphead_order_type INTO _r
51505   FROM shiphead
51506   WHERE ((shiphead_id=pShipheadId)
51507   AND (shiphead_order_type='TO'));
51508   
51509   IF (FOUND) THEN
51510     RETURN '';
51511   END IF;
51512
51513   _charval := '';
51514   _first := true;
51515
51516   FOR _r IN SELECT charass_value
51517             FROM char, charass
51518             WHERE ((char_id=charass_char_id)
51519             AND (charass_target_type='SI')
51520             AND (charass_target_id=pOrderItemId)) 
51521   LOOP
51522         IF (_first = false) THEN
51523           _charval := _charval || '
51524 ';
51525         END IF;
51526         _charval := _charval || _r.charass_value;
51527         _first := false;
51528   END LOOP;
51529
51530   RETURN _charval;
51531   
51532 END
51533 $_$;
51534
51535
51536 ALTER FUNCTION public.getpacklistcharvalue(integer, integer) OWNER TO admin;
51537
51538 --
51539 -- TOC entry 1727 (class 1255 OID 146566305)
51540 -- Dependencies: 4536 8
51541 -- Name: getpacklistitemlotserial(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51542 --
51543
51544 CREATE FUNCTION getpacklistitemlotserial(integer, integer) RETURNS text
51545     LANGUAGE plpgsql
51546     AS $_$
51547 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51548 -- See www.xtuple.com/CPAL for the full text of the software license.
51549 DECLARE
51550   pShipheadId ALIAS FOR $1;
51551   pOrderItemId ALIAS FOR $2;
51552   _lotserial text;
51553   _r RECORD;
51554   _first BOOLEAN;
51555   
51556 BEGIN
51557  
51558   --Test to see if Lot/Serial Enabled
51559   SELECT metric_value INTO _lotserial
51560   FROM metric
51561   WHERE ((metric_name='LotSerialControl')
51562   AND (metric_value ='t'));
51563
51564   IF (FOUND) THEN
51565     _lotserial := '';
51566     _first := true;
51567
51568     FOR _r IN SELECT DISTINCT ls_number
51569               FROM invdetail, invhist, shipitem, ls
51570              WHERE ((shipitem_shiphead_id=pShipheadId)
51571                AND  (shipitem_orderitem_id=pOrderItemId)
51572                AND  (shipitem_invhist_id=invhist_id)
51573                AND  (invhist_id=invdetail_invhist_id)
51574                AND  (invdetail_ls_id=ls_id)) LOOP
51575       IF (_first = false) THEN
51576         _lotserial := _lotserial || ', ';
51577       END IF;
51578       _lotserial := _lotserial || _r.ls_number;
51579       _first := false;
51580     END LOOP;
51581
51582     RETURN _lotserial;
51583   ELSE
51584     RETURN '';
51585   END IF;
51586   
51587 END
51588 $_$;
51589
51590
51591 ALTER FUNCTION public.getpacklistitemlotserial(integer, integer) OWNER TO admin;
51592
51593 --
51594 -- TOC entry 1730 (class 1255 OID 146566307)
51595 -- Dependencies: 4536 8
51596 -- Name: getperiodid(date); Type: FUNCTION; Schema: public; Owner: admin
51597 --
51598
51599 CREATE FUNCTION getperiodid(date) RETURNS integer
51600     LANGUAGE plpgsql
51601     AS $_$
51602 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51603 -- See www.xtuple.com/CPAL for the full text of the software license.
51604 DECLARE
51605   pPeriodDate ALIAS FOR $1;
51606   _returnVal INTEGER;
51607 BEGIN
51608   IF (pPeriodDate IS NULL) THEN
51609         RETURN NULL;
51610   END IF;
51611
51612   SELECT period_id INTO _returnVal
51613   FROM period
51614   WHERE ((pPeriodDate) between period_start AND period_end);
51615
51616   IF (_returnVal IS NULL) THEN
51617     RAISE EXCEPTION 'Period for % not found.', pPeriodDate;
51618   END IF;
51619
51620   RETURN _returnVal;
51621 END;
51622 $_$;
51623
51624
51625 ALTER FUNCTION public.getperiodid(date) OWNER TO admin;
51626
51627 --
51628 -- TOC entry 1729 (class 1255 OID 146566306)
51629 -- Dependencies: 4536 8
51630 -- Name: getperiodid(integer, character); Type: FUNCTION; Schema: public; Owner: admin
51631 --
51632
51633 CREATE FUNCTION getperiodid(integer, character) RETURNS SETOF integer
51634     LANGUAGE plpgsql IMMUTABLE
51635     AS $_$
51636 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51637 -- See www.xtuple.com/CPAL for the full text of the software license.
51638 DECLARE
51639   pPeriodId ALIAS FOR $1;
51640   pInterval ALIAS FOR $2;
51641   _x RECORD;
51642 BEGIN
51643
51644 -- Validate Interval
51645    IF pInterval <> 'M' AND pInterval <> 'Q' AND pInterval <> 'Y' THEN
51646      RAISE EXCEPTION 'Invalid Interval --> %', pInterval;
51647    END IF;
51648
51649    IF pInterval='M' THEN
51650        RETURN NEXT pPeriodId;
51651      ELSE IF pInterval='Q' THEN
51652         FOR _x IN SELECT qp.period_id AS period_id
51653                 FROM period cp, period qp
51654                 WHERE ((cp.period_id=pPeriodId)
51655                 AND (cp.period_yearperiod_id=qp.period_yearperiod_id)
51656                 AND (cp.period_quarter=qp.period_quarter)
51657                 AND (cp.period_start>=qp.period_start))
51658         ORDER BY qp.period_start
51659         LOOP
51660                 RETURN NEXT _x.period_id;
51661         END LOOP;
51662      ELSE
51663         FOR _x IN SELECT yp.period_id AS period_id
51664                 FROM period cp, period yp
51665                 WHERE ((cp.period_id=pPeriodId)
51666                 AND (cp.period_yearperiod_id=yp.period_yearperiod_id)
51667                 AND (cp.period_start>=yp.period_start))
51668         ORDER BY yp.period_start
51669         LOOP
51670                 RETURN NEXT _x.period_id;
51671         END LOOP;
51672      END IF;
51673    END IF;
51674   RETURN;
51675 END;
51676 $_$;
51677
51678
51679 ALTER FUNCTION public.getperiodid(integer, character) OWNER TO admin;
51680
51681 --
51682 -- TOC entry 1731 (class 1255 OID 146566308)
51683 -- Dependencies: 4536 8
51684 -- Name: getpkgheadid(text); Type: FUNCTION; Schema: public; Owner: admin
51685 --
51686
51687 CREATE FUNCTION getpkgheadid(text) RETURNS integer
51688     LANGUAGE plpgsql
51689     AS $_$
51690 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51691 -- See www.xtuple.com/CPAL for the full text of the software license.
51692 DECLARE
51693   ppkgname ALIAS FOR $1;
51694   _returnVal INTEGER;
51695 BEGIN
51696   IF (ppkgname IS NULL) THEN
51697     RETURN NULL;
51698   END IF;
51699
51700   SELECT pkghead_id INTO _returnVal
51701   FROM pkghead
51702   WHERE (UPPER(pkghead_name)=UPPER(ppkgname));
51703
51704   IF (_returnVal IS NULL) THEN
51705     RAISE EXCEPTION 'Package % not found.', ppkgname;
51706   END IF;
51707
51708   RETURN _returnVal;
51709 END;
51710 $_$;
51711
51712
51713 ALTER FUNCTION public.getpkgheadid(text) OWNER TO admin;
51714
51715 --
51716 -- TOC entry 1732 (class 1255 OID 146566309)
51717 -- Dependencies: 4536 8
51718 -- Name: getplancodeid(text); Type: FUNCTION; Schema: public; Owner: admin
51719 --
51720
51721 CREATE FUNCTION getplancodeid(text) RETURNS integer
51722     LANGUAGE plpgsql
51723     AS $_$
51724 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51725 -- See www.xtuple.com/CPAL for the full text of the software license.
51726 DECLARE
51727   pPlanCode ALIAS FOR $1;
51728   _returnVal INTEGER;
51729 BEGIN
51730   IF (pPlanCode IS NULL) THEN
51731         RETURN NULL;
51732   END IF;
51733
51734   SELECT plancode_id INTO _returnVal
51735   FROM plancode
51736   WHERE (plancode_code=pPlanCode);
51737
51738   IF (_returnVal IS NULL) THEN
51739         RAISE EXCEPTION 'Plan Code % not found.', pPlanCode;
51740   END IF;
51741
51742   RETURN _returnVal;
51743 END;
51744 $_$;
51745
51746
51747 ALTER FUNCTION public.getplancodeid(text) OWNER TO admin;
51748
51749 --
51750 -- TOC entry 1733 (class 1255 OID 146566310)
51751 -- Dependencies: 4536 8
51752 -- Name: getpoheadid(text); Type: FUNCTION; Schema: public; Owner: admin
51753 --
51754
51755 CREATE FUNCTION getpoheadid(text) RETURNS integer
51756     LANGUAGE plpgsql
51757     AS $_$
51758 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51759 -- See www.xtuple.com/CPAL for the full text of the software license.
51760 DECLARE
51761   pPurchaseOrderNumber ALIAS FOR $1;
51762   _returnVal INTEGER;
51763 BEGIN
51764   IF (pPurchaseOrderNumber IS NULL) THEN
51765     RETURN NULL;
51766   END IF;
51767
51768   SELECT pohead_id INTO _returnVal
51769   FROM pohead
51770   WHERE (pohead_number=pPurchaseOrderNumber);
51771
51772   IF (_returnVal IS NULL) THEN
51773         RAISE EXCEPTION 'Purchase Order % not found.', pPurchaseOrderNumber;
51774   END IF;
51775
51776   RETURN _returnVal;
51777 END;
51778 $_$;
51779
51780
51781 ALTER FUNCTION public.getpoheadid(text) OWNER TO admin;
51782
51783 --
51784 -- TOC entry 1734 (class 1255 OID 146566311)
51785 -- Dependencies: 4536 8
51786 -- Name: getpoitemid(text, integer); Type: FUNCTION; Schema: public; Owner: admin
51787 --
51788
51789 CREATE FUNCTION getpoitemid(text, integer) RETURNS integer
51790     LANGUAGE plpgsql
51791     AS $_$
51792 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51793 -- See www.xtuple.com/CPAL for the full text of the software license.
51794 DECLARE
51795   pPurchaseOrderNumber  ALIAS FOR $1;
51796   pLineNumber           ALIAS FOR $2;
51797   _returnVal            INTEGER;
51798 BEGIN
51799   IF (pPurchaseOrderNumber IS NULL OR pLineNumber IS NULL) THEN
51800     RETURN NULL;
51801   END IF;
51802
51803   SELECT poitem_id INTO _returnVal
51804   FROM pohead, poitem
51805   WHERE ((pohead_number=pPurchaseOrderNumber)
51806   AND (poitem_pohead_id=pohead_id)
51807   AND (poitem_linenumber=pLineNumber));
51808
51809   IF (_returnVal IS NULL) THEN
51810         RAISE EXCEPTION 'Purchase Order % not found.', pSalesOrderNumber;
51811   END IF;
51812
51813   RETURN _returnVal;
51814 END;
51815 $_$;
51816
51817
51818 ALTER FUNCTION public.getpoitemid(text, integer) OWNER TO admin;
51819
51820 --
51821 -- TOC entry 1735 (class 1255 OID 146566312)
51822 -- Dependencies: 4536 8
51823 -- Name: getprjaccntid(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
51824 --
51825
51826 CREATE FUNCTION getprjaccntid(integer, integer) RETURNS integer
51827     LANGUAGE plpgsql IMMUTABLE
51828     AS $_$
51829 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51830 -- See www.xtuple.com/CPAL for the full text of the software license.
51831 DECLARE
51832   pPrjid ALIAS FOR $1;
51833   pAccntid ALIAS FOR $2;
51834   
51835 BEGIN
51836   -- Project Accounting is required to fully implement this functionality
51837   RETURN pAccntId;
51838 END;
51839 $_$;
51840
51841
51842 ALTER FUNCTION public.getprjaccntid(integer, integer) OWNER TO admin;
51843
51844 --
51845 -- TOC entry 1736 (class 1255 OID 146566313)
51846 -- Dependencies: 4536 8
51847 -- Name: getprjid(text); Type: FUNCTION; Schema: public; Owner: admin
51848 --
51849
51850 CREATE FUNCTION getprjid(pprjnumber text) RETURNS integer
51851     LANGUAGE plpgsql STABLE
51852     AS $$
51853 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51854 -- See www.xtuple.com/CPAL for the full text of the software license.
51855 DECLARE
51856   _returnVal INTEGER;
51857 BEGIN
51858   IF (pPrjNumber IS NULL) THEN
51859         RETURN NULL;
51860   END IF;
51861
51862   SELECT prj_id INTO _returnVal
51863   FROM prj
51864   WHERE (prj_number=pPrjNumber);
51865
51866   IF (_returnVal IS NULL) THEN
51867         RAISE EXCEPTION 'Project Number % not found.', pPrjNumber;
51868   END IF;
51869
51870   RETURN _returnVal;
51871 END;
51872 $$;
51873
51874
51875 ALTER FUNCTION public.getprjid(pprjnumber text) OWNER TO admin;
51876
51877 --
51878 -- TOC entry 1737 (class 1255 OID 146566314)
51879 -- Dependencies: 4536 8
51880 -- Name: getprjtaskid(text, text); Type: FUNCTION; Schema: public; Owner: admin
51881 --
51882
51883 CREATE FUNCTION getprjtaskid(pprjnumber text, ptasknumber text) RETURNS integer
51884     LANGUAGE plpgsql STABLE
51885     AS $$
51886 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51887 -- See www.xtuple.com/CPAL for the full text of the software license.
51888 DECLARE
51889   _returnVal INTEGER;
51890 BEGIN
51891   IF (pPrjNumber IS NULL OR pTaskNumber IS NULL) THEN
51892         RETURN NULL;
51893   END IF;
51894
51895   SELECT prjtask_id INTO _returnVal
51896   FROM prjtask
51897     JOIN prj ON (prj_id=prjtask_prj_id)
51898   WHERE ((prj_number=pPrjNumber)
51899   AND (prjtask_number=pTaskNumber));
51900
51901   IF (_returnVal IS NULL) THEN
51902         RAISE EXCEPTION 'Project Task Number %-% not found.', pPrjNumber, pTaskNumber;
51903   END IF;
51904
51905   RETURN _returnVal;
51906 END;
51907 $$;
51908
51909
51910 ALTER FUNCTION public.getprjtaskid(pprjnumber text, ptasknumber text) OWNER TO admin;
51911
51912 --
51913 -- TOC entry 1738 (class 1255 OID 146566315)
51914 -- Dependencies: 4536 8
51915 -- Name: getprodcatid(text); Type: FUNCTION; Schema: public; Owner: admin
51916 --
51917
51918 CREATE FUNCTION getprodcatid(text) RETURNS integer
51919     LANGUAGE plpgsql
51920     AS $_$
51921 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51922 -- See www.xtuple.com/CPAL for the full text of the software license.
51923 DECLARE
51924   pProdCat ALIAS FOR $1;
51925   _returnVal INTEGER;
51926 BEGIN
51927   IF (pProdCat IS NULL) THEN
51928     RETURN NULL;
51929   END IF;
51930
51931   SELECT prodcat_id INTO _returnVal
51932   FROM prodcat
51933   WHERE (prodcat_code=pProdCat);
51934
51935   IF (_returnVal IS NULL) THEN
51936         RAISE EXCEPTION 'Product Category % not found.', pProdCat;
51937   END IF;
51938
51939   RETURN _returnVal;
51940 END;
51941 $_$;
51942
51943
51944 ALTER FUNCTION public.getprodcatid(text) OWNER TO admin;
51945
51946 --
51947 -- TOC entry 1739 (class 1255 OID 146566316)
51948 -- Dependencies: 4536 8
51949 -- Name: getprospectid(text); Type: FUNCTION; Schema: public; Owner: admin
51950 --
51951
51952 CREATE FUNCTION getprospectid(text) RETURNS integer
51953     LANGUAGE plpgsql
51954     AS $_$
51955 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51956 -- See www.xtuple.com/CPAL for the full text of the software license.
51957 DECLARE
51958   pProspectNumber ALIAS FOR $1;
51959   _returnVal INTEGER;
51960 BEGIN
51961   IF (pProspectNumber IS NULL) THEN
51962     RETURN NULL;
51963   END IF;
51964
51965   SELECT prospect_id INTO _returnVal
51966     FROM prospect
51967    WHERE(UPPER(prospect_number)=UPPER(pProspectNumber));
51968   IF (_returnVal IS NULL) THEN
51969     RAISE EXCEPTION 'Prospect Number % found.', pProspectNumber;
51970   END IF;
51971
51972   RETURN _returnVal;
51973 END;
51974 $_$;
51975
51976
51977 ALTER FUNCTION public.getprospectid(text) OWNER TO admin;
51978
51979 --
51980 -- TOC entry 1720 (class 1255 OID 146566317)
51981 -- Dependencies: 4536 8
51982 -- Name: getquoteid(text); Type: FUNCTION; Schema: public; Owner: admin
51983 --
51984
51985 CREATE FUNCTION getquoteid(text) RETURNS integer
51986     LANGUAGE plpgsql
51987     AS $_$
51988 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
51989 -- See www.xtuple.com/CPAL for the full text of the software license.
51990 DECLARE
51991   pQuoteNumber ALIAS FOR $1;
51992   _returnVal INTEGER;
51993 BEGIN
51994   IF (pQuoteNumber IS NULL) THEN
51995     RETURN NULL;
51996   END IF;
51997
51998   SELECT quhead_id INTO _returnVal
51999   FROM quhead
52000   WHERE (quhead_number=pQuoteNumber);
52001
52002   IF (_returnVal IS NULL) THEN
52003         RAISE EXCEPTION 'Quote Number % not found.', pQuoteNumber;
52004   END IF;
52005
52006   RETURN _returnVal;
52007 END;
52008 $_$;
52009
52010
52011 ALTER FUNCTION public.getquoteid(text) OWNER TO admin;
52012
52013 --
52014 -- TOC entry 1740 (class 1255 OID 146566318)
52015 -- Dependencies: 4536 8
52016 -- Name: getquotelineitemid(text, integer); Type: FUNCTION; Schema: public; Owner: admin
52017 --
52018
52019 CREATE FUNCTION getquotelineitemid(text, integer) RETURNS integer
52020     LANGUAGE plpgsql
52021     AS $_$
52022 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52023 -- See www.xtuple.com/CPAL for the full text of the software license.
52024 DECLARE
52025   pQuoteNumber ALIAS FOR $1;
52026   pLineNumber ALIAS FOR $2;
52027   _returnVal INTEGER;
52028 BEGIN
52029   IF ((pQuoteNumber IS NULL) OR (pLineNumber IS NULL)) THEN
52030     RETURN NULL;
52031   END IF;
52032
52033   SELECT quitem_id INTO _returnVal
52034   FROM quhead, quitem
52035   WHERE ((quhead_number=pQuoteNumber)
52036   AND (quhead_id=quitem_quhead_id)
52037   AND (quitem_linenumber=pLineNumber));
52038
52039   IF (_returnVal IS NULL) THEN
52040         RAISE EXCEPTION 'Quote Line Item %-%not found.', pQuoteNumber,pLineNumber;
52041   END IF;
52042
52043   RETURN _returnVal;
52044 END;
52045 $_$;
52046
52047
52048 ALTER FUNCTION public.getquotelineitemid(text, integer) OWNER TO admin;
52049
52050 --
52051 -- TOC entry 1741 (class 1255 OID 146566319)
52052 -- Dependencies: 4536 8
52053 -- Name: getquotescheddate(integer); Type: FUNCTION; Schema: public; Owner: admin
52054 --
52055
52056 CREATE FUNCTION getquotescheddate(integer) RETURNS date
52057     LANGUAGE plpgsql
52058     AS $_$
52059 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52060 -- See www.xtuple.com/CPAL for the full text of the software license.
52061 DECLARE
52062   pQuheadid ALIAS FOR $1;
52063   _minscheddate DATE;
52064
52065 BEGIN
52066
52067   SELECT MIN(quitem_scheddate) INTO _minscheddate
52068   FROM quitem
52069   WHERE (quitem_quhead_id=pQuheadid);
52070
52071   RETURN _minscheddate;
52072
52073 END;
52074 $_$;
52075
52076
52077 ALTER FUNCTION public.getquotescheddate(integer) OWNER TO admin;
52078
52079 --
52080 -- TOC entry 1742 (class 1255 OID 146566320)
52081 -- Dependencies: 4536 8
52082 -- Name: getrevid(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
52083 --
52084
52085 CREATE FUNCTION getrevid(text, text, text) RETURNS integer
52086     LANGUAGE plpgsql
52087     AS $_$
52088 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52089 -- See www.xtuple.com/CPAL for the full text of the software license.
52090 DECLARE
52091   pType ALIAS FOR $1;
52092   pItemNumber ALIAS FOR $2;
52093   pRevision ALIAS FOR $3;
52094   _returnVal INTEGER;
52095 BEGIN
52096   IF (pItemNumber IS NULL) THEN
52097     RETURN NULL;
52098   END IF;
52099
52100   IF (NOT fetchMetricBool('RevControl')) THEN
52101     RETURN -1;
52102   ELSIF ( (pRevision IS NULL) OR (LENGTH(pRevision)=0) ) THEN
52103     SELECT getActiveRevId(pType, getItemId(pItemNumber)) INTO _returnVal;
52104   ELSE
52105     IF (pType='BOM') THEN
52106       SELECT rev_id INTO _returnVal
52107       FROM item, bomhead, rev
52108       WHERE ((item_id=bomhead_item_id)
52109       AND (bomhead_rev_id=rev_id)
52110       AND (UPPER(item_number)=UPPER(pItemNumber))
52111       AND (rev_number=pRevision));
52112     ELSIF (pType='BOO') THEN
52113       SELECT rev_id INTO _returnVal
52114       FROM item, xtmfg.boohead, rev
52115       WHERE ((item_id=boohead_item_id)
52116       AND (boohead_rev_id=rev_id)
52117       AND (UPPER(item_number)=UPPER(pItemNumber))
52118       AND (rev_number=pRevision));   
52119     ELSE
52120       RAISE EXCEPTION 'Invalid Revision Type.';
52121     END IF;
52122   END IF;
52123     
52124   IF (_returnVal IS NULL) THEN
52125     RAISE EXCEPTION '% revision % for % not found.', pType, pRevision, pItemNumber;
52126   END IF;
52127
52128   RETURN _returnVal;
52129 END;
52130 $_$;
52131
52132
52133 ALTER FUNCTION public.getrevid(text, text, text) OWNER TO admin;
52134
52135 --
52136 -- TOC entry 1743 (class 1255 OID 146566321)
52137 -- Dependencies: 4536 8
52138 -- Name: getrsnid(text); Type: FUNCTION; Schema: public; Owner: admin
52139 --
52140
52141 CREATE FUNCTION getrsnid(text) RETURNS integer
52142     LANGUAGE plpgsql
52143     AS $_$
52144 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52145 -- See www.xtuple.com/CPAL for the full text of the software license.
52146 DECLARE
52147   pRsnCode ALIAS FOR $1;
52148   _returnVal INTEGER;
52149 BEGIN
52150   IF (pRsnCode IS NULL) THEN
52151     RETURN NULL;
52152   END IF;
52153
52154   SELECT rsncode_id INTO _returnVal
52155   FROM rsncode
52156   WHERE (rsncode_code=pRsnCode);
52157
52158   IF (_returnVal IS NULL) THEN
52159         RAISE EXCEPTION 'Reason Code % not found.', pRsnCode;
52160   END IF;
52161
52162   RETURN _returnVal;
52163 END;
52164 $_$;
52165
52166
52167 ALTER FUNCTION public.getrsnid(text) OWNER TO admin;
52168
52169 --
52170 -- TOC entry 1744 (class 1255 OID 146566322)
52171 -- Dependencies: 4536 8
52172 -- Name: getsalescatid(text); Type: FUNCTION; Schema: public; Owner: admin
52173 --
52174
52175 CREATE FUNCTION getsalescatid(text) RETURNS integer
52176     LANGUAGE plpgsql
52177     AS $_$
52178 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52179 -- See www.xtuple.com/CPAL for the full text of the software license.
52180 DECLARE
52181   pSalesCatName ALIAS FOR $1;
52182   _returnVal INTEGER;
52183 BEGIN
52184   IF (pSalesCatName IS NULL) THEN
52185     RETURN NULL;
52186   END IF;
52187
52188   SELECT salescat_id INTO _returnVal
52189   FROM salescat
52190   WHERE (salescat_name=pSalesCatName);
52191
52192   IF (_returnVal IS NULL) THEN
52193         RAISE EXCEPTION 'Sales Category % not found.', pSalesCatName;
52194   END IF;
52195
52196   RETURN _returnVal;
52197 END;
52198 $_$;
52199
52200
52201 ALTER FUNCTION public.getsalescatid(text) OWNER TO admin;
52202
52203 --
52204 -- TOC entry 1746 (class 1255 OID 146566324)
52205 -- Dependencies: 4536 8
52206 -- Name: getsaleslineitemid(text); Type: FUNCTION; Schema: public; Owner: admin
52207 --
52208
52209 CREATE FUNCTION getsaleslineitemid(text) RETURNS integer
52210     LANGUAGE plpgsql
52211     AS $_$
52212 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52213 -- See www.xtuple.com/CPAL for the full text of the software license.
52214 DECLARE
52215   pSalesOrderItem ALIAS FOR $1;
52216   _delpos INTEGER = 0;
52217   _order TEXT;
52218   _part TEXT;
52219   _ln INTEGER;
52220   _sn INTEGER;
52221 BEGIN
52222   IF (pSalesOrderItem IS NULL) THEN
52223     RETURN NULL;
52224   END IF;
52225   _delpos := strpos(pSalesOrderItem, '-');
52226   IF (_delpos > 0) THEN
52227     _order := substr(pSalesOrderItem, 1, (_delpos - 1));
52228     _part := substr(pSalesOrderItem, (_delpos + 1));
52229     _delpos := strpos(_part, '.');
52230     IF (_delpos > 0) THEN
52231       _ln := CAST(substr(_part, 1, (_delpos - 1)) AS INTEGER);
52232       _sn := CAST(substr(_part, (_delpos + 1)) AS INTEGER);
52233     ELSE
52234       _ln := CAST(_part AS INTEGER);
52235       _sn := 0;
52236     END IF;
52237     RETURN getSalesLineItemId( _order, _ln, _sn );
52238   END IF;
52239   RETURN 0;
52240 END;
52241 $_$;
52242
52243
52244 ALTER FUNCTION public.getsaleslineitemid(text) OWNER TO admin;
52245
52246 --
52247 -- TOC entry 1745 (class 1255 OID 146566323)
52248 -- Dependencies: 4536 8
52249 -- Name: getsaleslineitemid(text, integer); Type: FUNCTION; Schema: public; Owner: admin
52250 --
52251
52252 CREATE FUNCTION getsaleslineitemid(text, integer) RETURNS integer
52253     LANGUAGE plpgsql
52254     AS $_$
52255 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52256 -- See www.xtuple.com/CPAL for the full text of the software license.
52257 BEGIN
52258   RETURN getSalesLineItemId($1, $2, 0);
52259 END
52260 $_$;
52261
52262
52263 ALTER FUNCTION public.getsaleslineitemid(text, integer) OWNER TO admin;
52264
52265 --
52266 -- TOC entry 1747 (class 1255 OID 146566325)
52267 -- Dependencies: 4536 8
52268 -- Name: getsaleslineitemid(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
52269 --
52270
52271 CREATE FUNCTION getsaleslineitemid(text, integer, integer) RETURNS integer
52272     LANGUAGE plpgsql
52273     AS $_$
52274 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52275 -- See www.xtuple.com/CPAL for the full text of the software license.
52276 DECLARE
52277   pSalesOrderNumber ALIAS FOR $1;
52278   pLineNumber ALIAS FOR $2;
52279   pSubNumber ALIAS FOR $3;
52280   _returnVal INTEGER;
52281 BEGIN
52282   IF ((pSalesOrderNumber IS NULL) OR (pLineNumber IS NULL)) THEN
52283     RETURN NULL;
52284   END IF;
52285
52286   SELECT coitem_id INTO _returnVal
52287   FROM cohead, coitem
52288   WHERE ((cohead_number=pSalesOrderNumber)
52289   AND (cohead_id=coitem_cohead_id)
52290   AND (coitem_linenumber=pLineNumber)
52291   AND (coitem_subnumber=pSubNumber));
52292
52293   IF (_returnVal IS NULL) THEN
52294         RAISE EXCEPTION 'Sales Line Item %-%not found.', pSalesOrderNumber,pLineNumber;
52295   END IF;
52296
52297   RETURN _returnVal;
52298 END;
52299 $_$;
52300
52301
52302 ALTER FUNCTION public.getsaleslineitemid(text, integer, integer) OWNER TO admin;
52303
52304 --
52305 -- TOC entry 1748 (class 1255 OID 146566326)
52306 -- Dependencies: 4536 8
52307 -- Name: getsalesorderid(text); Type: FUNCTION; Schema: public; Owner: admin
52308 --
52309
52310 CREATE FUNCTION getsalesorderid(text) RETURNS integer
52311     LANGUAGE plpgsql
52312     AS $_$
52313 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52314 -- See www.xtuple.com/CPAL for the full text of the software license.
52315 DECLARE
52316   pSalesOrderNumber ALIAS FOR $1;
52317   _returnVal INTEGER;
52318 BEGIN
52319   IF (pSalesOrderNumber IS NULL) THEN
52320     RETURN NULL;
52321   END IF;
52322
52323   SELECT cohead_id INTO _returnVal
52324   FROM cohead
52325   WHERE (cohead_number=pSalesOrderNumber);
52326
52327   IF (_returnVal IS NULL) THEN
52328         RAISE EXCEPTION 'Sales Order Number % not found.', pSalesOrderNumber;
52329   END IF;
52330
52331   RETURN _returnVal;
52332 END;
52333 $_$;
52334
52335
52336 ALTER FUNCTION public.getsalesorderid(text) OWNER TO admin;
52337
52338 --
52339 -- TOC entry 1749 (class 1255 OID 146566327)
52340 -- Dependencies: 4536 8
52341 -- Name: getsalesrepid(text); Type: FUNCTION; Schema: public; Owner: admin
52342 --
52343
52344 CREATE FUNCTION getsalesrepid(text) RETURNS integer
52345     LANGUAGE plpgsql
52346     AS $_$
52347 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52348 -- See www.xtuple.com/CPAL for the full text of the software license.
52349 DECLARE
52350   pSalesRepNumber ALIAS FOR $1;
52351   _returnVal INTEGER;
52352 BEGIN
52353   IF (pSalesRepNumber IS NULL) THEN
52354     RETURN NULL;
52355   END IF;
52356
52357   SELECT salesrep_id INTO _returnVal
52358   FROM salesrep
52359   WHERE (salesrep_number=pSalesRepNumber);
52360
52361   IF (_returnVal IS NULL) THEN
52362         RAISE EXCEPTION 'Sales Rep Number % not found.', pSalesRepNumber;
52363   END IF;
52364
52365   RETURN _returnVal;
52366 END;
52367 $_$;
52368
52369
52370 ALTER FUNCTION public.getsalesrepid(text) OWNER TO admin;
52371
52372 --
52373 -- TOC entry 1751 (class 1255 OID 146566328)
52374 -- Dependencies: 4536 8
52375 -- Name: getsaletypeid(text); Type: FUNCTION; Schema: public; Owner: admin
52376 --
52377
52378 CREATE FUNCTION getsaletypeid(psaletype text) RETURNS integer
52379     LANGUAGE plpgsql
52380     AS $$
52381 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52382 -- See www.xtuple.com/CPAL for the full text of the software license.
52383 DECLARE
52384   _returnVal INTEGER;
52385 BEGIN
52386   IF (pSaleType IS NULL) THEN
52387     RETURN NULL;
52388   END IF;
52389
52390   SELECT saletype_id INTO _returnVal
52391   FROM saletype
52392   WHERE (saletype_code=UPPER(pSaleType));
52393
52394   IF (_returnVal IS NULL) THEN
52395     RAISE EXCEPTION 'Sale Type % not found.', pSaleType;
52396   END IF;
52397
52398   RETURN _returnVal;
52399 END;
52400 $$;
52401
52402
52403 ALTER FUNCTION public.getsaletypeid(psaletype text) OWNER TO admin;
52404
52405 --
52406 -- TOC entry 1752 (class 1255 OID 146566329)
52407 -- Dependencies: 4536 8
52408 -- Name: getshiftid(text); Type: FUNCTION; Schema: public; Owner: admin
52409 --
52410
52411 CREATE FUNCTION getshiftid(text) RETURNS integer
52412     LANGUAGE plpgsql
52413     AS $_$
52414 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52415 -- See www.xtuple.com/CPAL for the full text of the software license.
52416 DECLARE
52417   pShiftNumber ALIAS FOR $1;
52418   _returnVal INTEGER;
52419 BEGIN
52420   IF (COALESCE(TRIM(pShiftNumber), '') = '') THEN
52421       RETURN NULL;
52422   END IF;
52423
52424   SELECT shift_id INTO _returnVal
52425   FROM shift
52426   WHERE (UPPER(shift_number)=UPPER(pShiftNumber));
52427
52428   IF (_returnVal IS NULL) THEN
52429     RAISE EXCEPTION 'Shift % not found.', pShiftNumber;
52430   END IF;
52431
52432   RETURN _returnVal;
52433 END;
52434 $_$;
52435
52436
52437 ALTER FUNCTION public.getshiftid(text) OWNER TO admin;
52438
52439 --
52440 -- TOC entry 1753 (class 1255 OID 146566330)
52441 -- Dependencies: 4536 8
52442 -- Name: getshipchrgid(text); Type: FUNCTION; Schema: public; Owner: admin
52443 --
52444
52445 CREATE FUNCTION getshipchrgid(text) RETURNS integer
52446     LANGUAGE plpgsql
52447     AS $_$
52448 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52449 -- See www.xtuple.com/CPAL for the full text of the software license.
52450 DECLARE
52451   pShipChrgName ALIAS FOR $1;
52452   _returnVal INTEGER;
52453 BEGIN
52454   IF (pShipChrgName IS NULL) THEN
52455         RETURN NULL;
52456   END IF;
52457
52458   SELECT shipchrg_id INTO _returnVal
52459   FROM shipchrg
52460   WHERE (shipchrg_name=pShipChrgName);
52461
52462   IF (_returnVal IS NULL) THEN
52463         RAISE EXCEPTION 'Ship Charge % not found.', pShipChrgName;
52464   END IF;
52465
52466   RETURN _returnVal;
52467 END;
52468 $_$;
52469
52470
52471 ALTER FUNCTION public.getshipchrgid(text) OWNER TO admin;
52472
52473 --
52474 -- TOC entry 1754 (class 1255 OID 146566331)
52475 -- Dependencies: 4536 8
52476 -- Name: getshipformid(text); Type: FUNCTION; Schema: public; Owner: admin
52477 --
52478
52479 CREATE FUNCTION getshipformid(text) RETURNS integer
52480     LANGUAGE plpgsql
52481     AS $_$
52482 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52483 -- See www.xtuple.com/CPAL for the full text of the software license.
52484 DECLARE
52485   pShipFormName ALIAS FOR $1;
52486   _returnVal INTEGER;
52487 BEGIN
52488   IF (pShipFormName IS NULL) THEN
52489         RETURN NULL;
52490   END IF;
52491
52492   SELECT shipform_id INTO _returnVal
52493   FROM shipform
52494   WHERE (shipform_name=pShipFormName) LIMIT 1;
52495
52496   IF (_returnVal IS NULL) THEN
52497         RAISE EXCEPTION 'Ship Form % not found.', pShipFormName;
52498   END IF;
52499
52500   RETURN _returnVal;
52501 END;
52502 $_$;
52503
52504
52505 ALTER FUNCTION public.getshipformid(text) OWNER TO admin;
52506
52507 --
52508 -- TOC entry 1755 (class 1255 OID 146566332)
52509 -- Dependencies: 4536 8
52510 -- Name: getshipheadid(text); Type: FUNCTION; Schema: public; Owner: admin
52511 --
52512
52513 CREATE FUNCTION getshipheadid(text) RETURNS integer
52514     LANGUAGE plpgsql
52515     AS $_$
52516 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52517 -- See www.xtuple.com/CPAL for the full text of the software license.
52518 DECLARE
52519   pShipmentNumber ALIAS FOR $1;
52520   _returnVal INTEGER;
52521 BEGIN
52522   IF (pShipmentNumber IS NULL OR pShipmentNumber = '') THEN
52523     RETURN NULL;
52524   END IF;
52525
52526   SELECT shiphead_id INTO _returnVal
52527   FROM shiphead
52528   WHERE (shiphead_number=pShipmentNumber);
52529
52530   IF (_returnVal IS NULL) THEN
52531         RAISE EXCEPTION 'Shipment % not found.', pShipmentNumber;
52532   END IF;
52533
52534   RETURN _returnVal;
52535 END;
52536 $_$;
52537
52538
52539 ALTER FUNCTION public.getshipheadid(text) OWNER TO admin;
52540
52541 --
52542 -- TOC entry 1756 (class 1255 OID 146566333)
52543 -- Dependencies: 4536 8
52544 -- Name: getshiptoid(text, text); Type: FUNCTION; Schema: public; Owner: admin
52545 --
52546
52547 CREATE FUNCTION getshiptoid(text, text) RETURNS integer
52548     LANGUAGE plpgsql
52549     AS $_$
52550 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52551 -- See www.xtuple.com/CPAL for the full text of the software license.
52552 DECLARE
52553   pCustNumber ALIAS FOR $1;
52554   pShiptoNumber ALIAS FOR $2;
52555   _returnVal INTEGER;
52556 BEGIN
52557   IF ((pCustNumber IS NULL) OR (pShiptoNumber IS NULL)) THEN
52558         RETURN NULL;
52559   END IF;
52560
52561   SELECT shipto_id INTO _returnVal
52562   FROM shiptoinfo
52563   WHERE ((shipto_cust_id=getCustId(pCustNumber,true))
52564   AND (UPPER(shipto_num)=UPPER(pShiptoNumber)));
52565
52566   IF (_returnVal IS NULL) THEN
52567         RAISE EXCEPTION 'Shipto % not found.', pShiptoNumber;
52568   END IF;
52569
52570   RETURN _returnVal;
52571 END;
52572 $_$;
52573
52574
52575 ALTER FUNCTION public.getshiptoid(text, text) OWNER TO admin;
52576
52577 --
52578 -- TOC entry 1757 (class 1255 OID 146566334)
52579 -- Dependencies: 4536 8
52580 -- Name: getshiptonumberfrominfo(text, text, text, text, text, text, text, text, text, text, text, text, text, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
52581 --
52582
52583 CREATE FUNCTION getshiptonumberfrominfo(text, text, text, text, text, text, text, text, text, text, text, text, text, boolean, boolean) RETURNS text
52584     LANGUAGE plpgsql
52585     AS $_$
52586 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52587 -- See www.xtuple.com/CPAL for the full text of the software license.
52588 DECLARE
52589   _custname TEXT := COALESCE(TRIM(UPPER( $1)), '');
52590   _email TEXT    := COALESCE(TRIM(UPPER( $2)), '');
52591   _company TEXT  := COALESCE(TRIM(UPPER( $3)), '');
52592   _first TEXT    := COALESCE(TRIM(UPPER( $4)), '');
52593   _last TEXT     := COALESCE(TRIM(UPPER( $5)), '');
52594   _fullname TEXT := COALESCE(TRIM(UPPER( $6)), '');
52595   _addr1 TEXT    := COALESCE(TRIM(UPPER( $7)), '');
52596   _addr2 TEXT    := COALESCE(TRIM(UPPER( $8)), '');
52597   _addr3 TEXT    := COALESCE(TRIM(UPPER( $9)), '');
52598   _city TEXT     := COALESCE(TRIM(UPPER($10)), '');
52599   _state TEXT    := COALESCE(TRIM(UPPER($11)), '');
52600   _postalcode TEXT := COALESCE(TRIM(UPPER($12)), '');
52601   _country TEXT  := COALESCE(TRIM(UPPER($13)), '');
52602   _generate BOOLEAN := COALESCE($14, FALSE);
52603   _create BOOLEAN := COALESCE($15, FALSE);
52604
52605   _citytrunc TEXT;
52606   _counter INTEGER;
52607   _custid INTEGER;
52608   _custnumber TEXT;
52609   _candidate TEXT;
52610   _r RECORD;
52611   _statetrunc TEXT;
52612 BEGIN
52613   IF (_custname = '') THEN
52614     _custname := getCustNameFromInfo(_email, _company, _first, _last,
52615                      _fullname, FALSE);
52616   END IF;
52617
52618
52619   SELECT COUNT(*) INTO _counter
52620   FROM custinfo, shiptoinfo, addr
52621   WHERE ((UPPER(cust_name)=UPPER(_custname))
52622     AND UPPER(shipto_name)=UPPER(_fullname)
52623     AND (cust_id=shipto_cust_id)
52624     AND (shipto_addr_id=addr_id));
52625
52626   IF (_counter = 1) THEN
52627     SELECT shipto_num INTO _candidate
52628     FROM custinfo, shiptoinfo, addr
52629     WHERE ((UPPER(cust_name)=UPPER(_custname))
52630       AND UPPER(shipto_name)=UPPER(_fullname)
52631       AND (cust_id=shipto_cust_id)
52632       AND (shipto_addr_id=addr_id));
52633
52634     RETURN _candidate;
52635
52636   ELSE
52637
52638     SELECT COUNT(*) INTO _counter
52639     FROM custinfo, shiptoinfo, addr
52640     WHERE ((UPPER(cust_name)=UPPER(_custname))
52641       AND (cust_id=shipto_cust_id)
52642       AND (shipto_addr_id=addr_id));
52643
52644     IF (_counter = 1) THEN
52645       SELECT shipto_num INTO _candidate
52646       FROM custinfo, shiptoinfo, addr
52647       WHERE ((UPPER(cust_name)=UPPER(_custname))
52648         AND (cust_id=shipto_cust_id)
52649         AND (shipto_addr_id=addr_id));
52650
52651       RETURN _candidate;
52652
52653     ELSIF (_counter > 1) THEN
52654       SELECT shipto_num,
52655          CASE WHEN (UPPER(addr_country) = _country) THEN 1 ELSE 0 END +
52656          CASE WHEN (UPPER(addr_postalcode) = _postalcode) THEN 1 ELSE 0 END +
52657          CASE WHEN (UPPER(addr_state) = _state) THEN 1 ELSE 0 END +
52658          CASE WHEN (UPPER(addr_city) = _city) THEN 1 ELSE 0 END +
52659          CASE WHEN (UPPER(addr_line3) = _addr3) THEN 1 ELSE 0 END +
52660          CASE WHEN (UPPER(addr_line2) = _addr2) THEN 1 ELSE 0 END +
52661          CASE WHEN (UPPER(addr_line1) = _addr1) THEN 1 ELSE 0 END
52662          AS maxquotient INTO _candidate, _counter
52663       FROM custinfo, shiptoinfo, addr
52664       WHERE ((UPPER(cust_name)=_custname)
52665         AND (cust_id=shipto_cust_id)
52666         AND (shipto_addr_id=addr_id))
52667       ORDER BY maxquotient desc
52668       LIMIT 1;
52669
52670       RETURN _candidate;
52671     END IF;
52672   END IF;
52673
52674   IF (_generate) THEN
52675     SELECT cust_number, cust_id INTO _custnumber, _custid
52676     FROM custinfo
52677     WHERE (UPPER(cust_name)=_custname);
52678
52679     -- keep the number short
52680     _citytrunc := SUBSTRING(_city FOR 5);
52681     _statetrunc := SUBSTRING(_state FOR 5);
52682
52683     IF (LENGTH(_citytrunc) > 0 AND NOT EXISTS(SELECT UPPER(shipto_num)
52684               FROM shiptoinfo
52685               WHERE ((shipto_cust_id=_custid)
52686                 AND (UPPER(shipto_num)=_citytrunc)) )) THEN
52687       _candidate := _citytrunc;
52688     ELSIF (LENGTH(_last || _citytrunc) > 0 AND NOT EXISTS(SELECT UPPER(shipto_num)
52689               FROM shiptoinfo
52690               WHERE ((shipto_cust_id=_custid)
52691                 AND (UPPER(shipto_num)=_last || _citytrunc)) )) THEN
52692       _candidate := _last || _citytrunc;
52693     ELSIF (LENGTH(_statetrunc) > 0 AND NOT EXISTS(SELECT UPPER(shipto_num)
52694            FROM shiptoinfo
52695            WHERE ((shipto_cust_id=_custid)
52696              AND (UPPER(shipto_num)=_statetrunc)) )) THEN
52697       _candidate := _statetrunc;
52698     ELSIF (LENGTH(_last || _statetrunc) > 0 AND NOT EXISTS(SELECT UPPER(shipto_num)
52699            FROM shiptoinfo
52700            WHERE ((shipto_cust_id=_custid)
52701              AND (UPPER(shipto_num)=_last || _statetrunc)) )) THEN
52702       _candidate := _last || _statetrunc;
52703
52704     ELSIF (LENGTH(_citytrunc || _statetrunc) > 0 AND NOT EXISTS(SELECT UPPER(shipto_num)
52705               FROM shiptoinfo
52706               WHERE ((shipto_cust_id=_custid)
52707                 AND (UPPER(shipto_num)=_citytrunc || _statetrunc)) )) THEN
52708       _candidate := _citytrunc || _statetrunc;
52709
52710     ELSE
52711       SELECT CAST(COALESCE(MAX(CAST(shipto_num AS INTEGER)), 0) + 1 AS TEXT)
52712       INTO _candidate
52713       FROM shiptoinfo
52714       WHERE ((shipto_cust_id=_custid)
52715        AND (shipto_num~'^[0-9]*$'));
52716     END IF;
52717
52718     IF (_create) THEN
52719       INSERT INTO api.custshipto (
52720     customer_number, shipto_number, name,
52721     address1, address2, address3,
52722     city, state, postal_code, country, address_change,
52723     first, last, email,
52724     edi_profile
52725       ) VALUES (
52726     _custnumber, _candidate, _candidate,
52727     _addr1, _addr2, _addr3,
52728     _city, _state, _postalcode, _country, 'CHANGEONE',
52729     _first, _last, LOWER(_email),
52730     'No EDI'
52731       );
52732     END IF;
52733
52734     RETURN _candidate;
52735   END IF;
52736
52737   RETURN '';
52738 END;
52739 $_$;
52740
52741
52742 ALTER FUNCTION public.getshiptonumberfrominfo(text, text, text, text, text, text, text, text, text, text, text, text, text, boolean, boolean) OWNER TO admin;
52743
52744 --
52745 -- TOC entry 1758 (class 1255 OID 146566335)
52746 -- Dependencies: 4536 8
52747 -- Name: getshipviaid(text); Type: FUNCTION; Schema: public; Owner: admin
52748 --
52749
52750 CREATE FUNCTION getshipviaid(text) RETURNS integer
52751     LANGUAGE plpgsql
52752     AS $_$
52753 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52754 -- See www.xtuple.com/CPAL for the full text of the software license.
52755 DECLARE
52756   pShipViaCode ALIAS FOR $1;
52757   _returnVal INTEGER;
52758 BEGIN
52759   IF (pShipViaCode IS NULL) THEN
52760         RETURN NULL;
52761   END IF;
52762
52763   SELECT shipvia_id INTO _returnVal
52764   FROM shipvia
52765   WHERE (shipvia_code=pShipViaCode);
52766
52767   IF (_returnVal IS NULL) THEN
52768         RAISE EXCEPTION 'ShipVia Code % not found.', pShipViaCode;
52769   END IF;
52770
52771   RETURN _returnVal;
52772 END;
52773 $_$;
52774
52775
52776 ALTER FUNCTION public.getshipviaid(text) OWNER TO admin;
52777
52778 --
52779 -- TOC entry 1759 (class 1255 OID 146566336)
52780 -- Dependencies: 4536 8
52781 -- Name: getshipzoneid(text); Type: FUNCTION; Schema: public; Owner: admin
52782 --
52783
52784 CREATE FUNCTION getshipzoneid(pshipzonename text) RETURNS integer
52785     LANGUAGE plpgsql
52786     AS $$
52787 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52788 -- See www.xtuple.com/CPAL for the full text of the software license.
52789 DECLARE
52790   _returnVal INTEGER;
52791 BEGIN
52792   IF (pShipZoneName IS NULL) THEN
52793     RETURN NULL;
52794   END IF;
52795
52796   SELECT shipzone_id INTO _returnVal
52797   FROM shipzone
52798   WHERE (shipzone_name=pShipZoneName);
52799
52800   IF (_returnVal IS NULL) THEN
52801     RAISE EXCEPTION 'Ship Zone % not found.', pShipZoneName;
52802   END IF;
52803
52804   RETURN _returnVal;
52805 END;
52806 $$;
52807
52808
52809 ALTER FUNCTION public.getshipzoneid(pshipzonename text) OWNER TO admin;
52810
52811 --
52812 -- TOC entry 1760 (class 1255 OID 146566337)
52813 -- Dependencies: 4536 8
52814 -- Name: getsitetypeid(text); Type: FUNCTION; Schema: public; Owner: admin
52815 --
52816
52817 CREATE FUNCTION getsitetypeid(text) RETURNS integer
52818     LANGUAGE plpgsql
52819     AS $_$
52820 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52821 -- See www.xtuple.com/CPAL for the full text of the software license.
52822 DECLARE
52823   pSiteType ALIAS FOR $1;
52824   _returnVal INTEGER;
52825 BEGIN
52826   IF (pSiteType IS NULL) THEN
52827         RETURN NULL;
52828   END IF;
52829
52830   SELECT sitetype_id INTO _returnVal
52831   FROM sitetype
52832   WHERE (sitetype_name=pSiteType);
52833
52834   IF (_returnVal IS NULL) THEN
52835         RAISE EXCEPTION 'Site Type % not found.', pSiteType;
52836   END IF;
52837
52838   RETURN _returnVal;
52839 END;
52840 $_$;
52841
52842
52843 ALTER FUNCTION public.getsitetypeid(text) OWNER TO admin;
52844
52845 --
52846 -- TOC entry 1761 (class 1255 OID 146566338)
52847 -- Dependencies: 4536 8
52848 -- Name: getsoitemstatus(integer); Type: FUNCTION; Schema: public; Owner: admin
52849 --
52850
52851 CREATE FUNCTION getsoitemstatus(pcoitemid integer) RETURNS text
52852     LANGUAGE plpgsql STABLE
52853     AS $$
52854 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52855 -- See www.xtuple.com/CPAL for the full text of the software license.
52856 DECLARE
52857   _result TEXT;
52858
52859 BEGIN
52860
52861   SELECT
52862       (CASE WHEN (coitem_status='O' AND (SELECT cust_creditstatus FROM custinfo WHERE cust_id=cohead_cust_id)='H') THEN 'H'
52863             WHEN (coitem_status='O' AND ((SELECT SUM(invcitem_billed)
52864                                             FROM invchead, invcitem
52865                                            WHERE ((CAST(invchead_ordernumber AS text)=cohead_number)
52866                                              AND  (invcitem_invchead_id=invchead_id)
52867                                              AND  (invcitem_item_id=itemsite_item_id)
52868                                              AND  (invcitem_warehous_id=itemsite_warehous_id)
52869                                              AND  (invcitem_linenumber=coitem_linenumber))) >= coitem_qtyord)) THEN 'I'
52870             WHEN (coitem_status='O' AND ((SELECT SUM(invcitem_billed)
52871                                             FROM invchead, invcitem
52872                                            WHERE ((CAST(invchead_ordernumber AS text)=cohead_number)
52873                                              AND  (invcitem_invchead_id=invchead_id)
52874                                              AND  (invcitem_item_id=itemsite_item_id)
52875                                              AND  (invcitem_warehous_id=itemsite_warehous_id)
52876                                              AND  (invcitem_linenumber=coitem_linenumber))) > 0)) THEN 'P'
52877             WHEN (coitem_status='O' AND (itemsite_qtyonhand - qtyAllocated(itemsite_id, CURRENT_DATE)
52878                                          + qtyOrdered(itemsite_id, CURRENT_DATE))
52879                                           >= ((coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) * coitem_qty_invuomratio)) THEN 'R'
52880             ELSE coitem_status END
52881        || CASE WHEN (coitem_firm) THEN 'F' ELSE '' END
52882        ) INTO _result
52883   FROM coitem JOIN cohead ON (cohead_id=coitem_cohead_id)
52884               JOIN custinfo ON (cust_id=cohead_cust_id)
52885               JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
52886   WHERE (coitem_id=pCoitemid);
52887
52888   RETURN _result;
52889
52890 END;
52891 $$;
52892
52893
52894 ALTER FUNCTION public.getsoitemstatus(pcoitemid integer) OWNER TO admin;
52895
52896 --
52897 -- TOC entry 1762 (class 1255 OID 146566339)
52898 -- Dependencies: 4536 8
52899 -- Name: getsoscheddate(integer); Type: FUNCTION; Schema: public; Owner: admin
52900 --
52901
52902 CREATE FUNCTION getsoscheddate(integer) RETURNS date
52903     LANGUAGE plpgsql
52904     AS $_$
52905 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52906 -- See www.xtuple.com/CPAL for the full text of the software license.
52907 DECLARE
52908   pCoheadid ALIAS FOR $1;
52909   _minscheddate DATE;
52910
52911 BEGIN
52912
52913   SELECT MIN(coitem_scheddate) INTO _minscheddate
52914   FROM coitem
52915   WHERE ( (coitem_cohead_id=pCoheadid)
52916     AND   (coitem_status NOT IN ('C', 'X')) );
52917
52918   RETURN _minscheddate;
52919
52920 END;
52921 $_$;
52922
52923
52924 ALTER FUNCTION public.getsoscheddate(integer) OWNER TO admin;
52925
52926 --
52927 -- TOC entry 1763 (class 1255 OID 146566340)
52928 -- Dependencies: 4536 8
52929 -- Name: getsostatus(integer); Type: FUNCTION; Schema: public; Owner: admin
52930 --
52931
52932 CREATE FUNCTION getsostatus(integer) RETURNS character
52933     LANGUAGE plpgsql STABLE
52934     AS $_$
52935 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52936 -- See www.xtuple.com/CPAL for the full text of the software license.
52937 DECLARE
52938   pCoheadid ALIAS FOR $1;
52939   _result char(1);
52940
52941 BEGIN
52942
52943   SELECT cohead_status INTO _result
52944   FROM cohead
52945   WHERE (cohead_id=pCoheadid);
52946
52947   RETURN _result;
52948
52949 END;
52950 $_$;
52951
52952
52953 ALTER FUNCTION public.getsostatus(integer) OWNER TO admin;
52954
52955 --
52956 -- TOC entry 1764 (class 1255 OID 146566341)
52957 -- Dependencies: 2702 4536 8
52958 -- Name: getsubtax(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
52959 --
52960
52961 CREATE FUNCTION getsubtax(integer, integer) RETURNS SETOF subtax
52962     LANGUAGE plpgsql
52963     AS $_$
52964 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
52965 -- See www.xtuple.com/CPAL for the full text of the software license.
52966 DECLARE
52967   pTaxCodeId ALIAS FOR $1;
52968   pLevel ALIAS FOR $2;
52969   _row subtax%ROWTYPE;
52970   _x RECORD;
52971   _y RECORD;
52972
52973 BEGIN
52974
52975   FOR _x IN --Select all tax codes whose calculation basis is pTaxCodeId
52976     SELECT tax_id, tax_code, tax_descrip
52977     FROM tax
52978     WHERE tax_basis_tax_id = pTaxCodeId
52979     
52980     
52981     LOOP
52982     _row.subtax_taxcode_id := _x.tax_id;
52983     _row.subtax_taxcode_code := _x.tax_code;
52984     _row.subtax_taxcode_descrip := _x.tax_descrip;
52985     _row.subtax_taxcode_level := pLevel + 1;
52986
52987    RETURN NEXT _row;  
52988   
52989     FOR _y IN SELECT * from getSubTax(_x.tax_id, pLevel + 1) --This is the recursive part.
52990     LOOP
52991
52992       _row.subtax_taxcode_id := _y.subtax_taxcode_id;
52993       _row.subtax_taxcode_code := _y.subtax_taxcode_code ;
52994       _row.subtax_taxcode_descrip := _y.subtax_taxcode_descrip;
52995       _row.subtax_taxcode_level := pLevel + 2;
52996
52997       RETURN NEXT _row;
52998
52999     END LOOP;
53000  
53001   END LOOP;
53002
53003 END;
53004 $_$;
53005
53006
53007 ALTER FUNCTION public.getsubtax(integer, integer) OWNER TO admin;
53008
53009 --
53010 -- TOC entry 1765 (class 1255 OID 146566342)
53011 -- Dependencies: 4536 8
53012 -- Name: gettaxauthid(text); Type: FUNCTION; Schema: public; Owner: admin
53013 --
53014
53015 CREATE FUNCTION gettaxauthid(text) RETURNS integer
53016     LANGUAGE plpgsql
53017     AS $_$
53018 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53019 -- See www.xtuple.com/CPAL for the full text of the software license.
53020 DECLARE
53021   pTaxAuthCode ALIAS FOR $1;
53022   _returnVal INTEGER;
53023 BEGIN
53024   IF (pTaxAuthCode IS NULL) THEN
53025         RETURN NULL;
53026   END IF;
53027
53028   SELECT taxauth_id INTO _returnVal
53029   FROM taxauth
53030   WHERE (taxauth_code=pTaxAuthCode);
53031
53032   IF (_returnVal IS NULL) THEN
53033         RAISE EXCEPTION 'Tax Authority % not found.', pTaxAuthCode;
53034   END IF;
53035
53036   RETURN _returnVal;
53037 END;
53038 $_$;
53039
53040
53041 ALTER FUNCTION public.gettaxauthid(text) OWNER TO admin;
53042
53043 --
53044 -- TOC entry 1766 (class 1255 OID 146566343)
53045 -- Dependencies: 4536 8
53046 -- Name: gettaxid(text); Type: FUNCTION; Schema: public; Owner: admin
53047 --
53048
53049 CREATE FUNCTION gettaxid(text) RETURNS integer
53050     LANGUAGE plpgsql
53051     AS $_$
53052 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53053 -- See www.xtuple.com/CPAL for the full text of the software license.
53054 DECLARE
53055   pTaxCode ALIAS FOR $1;
53056   _returnVal INTEGER;
53057 BEGIN
53058   IF (pTaxCode IS NULL) THEN
53059         RETURN NULL;
53060   END IF;
53061
53062   SELECT tax_id INTO _returnVal
53063   FROM tax
53064   WHERE (tax_code=pTaxCode);
53065
53066   IF (_returnVal IS NULL) THEN
53067         RAISE EXCEPTION 'Tax Code % not found.', pTaxCode;
53068   END IF;
53069
53070   RETURN _returnVal;
53071 END;
53072 $_$;
53073
53074
53075 ALTER FUNCTION public.gettaxid(text) OWNER TO admin;
53076
53077 --
53078 -- TOC entry 1767 (class 1255 OID 146566344)
53079 -- Dependencies: 4536 8
53080 -- Name: gettaxtypeid(text); Type: FUNCTION; Schema: public; Owner: admin
53081 --
53082
53083 CREATE FUNCTION gettaxtypeid(text) RETURNS integer
53084     LANGUAGE plpgsql
53085     AS $_$
53086 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53087 -- See www.xtuple.com/CPAL for the full text of the software license.
53088 DECLARE
53089   pTaxType ALIAS FOR $1;
53090   _returnVal INTEGER;
53091 BEGIN
53092   IF (pTaxType IS NULL) THEN
53093         RETURN NULL;
53094   END IF;
53095
53096   SELECT taxtype_id INTO _returnVal
53097   FROM taxtype
53098   WHERE (taxtype_name=pTaxType);
53099
53100   IF (_returnVal IS NULL) THEN
53101         RAISE EXCEPTION 'Tax Type % not found.', pTaxType;
53102   END IF;
53103
53104   RETURN _returnVal;
53105 END;
53106 $_$;
53107
53108
53109 ALTER FUNCTION public.gettaxtypeid(text) OWNER TO admin;
53110
53111 --
53112 -- TOC entry 1768 (class 1255 OID 146566345)
53113 -- Dependencies: 4536 8
53114 -- Name: gettaxzoneid(text); Type: FUNCTION; Schema: public; Owner: admin
53115 --
53116
53117 CREATE FUNCTION gettaxzoneid(text) RETURNS integer
53118     LANGUAGE plpgsql
53119     AS $_$
53120 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53121 -- See www.xtuple.com/CPAL for the full text of the software license.
53122 DECLARE
53123   pTaxZone ALIAS FOR $1;
53124   _returnVal INTEGER;
53125 BEGIN
53126   IF (pTaxZone IS NULL) THEN
53127         RETURN NULL;
53128   END IF;
53129
53130   SELECT taxzone_id INTO _returnVal
53131   FROM taxzone
53132   WHERE (taxzone_code=pTaxZone);
53133
53134   IF (_returnVal IS NULL) THEN
53135         RAISE EXCEPTION 'Tax Zone % not found.', pTaxZone;
53136   END IF;
53137
53138   RETURN _returnVal;
53139 END;
53140 $_$;
53141
53142
53143 ALTER FUNCTION public.gettaxzoneid(text) OWNER TO admin;
53144
53145 --
53146 -- TOC entry 1769 (class 1255 OID 146566346)
53147 -- Dependencies: 4536 8
53148 -- Name: gettermsid(text); Type: FUNCTION; Schema: public; Owner: admin
53149 --
53150
53151 CREATE FUNCTION gettermsid(text) RETURNS integer
53152     LANGUAGE plpgsql
53153     AS $_$
53154 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53155 -- See www.xtuple.com/CPAL for the full text of the software license.
53156 DECLARE
53157   pTermsCode ALIAS FOR $1;
53158   _returnVal INTEGER;
53159 BEGIN
53160   IF (pTermsCode IS NULL) THEN
53161         RETURN NULL;
53162   END IF;
53163
53164   SELECT terms_id INTO _returnVal
53165   FROM terms
53166   WHERE (terms_code=pTermsCode);
53167
53168   IF (_returnVal IS NULL) THEN
53169         RAISE EXCEPTION 'Terms Code % not found.', pTermsCode;
53170   END IF;
53171
53172   RETURN _returnVal;
53173 END;
53174 $_$;
53175
53176
53177 ALTER FUNCTION public.gettermsid(text) OWNER TO admin;
53178
53179 --
53180 -- TOC entry 1770 (class 1255 OID 146566347)
53181 -- Dependencies: 4536 8
53182 -- Name: getunassignedaccntid(); Type: FUNCTION; Schema: public; Owner: admin
53183 --
53184
53185 CREATE FUNCTION getunassignedaccntid() RETURNS integer
53186     LANGUAGE plpgsql STABLE
53187     AS $$
53188 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53189 -- See www.xtuple.com/CPAL for the full text of the software license.
53190 DECLARE
53191   _test INTEGER;
53192   _returnVal INTEGER;
53193 BEGIN
53194   SELECT fetchMetricValue('UnassignedAccount') INTO _test;
53195
53196   IF (_test IS NULL) THEN
53197     RAISE EXCEPTION 'Metric not found for UnassignedAccount';
53198   END IF;
53199
53200   SELECT accnt_id INTO _returnVal
53201   FROM accnt
53202   WHERE (accnt_id=_test);
53203
53204   IF (NOT FOUND) THEN
53205     RAISE EXCEPTION 'Metric UnassignedAccount is an invalid G/L Account';
53206   END IF;
53207
53208   RETURN _returnVal;
53209 END;
53210 $$;
53211
53212
53213 ALTER FUNCTION public.getunassignedaccntid() OWNER TO admin;
53214
53215 --
53216 -- TOC entry 1771 (class 1255 OID 146566348)
53217 -- Dependencies: 4536 8
53218 -- Name: getuomid(text); Type: FUNCTION; Schema: public; Owner: admin
53219 --
53220
53221 CREATE FUNCTION getuomid(text) RETURNS integer
53222     LANGUAGE plpgsql
53223     AS $_$
53224 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53225 -- See www.xtuple.com/CPAL for the full text of the software license.
53226 DECLARE
53227   pUom ALIAS FOR $1;
53228   _returnVal INTEGER;
53229 BEGIN
53230   IF (pUom IS NULL) THEN
53231     RETURN NULL;
53232   END IF;
53233
53234   SELECT uom_id INTO _returnVal
53235   FROM uom
53236   WHERE (uom_name=pUom);
53237
53238   IF (_returnVal IS NULL) THEN
53239         RAISE EXCEPTION 'Unit of Measure % not found.', pUom;
53240   END IF;
53241
53242   RETURN _returnVal;
53243 END;
53244 $_$;
53245
53246
53247 ALTER FUNCTION public.getuomid(text) OWNER TO admin;
53248
53249 --
53250 -- TOC entry 1773 (class 1255 OID 146566349)
53251 -- Dependencies: 4536 8
53252 -- Name: getuomtypeid(text); Type: FUNCTION; Schema: public; Owner: admin
53253 --
53254
53255 CREATE FUNCTION getuomtypeid(text) RETURNS integer
53256     LANGUAGE plpgsql
53257     AS $_$
53258 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53259 -- See www.xtuple.com/CPAL for the full text of the software license.
53260 DECLARE
53261   pUomType ALIAS FOR $1;
53262   _returnVal INTEGER;
53263 BEGIN
53264   IF (pUomType IS NULL) THEN
53265         RETURN NULL;
53266   END IF;
53267
53268   SELECT uomtype_id INTO _returnVal
53269   FROM uomtype
53270   WHERE (UPPER(uomtype_name)=UPPER(pUomType));
53271
53272   IF (_returnVal IS NULL) THEN
53273         RAISE EXCEPTION 'Unit of Measuer Type % not found.', pUomType;
53274   END IF;
53275
53276   RETURN _returnVal;
53277 END;
53278 $_$;
53279
53280
53281 ALTER FUNCTION public.getuomtypeid(text) OWNER TO admin;
53282
53283 --
53284 -- TOC entry 1774 (class 1255 OID 146566350)
53285 -- Dependencies: 4536 8
53286 -- Name: getuomtypeid(text[]); Type: FUNCTION; Schema: public; Owner: admin
53287 --
53288
53289 CREATE FUNCTION getuomtypeid(text[]) RETURNS integer[]
53290     LANGUAGE plpgsql
53291     AS $_$
53292 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53293 -- See www.xtuple.com/CPAL for the full text of the software license.
53294 DECLARE
53295   pUomTypes ALIAS FOR $1;
53296   _returnVal INTEGER[];
53297   _val INTEGER;
53298   _i INTEGER;
53299 BEGIN
53300   IF (pUomTypes IS NULL) OR (ARRAY_UPPER(pUomTypes,1) = 0) THEN
53301         RETURN NULL;
53302   END IF;
53303
53304   FOR _i IN 1..ARRAY_UPPER(pUomTypes,1)
53305   LOOP
53306     SELECT uomtype_id INTO _val
53307     FROM uomtype
53308     WHERE (UPPER(uomtype_name)=UPPER(pUomTypes[_i]));
53309
53310     IF (_val IS NULL) THEN
53311         RAISE EXCEPTION 'Unit of Measure Type % not found.', pUomTypes[_i];
53312     ELSE
53313       _returnVal[_i] := _val;
53314     END IF;
53315   END LOOP;
53316
53317   RETURN _returnVal;
53318 END;
53319 $_$;
53320
53321
53322 ALTER FUNCTION public.getuomtypeid(text[]) OWNER TO admin;
53323
53324 --
53325 -- TOC entry 1775 (class 1255 OID 146566351)
53326 -- Dependencies: 4536 8
53327 -- Name: getusrid(text); Type: FUNCTION; Schema: public; Owner: admin
53328 --
53329
53330 CREATE FUNCTION getusrid(pusr text) RETURNS integer
53331     LANGUAGE plpgsql STABLE
53332     AS $$
53333 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53334 -- See www.xtuple.com/CPAL for the full text of the software license.
53335 DECLARE
53336   _returnVal INTEGER;
53337 BEGIN
53338   SELECT usr_id INTO _returnVal
53339   FROM usr
53340   WHERE (usr_username=COALESCE(pUsr, getEffectiveXtUser()));
53341
53342   IF (_returnVal IS NULL) THEN
53343         RAISE EXCEPTION 'User % not found.', pUsr;
53344   END IF;
53345
53346   RETURN _returnVal;
53347 END;
53348 $$;
53349
53350
53351 ALTER FUNCTION public.getusrid(pusr text) OWNER TO admin;
53352
53353 --
53354 -- TOC entry 1776 (class 1255 OID 146566352)
53355 -- Dependencies: 4536 8
53356 -- Name: getusrlocaleid(); Type: FUNCTION; Schema: public; Owner: admin
53357 --
53358
53359 CREATE FUNCTION getusrlocaleid() RETURNS integer
53360     LANGUAGE plpgsql IMMUTABLE
53361     AS $$
53362 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53363 -- See www.xtuple.com/CPAL for the full text of the software license.
53364 DECLARE
53365   _returnVal INTEGER;
53366 BEGIN
53367   SELECT CAST(usrpref_value AS INTEGER)
53368   FROM usrpref
53369   WHERE (usrpref_username=getEffectiveXTUser())
53370     AND (usrpref_name='locale_id') INTO _returnVal;
53371
53372   IF (_returnVal IS NULL) THEN
53373     SELECT locale_id
53374     FROM locale
53375     WHERE (LOWER(locale_code) = 'default')
53376     LIMIT 1 INTO _returnVal;
53377   END IF;
53378
53379   IF (_returnVal IS NULL) THEN
53380     SELECT locale_id
53381     FROM locale
53382     ORDER BY locale_id
53383     LIMIT 1 INTO _returnVal;
53384   END IF;
53385
53386   IF (_returnVal IS NULL) THEN
53387         RAISE EXCEPTION 'User Locale not found.';
53388   END IF;
53389
53390   RETURN _returnVal;
53391 END;
53392 $$;
53393
53394
53395 ALTER FUNCTION public.getusrlocaleid() OWNER TO admin;
53396
53397 --
53398 -- TOC entry 1777 (class 1255 OID 146566353)
53399 -- Dependencies: 4536 8
53400 -- Name: getvendaddrid(text, text); Type: FUNCTION; Schema: public; Owner: admin
53401 --
53402
53403 CREATE FUNCTION getvendaddrid(text, text) RETURNS integer
53404     LANGUAGE plpgsql
53405     AS $_$
53406 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53407 -- See www.xtuple.com/CPAL for the full text of the software license.
53408 DECLARE
53409   pVendNumber   ALIAS FOR $1;
53410   pVendAddrCode ALIAS FOR $2;
53411   _returnVal INTEGER;
53412 BEGIN
53413   IF ( (pVendNumber IS NULL) OR (pVendAddrCode IS NULL) ) THEN
53414     RETURN NULL;
53415   END IF;
53416
53417   SELECT vendaddr_id INTO _returnVal
53418     FROM vendaddrinfo
53419     JOIN vendinfo ON (vend_id=vendaddr_vend_id)
53420   WHERE ( (vendaddr_code=pVendAddrCode)
53421     AND   (vend_number=pVendNumber) );
53422
53423   IF (_returnVal IS NULL) THEN
53424     RAISE EXCEPTION 'Vendor Number % Address % not found.',
53425     pVendNumber, pVendAddrCode;
53426   END IF;
53427
53428   RETURN _returnVal;
53429 END;
53430 $_$;
53431
53432
53433 ALTER FUNCTION public.getvendaddrid(text, text) OWNER TO admin;
53434
53435 --
53436 -- TOC entry 1778 (class 1255 OID 146566354)
53437 -- Dependencies: 4536 8
53438 -- Name: getvendid(text); Type: FUNCTION; Schema: public; Owner: admin
53439 --
53440
53441 CREATE FUNCTION getvendid(text) RETURNS integer
53442     LANGUAGE plpgsql
53443     AS $_$
53444 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53445 -- See www.xtuple.com/CPAL for the full text of the software license.
53446 DECLARE
53447   pVendNumber ALIAS FOR $1;
53448   _returnVal INTEGER;
53449 BEGIN
53450   IF (pVendNumber IS NULL) THEN
53451     RETURN NULL;
53452   END IF;
53453
53454   SELECT vend_id INTO _returnVal
53455     FROM vendinfo
53456    WHERE (vend_number=pVendNumber);
53457
53458   IF (_returnVal IS NULL) THEN
53459     RAISE EXCEPTION 'Vendor Number % not found.', pVendNumber;
53460   END IF;
53461
53462   RETURN _returnVal;
53463 END;
53464 $_$;
53465
53466
53467 ALTER FUNCTION public.getvendid(text) OWNER TO admin;
53468
53469 --
53470 -- TOC entry 1779 (class 1255 OID 146566355)
53471 -- Dependencies: 4536 8
53472 -- Name: getvendtypeid(text); Type: FUNCTION; Schema: public; Owner: admin
53473 --
53474
53475 CREATE FUNCTION getvendtypeid(text) RETURNS integer
53476     LANGUAGE plpgsql
53477     AS $_$
53478 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53479 -- See www.xtuple.com/CPAL for the full text of the software license.
53480 DECLARE
53481   pVendTypeCode ALIAS FOR $1;
53482   _returnVal INTEGER;
53483 BEGIN
53484   IF (pVendTypeCode IS NULL) THEN
53485     RETURN NULL;
53486   END IF;
53487
53488   SELECT vendtype_id INTO _returnVal
53489   FROM vendtype
53490   WHERE (UPPER(vendtype_code)=UPPER(pVendTypeCode));
53491
53492   IF (_returnVal IS NULL) THEN
53493         RAISE EXCEPTION 'Vendor Type % not found.', pVendTypeCode;
53494   END IF;
53495
53496   RETURN _returnVal;
53497 END;
53498 $_$;
53499
53500
53501 ALTER FUNCTION public.getvendtypeid(text) OWNER TO admin;
53502
53503 --
53504 -- TOC entry 1780 (class 1255 OID 146566356)
53505 -- Dependencies: 4536 8
53506 -- Name: getwarehousid(text, text); Type: FUNCTION; Schema: public; Owner: admin
53507 --
53508
53509 CREATE FUNCTION getwarehousid(pwarehouscode text, ptype text) RETURNS integer
53510     LANGUAGE plpgsql STABLE
53511     AS $$
53512 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53513 -- See www.xtuple.com/CPAL for the full text of the software license.
53514 DECLARE
53515   _active BOOL;
53516   _shipping BOOL;
53517   _returnVal INTEGER;
53518 BEGIN
53519   IF (pWarehousCode IS NULL) THEN
53520         RETURN NULL;
53521   END IF;
53522  
53523   IF (UPPER(pType) NOT IN ('ALL','ACTIVE','SHIPPING')) THEN
53524         RAISE EXCEPTION 'Warehouse lookip type % not valid. Valid types are ALL, ACTIVE and SHIPPING', pType;
53525   END IF;
53526
53527   SELECT warehous_id, warehous_active, warehous_shipping INTO _returnVal, _active, _shipping
53528   FROM site()
53529   WHERE (warehous_code=UPPER(pWarehousCode));
53530
53531   IF (_returnVal IS NULL) THEN
53532     RAISE EXCEPTION 'Warehouse Code % not found.', pWarehousCode;
53533     ELSE IF ((pType='SHIPPING') AND (_shipping=false)) THEN
53534       RAISE EXCEPTION 'Warehouse Code % is not a vaild shipping warehouse.', pWarehousCode;
53535       ELSE IF ((pType IN ('SHIPPING','ACTIVE')) AND (_active=false)) THEN
53536         RAISE EXCEPTION 'Warehouse Code % is inactive.', pWarehousCode;
53537       END IF;
53538     END IF;
53539   END IF;
53540
53541   RETURN _returnVal;
53542 END;
53543 $$;
53544
53545
53546 ALTER FUNCTION public.getwarehousid(pwarehouscode text, ptype text) OWNER TO admin;
53547
53548 --
53549 -- TOC entry 1781 (class 1255 OID 146566357)
53550 -- Dependencies: 4536 8
53551 -- Name: getwhsezoneid(text, text); Type: FUNCTION; Schema: public; Owner: admin
53552 --
53553
53554 CREATE FUNCTION getwhsezoneid(text, text) RETURNS integer
53555     LANGUAGE plpgsql
53556     AS $_$
53557 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53558 -- See www.xtuple.com/CPAL for the full text of the software license.
53559 DECLARE
53560   pWhseCode ALIAS FOR $1;
53561   pWhseZoneName ALIAS FOR $2;
53562   _returnVal INTEGER;
53563 BEGIN
53564   IF ((pWhseCode IS NULL) OR (pWhseZoneName IS NULL)) THEN
53565         RETURN NULL;
53566   END IF;
53567
53568   SELECT whsezone_id INTO _returnVal
53569   FROM whsezone
53570   WHERE ( (whsezone_warehous_id=getWarehousId(pWhseCode, 'ACTIVE'))
53571       AND (UPPER(whsezone_name)=UPPER(pWhseZoneName)) );
53572
53573   IF (_returnVal IS NULL) THEN
53574         RAISE EXCEPTION 'Whsezone % not found.', pWhseZoneName;
53575   END IF;
53576
53577   RETURN _returnVal;
53578 END;
53579 $_$;
53580
53581
53582 ALTER FUNCTION public.getwhsezoneid(text, text) OWNER TO admin;
53583
53584 --
53585 -- TOC entry 1782 (class 1255 OID 146566358)
53586 -- Dependencies: 4536 8
53587 -- Name: grantallmodulecmnttypesource(integer, text); Type: FUNCTION; Schema: public; Owner: admin
53588 --
53589
53590 CREATE FUNCTION grantallmodulecmnttypesource(integer, text) RETURNS integer
53591     LANGUAGE plpgsql
53592     AS $_$
53593 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53594 -- See www.xtuple.com/CPAL for the full text of the software license.
53595 DECLARE
53596   pCmnttypeid ALIAS FOR $1;
53597   pModuleName ALIAS FOR $2;
53598   _source RECORD;
53599   _sourceCounter INTEGER;
53600
53601 BEGIN
53602
53603   _sourceCounter := 0;
53604
53605   FOR _source IN SELECT source_id
53606                  FROM source 
53607                  WHERE (source_module=pModuleName) LOOP
53608
53609     IF (SELECT grantCmnttypeSource(pCmnttypeid, _source.source_id)) THEN
53610       _sourceCounter := _sourceCounter + 1;
53611     END IF;
53612
53613   END LOOP;
53614
53615   RETURN _sourceCounter;
53616
53617 END;
53618 $_$;
53619
53620
53621 ALTER FUNCTION public.grantallmodulecmnttypesource(integer, text) OWNER TO admin;
53622
53623 --
53624 -- TOC entry 1783 (class 1255 OID 146566359)
53625 -- Dependencies: 4536 8
53626 -- Name: grantallmodulepriv(text, text); Type: FUNCTION; Schema: public; Owner: admin
53627 --
53628
53629 CREATE FUNCTION grantallmodulepriv(text, text) RETURNS integer
53630     LANGUAGE plpgsql
53631     AS $_$
53632 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53633 -- See www.xtuple.com/CPAL for the full text of the software license.
53634 DECLARE
53635   pUsername ALIAS FOR $1;
53636   pModuleName ALIAS FOR $2;
53637   _priv RECORD;
53638   _privCounter INTEGER;
53639
53640 BEGIN
53641
53642   _privCounter := 0;
53643
53644   FOR _priv IN SELECT priv_id
53645                FROM priv 
53646                WHERE (priv_module=pModuleName) LOOP
53647
53648     IF (SELECT grantPriv(pUsername, _priv.priv_id)) THEN
53649       _privCounter := _privCounter + 1;
53650     END IF;
53651
53652   END LOOP;
53653
53654   RETURN _privCounter;
53655
53656 END;
53657 $_$;
53658
53659
53660 ALTER FUNCTION public.grantallmodulepriv(text, text) OWNER TO admin;
53661
53662 --
53663 -- TOC entry 1784 (class 1255 OID 146566360)
53664 -- Dependencies: 4536 8
53665 -- Name: grantallmoduleprivgroup(integer, text); Type: FUNCTION; Schema: public; Owner: admin
53666 --
53667
53668 CREATE FUNCTION grantallmoduleprivgroup(integer, text) RETURNS integer
53669     LANGUAGE plpgsql
53670     AS $_$
53671 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53672 -- See www.xtuple.com/CPAL for the full text of the software license.
53673 DECLARE
53674   pGrpid ALIAS FOR $1;
53675   pModuleName ALIAS FOR $2;
53676   _priv RECORD;
53677   _privCounter INTEGER;
53678
53679 BEGIN
53680
53681   _privCounter := 0;
53682
53683   FOR _priv IN SELECT priv_id
53684                FROM priv 
53685                WHERE (priv_module=pModuleName) LOOP
53686
53687     IF (SELECT grantPrivGroup(pGrpid, _priv.priv_id)) THEN
53688       _privCounter := _privCounter + 1;
53689     END IF;
53690
53691   END LOOP;
53692
53693   RETURN _privCounter;
53694
53695 END;
53696 $_$;
53697
53698
53699 ALTER FUNCTION public.grantallmoduleprivgroup(integer, text) OWNER TO admin;
53700
53701 --
53702 -- TOC entry 1785 (class 1255 OID 146566361)
53703 -- Dependencies: 4536 8
53704 -- Name: grantcmnttypesource(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
53705 --
53706
53707 CREATE FUNCTION grantcmnttypesource(integer, integer) RETURNS boolean
53708     LANGUAGE plpgsql
53709     AS $_$
53710 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53711 -- See www.xtuple.com/CPAL for the full text of the software license.
53712 DECLARE
53713   pCmnttypeid ALIAS FOR $1;
53714   pSourceid ALIAS FOR $2;
53715   _test INTEGER;
53716
53717 BEGIN
53718
53719   SELECT cmnttypesource_id INTO _test
53720   FROM cmnttypesource
53721   WHERE ( (cmnttypesource_cmnttype_id=pCmnttypeid)
53722     AND (cmnttypesource_source_id=pSourceid) );
53723
53724   IF (FOUND) THEN
53725     RETURN FALSE;
53726   END IF;
53727
53728   INSERT INTO cmnttypesource
53729   ( cmnttypesource_cmnttype_id, cmnttypesource_source_id )
53730   VALUES
53731   ( pCmnttypeid, pSourceid );
53732
53733   RETURN TRUE;
53734
53735 END;
53736 $_$;
53737
53738
53739 ALTER FUNCTION public.grantcmnttypesource(integer, integer) OWNER TO admin;
53740
53741 --
53742 -- TOC entry 1786 (class 1255 OID 146566362)
53743 -- Dependencies: 4536 8
53744 -- Name: grantgroup(text, integer); Type: FUNCTION; Schema: public; Owner: admin
53745 --
53746
53747 CREATE FUNCTION grantgroup(text, integer) RETURNS boolean
53748     LANGUAGE plpgsql
53749     AS $_$
53750 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53751 -- See www.xtuple.com/CPAL for the full text of the software license.
53752 DECLARE
53753   pUsername ALIAS FOR $1;
53754   pGrpid ALIAS FOR $2;
53755   _test INTEGER;
53756
53757 BEGIN
53758
53759   SELECT usrgrp_id INTO _test
53760   FROM usrgrp
53761   WHERE ( (usrgrp_username=pUsername)
53762    AND (usrgrp_grp_id=pGrpid) );
53763
53764   IF (FOUND) THEN
53765     RETURN FALSE;
53766   END IF;
53767
53768   INSERT INTO usrgrp
53769   ( usrgrp_username, usrgrp_grp_id )
53770   VALUES
53771   ( pUsername, pGrpid );
53772
53773   RETURN TRUE;
53774
53775 END;
53776 $_$;
53777
53778
53779 ALTER FUNCTION public.grantgroup(text, integer) OWNER TO admin;
53780
53781 --
53782 -- TOC entry 1787 (class 1255 OID 146566363)
53783 -- Dependencies: 4536 8
53784 -- Name: grantpriv(text, integer); Type: FUNCTION; Schema: public; Owner: admin
53785 --
53786
53787 CREATE FUNCTION grantpriv(text, integer) RETURNS boolean
53788     LANGUAGE plpgsql
53789     AS $_$
53790 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53791 -- See www.xtuple.com/CPAL for the full text of the software license.
53792 DECLARE
53793   pUsername ALIAS FOR $1;
53794   pPrivid ALIAS FOR $2;
53795   _test INTEGER;
53796
53797 BEGIN
53798
53799   SELECT usrpriv_id INTO _test
53800   FROM usrpriv
53801   WHERE ( (usrpriv_username=pUsername)
53802    AND (usrpriv_priv_id=pPrivid) );
53803
53804   IF (FOUND) THEN
53805     RETURN FALSE;
53806   END IF;
53807
53808   INSERT INTO usrpriv
53809   ( usrpriv_username, usrpriv_priv_id )
53810   VALUES
53811   ( pUsername, pPrivid );
53812
53813   NOTIFY "usrprivUpdated";
53814
53815   RETURN TRUE;
53816
53817 END;
53818 $_$;
53819
53820
53821 ALTER FUNCTION public.grantpriv(text, integer) OWNER TO admin;
53822
53823 --
53824 -- TOC entry 1788 (class 1255 OID 146566364)
53825 -- Dependencies: 4536 8
53826 -- Name: grantpriv(text, text); Type: FUNCTION; Schema: public; Owner: admin
53827 --
53828
53829 CREATE FUNCTION grantpriv(text, text) RETURNS boolean
53830     LANGUAGE plpgsql
53831     AS $_$
53832 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53833 -- See www.xtuple.com/CPAL for the full text of the software license.
53834 DECLARE
53835   pUsername ALIAS FOR $1;
53836   pPrivname ALIAS FOR $2;
53837   _test INTEGER;
53838
53839 BEGIN
53840
53841   SELECT usrpriv_id INTO _test
53842     FROM usrpriv
53843     JOIN priv ON (usrpriv_priv_id=priv_id)
53844   WHERE ((usrpriv_username=pUsername)
53845      AND (priv_name=pPrivname) );
53846
53847   IF (FOUND) THEN
53848     RETURN FALSE;
53849   END IF;
53850
53851   INSERT INTO usrpriv
53852   ( usrpriv_username, usrpriv_priv_id )
53853   SELECT pUsername, priv_id
53854     FROM priv
53855    WHERE (priv_name=pPrivname);
53856
53857   NOTIFY "usrprivUpdated";
53858
53859   RETURN TRUE;
53860
53861 END;
53862 $_$;
53863
53864
53865 ALTER FUNCTION public.grantpriv(text, text) OWNER TO admin;
53866
53867 --
53868 -- TOC entry 1789 (class 1255 OID 146566365)
53869 -- Dependencies: 4536 8
53870 -- Name: grantprivgroup(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
53871 --
53872
53873 CREATE FUNCTION grantprivgroup(integer, integer) RETURNS boolean
53874     LANGUAGE plpgsql
53875     AS $_$
53876 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53877 -- See www.xtuple.com/CPAL for the full text of the software license.
53878 DECLARE
53879   pGrpid ALIAS FOR $1;
53880   pPrivid ALIAS FOR $2;
53881   _test INTEGER;
53882
53883 BEGIN
53884
53885   SELECT grppriv_id INTO _test
53886   FROM grppriv
53887   WHERE ( (grppriv_grp_id=pGrpid)
53888    AND (grppriv_priv_id=pPrivid) );
53889
53890   IF (FOUND) THEN
53891     RETURN FALSE;
53892   END IF;
53893
53894   INSERT INTO grppriv
53895   ( grppriv_grp_id, grppriv_priv_id )
53896   VALUES
53897   ( pGrpid, pPrivid );
53898
53899   RETURN TRUE;
53900
53901 END;
53902 $_$;
53903
53904
53905 ALTER FUNCTION public.grantprivgroup(integer, integer) OWNER TO admin;
53906
53907 --
53908 -- TOC entry 1790 (class 1255 OID 146566366)
53909 -- Dependencies: 4536 8
53910 -- Name: hasalarms(); Type: FUNCTION; Schema: public; Owner: admin
53911 --
53912
53913 CREATE FUNCTION hasalarms() RETURNS boolean
53914     LANGUAGE plpgsql
53915     AS $$
53916 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
53917 -- See www.xtuple.com/CPAL for the full text of the software license.
53918 DECLARE
53919   _alarm          RECORD;
53920   _batchId        INTEGER;
53921   _evntlogordtype TEXT;
53922   _evnttypeid     INTEGER;
53923   _evnttypename   TEXT;
53924   _fromEmail      TEXT;
53925   _itemid         INTEGER;
53926   _longsource     TEXT;
53927   _msgId          INTEGER;
53928   _recipient      TEXT;
53929   _recipientPart  INTEGER;
53930   _returnVal      BOOLEAN := FALSE;
53931   _summary        TEXT;
53932   _whsId          INTEGER := -1;
53933
53934 BEGIN
53935   FOR _alarm IN SELECT *
53936                 FROM alarm
53937                 WHERE ((alarm_creator=getEffectiveXtUser())
53938                    AND (CURRENT_TIMESTAMP > alarm_trigger)) LOOP
53939     _returnVal := TRUE;
53940
53941     IF (_alarm.alarm_source = 'TODO') THEN
53942       SELECT (todoitem_name || '-' || todoitem_description),
53943              'T', 'TodoAlarm', 'To-Do Item'
53944       INTO _summary, _evntlogordtype, _evnttypename, _longsource
53945       FROM todoitem
53946       WHERE (todoitem_id = _alarm.alarm_source_id);
53947
53948     ELSIF (_alarm.alarm_source = 'INCDT') THEN
53949       SELECT (incdt_number || '-' || incdt_summary),
53950              'I', 'IncidentAlarm', 'Incident'
53951       INTO _summary, _evntlogordtype, _evnttypename, _longsource
53952       FROM incdt
53953       WHERE (incdt_id = _alarm.alarm_source_id);
53954
53955     ELSIF (_alarm.alarm_source = 'J') THEN
53956       SELECT (prj_number || ' ' || prj_name || '-' || prjtask_name),
53957               'J', 'TaskAlarm', 'Project Task'
53958       INTO _summary, _evntlogordtype, _evnttypename, _longsource
53959       FROM prjtask JOIN prj ON (prj_id=prjtask_prj_id)
53960       WHERE (prjtask_id = _alarm.alarm_source_id);
53961
53962     ELSE
53963       CONTINUE; -- there's nothing to do for this iteration of the loop
53964     END IF;
53965
53966     -- if event alarm
53967     IF (_alarm.alarm_event) THEN
53968       SELECT evnttype_id INTO _evnttypeid
53969       FROM evnttype
53970       WHERE (evnttype_name=_evnttypename);
53971
53972       _recipientPart := 1;
53973       LOOP
53974         _recipient := SPLIT_PART(_alarm.alarm_event_recipient, ',', _recipientPart);
53975         EXIT WHEN (LENGTH(_recipient) = 0);
53976
53977         SELECT usrpref_value INTO _whsId
53978         FROM usrpref
53979         WHERE ( (usrpref_username = _recipient)
53980           AND   (usrpref_name = 'PreferredWarehouse') );
53981
53982         INSERT INTO evntlog (evntlog_evnttime, evntlog_username,
53983                              evntlog_evnttype_id, evntlog_ordtype,
53984                              evntlog_ord_id, evntlog_warehous_id, evntlog_number
53985                    ) VALUES (CURRENT_TIMESTAMP, _recipient,
53986                              _evnttypeid, _evntlogordtype,
53987                              _alarm.alarm_source_id, _whsId, _summary);
53988
53989         _recipientPart := _recipientPart + 1;
53990       END LOOP;
53991     END IF;
53992
53993     IF (_alarm.alarm_email) THEN
53994       SELECT usr_email INTO _fromEmail
53995       FROM usr
53996       WHERE (usr_username = _alarm.alarm_creator);
53997
53998       _recipientPart := 1;
53999       LOOP
54000         _recipient := SPLIT_PART(_alarm.alarm_email_recipient, ',', _recipientPart);
54001         EXIT WHEN (LENGTH(_recipient) <= 0);
54002         _batchId := xtbatch.submitEmailToBatch(_fromEmail, _recipient, '',
54003                                                _summary,
54004                                                'Alarm reminder for '
54005                                                || _longsource || '.',
54006                                                NULL, CURRENT_TIMESTAMP,
54007                                                FALSE, NULL, NULL);
54008         _recipientPart := _recipientPart + 1;
54009       END LOOP;
54010     END IF;
54011
54012     IF (_alarm.alarm_sysmsg) THEN
54013       _recipientPart := 1;
54014       LOOP
54015         _recipient := SPLIT_PART(_alarm.alarm_sysmsg_recipient, ',', _recipientPart);
54016         EXIT WHEN (LENGTH(_recipient) <= 0);
54017         _msgId := postMessage(_recipient, (_longsource || ' - ' || _summary));
54018         _recipientPart := _recipientPart + 1;
54019       END LOOP;
54020     END IF;
54021
54022     DELETE FROM alarm WHERE alarm_id=_alarm.alarm_id;
54023   END LOOP;
54024   RETURN _returnVal;
54025
54026 END;
54027 $$;
54028
54029
54030 ALTER FUNCTION public.hasalarms() OWNER TO admin;
54031
54032 --
54033 -- TOC entry 1791 (class 1255 OID 146566367)
54034 -- Dependencies: 4536 8
54035 -- Name: hasevents(); Type: FUNCTION; Schema: public; Owner: admin
54036 --
54037
54038 CREATE FUNCTION hasevents() RETURNS boolean
54039     LANGUAGE plpgsql
54040     AS $$
54041 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54042 -- See www.xtuple.com/CPAL for the full text of the software license.
54043 BEGIN
54044
54045   PERFORM evntlog_id
54046   FROM evntlog
54047   WHERE ( (evntlog_dispatched IS NULL)
54048    AND (evntlog_username=getEffectiveXtUser()) )
54049   LIMIT 1;
54050   RETURN FOUND;
54051
54052 END;
54053 $$;
54054
54055
54056 ALTER FUNCTION public.hasevents() OWNER TO admin;
54057
54058 --
54059 -- TOC entry 1792 (class 1255 OID 146566368)
54060 -- Dependencies: 4536 8
54061 -- Name: hasmessages(); Type: FUNCTION; Schema: public; Owner: admin
54062 --
54063
54064 CREATE FUNCTION hasmessages() RETURNS boolean
54065     LANGUAGE plpgsql
54066     AS $$
54067 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54068 -- See www.xtuple.com/CPAL for the full text of the software license.
54069 BEGIN
54070
54071   PERFORM msguser_id
54072   FROM msg, msguser
54073   WHERE ( (msguser_username=getEffectiveXtUser())
54074    AND (msguser_msg_id=msg_id)
54075    AND (CURRENT_TIMESTAMP BETWEEN msg_scheduled AND msg_expires)
54076    AND (msguser_viewed IS NULL) )
54077   LIMIT 1;
54078   RETURN FOUND;
54079
54080 END;
54081 $$;
54082
54083
54084 ALTER FUNCTION public.hasmessages() OWNER TO admin;
54085
54086 --
54087 -- TOC entry 1794 (class 1255 OID 146566369)
54088 -- Dependencies: 4536 8
54089 -- Name: haspriv(text); Type: FUNCTION; Schema: public; Owner: admin
54090 --
54091
54092 CREATE FUNCTION haspriv(text) RETURNS boolean
54093     LANGUAGE plpgsql
54094     AS $_$
54095 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54096 -- See www.xtuple.com/CPAL for the full text of the software license.
54097 DECLARE
54098   pPrivName     ALIAS FOR $1;
54099   _result       INTEGER;
54100   _returnVal    BOOLEAN;
54101
54102 BEGIN
54103   RAISE NOTICE 'hasPriv(TEXT) is deprecated. Use checkPrivilege(TEXT) instead.';
54104   SELECT priv_id INTO _result
54105     FROM priv, grppriv, usrgrp
54106    WHERE((usrgrp_grp_id=grppriv_grp_id)
54107      AND (grppriv_priv_id=priv_id)
54108      AND (priv_name=pPrivName)
54109      AND (usrgrp_username=getEffectiveXtUser()));
54110   IF (FOUND) THEN
54111     RETURN true;
54112   END IF;
54113
54114   SELECT COALESCE(usrpriv_id, 0) != 0 INTO _returnVal
54115   FROM priv LEFT OUTER JOIN
54116        usrpriv ON (priv_id=usrpriv_priv_id AND usrpriv_username = getEffectiveXtUser())
54117   WHERE (priv_name=pPrivName);
54118   IF (_returnVal IS NULL) THEN
54119     _returnVal := FALSE;
54120   END IF;
54121
54122   RETURN _returnVal;
54123 END;
54124 $_$;
54125
54126
54127 ALTER FUNCTION public.haspriv(text) OWNER TO admin;
54128
54129 --
54130 -- TOC entry 1795 (class 1255 OID 146566370)
54131 -- Dependencies: 4536 8
54132 -- Name: hasprivonobject(text, text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
54133 --
54134
54135 CREATE FUNCTION hasprivonobject(pprivtype text, pobjecttype text, pobjectid integer DEFAULT NULL::integer, puser text DEFAULT NULL::text) RETURNS boolean
54136     LANGUAGE plpgsql STABLE
54137     AS $$
54138 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54139 -- See www.xtuple.com/CPAL for the full text of the software license.
54140 DECLARE
54141   _haspriv   BOOLEAN := FALSE;
54142   _privfound BOOLEAN := FALSE;
54143   _pkey      TEXT[];
54144   _privdesc  RECORD;
54145   _qstr      TEXT;
54146
54147 BEGIN
54148   IF UPPER(pPrivType) NOT IN ('CREATE', 'EDIT', 'VIEW', 'DELETE') THEN
54149     RAISE EXCEPTION 'Cannot check if user has % on % [xtuple: hasPrivOnObject, -1, %, %]',
54150                      pPrivType, pObjectType, pPrivType, pObjectType;
54151   END IF;
54152
54153   /* TODO: create privdesc table? can't do it yet because this is a fix for a minor release
54154      NOTE: only include tables that have a single integer column as pkey
54155      NOTE: some of these are part of proprietary extensions. how do we make them part of the extension?
54156   */
54157   FOR _privdesc IN
54158   WITH privdesc AS (
54159     SELECT 'ADDR' AS otype,    'public' AS masterschema,
54160                                          'addr' AS mastertable,
54161                                                      'MaintainAddressMasters' AS editall,
54162                                                                                      'ViewAddressMasters' AS viewall,
54163                                                                                                                NULL AS ownerfield,        NULL AS editmine,                NULL AS viewmine
54164      UNION ALL SELECT 'BBH',   'xtmfg',  'bbom',     'MaintainBBOMs',                'ViewBBOMs',              NULL,                      NULL,                            NULL
54165      UNION ALL SELECT 'BBI',   'xtmfg',  'bbom',     'MaintainBBOMs',                'ViewBBOMs',              NULL,                      NULL,                            NULL
54166      UNION ALL SELECT 'BMH',   'public', 'bom',      'MaintainBOMs',                 'ViewBOMs',               NULL,                      NULL,                            NULL
54167      UNION ALL SELECT 'BMI',   'public', 'bom',      'MaintainBOMs',                 'ViewBOMs',               NULL,                      NULL,                            NULL
54168      UNION ALL SELECT 'BOH',   'xtmfg',  'boo',      'MaintainBOOs',                 'ViewBOOs',               NULL,                      NULL,                            NULL
54169      UNION ALL SELECT 'BOI',   'xtmfg',  'boo',      'MaintainBOOs',                 'ViewBOOs',               NULL,                      NULL,                            NULL
54170      UNION ALL SELECT 'C',     'public', 'custinfo', 'MaintainCustomerMasters',      'ViewCustomerMasters',    NULL,                      NULL,                            NULL
54171      UNION ALL SELECT 'CRMA',  'public', 'crmacct',  'MaintainAllCRMAccounts',       'ViewAllCRMAccounts',     'crmacct_owner_username',  'MaintainPersonalCRMAccounts',   'ViewPersonalCRMAccounts'
54172      UNION ALL SELECT 'EMP',   'public', 'emp',      'MaintainEmployees',            'ViewEmployees',          NULL,                      NULL,                            NULL
54173      UNION ALL SELECT 'I',     'public', 'item',     'MaintainItemMasters',          'ViewItemMasters',        NULL,                      NULL,                            NULL
54174      UNION ALL SELECT 'INCDT', 'public', 'incdt',    'MaintainAllIncidents',         'ViewAllIncidents',       'incdt_owner_username',    'MaintainPersonalIncidents',     'ViewPersonalIncidents'
54175      UNION ALL SELECT 'IR',    'public', 'itemsrc',  'MaintainItemSources',          'ViewItemSources',        NULL,                      NULL,                            NULL
54176      UNION ALL SELECT 'IS',    'public', 'itemsite', 'MaintainItemSites',            'ViewItemSites',          NULL,                      NULL,                            NULL
54177      UNION ALL SELECT 'J',     'public', 'prj',      'MaintainAllProjects',          'ViewAllProjects',        'prj_owner_username',      'MaintainPersonalProjects',      'ViewPersonalProjects'
54178      UNION ALL SELECT 'J',     'public', 'prj',      'MaintainAllProjects',          'ViewAllProjects',        'prj_username',            'MaintainPersonalProjects',      'ViewPersonalProjects'
54179      UNION ALL SELECT 'L',     'public', 'location', 'MaintainLocations',            'ViewLocations',          NULL,                      NULL,                            NULL
54180      UNION ALL SELECT 'OPP',   'public', 'ophead',   'MaintainAllOpportunities',     'ViewAllOpportunities',   'ophead_owner_username',   'MaintainPersonalOpportunities', 'ViewPersonalOpportunities'
54181      UNION ALL SELECT 'P',     'public', 'pohead',   'MaintainPurchaseOrders',       'ViewPurchaseOrders',     NULL,                      NULL,                            NULL
54182      UNION ALL SELECT 'PI',    'public', 'pohead',   'MaintainPurchaseOrders',       'ViewPurchaseOrders',     NULL,                      NULL,                            NULL
54183      UNION ALL SELECT 'Q',     'public', 'quhead',   'MaintainQuotes',               'ViewQuotes',             NULL,                      NULL,                            NULL
54184      UNION ALL SELECT 'QI',    'public', 'quhead',   'MaintainQuotes',               'ViewQuotes',             NULL,                      NULL,                            NULL
54185      UNION ALL SELECT 'RA',    'public', 'rahead',   'MaintainReturns',              'ViewReturns',            NULL,                      NULL,                            NULL
54186      UNION ALL SELECT 'RI',    'public', 'rahead',   'MaintainReturns',              'ViewReturns',            NULL,                      NULL,                            NULL
54187      UNION ALL SELECT 'S',     'public', 'cohead',   'MaintainSalesOrders',          'ViewSalesOrders',        NULL,                      NULL,                            NULL
54188      UNION ALL SELECT 'SI',    'public', 'cohead',   'MaintainSalesOrders',          'ViewSalesOrders',        NULL,                      NULL,                            NULL
54189      UNION ALL SELECT 'T',     'public', 'cntct',    'MaintainAllContacts',          'ViewAllContacts',        'cntct_owner_username',    'MaintainPersonalContacts',      'ViewPersonalContacts'
54190      UNION ALL SELECT 'TE',    'te',     'tehead',   'MaintainTimeExpense',          'ViewTimeExpenseHistory', 'tehead_username',         'MaintainTimeExpenseSelf',       NULL
54191      UNION ALL SELECT 'TE',    'te',     'tehead',   'MaintainTimeExpenseOthers',    'ViewTimeExpenseHistory', 'tehead_username',         'MaintainTimeExpenseSelf',       NULL
54192      UNION ALL SELECT 'TI',    'public', 'tohead',   'MaintainTransferOrders',       'ViewTransferOrders',     NULL,                      NULL,                            NULL
54193      UNION ALL SELECT 'TO',    'public', 'tohead',   'MaintainTransferOrders',       'ViewTransferOrders',     NULL,                      NULL,                            NULL
54194      UNION ALL SELECT 'TODO',  'public', 'todoitem', 'MaintainAllToDoItems',         'ViewAllToDoItems',       'todoitem_owner_username', 'MaintainPersonalToDoItems',     'ViewPersonalToDoItems'
54195      UNION ALL SELECT 'V',     'public', 'vendinfo', 'MaintainVendors',              'ViewVendors',            NULL,                      NULL,                            NULL
54196      UNION ALL SELECT 'W',     'public', 'wo',       'MaintainWorkOrders',           'ViewWorkOrders',         NULL,                      NULL,                            NULL
54197      UNION ALL SELECT 'WH',    'public', 'whsinfo',  'MaintainWarehouses',           'ViewWarehouses',         NULL,                      NULL,                            NULL)
54198   -- UNION ALL SELECT 'LS',    'public', 'ls',       NULL,                           NULL,                     NULL,                      NULL,                            NULL
54199   -- UNION ALL SELECT 'P',     'public', 'pohead',   'MaintainPostedPurchaseOrders', 'ViewPurchaseOrders',     NULL,                      NULL,                            NULL -- additional criteria?
54200   -- UNION ALL SELECT 'PI',    'public', 'pohead',   'MaintainPostedPurchaseOrders', 'ViewPurchaseOrders',     NULL,                      NULL,                            NULL -- additional criteria?
54201      SELECT *
54202        FROM privdesc
54203       WHERE otype = pObjectType
54204   LOOP
54205     _privfound := TRUE;
54206     RAISE DEBUG '% % % % % % %',
54207                 _privdesc.otype, _privdesc.masterschema, _privdesc.mastertable,
54208                 _privdesc.editall, _privdesc.viewall, _privdesc.editmine, _privdesc.viewmine;
54209
54210     IF checkPrivilege(CASE UPPER(pPrivType) WHEN 'CREATE' THEN _privdesc.editall
54211                                             WHEN 'EDIT'   THEN _privdesc.editall
54212                                             WHEN 'DELETE' THEN _privdesc.editall
54213                                             WHEN 'VIEW'   THEN _privdesc.viewall
54214                       END) THEN
54215       _haspriv = TRUE;
54216
54217     ELSIF checkPrivilege(CASE UPPER(pPrivType) WHEN 'CREATE' THEN _privdesc.editmine
54218                                                WHEN 'EDIT'   THEN _privdesc.editmine
54219                                                WHEN 'DELETE' THEN _privdesc.editmine
54220                                                WHEN 'VIEW'   THEN _privdesc.viewmine
54221                          END) THEN
54222       IF pObjectId IS NULL THEN
54223       _haspriv = TRUE;
54224
54225       ELSE
54226         _pkey := primaryKeyFields(_privdesc.masterschema, _privdesc.mastertable);
54227
54228         -- SELECT ... FROM schema.table WHERE pkeyfield = pObjectId AND ownerfield = pUser
54229         _qstr := 'SELECT EXISTS(SELECT 1
54230                                   FROM ' || quote_ident(_privdesc.masterschema)
54231                                    || '.' || quote_ident(_privdesc.mastertable)
54232                                    || ' WHERE ' || quote_ident(_pkey[1]) || ' = ' || pObjectId
54233                                    || '   AND ' || quote_ident(_privdesc.ownerfield)
54234                                    || '= ' || quote_literal(COALESCE(pUser, getEffectiveXtUser())) || ');';
54235         RAISE DEBUG '%', _qstr;
54236
54237         EXECUTE _qstr INTO _haspriv;
54238       END IF;
54239     END IF;
54240
54241     EXIT WHEN _haspriv;
54242   END LOOP;
54243
54244   RETURN _haspriv OR NOT _privfound;
54245
54246 END;
54247 $$;
54248
54249
54250 ALTER FUNCTION public.hasprivonobject(pprivtype text, pobjecttype text, pobjectid integer, puser text) OWNER TO admin;
54251
54252 --
54253 -- TOC entry 8975 (class 0 OID 0)
54254 -- Dependencies: 1795
54255 -- Name: FUNCTION hasprivonobject(pprivtype text, pobjecttype text, pobjectid integer, puser text); Type: COMMENT; Schema: public; Owner: admin
54256 --
54257
54258 COMMENT ON FUNCTION hasprivonobject(pprivtype text, pobjecttype text, pobjectid integer, puser text) IS 'Return if a user has permission to view or edit a specific database object.
54259 pPrivType is either CREATE, EDIT, DELETE, or VIEW, and controls which privilege is checked.
54260 pObjectType is one of the string constants used by the Documents widget, such as ADDR for Addresses.
54261 pObjectId is the internal id of the record in the table associated with pObjectType (defaults to NULL).
54262 pUser is the username to be checked for those pObjectTypes that restrict access to individual users (NULL == current user and is the default).';
54263
54264
54265 --
54266 -- TOC entry 1796 (class 1255 OID 146566372)
54267 -- Dependencies: 8
54268 -- Name: hmac(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
54269 --
54270
54271 CREATE FUNCTION hmac(text, text, text) RETURNS bytea
54272     LANGUAGE c IMMUTABLE STRICT
54273     AS '$libdir/pgcrypto', 'pg_hmac';
54274
54275
54276 ALTER FUNCTION public.hmac(text, text, text) OWNER TO admin;
54277
54278 --
54279 -- TOC entry 1797 (class 1255 OID 146566373)
54280 -- Dependencies: 8
54281 -- Name: hmac(bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
54282 --
54283
54284 CREATE FUNCTION hmac(bytea, bytea, text) RETURNS bytea
54285     LANGUAGE c IMMUTABLE STRICT
54286     AS '$libdir/pgcrypto', 'pg_hmac';
54287
54288
54289 ALTER FUNCTION public.hmac(bytea, bytea, text) OWNER TO admin;
54290
54291 --
54292 -- TOC entry 1798 (class 1255 OID 146566374)
54293 -- Dependencies: 4536 8
54294 -- Name: implodewo(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
54295 --
54296
54297 CREATE FUNCTION implodewo(integer, boolean) RETURNS integer
54298     LANGUAGE plpgsql
54299     AS $_$
54300 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54301 -- See www.xtuple.com/CPAL for the full text of the software license.
54302 DECLARE
54303   pWoid ALIAS FOR $1;
54304   implodeChildren ALIAS FOR $2;
54305   resultCode INTEGER;
54306   _wotcCnt   INTEGER;
54307   _routings  BOOLEAN;
54308
54309 BEGIN
54310   SELECT metric_value='t' INTO _routings
54311          FROM metric
54312          WHERE (metric_name='Routings');
54313
54314   IF ((SELECT wo_id
54315        FROM wo
54316        WHERE ((wo_status='E')
54317         AND (wo_id=pWoid))) IS NULL) THEN
54318     RETURN 0;
54319   END IF;
54320
54321   IF (_routings) THEN
54322     SELECT count(*) INTO _wotcCnt
54323     FROM xtmfg.wotc
54324     WHERE (wotc_wo_id=pWoid);
54325     IF (_wotcCnt > 0) THEN
54326       RETURN -1;
54327     END IF;
54328   END IF;
54329
54330 --  Delete any created P/R's for this W/O
54331   PERFORM deletePr('W', womatl_id)
54332   FROM womatl
54333   WHERE (womatl_wo_id=pWoid);
54334
54335   DELETE FROM womatl
54336   WHERE (womatl_id IN ( SELECT womatl_id
54337                         FROM womatl, wo
54338                         WHERE ((womatl_wo_id=wo_id)
54339                          AND (wo_status='E')
54340                          AND (wo_id=pWoid)) ));
54341
54342   IF _routings THEN
54343
54344     DELETE FROM xtmfg.wooper
54345     WHERE (wooper_id IN ( SELECT wooper_id
54346                           FROM xtmfg.wooper, wo
54347                           WHERE ((wooper_wo_id=wo_id)
54348                            AND (wo_status='E')
54349                            AND (wo_id=pWoid)) ));
54350   END IF;
54351
54352   UPDATE wo
54353   SET wo_status='O'
54354   WHERE (wo_id=pWoid);
54355
54356   IF (implodeChildren) THEN
54357     resultCode := (SELECT MAX(implodeWo(wo_id, TRUE))
54358                    FROM wo
54359                    WHERE ((wo_ordtype='W')
54360                     AND (wo_ordid=pWoid)));
54361
54362     resultCode := (SELECT MAX(deleteWo(wo_id, TRUE))
54363                    FROM wo
54364                    WHERE ((wo_ordtype='W')
54365                     AND (wo_ordid=pWoid)));
54366   END IF;
54367
54368   RETURN 0;
54369 END;
54370 $_$;
54371
54372
54373 ALTER FUNCTION public.implodewo(integer, boolean) OWNER TO admin;
54374
54375 --
54376 -- TOC entry 206 (class 1259 OID 146566375)
54377 -- Dependencies: 5952 5953 5954 8
54378 -- Name: incdt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
54379 --
54380
54381 CREATE TABLE incdt (
54382     incdt_id integer NOT NULL,
54383     incdt_number integer NOT NULL,
54384     incdt_crmacct_id integer,
54385     incdt_cntct_id integer,
54386     incdt_summary text,
54387     incdt_descrip text,
54388     incdt_item_id integer,
54389     incdt_timestamp timestamp without time zone DEFAULT now() NOT NULL,
54390     incdt_status character(1) DEFAULT 'N'::bpchar NOT NULL,
54391     incdt_assigned_username text,
54392     incdt_incdtcat_id integer,
54393     incdt_incdtseverity_id integer,
54394     incdt_incdtpriority_id integer,
54395     incdt_incdtresolution_id integer,
54396     incdt_lotserial text,
54397     incdt_ls_id integer,
54398     incdt_aropen_id integer,
54399     incdt_owner_username text,
54400     incdt_recurring_incdt_id integer,
54401     incdt_updated timestamp without time zone DEFAULT now() NOT NULL,
54402     incdt_prj_id integer,
54403     incdt_public boolean
54404 );
54405
54406
54407 ALTER TABLE public.incdt OWNER TO admin;
54408
54409 --
54410 -- TOC entry 8976 (class 0 OID 0)
54411 -- Dependencies: 206
54412 -- Name: TABLE incdt; Type: COMMENT; Schema: public; Owner: admin
54413 --
54414
54415 COMMENT ON TABLE incdt IS 'Incident table';
54416
54417
54418 --
54419 -- TOC entry 8977 (class 0 OID 0)
54420 -- Dependencies: 206
54421 -- Name: COLUMN incdt.incdt_lotserial; Type: COMMENT; Schema: public; Owner: admin
54422 --
54423
54424 COMMENT ON COLUMN incdt.incdt_lotserial IS 'incdt_lotserial is deprecated';
54425
54426
54427 --
54428 -- TOC entry 8978 (class 0 OID 0)
54429 -- Dependencies: 206
54430 -- Name: COLUMN incdt.incdt_recurring_incdt_id; Type: COMMENT; Schema: public; Owner: admin
54431 --
54432
54433 COMMENT ON COLUMN incdt.incdt_recurring_incdt_id IS 'The first incdt record in the series if this is a recurring Incident. If the incdt_recurring_incdt_id is the same as the incdt_id, this record is the first in the series.';
54434
54435
54436 --
54437 -- TOC entry 1799 (class 1255 OID 146566384)
54438 -- Dependencies: 2785 4536 8
54439 -- Name: incdt(); Type: FUNCTION; Schema: public; Owner: admin
54440 --
54441
54442 CREATE FUNCTION incdt() RETURNS SETOF incdt
54443     LANGUAGE plpgsql
54444     AS $$
54445 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54446 -- See www.xtuple.com/CPAL for the full text of the software license.
54447 DECLARE
54448   _row incdt%ROWTYPE;
54449   _priv TEXT;
54450   _grant BOOLEAN;
54451
54452 BEGIN
54453   -- This query will give us the most permissive privilege the user has been granted
54454   SELECT privilege, granted INTO _priv, _grant
54455   FROM privgranted 
54456   WHERE privilege IN ('MaintainAllIncidents','ViewAllIncidents','MaintainPersonalIncidents','ViewPersonalIncidents')
54457   ORDER BY granted DESC, sequence
54458   LIMIT 1;
54459
54460   -- If have an 'All' privilege return all results
54461   IF (_priv ~ 'All' AND _grant) THEN
54462     FOR _row IN 
54463       SELECT * FROM incdt
54464     LOOP
54465       RETURN NEXT _row;
54466     END LOOP;
54467   -- Otherwise if have any other grant, must be personal privilege.
54468   ELSIF (_grant) THEN
54469     FOR _row IN 
54470       SELECT * FROM incdt 
54471       WHERE  getEffectiveXtUser() IN (incdt_owner_username, incdt_assigned_username)
54472     LOOP
54473       RETURN NEXT _row;
54474     END LOOP;
54475   END IF;
54476
54477   RETURN;
54478
54479 END;
54480 $$;
54481
54482
54483 ALTER FUNCTION public.incdt() OWNER TO admin;
54484
54485 --
54486 -- TOC entry 8980 (class 0 OID 0)
54487 -- Dependencies: 1799
54488 -- Name: FUNCTION incdt(); Type: COMMENT; Schema: public; Owner: admin
54489 --
54490
54491 COMMENT ON FUNCTION incdt() IS 'A table function that returns Incident results according to privilege settings.';
54492
54493
54494 --
54495 -- TOC entry 1800 (class 1255 OID 146566385)
54496 -- Dependencies: 4536 8
54497 -- Name: indentedbom(integer); Type: FUNCTION; Schema: public; Owner: admin
54498 --
54499
54500 CREATE FUNCTION indentedbom(integer) RETURNS integer
54501     LANGUAGE plpgsql
54502     AS $_$
54503 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54504 -- See www.xtuple.com/CPAL for the full text of the software license.
54505 DECLARE
54506   pItemid ALIAS FOR $1;
54507   _revid INTEGER;
54508
54509 BEGIN
54510
54511   SELECT getActiveRevId('BOM',pItemid) INTO _revid;
54512
54513   RETURN indentedBOM(pItemid, _revid);
54514
54515 END;
54516 $_$;
54517
54518
54519 ALTER FUNCTION public.indentedbom(integer) OWNER TO admin;
54520
54521 --
54522 -- TOC entry 1801 (class 1255 OID 146566386)
54523 -- Dependencies: 4536 8
54524 -- Name: indentedbom(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
54525 --
54526
54527 CREATE FUNCTION indentedbom(integer, integer) RETURNS integer
54528     LANGUAGE plpgsql
54529     AS $_$
54530 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54531 -- See www.xtuple.com/CPAL for the full text of the software license.
54532 DECLARE
54533   pItemid ALIAS FOR $1;
54534   pRevisionid ALIAS FOR $2;
54535   _bomworkid INTEGER;
54536   _indexid INTEGER;
54537   _r RECORD;
54538   _batchsize NUMERIC;
54539
54540 BEGIN
54541
54542   -- Get the batch quantity
54543   SELECT COALESCE( (
54544     SELECT bomhead_batchsize
54545     FROM bomhead
54546     WHERE ((bomhead_item_id=pItemId)
54547     AND (bomhead_rev_id=pRevisionid)) LIMIT 1),1) INTO _batchsize;
54548  
54549 --  Check on the temporary workspace
54550 --  PERFORM maintainBOMWorkspace();
54551
54552 --  Grab a new index for this bomwork set
54553   SELECT NEXTVAL('misc_index_seq') INTO _indexid;
54554
54555 --  Step through all of the components of the passed pItemid
54556   FOR _r IN SELECT bomitem.*,
54557                    item_id,
54558                    itemuomtouom(item_id, item_inv_uom_id, NULL, (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper') AS qtyreq,
54559                    (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL)
54560                                * bomitem_qtyfxd) AS qtyfxd,
54561                    (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL)
54562                                * bomitem_qtyper) AS qtyper,
54563                    stdcost(item_id, bomitem_id) AS standardcost,
54564                    actcost(item_id, bomitem_id) AS actualcost
54565   FROM bomitem(pItemId, pRevisionid), item
54566   WHERE ( (bomitem_item_id=item_id) ) LOOP
54567
54568 --  Insert the component and bomitem parameters
54569     SELECT NEXTVAL('bomwork_bomwork_id_seq') INTO _bomworkid;
54570     INSERT INTO bomwork
54571     ( bomwork_id, bomwork_set_id, bomwork_parent_id, bomwork_level,
54572       bomwork_parent_seqnumber, bomwork_seqnumber,
54573       bomwork_item_id, bomwork_createwo, bomwork_qtyreq,
54574       bomwork_qtyfxd, bomwork_qtyper, bomwork_scrap, bomwork_issuemethod,
54575       bomwork_effective, bomwork_expires,
54576       bomwork_stdunitcost, bomwork_actunitcost,
54577       bomwork_char_id, bomwork_value, bomwork_notes, bomwork_ref,
54578       bomwork_bomitem_id, bomwork_ecn )
54579     VALUES
54580     ( _bomworkid, _indexid, -1, 1,
54581       0, _r.bomitem_seqnumber,
54582       _r.item_id, _r.bomitem_createwo, _r.qtyreq,
54583       _r.qtyfxd, _r.qtyper, _r.bomitem_scrap, _r.bomitem_issuemethod,
54584       _r.bomitem_effective, _r.bomitem_expires,
54585       _r.standardcost, _r.actualcost,
54586       _r.bomitem_char_id, _r.bomitem_value, _r.bomitem_notes, _r.bomitem_ref,
54587       _r.bomitem_id, _r.bomitem_ecn );
54588
54589 --  Explode the components of the current component
54590     PERFORM explodeBOM(_r.item_id, _bomworkid, 1);
54591
54592   END LOOP;
54593
54594 --  Return a key to the result
54595   RETURN _indexid;
54596
54597 END;
54598 $_$;
54599
54600
54601 ALTER FUNCTION public.indentedbom(integer, integer) OWNER TO admin;
54602
54603 --
54604 -- TOC entry 1802 (class 1255 OID 146566387)
54605 -- Dependencies: 2657 4536 8
54606 -- Name: indentedbom(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
54607 --
54608
54609 CREATE FUNCTION indentedbom(integer, integer, integer, integer) RETURNS SETOF bomdata
54610     LANGUAGE plpgsql
54611     AS $_$
54612 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54613 -- See www.xtuple.com/CPAL for the full text of the software license.
54614 DECLARE
54615   pItemid ALIAS FOR $1;
54616   pRevisionid ALIAS FOR $2;
54617   pExpiredDays ALIAS FOR $3;
54618   pFutureDays ALIAS FOR $4;
54619   _row bomdata%ROWTYPE;
54620   _bomworksetid INTEGER;
54621   _x RECORD;
54622   _check CHAR(1);
54623   _inactive BOOLEAN := FALSE;
54624   _batchsize NUMERIC;
54625 BEGIN
54626
54627   IF (pRevisionid != -1) THEN
54628     --Is this a deactivated revision?
54629     SELECT rev_status INTO _check
54630     FROM rev
54631     WHERE ((rev_id=pRevisionid)
54632     AND (rev_status='I'));
54633     IF (FOUND) THEN
54634       _inactive := TRUE;
54635     END IF;
54636   END IF;
54637  
54638   -- Get the batch quantity
54639   SELECT COALESCE( (
54640     SELECT bomhead_batchsize
54641     FROM bomhead
54642     WHERE ((bomhead_item_id=pItemId)
54643     AND (bomhead_rev_id=pRevisionid)) LIMIT 1),1) INTO _batchsize;
54644  
54645   IF NOT (_inactive) THEN
54646
54647     --We can explode this out based on current data
54648     SELECT indentedBOM(pItemid, pRevisionid) INTO _bomworksetid;  
54649
54650     FOR _x IN
54651         SELECT bomwork_id, bomwork_parent_id, bomwork_level,
54652                bomworkSequence(bomwork_id) AS seq_ord,
54653                bomwork_seqnumber, item_id, item_number, uom_name,
54654                item_descrip1, item_descrip2,
54655                (item_descrip1 || ' ' || item_descrip2) AS itemdescription,
54656                bomwork_qtyreq, bomwork_qtyfxd, bomwork_qtyper, bomwork_scrap, bomwork_createwo,
54657        CASE WHEN (bomwork_issuemethod='S') THEN 'Push'
54658             WHEN (bomwork_issuemethod='L') THEN 'Pull'
54659             WHEN (bomwork_issuemethod='M') THEN 'Mixed'
54660             ELSE 'Special'
54661        END AS issuemethod,
54662        bomwork_effective, bomwork_expires,
54663        (bomwork_expires <= CURRENT_DATE) AS expired,
54664        (bomwork_effective > CURRENT_DATE) AS future,
54665        bomwork_actunitcost AS actunitcost,
54666        bomwork_stdunitcost AS stdunitcost,
54667        CASE WHEN item_type NOT IN ('R','T') THEN
54668          itemuomtouom(item_id, item_inv_uom_id, NULL, (bomwork_qtyfxd/_batchsize + bomwork_qtyper) * (1 + bomwork_scrap), 'qtyper') * bomwork_actunitcost
54669        ELSE 0.0 END AS actextendedcost,
54670        CASE WHEN item_type NOT IN ('R','T') THEN
54671          itemuomtouom(item_id, item_inv_uom_id, NULL, (bomwork_qtyfxd/_batchsize + bomwork_qtyper) * (1 + bomwork_scrap), 'qtyper') * bomwork_stdunitcost
54672        ELSE 0.0 END AS stdextendedcost,
54673        bomwork_char_id,
54674        bomwork_value, bomwork_notes, bomwork_ref,
54675        bomwork_bomitem_id, bomwork_ecn
54676        FROM bomwork, item, uom 
54677        WHERE ( (bomwork_item_id=item_id)
54678        AND (item_inv_uom_id=uom_id)
54679        AND (bomwork_set_id=_bomworksetid) )
54680        AND (bomwork_expires > (CURRENT_DATE - pExpiredDays))
54681        AND (bomwork_effective <= (CURRENT_DATE + pFutureDays))
54682        UNION
54683        SELECT -1, -1, 1,
54684               '0',
54685               NULL,-1, costelem_type AS bomdata_item_number, '',
54686               '', '',
54687               '',
54688               NULL, NULL, NULL, NULL, NULL,
54689               '',
54690               NULL, NULL,
54691               false,
54692               false,
54693               currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE) AS actunitcost,
54694               itemcost_stdcost AS stdunitcost,
54695               currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE) AS actextendedcost,
54696               itemcost_stdcost AS stdextendedcost,
54697               NULL,
54698               NULL,NULL,NULL,
54699               NULL,NULL
54700        FROM itemcost, costelem 
54701        WHERE ( (itemcost_costelem_id=costelem_id)
54702        AND (NOT itemcost_lowlevel)
54703        AND (itemcost_item_id=pItemid) )
54704        ORDER BY seq_ord
54705     LOOP
54706         _row.bomdata_bomwork_id := _x.bomwork_id;
54707         _row.bomdata_bomwork_parent_id := _x.bomwork_parent_id;
54708         _row.bomdata_bomwork_level := _x.bomwork_level;
54709         _row.bomdata_bomwork_seqnumber := _x.bomwork_seqnumber;
54710         _row.bomdata_bomitem_id := _x.bomwork_bomitem_id;
54711         _row.bomdata_item_id := _x.item_id;
54712         _row.bomdata_item_number := _x.item_number;
54713         _row.bomdata_uom_name := _x.uom_name;
54714         _row.bomdata_item_descrip1 := _x.item_descrip1;
54715         _row.bomdata_item_descrip2 := _x.item_descrip2;
54716         _row.bomdata_itemdescription := _x.itemdescription;
54717         _row.bomdata_batchsize := _batchsize;
54718         _row.bomdata_qtyreq := _x.bomwork_qtyreq;
54719         _row.bomdata_qtyfxd := _x.bomwork_qtyfxd;
54720         _row.bomdata_qtyper := _x.bomwork_qtyper;
54721         _row.bomdata_scrap := _x.bomwork_scrap;
54722         _row.bomdata_createchild := _x.bomwork_createwo;
54723         _row.bomdata_issuemethod := _x.issuemethod;
54724         _row.bomdata_effective := _x.bomwork_effective;
54725         _row.bomdata_expires := _x.bomwork_expires;
54726         _row.bomdata_expired := _x.expired;
54727         _row.bomdata_future := _x.future;
54728         _row.bomdata_actunitcost := _x.actunitcost;
54729         _row.bomdata_stdunitcost := _x.stdunitcost;
54730         _row.bomdata_actextendedcost := _x.actextendedcost;
54731         _row.bomdata_stdextendedcost := _x.stdextendedcost;
54732         _row.bomdata_ecn := _x.bomwork_ecn;
54733         _row.bomdata_char_id := _x.bomwork_char_id;
54734         _row.bomdata_value := _x.bomwork_value;
54735         _row.bomdata_notes := _x.bomwork_notes;
54736         _row.bomdata_ref := _x.bomwork_ref;
54737         RETURN NEXT _row;
54738     END LOOP;
54739     
54740     PERFORM deleteBOMWorkset(_bomworksetid);
54741
54742   ELSE
54743
54744 -- Use historical snapshot for inactive revisions
54745     FOR _x IN
54746         SELECT bomhist_id, bomhist_parent_id, bomhist_level,
54747                bomhistSequence(bomhist_seq_id) AS seq_ord,
54748                bomhist_seqnumber, item_id, item_number, uom_name,
54749                item_descrip1, item_descrip2,
54750                (item_descrip1 || ' ' || item_descrip2) AS itemdescription,
54751                bomhist_qtyreq, bomhist_qtyfxd, bomhist_qtyper, bomhist_scrap,
54752                bomhist_createwo,
54753        CASE WHEN (bomhist_issuemethod='S') THEN 'Push'
54754             WHEN (bomhist_issuemethod='L') THEN 'Pull'
54755             WHEN (bomhist_issuemethod='M') THEN 'Mixed'
54756             ELSE 'Special'
54757        END AS issuemethod,
54758        bomhist_effective, bomhist_expires,
54759        (bomhist_expires <= CURRENT_DATE) AS expired,
54760        (bomhist_effective > CURRENT_DATE) AS future,
54761        bomhist_actunitcost AS actunitcost,
54762        bomhist_stdunitcost AS stdunitcost,
54763        CASE WHEN item_type NOT IN ('R','T') THEN
54764          (bomist_qtyfxd/_batchsize + bomhist_qtyper) * (1 + bomhist_scrap) * bomhist_actunitcost
54765        ELSE 0 END AS actextendedcost,
54766        CASE WHEN item_type NOT IN ('R','T') THEN
54767          (bomist_qtyfxd/_batchsize + bomhist_qtyper) * (1 + bomhist_scrap) * bomhist_stdunitcost
54768        ELSE 0 END AS stdextendedcost,
54769        bomhist_char_id, bomhist_value, bomhist_notes, bomhist_ref 
54770        FROM bomhist, item, uom 
54771        WHERE ( (bomhist_item_id=item_id)
54772        AND (item_inv_uom_id=uom_id)
54773        AND (bomhist_rev_id=pRevisionid) )
54774        AND (bomhist_expires > (CURRENT_DATE - pExpiredDays))
54775        AND (bomhist_effective <= (CURRENT_DATE + pFutureDays))
54776        UNION
54777        SELECT -1, -1, 1,
54778               '0',
54779               NULL,-1, costelem_type AS bomdata_item_number, '',
54780               '', '',
54781               '',
54782               NULL, NULL, NULL, NULL,
54783               false,
54784               '', NULL, NULL,
54785               false,
54786               false,
54787               bomhist_actunitcost AS actunitcost,
54788               bomhist_stdunitcost AS stdunitcost,
54789               bomhist_actunitcost AS actextendedcost,
54790               bomhist_stdunitcost AS stdextendedcost,
54791               NULL,NULL,NULL,NULL 
54792        FROM bomhist, costelem 
54793        WHERE ((bomhist_rev_id=pRevisionid)
54794        AND (costelem_id=bomhist_item_id))
54795        ORDER BY seq_ord
54796     LOOP
54797         _row.bomdata_bomwork_id := _x.bomhist_id;
54798         _row.bomdata_bomwork_parent_id := _x.bomhist_parent_id;
54799         _row.bomdata_bomwork_level := _x.bomhist_level;
54800         _row.bomdata_bomwork_seqnumber := _x.bomhist_seqnumber;
54801         _row.bomdata_bomitem_id := -1;
54802         _row.bomdata_item_id := _x.item_id;
54803         _row.bomdata_item_number := _x.item_number;
54804         _row.bomdata_uom_name := _x.uom_name;
54805         _row.bomdata_item_descrip1 := _x.item_descrip1;
54806         _row.bomdata_item_descrip2 := _x.item_descrip2;
54807         _row.bomdata_itemdescription := _x.itemdescription;
54808         _row.bomdata_batchsize := _batchsize;
54809         _row.bomdata_qtyreq := _x.bomhist_qtyreq;
54810         _row.bomdata_qtyfxd := _x.bomist_qtyfxd;
54811         _row.bomdata_qtyper := _x.bomhist_qtyper;
54812         _row.bomdata_scrap := _x.bomhist_scrap;
54813         _row.bomdata_createchild := _x.bomhist_createwo;
54814         _row.bomdata_issuemethod := _x.issuemethod;
54815         _row.bomdata_effective := _x.bomhist_effective;
54816         _row.bomdata_expires := _x.bomhist_expires;
54817         _row.bomdata_expired := _x.expired;
54818         _row.bomdata_future := _x.future;
54819         _row.bomdata_actunitcost := _x.actunitcost;
54820         _row.bomdata_stdunitcost := _x.stdunitcost;
54821         _row.bomdata_actextendedcost := _x.actextendedcost;
54822         _row.bomdata_stdextendedcost := _x.stdextendedcost;
54823         _row.bomdata_ecn := '';
54824         _row.bomdata_char_id := _x.bomhist_char_id;
54825         _row.bomdata_value := _x.bomhist_value;
54826         _row.bomdata_notes := _x.bomhist_notes;
54827         _row.bomdata_ref := _x.bomhist_ref;
54828         RETURN NEXT _row;
54829     END LOOP;
54830   END IF;   
54831
54832   RETURN;
54833 END;
54834 $_$;
54835
54836
54837 ALTER FUNCTION public.indentedbom(integer, integer, integer, integer) OWNER TO admin;
54838
54839 --
54840 -- TOC entry 1805 (class 1255 OID 146566389)
54841 -- Dependencies: 4536 8
54842 -- Name: indentedwhereused(integer); Type: FUNCTION; Schema: public; Owner: admin
54843 --
54844
54845 CREATE FUNCTION indentedwhereused(integer) RETURNS integer
54846     LANGUAGE plpgsql
54847     AS $_$
54848 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54849 -- See www.xtuple.com/CPAL for the full text of the software license.
54850 DECLARE
54851   pItemid ALIAS FOR $1;
54852   _indexid INTEGER;
54853   _level INTEGER;
54854
54855 BEGIN
54856
54857 --  Check on the temporary workspace
54858 --  PERFORM maintainBOMWorkspace();
54859
54860   _indexid := (SELECT NEXTVAL('misc_index_seq'));
54861   _level := 1;
54862
54863   INSERT INTO bomwork
54864   ( bomwork_set_id, bomwork_parent_id,
54865     bomwork_level, bomwork_seqnumber,
54866     bomwork_item_id, bomwork_item_type, bomwork_createwo,
54867     bomwork_qtyfxd, bomwork_qtyper,
54868     bomwork_scrap, bomwork_issuemethod,
54869     bomwork_effective, bomwork_expires, bomwork_status,
54870     bomwork_stdunitcost, bomwork_actunitcost )
54871   SELECT _indexid, -1,
54872          1, bomitem_seqnumber,
54873          item_id, item_type, bomitem_createwo,
54874          (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyfxd),
54875          (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyper),
54876          bomitem_scrap, bomitem_issuemethod,
54877          bomitem_effective, bomitem_expires, 'U',
54878          stdcost(item_id), actcost(item_id)
54879   FROM bomitem, item
54880   WHERE ((bomitem_item_id=pItemid)
54881     AND (bomitem_parent_item_id=item_id)
54882     AND (CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1))
54883     AND (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id)));
54884
54885   WHILE ( ( SELECT count(*)
54886             FROM bomwork
54887             WHERE ((bomwork_status='U')
54888               AND (bomwork_set_id=_indexid)) ) > 0) LOOP
54889
54890     _level := _level + 1;
54891
54892     INSERT INTO bomwork
54893     ( bomwork_set_id, bomwork_parent_id,
54894       bomwork_level, bomwork_seqnumber,
54895       bomwork_item_id, bomwork_item_type, bomwork_createwo,
54896       bomwork_qtyfxd, bomwork_qtyper,
54897       bomwork_scrap, bomwork_issuemethod,
54898       bomwork_effective, bomwork_expires, bomwork_status,
54899       bomwork_stdunitcost, bomwork_actunitcost )
54900     SELECT _indexid, bomwork_id,
54901            _level, bomitem_seqnumber,
54902            item_id, item_type, bomitem_createwo,
54903            (bomwork_qtyper * (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyfxd)),
54904            (bomwork_qtyper * (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyper)),
54905            bomitem_scrap, bomitem_issuemethod,
54906            CASE WHEN bomitem_effective < bomwork_effective THEN
54907              bomwork_effective
54908            ELSE bomitem_effective END, 
54909            CASE WHEN bomitem_expires > bomwork_expires THEN
54910              bomwork_expires
54911            ELSE bomitem_expires END,
54912            'N',
54913            stdcost(item_id), actcost(item_id)
54914     FROM bomwork JOIN bomitem ON ( (bomitem_item_id=bomwork_item_id)
54915                                AND (CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1))
54916                                AND (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id)) )
54917                  JOIN item ON (item_id=bomitem_parent_item_id)
54918     WHERE (bomwork_status='U');
54919
54920     UPDATE bomwork
54921     SET bomwork_status='C'
54922     WHERE ((bomwork_status='U')
54923       AND (bomwork_set_id=_indexid));
54924
54925     UPDATE bomwork
54926     SET bomwork_status='U'
54927     WHERE ((bomwork_status='N')
54928       AND (bomwork_set_id=_indexid));
54929
54930   END LOOP;
54931
54932   RETURN _indexid;
54933 END;
54934 $_$;
54935
54936
54937 ALTER FUNCTION public.indentedwhereused(integer) OWNER TO admin;
54938
54939 --
54940 -- TOC entry 1806 (class 1255 OID 146566390)
54941 -- Dependencies: 2711 4536 8
54942 -- Name: indentedwo(integer, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
54943 --
54944
54945 CREATE FUNCTION indentedwo(integer, boolean, boolean, boolean) RETURNS SETOF wodata
54946     LANGUAGE plpgsql
54947     AS $_$
54948 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
54949 -- See www.xtuple.com/CPAL for the full text of the software license.
54950 DECLARE
54951    pwoid ALIAS FOR $1;
54952    pshowops ALIAS FOR $2;
54953    pshowmatl ALIAS FOR $3; 
54954    pshowindent ALIAS FOR $4;   
54955   _row wodata%ROWTYPE;
54956   _subrow wodata%ROWTYPE;  
54957   _opx wodata%ROWTYPE;
54958   _x RECORD;
54959   _level INTEGER;
54960    
54961 BEGIN 
54962     --The wodata_id_type column is used to indicate the source of the wodata_id
54963     --there are three different tables used wo, womatl and womatlvar
54964     --wodata_id_type = 1 = wo_id
54965     --wodata_id_type = 2 = womatl_id
54966     --wodata_id_type = 3 = wooper_id
54967     --initialise values
54968     _level := 0;   
54969     --get top level works orders
54970     FOR _x IN
54971        SELECT wo_id,wo_number,wo_subnumber,wo_status,wo_startdate,
54972          wo_duedate,wo_adhoc,wo_itemsite_id,itemsite_qtyonhand,
54973          wo_qtyord,wo_qtyrcv,wo_prodnotes, item_number,
54974          item_descrip1, item_descrip2, item_listprice, uom_name
54975        FROM wo, itemsite, item, uom     
54976        WHERE ((wo_id = pwoid)
54977          AND (itemsite_id = wo_itemsite_id)
54978          AND (itemsite_item_id=item_id)
54979          AND (item_inv_uom_id=uom_id))      
54980        ORDER BY wo_number, wo_subnumber
54981     LOOP
54982         _row.wodata_id := _x.wo_id;
54983         _row.wodata_id_type := 1;            
54984         _row.wodata_number := _x.wo_number;
54985         _row.wodata_subnumber := _x.wo_subnumber;
54986         _row.wodata_itemnumber := _x.item_number;
54987         _row.wodata_descrip := _x.item_descrip1 || '-' || _x.item_descrip2;
54988         _row.wodata_status := _x.wo_status;
54989         _row.wodata_startdate := _x.wo_startdate;
54990         _row.wodata_duedate := _x.wo_duedate;
54991         _row.wodata_adhoc := _x.wo_adhoc;     
54992         _row.wodata_itemsite_id := _x.wo_itemsite_id;
54993         _row.wodata_custprice := _x.item_listprice;
54994         _row.wodata_listprice := _x.item_listprice;
54995         _row.wodata_qoh := _x.itemsite_qtyonhand;
54996         _row.wodata_short := noneg(_x.wo_qtyord - _x.wo_qtyrcv);
54997         _row.wodata_qtyrcv := _x.wo_qtyrcv;   
54998         _row.wodata_qtyordreq := _x.wo_qtyord;   
54999         _row.wodata_qtyuom := _x.uom_name;    
55000         _row.wodata_scrap := 0;        
55001         _row.wodata_notes := _x.wo_prodnotes;     
55002         _row.wodata_level := _level;                
55003         RETURN NEXT _row;
55004         IF (pshowmatl AND NOT pshowops) THEN
55005           --expand materials      
55006           FOR _subrow IN
55007              SELECT * FROM indentedwomatl(pwoid, _level)
55008           LOOP                                                  
55009             RETURN NEXT _subrow;
55010           END LOOP;
55011         END IF;
55012         
55013         IF ((pshowmatl OR pshowindent) AND NOT pshowops) THEN
55014           --expand next level down               
55015           FOR _subrow IN
55016            SELECT * FROM indentedwo(_x.wo_id, NULL, _level + 1, pshowmatl, pshowindent) 
55017           LOOP                                           
55018             RETURN NEXT _subrow; 
55019           END LOOP;
55020         END IF;
55021           
55022         IF (pshowops) THEN
55023          --expand materials not on operations   
55024          IF (pshowmatl) THEN   
55025            FOR _subrow IN
55026              SELECT * FROM indentedwomatl(pwoid, -1, _level)
55027            LOOP                                                  
55028              RETURN NEXT _subrow;
55029            END LOOP;
55030          END IF;
55031
55032          IF (pshowmatl OR pshowindent) THEN
55033            --expand next level down             
55034            FOR _subrow IN
55035              SELECT * FROM indentedwo(_x.wo_id, -1, _level + 1,  pshowmatl, pshowindent) 
55036            LOOP                                           
55037              RETURN NEXT _subrow; 
55038            END LOOP;
55039          END IF;
55040
55041          --expand opeartions
55042          FOR _opx IN
55043            SELECT * FROM xtmfg.indentedwoops(pwoid,_level)
55044          LOOP
55045            RETURN NEXT _opx;
55046
55047            IF (pshowmatl) THEN  
55048               --expand materials on operations      
55049               FOR _subrow IN
55050                  SELECT * FROM indentedwomatl(pwoid, _opx.wodata_id, _level + 1)
55051               LOOP                                                  
55052                 RETURN NEXT _subrow;
55053               END LOOP;
55054            END IF;
55055
55056            IF (pshowmatl OR pshowindent) THEN
55057               --expand next level down             
55058               FOR _subrow IN
55059                 SELECT * FROM indentedwo(_x.wo_id, _opx.wodata_id, _level + 2,  pshowmatl, pshowindent) 
55060               LOOP                                           
55061                 RETURN NEXT _subrow; 
55062               END LOOP;
55063            END IF; 
55064          END LOOP; 
55065        END IF;                           
55066   END LOOP;                     
55067   RETURN;
55068 END;
55069 $_$;
55070
55071
55072 ALTER FUNCTION public.indentedwo(integer, boolean, boolean, boolean) OWNER TO admin;
55073
55074 --
55075 -- TOC entry 1807 (class 1255 OID 146566391)
55076 -- Dependencies: 2711 4536 8
55077 -- Name: indentedwo(integer, integer, integer, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
55078 --
55079
55080 CREATE FUNCTION indentedwo(integer, integer, integer, boolean, boolean) RETURNS SETOF wodata
55081     LANGUAGE plpgsql
55082     AS $_$
55083 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
55084 -- See www.xtuple.com/CPAL for the full text of the software license.
55085 DECLARE
55086    pwoid ALIAS FOR $1;   
55087    pwooperid ALIAS FOR $2;
55088    plevel ALIAS FOR $3;
55089    pshowmatl ALIAS FOR $4; 
55090    pshowindent ALIAS FOR $5;  
55091   _row wodata%ROWTYPE;   
55092   _opx wodata%ROWTYPE; 
55093   _x RECORD;
55094   _subx RECORD;
55095   _index INTEGER;
55096   _level INTEGER;
55097   _qry TEXT;
55098    
55099 BEGIN 
55100     --The wodata id column is used to indicate the source of the id
55101     --there are three different tables used wo, womatl and womatlvar
55102     --wodata_id_type = 1 = wo_id
55103     --wodata_id_type = 2 = womatl_id
55104     --wodata_id_type = 3 = wooper_id
55105     _level := (plevel + 1);    
55106     --find all WO with the ordid of the next level up
55107     _qry := 'SELECT wo_id,wo_number,wo_subnumber,wo_status,wo_startdate,wo_duedate,
55108          wo_adhoc,wo_itemsite_id,itemsite_qtyonhand,wo_qtyord,wo_qtyrcv, wo_prodnotes,
55109          item_number,item_descrip1, item_descrip2, item_listprice, uom_name,
55110          womatl_qtyiss, womatl_scrap, womatl_wooper_id
55111        FROM itemsite,  wo, item, uom, womatl 
55112        WHERE ((wo_ordid = ' || pwoid || ')
55113          AND (wo_ordtype = ''W'')
55114          AND (itemsite_item_id=item_id)
55115          AND (item_inv_uom_id=uom_id)   
55116          AND (wo_womatl_id=womatl_id)   
55117          AND (wo_itemsite_id = itemsite_id) ';
55118
55119     IF (pwooperid IS NOT NULL) THEN
55120       _qry := _qry || ' AND (womatl_wooper_id=' || pwooperid || ') ';
55121     END IF;               
55122
55123     _qry := _qry || ') ORDER BY wo_number, wo_subnumber';
55124  /* if (pwooperid IS NOT NULL) THEN
55125     raise exception 'stop %',_qry;
55126   END IF;*/
55127     FOR _x IN
55128       EXECUTE _qry
55129     LOOP 
55130         _row.wodata_id := _x.wo_id;
55131         _row.wodata_id_type := 1;                     
55132         _row.wodata_number := _x.wo_number;
55133         _row.wodata_subnumber := _x.wo_subnumber;
55134         _row.wodata_itemnumber := _x.item_number;
55135         _row.wodata_descrip := _x.item_descrip1 || '-' || _x.item_descrip2;
55136         _row.wodata_status := _x.wo_status;
55137         _row.wodata_startdate := _x.wo_startdate;
55138         _row.wodata_duedate := _x.wo_duedate;
55139         _row.wodata_adhoc := _x.wo_adhoc;      
55140         _row.wodata_itemsite_id := _x.wo_itemsite_id;        
55141         _row.wodata_custprice := _x.item_listprice;
55142         _row.wodata_listprice := _x.item_listprice;
55143         _row.wodata_qoh := _x.itemsite_qtyonhand;
55144         _row.wodata_short := noneg(_x.wo_qtyord - _x.wo_qtyrcv);
55145         _row.wodata_qtyiss := _x.womatl_qtyiss;  
55146         _row.wodata_qtyrcv := _x.wo_qtyrcv;   
55147         _row.wodata_qtyordreq := _x.wo_qtyord; 
55148         _row.wodata_scrap := _x.womatl_scrap;  
55149         _row.wodata_notes := _x.wo_prodnotes;       
55150         _row.wodata_level := plevel;                
55151         RETURN NEXT _row;  
55152         --if indentation require expand next level
55153         IF (pshowindent AND pwooperid IS NULL) THEN
55154           IF (pshowmatl AND pshowindent) THEN    
55155             --get materials for this level
55156             FOR _subx IN
55157               SELECT * FROM indentedwomatl(_x.wo_id, plevel) 
55158             LOOP                                            
55159               RETURN NEXT _subx;
55160             END LOOP;
55161           END IF;
55162
55163           IF (pshowindent) THEN  
55164             --expand lower levels 
55165             FOR _subx IN
55166               SELECT * FROM indentedwo(_x.wo_id, NULL, _level, pshowmatl, pshowindent )
55167             LOOP                                           
55168               RETURN NEXT _subx; 
55169             END LOOP; 
55170           END IF;    
55171             
55172         ELSIF (pshowindent) THEN --Handle operations
55173           --expand materials not on operations   
55174           IF (pshowmatl) THEN   
55175             FOR _subx IN
55176               SELECT * FROM indentedwomatl(_x.wo_id, -1, plevel)
55177             LOOP                                                  
55178               RETURN NEXT _subx;
55179             END LOOP;
55180           END IF;
55181
55182           --expand next level down not on operations
55183           FOR _subx IN
55184             SELECT * FROM indentedwo(_x.wo_id, -1, _level,  pshowmatl, pshowindent) 
55185           LOOP                                           
55186             RETURN NEXT _subx; 
55187           END LOOP;
55188           
55189           --expand operations
55190           FOR _opx IN
55191             SELECT * FROM xtmfg.indentedwoops(_x.wo_id,plevel)
55192           LOOP
55193             RETURN NEXT _opx;
55194
55195             IF (pshowmatl) THEN  
55196               --expand materials on operations      
55197               FOR _subx IN
55198                  SELECT * FROM indentedwomatl(_x.wo_id, _opx.wodata_id, _level)
55199               LOOP                                                  
55200                 RETURN NEXT _subx;
55201                 --      raise exception 'stop %',_opx.wodata_id;
55202               END LOOP;
55203             END IF;
55204               
55205             --expand next level down   
55206             FOR _subx IN
55207               SELECT * FROM indentedwo(_x.wo_id, _opx.wodata_id, _level + 2,  pshowmatl, pshowindent) 
55208             LOOP                                        
55209               RETURN NEXT _subx; 
55210             END LOOP;
55211               
55212           END LOOP;
55213         END IF;                       
55214       END LOOP;                         
55215   RETURN;
55216 END;
55217 $_$;
55218
55219
55220 ALTER FUNCTION public.indentedwo(integer, integer, integer, boolean, boolean) OWNER TO admin;
55221
55222 --
55223 -- TOC entry 1808 (class 1255 OID 146566392)
55224 -- Dependencies: 2711 4536 8
55225 -- Name: indentedwomatl(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
55226 --
55227
55228 CREATE FUNCTION indentedwomatl(integer, integer) RETURNS SETOF wodata
55229     LANGUAGE plpgsql
55230     AS $_$
55231 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
55232 -- See www.xtuple.com/CPAL for the full text of the software license.
55233 DECLARE
55234    pwoid ALIAS FOR $1;   
55235    plevel ALIAS FOR $2;
55236   _subx RECORD;
55237    
55238 BEGIN
55239   FOR _subx IN
55240     SELECT * FROM indentedwomatl(pwoid, NULL::integer, plevel)
55241   LOOP
55242     RETURN NEXT _subx;
55243   END LOOP;        
55244   RETURN;
55245 END;
55246 $_$;
55247
55248
55249 ALTER FUNCTION public.indentedwomatl(integer, integer) OWNER TO admin;
55250
55251 --
55252 -- TOC entry 1809 (class 1255 OID 146566393)
55253 -- Dependencies: 2711 4536 8
55254 -- Name: indentedwomatl(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
55255 --
55256
55257 CREATE FUNCTION indentedwomatl(integer, integer, integer) RETURNS SETOF wodata
55258     LANGUAGE plpgsql
55259     AS $_$
55260 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
55261 -- See www.xtuple.com/CPAL for the full text of the software license.
55262 DECLARE
55263    pwoid ALIAS FOR $1;  
55264    pwooperid ALIAS FOR $2; 
55265    plevel ALIAS FOR $3;
55266   _status TEXT; 
55267   _subrow wodata%ROWTYPE;  
55268   _subx RECORD;
55269   _level INTEGER;
55270   _qry TEXT;
55271    
55272 BEGIN
55273   --The wodata id column is used to indicate the source of the id
55274   --there are three different tables used wo, womatl and womatlvar
55275   --wodata_id_type = 1 = wo_id
55276   --wodata_id_type = 2 = womatl_id
55277   --wodata_id_type = 3 = wooper_id
55278
55279   _qry := 'SELECT womatl_id, wo_number, wo_subnumber, 
55280       wo_startdate, womatl_duedate, womatl_itemsite_id,
55281       itemsite_qtyonhand, womatl_qtyreq, womatl_qtyiss,
55282       womatl_qtyper, womatl_qtyreq, womatl_scrap,
55283       womatl_ref, womatl_notes, womatl_price, item_listprice,
55284       item_number, item_descrip1, item_descrip2,
55285       uom_name
55286     FROM womatl, wo, itemsite, item, uom
55287     WHERE ((wo_id = womatl_wo_id)
55288      AND (wo_id = ' || pwoid || ')
55289      AND (womatl_itemsite_id = itemsite_id)
55290      AND (itemsite_item_id=item_id)
55291      AND (womatl_uom_id=uom_id) ';
55292 -- Need to display in case child w/o is deleted
55293 --     AND (NOT womatl_createwo OR womatl_createwo IS NULL) ';
55294
55295   IF (pwooperid IS NOT NULL) THEN
55296     _qry := _qry || 'AND (womatl_wooper_id=' || pwooperid  || ')';
55297   END IF;
55298
55299   _qry := _qry || ') ORDER BY item_number;';
55300   
55301   _level := plevel + 1;    
55302   SELECT wo_status FROM wo WHERE wo_id = pwoid  LIMIT 1 INTO _status;
55303  
55304   FOR _subx IN
55305     EXECUTE _qry
55306   LOOP
55307     _subrow.wodata_id := _subx.womatl_id;
55308     _subrow.wodata_id_type  := 2;       
55309     _subrow.wodata_number := _subx.wo_number;
55310     _subrow.wodata_subnumber := _subx.wo_subnumber;
55311     _subrow.wodata_itemnumber := _subx.item_number;
55312     _subrow.wodata_descrip := _subx.item_descrip1 || '-' || _subx.item_descrip2;
55313     _subrow.wodata_status := _status;
55314     _subrow.wodata_startdate := _subx.wo_startdate;
55315     _subrow.wodata_duedate := _subx.womatl_duedate;
55316     _subrow.wodata_itemsite_id := _subx.womatl_itemsite_id;    
55317     _subrow.wodata_custprice := _subx.womatl_price;
55318     _subrow.wodata_listprice := _subx.item_listprice;
55319     _subrow.wodata_qoh := _subx.itemsite_qtyonhand;
55320     IF((_subx.itemsite_qtyonhand > (_subx.womatl_qtyreq - _subx.womatl_qtyiss))) THEN
55321       _subrow.wodata_short := 0;
55322     ELSE
55323       _subrow.wodata_short := (_subx.womatl_qtyreq - _subx.womatl_qtyiss) -  _subx.itemsite_qtyonhand;
55324     END IF;
55325     _subrow.wodata_qtyper := _subx.womatl_qtyper;
55326     _subrow.wodata_qtyiss := _subx.womatl_qtyiss;         
55327     _subrow.wodata_qtyordreq := _subx.womatl_qtyreq;     
55328     _subrow.wodata_qtyuom := _subx.uom_name;   
55329     _subrow.wodata_scrap := _subx.womatl_scrap;        
55330     _subrow.wodata_notes := _subx.womatl_notes;
55331     _subrow.wodata_ref := _subx.womatl_ref;       
55332     _subrow.wodata_level := _level;                                   
55333     RETURN NEXT _subrow; 
55334   END LOOP;     
55335         
55336   RETURN;
55337 END;
55338 $_$;
55339
55340
55341 ALTER FUNCTION public.indentedwomatl(integer, integer, integer) OWNER TO admin;
55342
55343 --
55344 -- TOC entry 1810 (class 1255 OID 146566394)
55345 -- Dependencies: 4536 8
55346 -- Name: initeffectivextuser(); Type: FUNCTION; Schema: public; Owner: admin
55347 --
55348
55349 CREATE FUNCTION initeffectivextuser() RETURNS void
55350     LANGUAGE plpgsql
55351     AS $$
55352 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
55353 -- See www.xtuple.com/CPAL for the full text of the software license.
55354 BEGIN
55355   -- Effective users use a temporary table to store the user information
55356   -- and this function, called by the other functions, makes sure the temp
55357   -- tables exist first.
55358   PERFORM *
55359      FROM pg_catalog.pg_class
55360     WHERE relname = 'effective_user'
55361       AND relnamespace = pg_catalog.pg_my_temp_schema();
55362
55363   IF NOT FOUND THEN
55364     CREATE TEMPORARY TABLE effective_user (
55365       effective_key TEXT,
55366       effective_value TEXT
55367     );
55368     CREATE UNIQUE INDEX effective_user_pkey ON effective_user (effective_key);
55369   END IF;
55370 END;
55371 $$;
55372
55373
55374 ALTER FUNCTION public.initeffectivextuser() OWNER TO admin;
55375
55376 --
55377 -- TOC entry 1812 (class 1255 OID 146566395)
55378 -- Dependencies: 4536 8
55379 -- Name: initialdistribution(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
55380 --
55381
55382 CREATE FUNCTION initialdistribution(integer, integer) RETURNS integer
55383     LANGUAGE plpgsql
55384     AS $_$
55385 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
55386 -- See www.xtuple.com/CPAL for the full text of the software license.
55387 DECLARE
55388   pItemsiteid ALIAS FOR $1;
55389   pLocationid ALIAS FOR $2;
55390   _itemlocid INTEGER;
55391   _invhistid INTEGER;
55392   _itemlocSeries INTEGER;
55393   _r RECORD;
55394
55395 BEGIN
55396
55397 --  Make sure the passed itemsite points to a real item
55398   IF ( (SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
55399          FROM itemsite, item
55400          WHERE ( (itemsite_item_id=item_id)
55401           AND (itemsite_id=pItemsiteid) ) ) ) THEN
55402     RETURN 0;
55403   END IF;
55404
55405   _itemlocSeries := NEXTVAL('itemloc_series_seq');
55406
55407 --  Reassign the location_id for all existing itemlocs if
55408 --  the passed itemsite is already lot/serial controlled
55409   IF ( ( SELECT (itemsite_controlmethod IN ('L', 'S'))
55410          FROM itemsite
55411          WHERE (itemsite_id=pItemsiteid) ) ) THEN
55412
55413     FOR _r IN SELECT itemloc_id, itemloc_ls_id, itemloc_qty
55414               FROM itemloc
55415               WHERE (itemloc_itemsite_id=pItemsiteid) LOOP
55416
55417 --  Create the RL transaction
55418       SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
55419       INSERT INTO invhist
55420       ( invhist_id, invhist_itemsite_id, invhist_series,
55421         invhist_transtype, invhist_invqty,
55422         invhist_qoh_before, invhist_qoh_after,
55423         invhist_comments,
55424         invhist_invuom, invhist_unitcost, invhist_hasdetail,
55425         invhist_costmethod, invhist_value_before, invhist_value_after ) 
55426       SELECT _invhistid, itemsite_id, _itemlocSeries,
55427              'RL', 0,
55428              _r.itemloc_qty, _r.itemloc_qty,
55429              'Initial Distribution',
55430              uom_name, stdCost(item_id), TRUE,
55431              itemsite_costmethod, itemsite_value, itemsite_value
55432       FROM item, itemsite, uom
55433       WHERE ( (itemsite_item_id=item_id)
55434        AND (item_inv_uom_id=uom_id)
55435        AND (itemsite_controlmethod <> 'N')
55436        AND (itemsite_id=pItemsiteid) );
55437
55438 --  Update the itemloc
55439       UPDATE itemloc
55440       SET itemloc_location_id=pLocationid
55441       WHERE (itemloc_id=_r.itemloc_id);
55442
55443 --  Record the detail transaction
55444       INSERT INTO invdetail
55445       ( invdetail_invhist_id, invdetail_location_id, invdetail_ls_id,
55446         invdetail_qty, invdetail_qty_before, invdetail_qty_after )
55447       VALUES
55448       ( _invhistid, pLocationid, _r.itemloc_ls_id,
55449         _r.itemloc_qty, 0, _r.itemloc_qty );
55450
55451 --  Adjust QOH if this itemlocdist is to/from a non-netable location
55452       IF ( SELECT (NOT location_netable)
55453            FROM location
55454            WHERE (location_id=pLocationid) ) THEN
55455
55456         INSERT INTO invhist
55457         ( invhist_itemsite_id, invhist_series,
55458           invhist_transtype, invhist_invqty,
55459           invhist_qoh_before, invhist_qoh_after,
55460           invhist_comments,
55461           invhist_invuom, invhist_unitcost,
55462           invhist_costmethod, invhist_value_before, invhist_value_after  ) 
55463         SELECT itemsite_id, _itemlocSeries,
55464                'NN', (_r.itemloc_qty * -1),
55465                _r.itemloc_qty, 0,
55466                'Initial Distribution',
55467                uom_name, stdCost(item_id),
55468                itemsite_costmethod, itemsite_value, itemsite_value
55469         FROM itemsite, item, uom
55470         WHERE ( (itemsite_item_id=item_id)
55471          AND (item_inv_uom_id=uom_id)
55472          AND (itemsite_controlmethod <> 'N')
55473          AND (itemsite_id=pItemsiteid) );
55474
55475         UPDATE itemsite
55476         SET itemsite_nnqoh = (itemsite_nnqoh + _r.itemloc_qty),
55477             itemsite_qtyonhand = (itemsite_qtyonhand - _r.itemloc_qty) 
55478         WHERE (itemsite_id=pItemsiteid);
55479
55480       END IF;
55481
55482     END LOOP;
55483
55484   ELSE
55485 --  The passed itemsite is not lot/serial controlled
55486 --  Make sure that there are not any stagnent itemlocs
55487     DELETE FROM itemloc
55488     WHERE (itemloc_itemsite_id=pItemsiteid);
55489
55490 --  Create the RL transaction
55491     SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
55492     INSERT INTO invhist
55493     ( invhist_id, invhist_itemsite_id, invhist_series,
55494       invhist_transtype, invhist_invqty,
55495       invhist_qoh_before, invhist_qoh_after,
55496       invhist_comments,
55497       invhist_invuom, invhist_unitcost, invhist_hasdetail,
55498       invhist_costmethod, invhist_value_before, invhist_value_after  ) 
55499     SELECT _invhistid, itemsite_id, _itemlocSeries,
55500            'RL', 0,
55501            itemsite_qtyonhand, itemsite_qtyonhand,
55502            'Initial Distribution',
55503            uom_name, stdCost(item_id), TRUE,
55504            itemsite_costmethod, itemsite_value, itemsite_value
55505     FROM item, itemsite, uom
55506     WHERE ( (itemsite_item_id=item_id)
55507      AND (item_inv_uom_id=uom_id)
55508      AND (itemsite_controlmethod <> 'N')
55509      AND (itemsite_id=pItemsiteid) );
55510
55511 --  Create the itemloc
55512     SELECT NEXTVAL('itemloc_itemloc_id_seq') INTO _itemlocid;
55513     INSERT INTO itemloc
55514     ( itemloc_id, itemloc_itemsite_id, itemloc_location_id,
55515       itemloc_expiration, itemloc_qty )
55516     SELECT _itemlocid, itemsite_id, pLocationid,
55517            endOfTime(), itemsite_qtyonhand
55518     FROM itemsite
55519     WHERE (itemsite_id=pItemsiteid);
55520
55521 --  Record the detail transaction
55522     INSERT INTO invdetail
55523     ( invdetail_invhist_id, invdetail_location_id,
55524       invdetail_qty, invdetail_qty_before, invdetail_qty_after )
55525     SELECT _invhistid, pLocationid,
55526            itemsite_qtyonhand, 0, itemsite_qtyonhand
55527     FROM itemsite
55528     WHERE (itemsite_id=pItemsiteid);
55529
55530 --  Adjust QOH if this itemlocdist is to/from a non-netable location
55531     IF ( SELECT (NOT location_netable)
55532          FROM location
55533          WHERE (location_id=pLocationid) ) THEN
55534
55535       INSERT INTO invhist
55536       ( invhist_itemsite_id, invhist_series,
55537         invhist_transtype, invhist_invqty,
55538         invhist_qoh_before, invhist_qoh_after,
55539         invhist_comments,
55540         invhist_invuom, invhist_unitcost,
55541         invhist_costmethod, invhist_value_before, invhist_value_after  ) 
55542       SELECT itemsite_id, _itemlocSeries,
55543              'NN', (itemloc_qty * -1),
55544              itemloc_qty, 0,
55545              'Initial Distribution',
55546              uom_name, stdCost(item_id),
55547              itemsite_costmethod, itemsite_value, itemsite_value
55548       FROM itemloc, itemsite, item, uom
55549       WHERE ( (itemsite_item_id=item_id)
55550        AND (item_inv_uom_id=uom_id)
55551        AND (itemsite_controlmethod <> 'N')
55552        AND (itemloc_itemsite_id=itemsite_id)
55553        AND (itemloc_id=_itemlocid) );
55554
55555       UPDATE itemsite
55556       SET itemsite_nnqoh = itemsite_qtyonhand,
55557           itemsite_qtyonhand = 0 
55558       FROM itemloc
55559       WHERE ( (itemloc_itemsite_id=itemsite_id)
55560        AND (itemloc_id=_itemlocid) );
55561
55562     END IF;
55563
55564   END IF;
55565
55566   RETURN _itemlocid;
55567
55568 END;
55569 $_$;
55570
55571
55572 ALTER FUNCTION public.initialdistribution(integer, integer) OWNER TO admin;
55573
55574 --
55575 -- TOC entry 207 (class 1259 OID 146566396)
55576 -- Dependencies: 5956 5957 5958 5959 5960 5961 5962 5963 5964 8
55577 -- Name: apopen; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
55578 --
55579
55580 CREATE TABLE apopen (
55581     apopen_id integer DEFAULT nextval(('"apopen_apopen_id_seq"'::text)::regclass) NOT NULL,
55582     apopen_docdate date,
55583     apopen_duedate date,
55584     apopen_terms_id integer,
55585     apopen_vend_id integer,
55586     apopen_doctype character(1),
55587     apopen_docnumber text,
55588     apopen_amount numeric(20,2),
55589     apopen_notes text,
55590     apopen_posted boolean,
55591     apopen_reference text,
55592     apopen_invcnumber text,
55593     apopen_ponumber text,
55594     apopen_journalnumber integer,
55595     apopen_paid numeric(20,2) DEFAULT 0,
55596     apopen_open boolean,
55597     apopen_username text,
55598     apopen_discount boolean DEFAULT false NOT NULL,
55599     apopen_accnt_id integer DEFAULT (-1),
55600     apopen_curr_id integer DEFAULT basecurrid(),
55601     apopen_closedate date,
55602     apopen_distdate date,
55603     apopen_void boolean DEFAULT false NOT NULL,
55604     apopen_curr_rate numeric NOT NULL,
55605     apopen_discountable_amount numeric(20,2) DEFAULT 0,
55606     apopen_status text,
55607     CONSTRAINT apopen_apopen_status_check CHECK ((((apopen_status = 'O'::text) OR (apopen_status = 'H'::text)) OR (apopen_status = 'C'::text))),
55608     CONSTRAINT apopen_apopen_status_notnull CHECK ((apopen_status IS NOT NULL))
55609 );
55610
55611
55612 ALTER TABLE public.apopen OWNER TO admin;
55613
55614 --
55615 -- TOC entry 8981 (class 0 OID 0)
55616 -- Dependencies: 207
55617 -- Name: TABLE apopen; Type: COMMENT; Schema: public; Owner: admin
55618 --
55619
55620 COMMENT ON TABLE apopen IS 'Accounts Payable (A/P) open Items information';
55621
55622
55623 --
55624 -- TOC entry 208 (class 1259 OID 146566411)
55625 -- Dependencies: 5966 8
55626 -- Name: curr_symbol; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
55627 --
55628
55629 CREATE TABLE curr_symbol (
55630     curr_id integer NOT NULL,
55631     curr_base boolean DEFAULT false NOT NULL,
55632     curr_name character varying(50) NOT NULL,
55633     curr_symbol character varying(9) NOT NULL,
55634     curr_abbr character varying(3) NOT NULL
55635 );
55636
55637
55638 ALTER TABLE public.curr_symbol OWNER TO admin;
55639
55640 --
55641 -- TOC entry 8983 (class 0 OID 0)
55642 -- Dependencies: 208
55643 -- Name: TABLE curr_symbol; Type: COMMENT; Schema: public; Owner: admin
55644 --
55645
55646 COMMENT ON TABLE curr_symbol IS 'Currency Names, Symbols, and Abbreviations';
55647
55648
55649 --
55650 -- TOC entry 209 (class 1259 OID 146566415)
55651 -- Dependencies: 5967 5968 5969 8
55652 -- Name: terms; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
55653 --
55654
55655 CREATE TABLE terms (
55656     terms_id integer DEFAULT nextval(('terms_terms_id_seq'::text)::regclass) NOT NULL,
55657     terms_code text NOT NULL,
55658     terms_descrip text,
55659     terms_type character(1),
55660     terms_duedays integer,
55661     terms_discdays integer,
55662     terms_discprcnt numeric(10,6),
55663     terms_cutoffday integer,
55664     terms_ap boolean,
55665     terms_ar boolean,
55666     terms_fincharg boolean DEFAULT true NOT NULL,
55667     CONSTRAINT terms_terms_code_check CHECK ((terms_code <> ''::text))
55668 );
55669
55670
55671 ALTER TABLE public.terms OWNER TO admin;
55672
55673 --
55674 -- TOC entry 8985 (class 0 OID 0)
55675 -- Dependencies: 209
55676 -- Name: TABLE terms; Type: COMMENT; Schema: public; Owner: admin
55677 --
55678
55679 COMMENT ON TABLE terms IS 'Billing Terms information';
55680
55681
55682 --
55683 -- TOC entry 210 (class 1259 OID 146566424)
55684 -- Dependencies: 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 8
55685 -- Name: vendinfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
55686 --
55687
55688 CREATE TABLE vendinfo (
55689     vend_id integer DEFAULT nextval(('vend_vend_id_seq'::text)::regclass) NOT NULL,
55690     vend_name text,
55691     vend_lastpurchdate date,
55692     vend_active boolean,
55693     vend_po boolean,
55694     vend_comments text,
55695     vend_pocomments text,
55696     vend_number text NOT NULL,
55697     vend_1099 boolean,
55698     vend_exported boolean,
55699     vend_fobsource character(1),
55700     vend_fob text,
55701     vend_terms_id integer,
55702     vend_shipvia text,
55703     vend_vendtype_id integer,
55704     vend_qualified boolean,
55705     vend_ediemail text,
55706     vend_ediemailbody text,
55707     vend_edisubject text,
55708     vend_edifilename text,
55709     vend_accntnum text,
55710     vend_emailpodelivery boolean,
55711     vend_restrictpurch boolean,
55712     vend_edicc text,
55713     vend_curr_id integer DEFAULT basecurrid(),
55714     vend_cntct1_id integer,
55715     vend_cntct2_id integer,
55716     vend_addr_id integer,
55717     vend_match boolean DEFAULT false NOT NULL,
55718     vend_ach_enabled boolean DEFAULT false NOT NULL,
55719     vend_ach_accnttype text,
55720     vend_ach_use_vendinfo boolean DEFAULT true NOT NULL,
55721     vend_ach_indiv_number text DEFAULT ''::text NOT NULL,
55722     vend_ach_indiv_name text DEFAULT ''::text NOT NULL,
55723     vend_ediemailhtml boolean DEFAULT false NOT NULL,
55724     vend_ach_routingnumber bytea DEFAULT '\x00'::bytea NOT NULL,
55725     vend_ach_accntnumber bytea DEFAULT '\x00'::bytea NOT NULL,
55726     vend_taxzone_id integer,
55727     vend_accnt_id integer,
55728     vend_expcat_id integer DEFAULT (-1),
55729     vend_tax_id integer DEFAULT (-1),
55730     CONSTRAINT vendinfo_vend_ach_accnttype_check CHECK (((vend_ach_accnttype = 'K'::text) OR (vend_ach_accnttype = 'C'::text))),
55731     CONSTRAINT vendinfo_vend_number_check CHECK ((vend_number <> ''::text))
55732 );
55733
55734
55735 ALTER TABLE public.vendinfo OWNER TO admin;
55736
55737 --
55738 -- TOC entry 8987 (class 0 OID 0)
55739 -- Dependencies: 210
55740 -- Name: TABLE vendinfo; Type: COMMENT; Schema: public; Owner: admin
55741 --
55742
55743 COMMENT ON TABLE vendinfo IS 'Vendor information';
55744
55745
55746 --
55747 -- TOC entry 8988 (class 0 OID 0)
55748 -- Dependencies: 210
55749 -- Name: COLUMN vendinfo.vend_ach_accnttype; Type: COMMENT; Schema: public; Owner: admin
55750 --
55751
55752 COMMENT ON COLUMN vendinfo.vend_ach_accnttype IS 'Type of bank account: K = checKing, C = Cash = savings. These values were chosen to be consistent with bankaccnt_type.';
55753
55754
55755 SET search_path = api, pg_catalog;
55756
55757 --
55758 -- TOC entry 211 (class 1259 OID 146566444)
55759 -- Dependencies: 8471 6
55760 -- Name: apmemo; Type: VIEW; Schema: api; Owner: admin
55761 --
55762
55763 CREATE VIEW apmemo AS
55764     SELECT vendinfo.vend_number AS vendor_number, apopen.apopen_docdate AS document_date, apopen.apopen_duedate AS due_date, CASE WHEN (apopen.apopen_doctype = 'C'::bpchar) THEN 'Credit Memo'::text ELSE 'Debit Memo'::text END AS document_type, apopen.apopen_docnumber AS document_number, apopen.apopen_ponumber AS po_number, apopen.apopen_journalnumber AS journal_number, terms.terms_code AS terms, curr.curr_abbr AS currency, apopen.apopen_amount AS amount, apopen.apopen_paid AS paid, (apopen.apopen_amount - apopen.apopen_paid) AS balance, apopen.apopen_notes AS notes, CASE WHEN (apopen.apopen_accnt_id = (-1)) THEN NULL::text ELSE public.formatglaccount(apopen.apopen_accnt_id) END AS alternate_prepaid_account FROM (((public.apopen LEFT JOIN public.vendinfo ON ((vendinfo.vend_id = apopen.apopen_vend_id))) LEFT JOIN public.curr_symbol curr ON ((curr.curr_id = apopen.apopen_curr_id))) LEFT JOIN public.terms ON ((terms.terms_id = apopen.apopen_terms_id))) WHERE (apopen.apopen_doctype = ANY (ARRAY['C'::bpchar, 'D'::bpchar]));
55765
55766
55767 ALTER TABLE api.apmemo OWNER TO admin;
55768
55769 --
55770 -- TOC entry 8990 (class 0 OID 0)
55771 -- Dependencies: 211
55772 -- Name: VIEW apmemo; Type: COMMENT; Schema: api; Owner: admin
55773 --
55774
55775 COMMENT ON VIEW apmemo IS 'A/P Credit and Debit Memo';
55776
55777
55778 SET search_path = public, pg_catalog;
55779
55780 --
55781 -- TOC entry 1813 (class 1255 OID 146566449)
55782 -- Dependencies: 2804 4536 8
55783 -- Name: insertapmemo(api.apmemo); Type: FUNCTION; Schema: public; Owner: admin
55784 --
55785
55786 CREATE FUNCTION insertapmemo(api.apmemo) RETURNS boolean
55787     LANGUAGE plpgsql
55788     AS $_$
55789 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
55790 -- See www.xtuple.com/CPAL for the full text of the software license.
55791 DECLARE
55792   pNew ALIAS FOR $1;
55793   _result INTEGER;
55794
55795 BEGIN
55796   IF (pNew.document_type = 'Credit Memo') THEN
55797     SELECT createAPCreditMemo( getVendId(pNew.vendor_number),
55798                                pNew.document_number,
55799                                pNew.po_number,
55800                                pNew.document_date,
55801                                pNew.amount,
55802                                pNew.notes,
55803                                getGLAccntId(pNew.alternate_prepaid_account),
55804                                pNew.due_date,
55805                                getTermsId(pNew.terms) ) INTO _result;
55806     IF (_result <= 0) THEN
55807       RAISE EXCEPTION 'Function createAPCreditMemo failed with result = %', _result;
55808     END IF;
55809   ELSE
55810     IF (pNew.document_type = 'Debit Memo') THEN
55811       SELECT createAPDebitMemo( null, getVendId(pNew.vendor_number),
55812                                 pNew.journal_number,
55813                                 pNew.document_number,
55814                                 pNew.po_number,
55815                                 pNew.document_date,
55816                                 pNew.amount,
55817                                 pNew.notes,
55818                                 getGLAccntId(pNew.alternate_prepaid_account),
55819                                 pNew.due_date,
55820                                 getTermsId(pNew.terms),
55821                                 COALESCE(getCurrId(pNew.currency), baseCurrId()) ) INTO _result;
55822       IF (_result <= 0) THEN
55823         RAISE EXCEPTION 'Function createAPDebitMemo failed with result = %', _result;
55824       END IF;
55825     ELSE
55826       RAISE EXCEPTION 'Function insertAPMemo failed, invalid Document Type';
55827     END IF;
55828   END IF;
55829
55830   RETURN TRUE;
55831 END;
55832 $_$;
55833
55834
55835 ALTER FUNCTION public.insertapmemo(api.apmemo) OWNER TO admin;
55836
55837 --
55838 -- TOC entry 212 (class 1259 OID 146566450)
55839 -- Dependencies: 5984 5985 5986 5987 5988 5989 5990 5991 5992 8
55840 -- Name: aropen; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
55841 --
55842
55843 CREATE TABLE aropen (
55844     aropen_id integer DEFAULT nextval(('"aropen_aropen_id_seq"'::text)::regclass) NOT NULL,
55845     aropen_docdate date NOT NULL,
55846     aropen_duedate date NOT NULL,
55847     aropen_terms_id integer,
55848     aropen_cust_id integer,
55849     aropen_doctype character(1),
55850     aropen_docnumber text,
55851     aropen_applyto text,
55852     aropen_ponumber text,
55853     aropen_amount numeric(20,2) NOT NULL,
55854     aropen_notes text,
55855     aropen_posted boolean DEFAULT false NOT NULL,
55856     aropen_salesrep_id integer,
55857     aropen_commission_due numeric(20,2),
55858     aropen_commission_paid boolean DEFAULT false,
55859     aropen_ordernumber text,
55860     aropen_cobmisc_id integer DEFAULT (-1),
55861     aropen_journalnumber integer,
55862     aropen_paid numeric(20,2) DEFAULT 0,
55863     aropen_open boolean,
55864     aropen_username text,
55865     aropen_rsncode_id integer,
55866     aropen_salescat_id integer DEFAULT (-1),
55867     aropen_accnt_id integer DEFAULT (-1),
55868     aropen_curr_id integer DEFAULT basecurrid(),
55869     aropen_closedate date,
55870     aropen_distdate date,
55871     aropen_curr_rate numeric NOT NULL,
55872     aropen_discount boolean DEFAULT false NOT NULL,
55873     aropen_fincharg_date date,
55874     aropen_fincharg_amount numeric(20,2)
55875 );
55876
55877
55878 ALTER TABLE public.aropen OWNER TO admin;
55879
55880 --
55881 -- TOC entry 8992 (class 0 OID 0)
55882 -- Dependencies: 212
55883 -- Name: TABLE aropen; Type: COMMENT; Schema: public; Owner: admin
55884 --
55885
55886 COMMENT ON TABLE aropen IS 'Accounts Receivable (A/R) open Items information';
55887
55888
55889 --
55890 -- TOC entry 213 (class 1259 OID 146566465)
55891 -- Dependencies: 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 8
55892 -- Name: custinfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
55893 --
55894
55895 CREATE TABLE custinfo (
55896     cust_id integer DEFAULT nextval(('cust_cust_id_seq'::text)::regclass) NOT NULL,
55897     cust_active boolean NOT NULL,
55898     cust_custtype_id integer,
55899     cust_salesrep_id integer,
55900     cust_commprcnt numeric(10,6),
55901     cust_name text,
55902     cust_creditlmt integer,
55903     cust_creditrating text,
55904     cust_financecharge boolean,
55905     cust_backorder boolean NOT NULL,
55906     cust_partialship boolean NOT NULL,
55907     cust_terms_id integer,
55908     cust_discntprcnt numeric(10,6) NOT NULL,
55909     cust_balmethod character(1) NOT NULL,
55910     cust_ffshipto boolean NOT NULL,
55911     cust_shipform_id integer,
55912     cust_shipvia text,
55913     cust_blanketpos boolean NOT NULL,
55914     cust_shipchrg_id integer NOT NULL,
55915     cust_creditstatus character(1) NOT NULL,
55916     cust_comments text,
55917     cust_ffbillto boolean NOT NULL,
55918     cust_usespos boolean NOT NULL,
55919     cust_number text NOT NULL,
55920     cust_dateadded date DEFAULT ('now'::text)::date,
55921     cust_exported boolean DEFAULT false,
55922     cust_emaildelivery boolean DEFAULT false,
55923     cust_ediemail text,
55924     cust_edisubject text,
55925     cust_edifilename text,
55926     cust_ediemailbody text,
55927     cust_autoupdatestatus boolean NOT NULL,
55928     cust_autoholdorders boolean NOT NULL,
55929     cust_edicc text,
55930     cust_ediprofile_id integer,
55931     cust_preferred_warehous_id integer DEFAULT (-1) NOT NULL,
55932     cust_curr_id integer DEFAULT basecurrid(),
55933     cust_creditlmt_curr_id integer DEFAULT basecurrid(),
55934     cust_cntct_id integer,
55935     cust_corrcntct_id integer,
55936     cust_soemaildelivery boolean DEFAULT false,
55937     cust_soediemail text,
55938     cust_soedisubject text,
55939     cust_soedifilename text,
55940     cust_soediemailbody text,
55941     cust_soedicc text,
55942     cust_soediprofile_id integer,
55943     cust_gracedays integer,
55944     cust_ediemailhtml boolean DEFAULT false NOT NULL,
55945     cust_soediemailhtml boolean DEFAULT false NOT NULL,
55946     cust_taxzone_id integer,
55947     cust_statementcycle text,
55948     CONSTRAINT custinfo_balmethod_check CHECK (((cust_balmethod = 'B'::bpchar) OR (cust_balmethod = 'O'::bpchar))),
55949     CONSTRAINT custinfo_creditstatus_check CHECK ((((cust_creditstatus = 'G'::bpchar) OR (cust_creditstatus = 'W'::bpchar)) OR (cust_creditstatus = 'H'::bpchar))),
55950     CONSTRAINT custinfo_cust_number_check CHECK ((cust_number <> ''::text))
55951 );
55952
55953
55954 ALTER TABLE public.custinfo OWNER TO admin;
55955
55956 --
55957 -- TOC entry 8994 (class 0 OID 0)
55958 -- Dependencies: 213
55959 -- Name: TABLE custinfo; Type: COMMENT; Schema: public; Owner: admin
55960 --
55961
55962 COMMENT ON TABLE custinfo IS 'Customer information';
55963
55964
55965 --
55966 -- TOC entry 8995 (class 0 OID 0)
55967 -- Dependencies: 213
55968 -- Name: COLUMN custinfo.cust_ediemail; Type: COMMENT; Schema: public; Owner: admin
55969 --
55970
55971 COMMENT ON COLUMN custinfo.cust_ediemail IS 'Deprecated column - DO NOT USE';
55972
55973
55974 --
55975 -- TOC entry 8996 (class 0 OID 0)
55976 -- Dependencies: 213
55977 -- Name: COLUMN custinfo.cust_edisubject; Type: COMMENT; Schema: public; Owner: admin
55978 --
55979
55980 COMMENT ON COLUMN custinfo.cust_edisubject IS 'Deprecated column - DO NOT USE';
55981
55982
55983 --
55984 -- TOC entry 8997 (class 0 OID 0)
55985 -- Dependencies: 213
55986 -- Name: COLUMN custinfo.cust_edifilename; Type: COMMENT; Schema: public; Owner: admin
55987 --
55988
55989 COMMENT ON COLUMN custinfo.cust_edifilename IS 'Deprecated column - DO NOT USE';
55990
55991
55992 --
55993 -- TOC entry 8998 (class 0 OID 0)
55994 -- Dependencies: 213
55995 -- Name: COLUMN custinfo.cust_ediemailbody; Type: COMMENT; Schema: public; Owner: admin
55996 --
55997
55998 COMMENT ON COLUMN custinfo.cust_ediemailbody IS 'Deprecated column - DO NOT USE';
55999
56000
56001 --
56002 -- TOC entry 8999 (class 0 OID 0)
56003 -- Dependencies: 213
56004 -- Name: COLUMN custinfo.cust_edicc; Type: COMMENT; Schema: public; Owner: admin
56005 --
56006
56007 COMMENT ON COLUMN custinfo.cust_edicc IS 'Deprecated column - DO NOT USE';
56008
56009
56010 --
56011 -- TOC entry 9000 (class 0 OID 0)
56012 -- Dependencies: 213
56013 -- Name: COLUMN custinfo.cust_ediprofile_id; Type: COMMENT; Schema: public; Owner: admin
56014 --
56015
56016 COMMENT ON COLUMN custinfo.cust_ediprofile_id IS 'Deprecated column - DO NOT USE';
56017
56018
56019 --
56020 -- TOC entry 9001 (class 0 OID 0)
56021 -- Dependencies: 213
56022 -- Name: COLUMN custinfo.cust_soediemail; Type: COMMENT; Schema: public; Owner: admin
56023 --
56024
56025 COMMENT ON COLUMN custinfo.cust_soediemail IS 'Deprecated column - DO NOT USE';
56026
56027
56028 --
56029 -- TOC entry 9002 (class 0 OID 0)
56030 -- Dependencies: 213
56031 -- Name: COLUMN custinfo.cust_soedisubject; Type: COMMENT; Schema: public; Owner: admin
56032 --
56033
56034 COMMENT ON COLUMN custinfo.cust_soedisubject IS 'Deprecated column - DO NOT USE';
56035
56036
56037 --
56038 -- TOC entry 9003 (class 0 OID 0)
56039 -- Dependencies: 213
56040 -- Name: COLUMN custinfo.cust_soedifilename; Type: COMMENT; Schema: public; Owner: admin
56041 --
56042
56043 COMMENT ON COLUMN custinfo.cust_soedifilename IS 'Deprecated column - DO NOT USE';
56044
56045
56046 --
56047 -- TOC entry 9004 (class 0 OID 0)
56048 -- Dependencies: 213
56049 -- Name: COLUMN custinfo.cust_soediemailbody; Type: COMMENT; Schema: public; Owner: admin
56050 --
56051
56052 COMMENT ON COLUMN custinfo.cust_soediemailbody IS 'Deprecated column - DO NOT USE';
56053
56054
56055 --
56056 -- TOC entry 9005 (class 0 OID 0)
56057 -- Dependencies: 213
56058 -- Name: COLUMN custinfo.cust_soedicc; Type: COMMENT; Schema: public; Owner: admin
56059 --
56060
56061 COMMENT ON COLUMN custinfo.cust_soedicc IS 'Deprecated column - DO NOT USE';
56062
56063
56064 --
56065 -- TOC entry 9006 (class 0 OID 0)
56066 -- Dependencies: 213
56067 -- Name: COLUMN custinfo.cust_soediprofile_id; Type: COMMENT; Schema: public; Owner: admin
56068 --
56069
56070 COMMENT ON COLUMN custinfo.cust_soediprofile_id IS 'Deprecated column - DO NOT USE';
56071
56072
56073 --
56074 -- TOC entry 9007 (class 0 OID 0)
56075 -- Dependencies: 213
56076 -- Name: COLUMN custinfo.cust_ediemailhtml; Type: COMMENT; Schema: public; Owner: admin
56077 --
56078
56079 COMMENT ON COLUMN custinfo.cust_ediemailhtml IS 'Deprecated column - DO NOT USE';
56080
56081
56082 --
56083 -- TOC entry 9008 (class 0 OID 0)
56084 -- Dependencies: 213
56085 -- Name: COLUMN custinfo.cust_soediemailhtml; Type: COMMENT; Schema: public; Owner: admin
56086 --
56087
56088 COMMENT ON COLUMN custinfo.cust_soediemailhtml IS 'Deprecated column - DO NOT USE';
56089
56090
56091 --
56092 -- TOC entry 214 (class 1259 OID 146566484)
56093 -- Dependencies: 6007 8
56094 -- Name: rsncode; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56095 --
56096
56097 CREATE TABLE rsncode (
56098     rsncode_id integer NOT NULL,
56099     rsncode_code text NOT NULL,
56100     rsncode_descrip text,
56101     rsncode_doctype text,
56102     CONSTRAINT rsncode_rsncode_code_check CHECK ((rsncode_code <> ''::text))
56103 );
56104
56105
56106 ALTER TABLE public.rsncode OWNER TO admin;
56107
56108 --
56109 -- TOC entry 9010 (class 0 OID 0)
56110 -- Dependencies: 214
56111 -- Name: TABLE rsncode; Type: COMMENT; Schema: public; Owner: admin
56112 --
56113
56114 COMMENT ON TABLE rsncode IS 'Debit/Credit Memo Reason Code information';
56115
56116
56117 --
56118 -- TOC entry 215 (class 1259 OID 146566491)
56119 -- Dependencies: 6009 8
56120 -- Name: salescat; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56121 --
56122
56123 CREATE TABLE salescat (
56124     salescat_id integer NOT NULL,
56125     salescat_active boolean,
56126     salescat_name text NOT NULL,
56127     salescat_descrip text,
56128     salescat_sales_accnt_id integer,
56129     salescat_prepaid_accnt_id integer,
56130     salescat_ar_accnt_id integer,
56131     CONSTRAINT salescat_salescat_name_check CHECK ((salescat_name <> ''::text))
56132 );
56133
56134
56135 ALTER TABLE public.salescat OWNER TO admin;
56136
56137 --
56138 -- TOC entry 9012 (class 0 OID 0)
56139 -- Dependencies: 215
56140 -- Name: TABLE salescat; Type: COMMENT; Schema: public; Owner: admin
56141 --
56142
56143 COMMENT ON TABLE salescat IS 'Sales Category information';
56144
56145
56146 --
56147 -- TOC entry 216 (class 1259 OID 146566498)
56148 -- Dependencies: 6010 6011 8
56149 -- Name: salesrep; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56150 --
56151
56152 CREATE TABLE salesrep (
56153     salesrep_id integer DEFAULT nextval(('salesrep_salesrep_id_seq'::text)::regclass) NOT NULL,
56154     salesrep_active boolean,
56155     salesrep_number text NOT NULL,
56156     salesrep_name text,
56157     salesrep_commission numeric(8,4),
56158     salesrep_method character(1),
56159     salesrep_emp_id integer,
56160     CONSTRAINT salesrep_salesrep_number_check CHECK ((salesrep_number <> ''::text))
56161 );
56162
56163
56164 ALTER TABLE public.salesrep OWNER TO admin;
56165
56166 --
56167 -- TOC entry 9014 (class 0 OID 0)
56168 -- Dependencies: 216
56169 -- Name: TABLE salesrep; Type: COMMENT; Schema: public; Owner: admin
56170 --
56171
56172 COMMENT ON TABLE salesrep IS 'Sales Representative information';
56173
56174
56175 --
56176 -- TOC entry 9015 (class 0 OID 0)
56177 -- Dependencies: 216
56178 -- Name: COLUMN salesrep.salesrep_emp_id; Type: COMMENT; Schema: public; Owner: admin
56179 --
56180
56181 COMMENT ON COLUMN salesrep.salesrep_emp_id IS 'DEPRECATED - the relationship between Sales Rep and Employee is now maintained through the crmacct table.';
56182
56183
56184 SET search_path = api, pg_catalog;
56185
56186 --
56187 -- TOC entry 217 (class 1259 OID 146566506)
56188 -- Dependencies: 8472 6
56189 -- Name: armemo; Type: VIEW; Schema: api; Owner: admin
56190 --
56191
56192 CREATE VIEW armemo AS
56193     SELECT custinfo.cust_number AS customer_number, aropen.aropen_docdate AS document_date, aropen.aropen_duedate AS due_date, CASE WHEN (aropen.aropen_doctype = 'C'::bpchar) THEN 'Credit Memo'::text ELSE 'Debit Memo'::text END AS document_type, aropen.aropen_docnumber AS document_number, aropen.aropen_applyto AS order_number, aropen.aropen_journalnumber AS journal_number, rsncode.rsncode_code AS reason_code, terms.terms_code AS terms, salesrep.salesrep_number AS sales_rep, curr.curr_abbr AS currency, aropen.aropen_amount AS amount, aropen.aropen_paid AS paid, (aropen.aropen_amount - aropen.aropen_paid) AS balance, aropen.aropen_commission_due AS commission_due, aropen.aropen_commission_paid AS commission_paid, aropen.aropen_notes AS notes, salescat.salescat_name AS alternate_prepaid_sales_category, CASE WHEN (aropen.aropen_accnt_id = (-1)) THEN NULL::text ELSE public.formatglaccount(aropen.aropen_accnt_id) END AS alternate_prepaid_account FROM ((((((public.aropen LEFT JOIN public.custinfo ON ((custinfo.cust_id = aropen.aropen_cust_id))) LEFT JOIN public.curr_symbol curr ON ((curr.curr_id = aropen.aropen_curr_id))) LEFT JOIN public.salesrep ON ((salesrep.salesrep_id = aropen.aropen_salesrep_id))) LEFT JOIN public.terms ON ((terms.terms_id = aropen.aropen_terms_id))) LEFT JOIN public.salescat ON ((salescat.salescat_id = aropen.aropen_salescat_id))) LEFT JOIN public.rsncode ON ((rsncode.rsncode_id = aropen.aropen_rsncode_id))) WHERE (aropen.aropen_doctype = ANY (ARRAY['C'::bpchar, 'D'::bpchar]));
56194
56195
56196 ALTER TABLE api.armemo OWNER TO admin;
56197
56198 --
56199 -- TOC entry 9017 (class 0 OID 0)
56200 -- Dependencies: 217
56201 -- Name: VIEW armemo; Type: COMMENT; Schema: api; Owner: admin
56202 --
56203
56204 COMMENT ON VIEW armemo IS 'A/R Credit and Debit Memo';
56205
56206
56207 SET search_path = public, pg_catalog;
56208
56209 --
56210 -- TOC entry 1814 (class 1255 OID 146566511)
56211 -- Dependencies: 2827 4536 8
56212 -- Name: insertarmemo(api.armemo); Type: FUNCTION; Schema: public; Owner: admin
56213 --
56214
56215 CREATE FUNCTION insertarmemo(api.armemo) RETURNS boolean
56216     LANGUAGE plpgsql
56217     AS $_$
56218 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
56219 -- See www.xtuple.com/CPAL for the full text of the software license.
56220 DECLARE
56221   pNew ALIAS FOR $1;
56222   _result INTEGER;
56223
56224 BEGIN
56225   IF (pNew.document_type = 'Credit Memo') THEN
56226     SELECT createARCreditMemo( NULL,
56227                                getCustId(pNew.customer_number),
56228                                pNew.document_number,
56229                                pNew.order_number,
56230                                pNew.document_date,
56231                                pNew.amount,
56232                                pNew.notes,
56233                                getRsnId(pNew.reason_code),
56234                                getSalescatId(pNew.alternate_prepaid_sales_category),
56235                                getGLAccntId(pNew.alternate_prepaid_account),
56236                                pNew.due_date,
56237                                getTermsId(pNew.terms),
56238                                getSalesrepId(pNew.sales_rep),
56239                                pNew.commission_due,
56240                                pNew.journal_number,
56241                                COALESCE(getCurrId(pNew.currency), baseCurrId()) ) INTO _result;
56242     IF (_result <= 0) THEN
56243       RAISE EXCEPTION 'Function createARCreditMemo failed with result = %', _result;
56244     END IF;
56245   ELSE
56246     IF (pNew.document_type = 'Debit Memo') THEN
56247       SELECT createARDebitMemo( null, getCustId(pNew.customer_number),
56248                                 pNew.journal_number,
56249                                 pNew.document_number,
56250                                 pNew.order_number,
56251                                 pNew.document_date,
56252                                 pNew.amount,
56253                                 pNew.notes,
56254                                 getRsnId(pNew.reason_code),
56255                                 getSalescatId(pNew.alternate_prepaid_sales_category),
56256                                 getGLAccntId(pNew.alternate_prepaid_account),
56257                                 pNew.due_date,
56258                                 getTermsId(pNew.terms),
56259                                 getSalesrepId(pNew.sales_rep),
56260                                 pNew.commission_due,
56261                                 COALESCE(getCurrId(pNew.currency), baseCurrId()) ) INTO _result;
56262       IF (_result <= 0) THEN
56263         RAISE EXCEPTION 'Function createARDebitMemo failed with result = %', _result;
56264       END IF;
56265     ELSE
56266       RAISE EXCEPTION 'Function insertARMemo failed, invalid Document Type';
56267     END IF;
56268   END IF;
56269
56270   RETURN TRUE;
56271 END;
56272 $_$;
56273
56274
56275 ALTER FUNCTION public.insertarmemo(api.armemo) OWNER TO admin;
56276
56277 --
56278 -- TOC entry 1815 (class 1255 OID 146566512)
56279 -- Dependencies: 4536 8
56280 -- Name: insertccard(text, boolean, text, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
56281 --
56282
56283 CREATE FUNCTION insertccard(text, boolean, text, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, text) RETURNS boolean
56284     LANGUAGE plpgsql
56285     AS $_$
56286 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
56287 -- See www.xtuple.com/CPAL for the full text of the software license.
56288 DECLARE
56289   pCustomer ALIAS FOR $1;
56290   pActive ALIAS FOR $2;
56291   pType ALIAS FOR $3;
56292   pNumber ALIAS FOR $4;
56293   pName ALIAS FOR $5;
56294   pAddr1 ALIAS FOR $6;
56295   pAddr2 ALIAS FOR $7;
56296   pCity ALIAS FOR $8;
56297   pState ALIAS FOR $9;
56298   pPostal ALIAS FOR $10;
56299   pCountry ALIAS FOR $11;
56300   pMonth ALIAS FOR $12;
56301   pYear ALIAS FOR $13;
56302   pKey ALIAS FOR $14;
56303   _type CHAR;
56304   _number TEXT;
56305   _month INTEGER;
56306   _year INTEGER;
56307   _result INTEGER;
56308
56309 BEGIN
56310   --Initialize
56311   _number = CAST(encode(pNumber, 'escape') AS text);
56312   _month = CAST(encode(pMonth, 'escape') AS integer);
56313   _year = CAST(encode(pYear, 'escape') AS integer);
56314
56315   -- Check Card holder info
56316   IF (pName IS NULL) THEN
56317       RAISE EXCEPTION 'The name of the card holder must be entered';
56318   END IF;
56319   IF (pAddr1 IS NULL OR pAddr1 = '') THEN
56320       RAISE EXCEPTION 'The first address line must be entered';
56321   END IF;
56322   IF (pCity IS NULL OR pCity = '') THEN
56323       RAISE EXCEPTION 'The city must be entered';
56324   END IF;
56325   IF (pState IS NULL OR pState = '') THEN
56326       RAISE EXCEPTION 'The state must be entered';
56327   END IF;
56328   IF (pPostal IS NULL OR pPostal = '') THEN
56329       RAISE EXCEPTION 'The zip code must be entered';
56330   END IF;
56331   IF (pCountry IS NULL OR pCountry = '') THEN
56332       RAISE EXCEPTION 'The country must be entered';
56333   END IF;
56334   IF (pMonth IS NULL OR pMonth = '') THEN
56335       RAISE EXCEPTION 'The Expiration Month must be entered';
56336   END IF;
56337   IF (_month < 1 OR _month > 12) THEN
56338       RAISE EXCEPTION 'Valid Expiration Months are 01 through 12';
56339   END IF;
56340   IF (LENGTH(_year::text) <> 4) THEN
56341       RAISE EXCEPTION 'Valid Expiration Years are CCYY in format';
56342   END IF;
56343   IF (_year < 1970 OR _year > 2100) THEN
56344       RAISE EXCEPTION 'Valid Expiration Years are 1970 through 2100';
56345   END IF;
56346   
56347   -- Check Number Length
56348   IF ((NOT _number ~  '[0-9]{13,16}') OR (LENGTH(_number) = 14) OR (LENGTH(_number) > 16)) THEN
56349     RAISE EXCEPTION 'The credit card number must be all numeric (no spaces or hyphens) and must be 13, 15 or 16 characters in length';
56350   END IF;
56351  
56352   -- Convert Type
56353   IF (pType = 'Visa') THEN
56354     _type  = 'V';
56355   ELSE
56356     IF (pType = 'Master Card') THEN
56357       _type  = 'M';
56358     ELSE
56359       IF (pType = 'American Express') THEN
56360         _type  = 'A';
56361       ELSE
56362         IF (pType = 'Discover') THEN
56363           _type  = 'D';
56364         ELSE
56365           RAISE EXCEPTION 'You must select Master Card, Visa, American 
56366                             Express or Discover as the credit card type.';
56367         END IF;
56368       END IF;
56369     END IF;
56370   END IF;
56371   
56372   -- Check Card Specific Data
56373   SELECT editccnumber(_number, _type) INTO _result;
56374
56375   IF (_result = -1) THEN
56376     RAISE EXCEPTION 'You must select Master Card, Visa, American 
56377                       Express or Discover as the credit card type.';
56378   END IF;
56379   IF (_result = -2) THEN
56380     RAISE EXCEPTION 'The length of a Master Card credit card number
56381                       has to be 16 digits.';
56382   END IF;
56383   IF (_result = -3) THEN
56384     RAISE EXCEPTION 'The length of a Visa credit card number
56385                       has to be either 13 or 16 digits.';
56386   END IF;
56387   IF (_result = -4) THEN
56388     RAISE EXCEPTION 'The length of an American Express credit card
56389                       number has to be 15 digits.';
56390   END IF;
56391   IF (_result = -5) THEN
56392     RAISE EXCEPTION 'The length of a Discover credit card number 
56393                       has to be 16 digits.';
56394   END IF;
56395    IF (_result = -6) THEN
56396     RAISE EXCEPTION 'The first two digits for a valid Master Card
56397                       number must be between 51 and 55';
56398   END IF;
56399   IF (_result = -7) THEN
56400     RAISE EXCEPTION 'The first digit for a valid Visa number must
56401                       be 4';
56402   END IF;
56403    IF (_result = -8) THEN
56404     RAISE EXCEPTION 'The first two digits for a valid American
56405                       Express number must be 34 or 37.';
56406   END IF;
56407   IF (_result = -9) THEN
56408     RAISE EXCEPTION 'The first four digits for a valid Discover
56409                       Express number must be 6011.';
56410   END IF;
56411   IF ((_result = -10) AND NOT fetchmetricbool('CCTest')) THEN
56412     RAISE EXCEPTION 'The credit card number that you have provided
56413                       is not valid.';
56414   END IF;
56415   IF (_result < -10) THEN
56416     RAISE EXCEPTION 'Invalid Credit Card Information';
56417   END IF;
56418
56419   -- Insert Record
56420
56421   INSERT INTO ccard ( 
56422     ccard_seq, 
56423     ccard_cust_id,
56424     ccard_active, 
56425     ccard_name, 
56426     ccard_address1,
56427     ccard_address2,
56428     ccard_city, 
56429     ccard_state, 
56430     ccard_zip,
56431     ccard_country, 
56432     ccard_number,
56433     ccard_month_expired, 
56434     ccard_year_expired, 
56435     ccard_type)
56436     VALUES 
56437     ((SELECT COALESCE(MAX(ccard_seq), 0) + 10
56438       FROM ccard 
56439       WHERE (ccard_cust_id =getCustId(pCustomer))),
56440      getCustId(pCustomer),
56441      COALESCE(pActive),
56442      encrypt(setbytea(pName), setbytea(pKey), 'bf'),
56443      encrypt(setbytea(pAddr1), setbytea(pKey), 'bf'),
56444      encrypt(setbytea(pAddr2), setbytea(pKey), 'bf'),
56445      encrypt(setbytea(pCity), setbytea(pKey), 'bf'),
56446      encrypt(setbytea(pState), setbytea(pKey), 'bf'),
56447      encrypt(setbytea(pPostal), setbytea(pKey), 'bf'),
56448      encrypt(setbytea(pCountry), setbytea(pKey), 'bf'),
56449      encrypt(setbytea(pNumber), setbytea(pKey), 'bf'),
56450      encrypt(setbytea(pMonth), setbytea(pKey), 'bf'),
56451      encrypt(setbytea(pYear), setbytea(pKey), 'bf'),
56452      _type );
56453
56454   RETURN true;
56455 END;
56456 $_$;
56457
56458
56459 ALTER FUNCTION public.insertccard(text, boolean, text, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, text) OWNER TO admin;
56460
56461 --
56462 -- TOC entry 9019 (class 0 OID 0)
56463 -- Dependencies: 1815
56464 -- Name: FUNCTION insertccard(text, boolean, text, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, text); Type: COMMENT; Schema: public; Owner: admin
56465 --
56466
56467 COMMENT ON FUNCTION insertccard(text, boolean, text, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, bytea, text) IS 'This function is generally used to support the _custcreditcard API view';
56468
56469
56470 --
56471 -- TOC entry 218 (class 1259 OID 146566514)
56472 -- Dependencies: 6012 6013 6014 6015 8
56473 -- Name: cmhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56474 --
56475
56476 CREATE TABLE cmhead (
56477     cmhead_id integer DEFAULT nextval(('cmhead_cmhead_id_seq'::text)::regclass) NOT NULL,
56478     cmhead_number text NOT NULL,
56479     cmhead_posted boolean,
56480     cmhead_invcnumber text,
56481     cmhead_custponumber text,
56482     cmhead_cust_id integer,
56483     cmhead_docdate date,
56484     cmhead_shipto_id integer,
56485     cmhead_shipto_name text,
56486     cmhead_shipto_address1 text,
56487     cmhead_shipto_address2 text,
56488     cmhead_shipto_address3 text,
56489     cmhead_shipto_city text,
56490     cmhead_shipto_state text,
56491     cmhead_shipto_zipcode text,
56492     cmhead_salesrep_id integer,
56493     cmhead_freight numeric(16,4),
56494     cmhead_misc numeric(16,4),
56495     cmhead_comments text,
56496     cmhead_printed boolean,
56497     cmhead_billtoname text,
56498     cmhead_billtoaddress1 text,
56499     cmhead_billtoaddress2 text,
56500     cmhead_billtoaddress3 text,
56501     cmhead_billtocity text,
56502     cmhead_billtostate text,
56503     cmhead_billtozip text,
56504     cmhead_hold boolean,
56505     cmhead_commission numeric(8,4),
56506     cmhead_misc_accnt_id integer,
56507     cmhead_misc_descrip text,
56508     cmhead_rsncode_id integer,
56509     cmhead_curr_id integer DEFAULT basecurrid(),
56510     cmhead_freighttaxtype_id integer,
56511     cmhead_gldistdate date,
56512     cmhead_billtocountry text,
56513     cmhead_shipto_country text,
56514     cmhead_rahead_id integer,
56515     cmhead_taxzone_id integer,
56516     cmhead_prj_id integer,
56517     cmhead_void boolean DEFAULT false,
56518     cmhead_saletype_id integer,
56519     cmhead_shipzone_id integer,
56520     CONSTRAINT cmhead_cmhead_number_check CHECK ((cmhead_number <> ''::text))
56521 );
56522
56523
56524 ALTER TABLE public.cmhead OWNER TO admin;
56525
56526 --
56527 -- TOC entry 9020 (class 0 OID 0)
56528 -- Dependencies: 218
56529 -- Name: TABLE cmhead; Type: COMMENT; Schema: public; Owner: admin
56530 --
56531
56532 COMMENT ON TABLE cmhead IS 'S/O Credit Memo header information';
56533
56534
56535 --
56536 -- TOC entry 9021 (class 0 OID 0)
56537 -- Dependencies: 218
56538 -- Name: COLUMN cmhead.cmhead_freighttaxtype_id; Type: COMMENT; Schema: public; Owner: admin
56539 --
56540
56541 COMMENT ON COLUMN cmhead.cmhead_freighttaxtype_id IS 'Deprecated column - DO NOT USE';
56542
56543
56544 --
56545 -- TOC entry 9022 (class 0 OID 0)
56546 -- Dependencies: 218
56547 -- Name: COLUMN cmhead.cmhead_saletype_id; Type: COMMENT; Schema: public; Owner: admin
56548 --
56549
56550 COMMENT ON COLUMN cmhead.cmhead_saletype_id IS 'Associated sale type for credit memo.';
56551
56552
56553 --
56554 -- TOC entry 9023 (class 0 OID 0)
56555 -- Dependencies: 218
56556 -- Name: COLUMN cmhead.cmhead_shipzone_id; Type: COMMENT; Schema: public; Owner: admin
56557 --
56558
56559 COMMENT ON COLUMN cmhead.cmhead_shipzone_id IS 'Associated shipping zone for credit memo.';
56560
56561
56562 --
56563 -- TOC entry 219 (class 1259 OID 146566524)
56564 -- Dependencies: 6016 6017 8
56565 -- Name: shiptoinfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56566 --
56567
56568 CREATE TABLE shiptoinfo (
56569     shipto_id integer DEFAULT nextval(('shipto_shipto_id_seq'::text)::regclass) NOT NULL,
56570     shipto_cust_id integer NOT NULL,
56571     shipto_name text,
56572     shipto_salesrep_id integer,
56573     shipto_comments text,
56574     shipto_shipcomments text,
56575     shipto_shipzone_id integer,
56576     shipto_shipvia text,
56577     shipto_commission numeric(10,4) NOT NULL,
56578     shipto_shipform_id integer,
56579     shipto_shipchrg_id integer,
56580     shipto_active boolean NOT NULL,
56581     shipto_default boolean,
56582     shipto_num text,
56583     shipto_ediprofile_id integer,
56584     shipto_cntct_id integer,
56585     shipto_addr_id integer,
56586     shipto_taxzone_id integer,
56587     shipto_preferred_warehous_id integer DEFAULT (-1) NOT NULL
56588 );
56589
56590
56591 ALTER TABLE public.shiptoinfo OWNER TO admin;
56592
56593 --
56594 -- TOC entry 9025 (class 0 OID 0)
56595 -- Dependencies: 219
56596 -- Name: TABLE shiptoinfo; Type: COMMENT; Schema: public; Owner: admin
56597 --
56598
56599 COMMENT ON TABLE shiptoinfo IS 'Ship-To information';
56600
56601
56602 --
56603 -- TOC entry 9026 (class 0 OID 0)
56604 -- Dependencies: 219
56605 -- Name: COLUMN shiptoinfo.shipto_ediprofile_id; Type: COMMENT; Schema: public; Owner: admin
56606 --
56607
56608 COMMENT ON COLUMN shiptoinfo.shipto_ediprofile_id IS 'Deprecated column - DO NOT USE';
56609
56610
56611 --
56612 -- TOC entry 220 (class 1259 OID 146566532)
56613 -- Dependencies: 6019 8
56614 -- Name: taxzone; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56615 --
56616
56617 CREATE TABLE taxzone (
56618     taxzone_id integer NOT NULL,
56619     taxzone_code text NOT NULL,
56620     taxzone_descrip text,
56621     CONSTRAINT taxzone_taxzone_code_check CHECK ((taxzone_code <> ''::text))
56622 );
56623
56624
56625 ALTER TABLE public.taxzone OWNER TO admin;
56626
56627 --
56628 -- TOC entry 9028 (class 0 OID 0)
56629 -- Dependencies: 220
56630 -- Name: TABLE taxzone; Type: COMMENT; Schema: public; Owner: admin
56631 --
56632
56633 COMMENT ON TABLE taxzone IS 'Tax zone information';
56634
56635
56636 --
56637 -- TOC entry 9029 (class 0 OID 0)
56638 -- Dependencies: 220
56639 -- Name: COLUMN taxzone.taxzone_id; Type: COMMENT; Schema: public; Owner: admin
56640 --
56641
56642 COMMENT ON COLUMN taxzone.taxzone_id IS 'Primary key';
56643
56644
56645 --
56646 -- TOC entry 9030 (class 0 OID 0)
56647 -- Dependencies: 220
56648 -- Name: COLUMN taxzone.taxzone_code; Type: COMMENT; Schema: public; Owner: admin
56649 --
56650
56651 COMMENT ON COLUMN taxzone.taxzone_code IS 'Code';
56652
56653
56654 --
56655 -- TOC entry 9031 (class 0 OID 0)
56656 -- Dependencies: 220
56657 -- Name: COLUMN taxzone.taxzone_descrip; Type: COMMENT; Schema: public; Owner: admin
56658 --
56659
56660 COMMENT ON COLUMN taxzone.taxzone_descrip IS 'Description';
56661
56662
56663 SET search_path = api, pg_catalog;
56664
56665 --
56666 -- TOC entry 221 (class 1259 OID 146566539)
56667 -- Dependencies: 8473 6
56668 -- Name: creditmemo; Type: VIEW; Schema: api; Owner: admin
56669 --
56670
56671 CREATE VIEW creditmemo AS
56672     SELECT cmhead.cmhead_number AS memo_number, CASE WHEN (cmhead.cmhead_invcnumber = '-1'::text) THEN ''::text ELSE cmhead.cmhead_invcnumber END AS apply_to, cmhead.cmhead_docdate AS memo_date, CASE WHEN cmhead.cmhead_posted THEN 'Posted'::text ELSE 'Unposted'::text END AS status, salesrep.salesrep_number AS sales_rep, cmhead.cmhead_commission AS commission, COALESCE(taxzone.taxzone_code, 'None'::text) AS tax_zone, COALESCE(rsncode.rsncode_code, 'None'::text) AS reason_code, cmhead.cmhead_hold AS on_hold, custinfo.cust_number AS customer_number, cmhead.cmhead_billtoname AS billto_name, cmhead.cmhead_billtoaddress1 AS billto_address1, cmhead.cmhead_billtoaddress2 AS billto_address2, cmhead.cmhead_billtoaddress3 AS billto_address3, cmhead.cmhead_billtocity AS billto_city, cmhead.cmhead_billtostate AS billto_state, cmhead.cmhead_billtozip AS billto_postal_code, cmhead.cmhead_billtocountry AS billto_country, shiptoinfo.shipto_num AS shipto_number, cmhead.cmhead_shipto_name AS shipto_name, cmhead.cmhead_shipto_address1 AS shipto_address1, cmhead.cmhead_shipto_address2 AS shipto_address2, cmhead.cmhead_shipto_address3 AS shipto_address3, cmhead.cmhead_shipto_city AS shipto_city, cmhead.cmhead_shipto_state AS shipto_state, cmhead.cmhead_shipto_zipcode AS shipto_postal_code, cmhead.cmhead_shipto_country AS shipto_country, cmhead.cmhead_custponumber AS customer_po_number, cmhead.cmhead_comments AS notes, curr.curr_abbr AS currency, cmhead.cmhead_misc_descrip AS misc_charge_description, cmhead.cmhead_misc AS misc_charge_amount, CASE WHEN (cmhead.cmhead_misc_accnt_id = (-1)) THEN ''::text ELSE public.formatglaccount(cmhead.cmhead_misc_accnt_id) END AS misc_charge_credit_account, cmhead.cmhead_freight AS freight FROM ((((((public.cmhead LEFT JOIN public.custinfo ON ((custinfo.cust_id = cmhead.cmhead_cust_id))) LEFT JOIN public.shiptoinfo ON ((shiptoinfo.shipto_id = cmhead.cmhead_shipto_id))) LEFT JOIN public.curr_symbol curr ON ((curr.curr_id = cmhead.cmhead_curr_id))) LEFT JOIN public.salesrep ON ((salesrep.salesrep_id = cmhead.cmhead_salesrep_id))) LEFT JOIN public.taxzone ON ((taxzone.taxzone_id = cmhead.cmhead_taxzone_id))) LEFT JOIN public.rsncode ON ((rsncode.rsncode_id = cmhead.cmhead_rsncode_id)));
56673
56674
56675 ALTER TABLE api.creditmemo OWNER TO admin;
56676
56677 --
56678 -- TOC entry 9033 (class 0 OID 0)
56679 -- Dependencies: 221
56680 -- Name: VIEW creditmemo; Type: COMMENT; Schema: api; Owner: admin
56681 --
56682
56683 COMMENT ON VIEW creditmemo IS 'Credit Memo Header';
56684
56685
56686 SET search_path = public, pg_catalog;
56687
56688 --
56689 -- TOC entry 1816 (class 1255 OID 146566544)
56690 -- Dependencies: 2842 4536 8
56691 -- Name: insertcreditmemo(api.creditmemo); Type: FUNCTION; Schema: public; Owner: admin
56692 --
56693
56694 CREATE FUNCTION insertcreditmemo(api.creditmemo) RETURNS boolean
56695     LANGUAGE plpgsql
56696     AS $_$
56697 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
56698 -- See www.xtuple.com/CPAL for the full text of the software license.
56699 DECLARE
56700         pNew ALIAS FOR $1;
56701 BEGIN
56702         -- NOTE: (SELECT getCustId(...)) seems redundant, but it actually produces
56703         -- a HUGE performance increase because it makes the Postgres query planner
56704         -- use an index scan rather than an sequential table scan on cust_id
56705   INSERT INTO cmhead (
56706                 cmhead_number,
56707                 cmhead_posted,
56708                 cmhead_invcnumber,
56709                 cmhead_custponumber,
56710                 cmhead_cust_id,
56711                 cmhead_docdate,
56712                 cmhead_shipto_id,
56713                 cmhead_shipto_name,
56714                 cmhead_shipto_address1,
56715                 cmhead_shipto_address2,
56716                 cmhead_shipto_address3,
56717                 cmhead_shipto_city,
56718                 cmhead_shipto_state,
56719                 cmhead_shipto_zipcode,
56720                 cmhead_shipto_country,
56721                 cmhead_salesrep_id,
56722                 cmhead_freight,
56723                 cmhead_misc,
56724                 cmhead_comments,
56725                 cmhead_printed,
56726                 cmhead_billtoname,
56727                 cmhead_billtoaddress1,
56728                 cmhead_billtoaddress2,
56729                 cmhead_billtoaddress3,
56730                 cmhead_billtocity,
56731                 cmhead_billtostate,
56732                 cmhead_billtozip,
56733                 cmhead_billtocountry,
56734                 cmhead_hold,
56735                 cmhead_commission,
56736                 cmhead_misc_accnt_id,
56737                 cmhead_misc_descrip,
56738                 cmhead_rsncode_id,
56739                 cmhead_curr_id,
56740                 cmhead_taxzone_id,
56741                 cmhead_gldistdate,
56742                 cmhead_rahead_id
56743                 )
56744          SELECT
56745                 (CASE -- use a case here so we don't unnecessarily fetch a new CM number
56746                         WHEN pNew.memo_number IS NULL THEN fetchCMNumber()
56747                         ELSE pNew.memo_number
56748                 END),
56749                 FALSE, -- posted
56750                 pNew.apply_to,
56751                 pNew.customer_po_number,
56752                 cust_id,
56753                 COALESCE(pNew.memo_date, CURRENT_DATE),
56754                 COALESCE(shipto_id,-1),
56755                 pNew.shipto_name,
56756                 pNew.shipto_address1,
56757                 pNew.shipto_address2,
56758                 pNew.shipto_address3,
56759                 pNew.shipto_city,
56760                 pNew.shipto_state,
56761                 pNew.shipto_postal_code,
56762                 pNew.shipto_country,
56763                 COALESCE(getSalesRepId(pNew.sales_rep),shipto_salesrep_id,cust_salesrep_id),
56764                 COALESCE(pNew.freight, 0),
56765                 COALESCE(pNew.misc_charge_amount, 0),
56766                 pNew.notes,
56767                 FALSE, -- printed
56768                 COALESCE(pNew.billto_name, invchead_billto_name, cust_name),
56769                 COALESCE(pNew.billto_address1, invchead_billto_address1, addr_line1),
56770                 COALESCE(pNew.billto_address2, invchead_billto_address2, addr_line2),
56771                 COALESCE(pNew.billto_address3, invchead_billto_address3, addr_line3),
56772                 COALESCE(pNew.billto_city, invchead_billto_city, addr_city),
56773                 COALESCE(pNew.billto_state, invchead_billto_state, addr_state),
56774                 COALESCE(pNew.billto_postal_code, invchead_billto_zipcode, addr_postalcode),
56775                 COALESCE(pNew.billto_country, invchead_billto_country, addr_country),
56776                 COALESCE(pNew.on_hold, FALSE),
56777                 COALESCE(pNew.commission, 0),
56778                 COALESCE(getGlAccntId(pNew.misc_charge_credit_account),-1),
56779                 pNew.misc_charge_description,
56780                 (SELECT rsncode_id FROM rsncode WHERE rsncode_code = pNew.reason_code),
56781                 COALESCE(getCurrId(pNew.currency),cust_curr_id,basecurrid()),
56782                 CASE WHEN pNew.tax_zone = 'None' THEN NULL
56783                      ELSE COALESCE(getTaxZoneID(pNew.tax_zone),cust_taxzone_id)
56784                 END,
56785                 NULL,
56786                 NULL
56787         FROM custinfo
56788                 LEFT OUTER JOIN shiptoinfo ON (shipto_id=(SELECT CASE
56789                         WHEN getShiptoId(pNew.customer_number,pNew.shipto_number) IS NOT NULL
56790                                 THEN getShiptoId(pNew.customer_number,pNew.shipto_number)
56791                         ELSE (SELECT shipto_id FROM shiptoinfo WHERE shipto_cust_id=cust_id AND shipto_default)
56792                 END))
56793                 LEFT OUTER JOIN invchead ON (invchead_id=getInvcheadId(pNEW.apply_to))
56794                 LEFT OUTER JOIN cntct ON (cntct_id=cust_cntct_id)
56795                 LEFT OUTER JOIN addr ON (addr_id=cntct_addr_id)
56796         WHERE cust_id = (CASE
56797                 WHEN pNew.customer_number IS NOT NULL THEN (SELECT getCustId(pNew.customer_number))
56798                 ELSE (SELECT invchead_cust_id FROM invchead WHERE invchead_invcnumber = pNew.apply_to)
56799         END);
56800         RETURN TRUE;
56801 END;
56802 $_$;
56803
56804
56805 ALTER FUNCTION public.insertcreditmemo(api.creditmemo) OWNER TO admin;
56806
56807 --
56808 -- TOC entry 222 (class 1259 OID 146566545)
56809 -- Dependencies: 6020 6021 8
56810 -- Name: cmitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
56811 --
56812
56813 CREATE TABLE cmitem (
56814     cmitem_id integer DEFAULT nextval(('cmitem_cmitem_id_seq'::text)::regclass) NOT NULL,
56815     cmitem_cmhead_id integer NOT NULL,
56816     cmitem_linenumber integer NOT NULL,
56817     cmitem_itemsite_id integer NOT NULL,
56818     cmitem_qtycredit numeric(18,6) NOT NULL,
56819     cmitem_qtyreturned numeric(18,6) NOT NULL,
56820     cmitem_unitprice numeric(16,4) NOT NULL,
56821     cmitem_comments text,
56822     cmitem_rsncode_id integer,
56823     cmitem_taxtype_id integer,
56824     cmitem_qty_uom_id integer NOT NULL,
56825     cmitem_qty_invuomratio numeric(20,10) NOT NULL,
56826     cmitem_price_uom_id integer NOT NULL,
56827     cmitem_price_invuomratio numeric(20,10) NOT NULL,
56828     cmitem_raitem_id integer,
56829     cmitem_updateinv boolean DEFAULT true NOT NULL
56830 );
56831
56832
56833 ALTER TABLE public.cmitem OWNER TO admin;
56834
56835 --
56836 -- TOC entry 9035 (class 0 OID 0)
56837 -- Dependencies: 222
56838 -- Name: TABLE cmitem; Type: COMMENT; Schema: public; Owner: admin
56839 --
56840
56841 COMMENT ON TABLE cmitem IS 'S/O Credit Memo Line Item information';
56842
56843
56844 SET search_path = api, pg_catalog;
56845
56846 --
56847 -- TOC entry 223 (class 1259 OID 146566553)
56848 -- Dependencies: 8474 6
56849 -- Name: creditmemoline; Type: VIEW; Schema: api; Owner: admin
56850 --
56851
56852 CREATE VIEW creditmemoline AS
56853     SELECT cmhead.cmhead_number AS memo_number, cmitem.cmitem_linenumber AS line_number, item.item_number, whsinfo.warehous_code AS recv_site, rsncode.rsncode_code AS reason_code, cmitem.cmitem_qtyreturned AS qty_returned, cmitem.cmitem_qtycredit AS qty_to_credit, COALESCE(qty_uom.uom_name, 'None'::text) AS qty_uom, cmitem.cmitem_unitprice AS net_unit_price, COALESCE(price_uom.uom_name, 'None'::text) AS price_uom, COALESCE(taxtype.taxtype_name, 'None'::text) AS tax_type, cmitem.cmitem_comments AS notes FROM ((((((((public.cmitem LEFT JOIN public.cmhead ON ((cmitem.cmitem_cmhead_id = cmhead.cmhead_id))) LEFT JOIN public.itemsite ON ((itemsite.itemsite_id = cmitem.cmitem_itemsite_id))) LEFT JOIN public.item ON ((item.item_id = itemsite.itemsite_item_id))) LEFT JOIN public.whsinfo ON ((whsinfo.warehous_id = itemsite.itemsite_warehous_id))) LEFT JOIN public.rsncode ON ((rsncode.rsncode_id = cmitem.cmitem_rsncode_id))) LEFT JOIN public.taxtype ON ((taxtype.taxtype_id = cmitem.cmitem_taxtype_id))) LEFT JOIN public.uom qty_uom ON ((qty_uom.uom_id = cmitem.cmitem_qty_uom_id))) LEFT JOIN public.uom price_uom ON ((price_uom.uom_id = cmitem.cmitem_price_uom_id)));
56854
56855
56856 ALTER TABLE api.creditmemoline OWNER TO admin;
56857
56858 --
56859 -- TOC entry 9037 (class 0 OID 0)
56860 -- Dependencies: 223
56861 -- Name: VIEW creditmemoline; Type: COMMENT; Schema: api; Owner: admin
56862 --
56863
56864 COMMENT ON VIEW creditmemoline IS 'Credit Memo Line';
56865
56866
56867 SET search_path = public, pg_catalog;
56868
56869 --
56870 -- TOC entry 1817 (class 1255 OID 146566558)
56871 -- Dependencies: 2849 4536 8
56872 -- Name: insertcreditmemoline(api.creditmemoline); Type: FUNCTION; Schema: public; Owner: admin
56873 --
56874
56875 CREATE FUNCTION insertcreditmemoline(api.creditmemoline) RETURNS boolean
56876     LANGUAGE plpgsql
56877     AS $_$
56878 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
56879 -- See www.xtuple.com/CPAL for the full text of the software license.
56880 DECLARE
56881   pNew ALIAS FOR $1;
56882   _check INTEGER;
56883   _r RECORD;
56884
56885 BEGIN
56886   SELECT cmhead_id INTO _check
56887   FROM cmhead
56888   WHERE (cmhead_id=getCmheadId(pNew.memo_number, FALSE));
56889   IF (NOT FOUND) THEN
56890     RAISE EXCEPTION 'Credit Memo # % not found', pNew.memo_number;
56891   END IF;
56892
56893   INSERT INTO cmitem ( cmitem_cmhead_id,
56894                        cmitem_linenumber,
56895                        cmitem_itemsite_id,
56896                        cmitem_qtycredit,
56897                        cmitem_qtyreturned,
56898                        cmitem_unitprice,
56899                        cmitem_comments,
56900                        cmitem_rsncode_id,
56901                        cmitem_taxtype_id,
56902                        cmitem_qty_uom_id,
56903                        cmitem_qty_invuomratio,
56904                        cmitem_price_uom_id,
56905                        cmitem_price_invuomratio )
56906   SELECT cmhead_id,
56907          COALESCE(pNew.line_number,
56908                   (SELECT (COALESCE(MAX(cmitem_linenumber), 0) + 1)
56909                    FROM cmitem WHERE (cmitem_cmhead_id=cmhead_id))),
56910          COALESCE(itemsite_id, -1),
56911          COALESCE(pNew.qty_to_credit, 0),
56912          COALESCE(pNew.qty_returned, 0),
56913          COALESCE(pNew.net_unit_price, 0),
56914          pNew.notes,
56915          getRsnId(pNew.reason_code),
56916          taxtype_id,
56917          COALESCE(getUomId(pNew.qty_uom), item_inv_uom_id),
56918          CASE
56919            WHEN item_id IS NOT NULL THEN itemuomtouomratio(item_id, COALESCE(getUomId(pNew.qty_uom),item_inv_uom_id),item_inv_uom_id)
56920            ELSE 1
56921          END,
56922          COALESCE(getUomId(pNew.price_uom),item_price_uom_id),
56923          CASE
56924            WHEN item_id IS NOT NULL THEN itemuomtouomratio(item_id, COALESCE(getUomId(pNew.price_uom),item_price_uom_id),item_price_uom_id)
56925            ELSE 1
56926         END
56927   FROM cmhead LEFT OUTER JOIN item ON (item_id=getItemId(pNew.item_number))
56928               LEFT OUTER JOIN itemsite ON (itemsite_item_id=item_id AND itemsite_warehous_id=getWarehousId(pNew.recv_site, 'ALL'))
56929               LEFT OUTER JOIN taxtype ON (taxtype_id=CASE WHEN pNew.tax_type IS NULL THEN getItemTaxType(item_id,cmhead_taxzone_id)
56930                                                           WHEN pNew.tax_type = 'None' THEN NULL
56931                                                           ELSE getTaxTypeId(pNew.tax_type)
56932                                                      END)
56933   WHERE (cmhead_id=getCmheadId(pNew.memo_number, FALSE));
56934
56935   RETURN TRUE;
56936 END;
56937 $_$;
56938
56939
56940 ALTER FUNCTION public.insertcreditmemoline(api.creditmemoline) OWNER TO admin;
56941
56942 --
56943 -- TOC entry 1803 (class 1255 OID 146566559)
56944 -- Dependencies: 4536 8
56945 -- Name: insertflgroup(integer, integer, integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
56946 --
56947
56948 CREATE FUNCTION insertflgroup(integer, integer, integer, integer, boolean) RETURNS boolean
56949     LANGUAGE plpgsql
56950     AS $_$
56951 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
56952 -- See www.xtuple.com/CPAL for the full text of the software license.
56953 DECLARE
56954   pFlheadid  ALIAS FOR $1;
56955   pPeriodid  ALIAS FOR $2;
56956   pFlgrpid   ALIAS FOR $3;
56957   pLevel     ALIAS FOR $4;
56958   pSummarize ALIAS FOR $5;
56959
56960 BEGIN
56961   RETURN insertFlGroup(pFlheadid, pPeriodid, pFlgrpid, pLevel, pSummarize, NULL);
56962 END;
56963 $_$;
56964
56965
56966 ALTER FUNCTION public.insertflgroup(integer, integer, integer, integer, boolean) OWNER TO admin;
56967
56968 --
56969 -- TOC entry 1818 (class 1255 OID 146566560)
56970 -- Dependencies: 4536 8
56971 -- Name: insertflgroup(integer, integer, integer, integer, boolean, character); Type: FUNCTION; Schema: public; Owner: admin
56972 --
56973
56974 CREATE FUNCTION insertflgroup(integer, integer, integer, integer, boolean, character) RETURNS boolean
56975     LANGUAGE plpgsql
56976     AS $_$
56977 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
56978 -- See www.xtuple.com/CPAL for the full text of the software license.
56979 DECLARE
56980   pFlheadid  ALIAS FOR $1;
56981   pPeriodid  ALIAS FOR $2;
56982   pFlgrpid   ALIAS FOR $3;
56983   pLevel     ALIAS FOR $4;
56984   pSummarize ALIAS FOR $5;
56985   pInterval  ALIAS FOR $6;
56986
56987 BEGIN
56988   RETURN insertFlGroup(pFlheadid, pPeriodid, pFlgrpid, pLevel, pSummarize, pInterval, NULL);
56989 END;
56990 $_$;
56991
56992
56993 ALTER FUNCTION public.insertflgroup(integer, integer, integer, integer, boolean, character) OWNER TO admin;
56994
56995 --
56996 -- TOC entry 1819 (class 1255 OID 146566561)
56997 -- Dependencies: 4536 8
56998 -- Name: insertflgroup(integer, integer, integer, integer, boolean, character, integer); Type: FUNCTION; Schema: public; Owner: admin
56999 --
57000
57001 CREATE FUNCTION insertflgroup(integer, integer, integer, integer, boolean, character, integer) RETURNS boolean
57002     LANGUAGE plpgsql
57003     AS $_$
57004 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57005 -- See www.xtuple.com/CPAL for the full text of the software license.
57006 DECLARE
57007   pFlheadid  ALIAS FOR $1;
57008   pPeriodid  ALIAS FOR $2;
57009   pFlgrpid   ALIAS FOR $3;
57010   pLevel     ALIAS FOR $4;
57011   pSummarize ALIAS FOR $5;
57012   pInterval  ALIAS FOR $6;
57013   pPrjid     ALIAS FOR $7;
57014
57015   _subtotal BOOLEAN;
57016   _r RECORD;
57017   _g RECORD;
57018   _all BOOLEAN;
57019
57020 BEGIN
57021
57022   _all = COALESCE(pPrjid,-1) = -1;
57023   
57024 -- Check to see if this group wants a subtotal
57025   _subtotal := FALSE;
57026   IF (pFlgrpid != -1) THEN
57027     SELECT COALESCE(flgrp_subtotal, FALSE) INTO _subtotal
57028       FROM flgrp
57029      WHERE ((flgrp_flhead_id=pFlheadid)
57030        AND  (flgrp_id=pFlgrpid));
57031   END IF;
57032
57033   FOR _r IN SELECT 'G' AS type, flgrp_id AS type_id,
57034                    flgrp_order AS orderby,
57035                    flgrp_summarize AS summarize,
57036                    flgrp_subtract AS subtract,
57037                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showstart)) THEN NULL
57038                         ELSE 0.00
57039                    END AS beginning,
57040                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showend)) THEN NULL
57041                         ELSE 0.00
57042                    END AS ending,
57043                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showdelta)) THEN NULL
57044                         ELSE 0.00
57045                    END AS debits,
57046                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showdelta)) THEN NULL
57047                         ELSE 0.00
57048                    END AS credits,
57049                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showbudget)) THEN NULL
57050                         ELSE 0.00
57051                    END AS budget,
57052                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showdiff)) THEN NULL
57053                         ELSE 0.00
57054                    END AS diff,
57055                    CASE WHEN(flgrp_summarize AND (NOT flgrp_showcustom)) THEN NULL
57056                         ELSE 0.00
57057                    END AS custom,
57058                    CASE WHEN(flgrp_showstartprcnt) THEN 0.00
57059                         ELSE NULL
57060                    END AS beginningprcnt,
57061                    CASE WHEN(flgrp_showendprcnt) THEN 0.00
57062                         ELSE NULL
57063                    END AS endingprcnt,
57064                    CASE WHEN(flgrp_showdeltaprcnt) THEN 0.00
57065                         ELSE NULL
57066                    END AS debitsprcnt,
57067                    CASE WHEN(flgrp_showdeltaprcnt) THEN 0.00
57068                         ELSE NULL
57069                    END AS creditsprcnt,
57070                    CASE WHEN(flgrp_showbudgetprcnt) THEN 0.00
57071                         ELSE NULL
57072                    END AS budgetprcnt,
57073                    CASE WHEN(flgrp_showdiffprcnt) THEN 0.00
57074                         ELSE NULL
57075                    END AS diffprcnt,
57076                    CASE WHEN(flgrp_showcustomprcnt) THEN 0.00
57077                         ELSE NULL
57078                    END AS customprcnt,
57079                    -1 AS accnt_id,
57080                    '' AS accnt_number
57081               FROM flgrp
57082              WHERE ((flgrp_flgrp_id=pFlgrpid)
57083                AND  (flgrp_flhead_id=pFlheadid))
57084              UNION ALL
57085             SELECT 'I' AS type, flitem_id AS type_id,
57086                    flitem_order AS orderby,
57087                    FALSE AS summarize,
57088                    flitem_subtract AS subtract,
57089                    CASE WHEN (flitem_showstart AND (first_trialbal_id IS NULL)) THEN 0.00
57090                         WHEN (flitem_showstart) THEN normalizeTrialBal(first_trialbal_id, 'B')
57091                         ELSE NULL
57092                    END AS beginning,
57093                    CASE WHEN (flitem_showend AND (last_trialbal_id IS NULL)) THEN 0.00
57094                         WHEN (flitem_showend) THEN normalizeTrialBal(last_trialbal_id, 'E')
57095                         ELSE NULL
57096                    END AS ending,
57097                    CASE WHEN (flitem_showdelta) THEN sum_trialbal_debits
57098                         ELSE NULL
57099                    END AS debits,
57100                    CASE WHEN (flitem_showdelta) THEN sum_trialbal_credits
57101                         ELSE NULL
57102                    END AS credits,
57103                    CASE WHEN ((flitem_showbudget) AND (accnt_type IN ('R','E')) AND flhead_type IN ('I','C','A')) THEN COALESCE(sum_budget_amount,0)
57104                         WHEN ((flitem_showbudget) AND (accnt_type IN ('R','E')) AND flhead_type = 'B' ) THEN
57105                                 (SELECT COALESCE(SUM(b.budget_amount),0)
57106                                 FROM budget b,
57107                                         (SELECT ytd.period_id AS ytd_period_id
57108                                         FROM period cp, period ytd
57109                                         WHERE ((cp.period_id = last_flitem_period_id)
57110                                         AND (ytd.period_start <= cp.period_start)
57111                                 AND (ytd.period_yearperiod_id = cp.period_yearperiod_id))) AS periods
57112                                 WHERE ((b.budget_accnt_id=accnt_id)
57113                                 AND (b.budget_period_id=ytd_period_id)))
57114                         WHEN ((flitem_showbudget) AND (accnt_type IN ('A','L','Q')) AND flhead_type = 'C') THEN calccashbudget(accnt_id,last_flitem_period_id,pInterval)
57115                         ELSE COALESCE(last_budget_amount,0)
57116                    END AS budget,
57117                    CASE WHEN (flitem_showdiff AND (first_trialbal_id IS NULL)) THEN 0.00
57118                         WHEN (flitem_showdiff) THEN COALESCE(normalizeTrialBal(last_trialbal_id, 'E') - normalizeTrialBal(first_trialbal_id, 'B'), 0.00)
57119                         ELSE NULL
57120                    END AS diff,
57121                    CASE WHEN (NOT flitem_showcustom) THEN NULL
57122                         WHEN (flitem_custom_source='S' AND (first_trialbal_id IS NOT NULL)) THEN normalizeTrialBal(first_trialbal_id, 'B')
57123                         WHEN (flitem_custom_source='E' AND (first_trialbal_id IS NOT NULL)) THEN normalizeTrialBal(last_trialbal_id, 'E')
57124                         WHEN (flitem_custom_source='D') THEN sum_trialbal_debits
57125                         WHEN (flitem_custom_source='C') THEN sum_trialbal_credits
57126                         WHEN (flitem_custom_source='B') THEN (
57127                                 CASE
57128                                   WHEN (accnt_type IN ('R','E')) THEN sum_budget_amount
57129                                   ELSE last_budget_amount
57130                                 END)
57131                         WHEN (flitem_custom_source='F' AND  (first_trialbal_id IS NOT NULL)) THEN COALESCE(normalizeTrialBal(last_trialbal_id, 'E') - normalizeTrialBal(first_trialbal_id, 'B'), 0.00)
57132                         ELSE 0.00
57133                    END AS custom,
57134                    CASE WHEN(flitem_showstartprcnt) THEN 0.00
57135                         ELSE NULL
57136                    END AS beginningprcnt,
57137                    CASE WHEN(flitem_showendprcnt) THEN 0.00
57138                         ELSE NULL
57139                    END AS endingprcnt,
57140                    CASE WHEN(flitem_showdeltaprcnt) THEN 0.00
57141                         ELSE NULL
57142                    END AS debitsprcnt,
57143                    CASE WHEN(flitem_showdeltaprcnt) THEN 0.00
57144                         ELSE NULL
57145                    END AS creditsprcnt,
57146                    CASE WHEN(flitem_showbudgetprcnt) THEN 0.00
57147                         ELSE NULL
57148                    END AS budgetprcnt,
57149                    CASE WHEN(flitem_showdiffprcnt) THEN 0.00
57150                         ELSE NULL
57151                    END AS diffprcnt,
57152                    CASE WHEN(flitem_showcustomprcnt) THEN 0.00
57153                         ELSE NULL
57154                    END AS customprcnt,
57155                    accnt_id,
57156                    public.formatglaccount(accnt_id) AS accnt_number
57157               FROM
57158                 (SELECT 
57159                   flhead_type,flitem_id,flitem_order,flitem_subtract,flitem_showstart,flitem_showend,
57160                   flitem_showdelta,flitem_showbudget,flitem_showdiff,flitem_showcustom,
57161                   flitem_custom_source,flitem_showstartprcnt,flitem_showendprcnt,flitem_showdeltaprcnt,
57162                   flitem_showbudgetprcnt,flitem_showdiffprcnt,flitem_showcustomprcnt,
57163                   accnt_id,accnt_type,
57164                   FIRST(trialbal_id) AS first_trialbal_id, LAST(trialbal_id) AS last_trialbal_id,
57165                   SUM(trialbal_debits) AS sum_trialbal_debits, SUM(trialbal_credits) AS sum_trialbal_credits, 
57166                   LAST(flitem_period_id) AS last_flitem_period_id,
57167                   SUM(budget_amount) AS sum_budget_amount, LAST(budget_amount) AS last_budget_amount
57168                   FROM
57169                 (SELECT period_id AS flitem_period_id, period_start,flhead_type,flitem_id,flitem_order,flitem_subtract,flitem_showstart,flitem_showend,
57170                         flitem_showdelta,flitem_showbudget,flitem_showdiff,flitem_showcustom,
57171                         flitem_custom_source,flitem_showstartprcnt,flitem_showendprcnt,flitem_showdeltaprcnt,
57172                         flitem_showbudgetprcnt,flitem_showdiffprcnt,flitem_showcustomprcnt,
57173                         accnt_id,accnt_type,COALESCE(trialbal_id,getlasttrialbalid(accnt_id,period_id)) as trialbal_id,COALESCE(trialbal_debits,0) as trialbal_debits,
57174                         COALESCE(trialbal_credits,0) AS trialbal_credits,COALESCE(budget_amount,0) AS budget_amount
57175                    FROM (SELECT period_id, period_start, flhead_type, flitem_id,flitem_order,flitem_subtract,flitem_showstart,flitem_showend,
57176                                 flitem_showdelta,flitem_showbudget,flitem_showdiff,flitem_showcustom,flitem_custom_source,flitem_showstartprcnt,
57177                                 flitem_showendprcnt,flitem_showdeltaprcnt,flitem_showbudgetprcnt,flitem_showdiffprcnt,flitem_showcustomprcnt,
57178                                 accnt_id, accnt_type
57179                         FROM  period,flaccnt
57180                         WHERE ((flitem_flhead_id=pFlheadid)
57181                         AND (flitem_flgrp_id=pFlgrpid)
57182                         AND (_all OR prj_id=pPrjId)
57183                         AND (period_id IN  (SELECT * FROM getperiodid(pPeriodId,pInterval))))
57184                         ORDER BY flitem_id
57185                         ) AS flitem
57186                    LEFT OUTER JOIN trialbal
57187                      ON ((trialbal_accnt_id=accnt_id)
57188                      AND (trialbal_period_id=period_id))
57189                    LEFT OUTER JOIN budget
57190                      ON ((budget_accnt_id=accnt_id)
57191                      AND (budget_period_id=period_id))
57192              ORDER BY accnt_id, period_start) AS data
57193              GROUP BY flhead_type,flitem_id,flitem_order,flitem_subtract,flitem_showstart,flitem_showend,
57194                 flitem_showdelta,flitem_showbudget,flitem_showdiff,flitem_showcustom,
57195                 flitem_custom_source,flitem_showstartprcnt,flitem_showendprcnt,flitem_showdeltaprcnt,
57196                 flitem_showbudgetprcnt,flitem_showdiffprcnt,flitem_showcustomprcnt,accnt_id,accnt_type) AS agg
57197              UNION ALL
57198             SELECT 'S' AS type, flspec_id AS type_id,
57199                    flspec_order AS orderby,
57200                    FALSE AS summarize,
57201                    flspec_subtract AS subtract,
57202                    CASE WHEN (flspec_showstart) THEN findSpecialFinancial('S', flspec_type, pPeriodid)
57203                         ELSE NULL
57204                    END AS beginning,
57205                    CASE WHEN (flspec_showend) THEN findSpecialFinancial('E', flspec_type, pPeriodid)
57206                         ELSE NULL
57207                    END AS ending,
57208                    CASE WHEN (flspec_showdelta) THEN findSpecialFinancial('D', flspec_type, pPeriodid)
57209                         ELSE NULL
57210                    END AS debits,
57211                    CASE WHEN (flspec_showdelta) THEN findSpecialFinancial('C', flspec_type, pPeriodid)
57212                         ELSE NULL
57213                    END AS credits,
57214                    CASE WHEN (flspec_showbudget) THEN findSpecialFinancial('B', flspec_type, pPeriodid)
57215                         ELSE NULL
57216                    END AS budget,
57217                    CASE WHEN (flspec_showdiff) THEN findSpecialFinancial('E', flspec_type, pPeriodid) - findSpecialFinancial('S', flspec_type, pPeriodid)
57218                         ELSE NULL
57219                    END AS diff,
57220                    CASE WHEN (NOT flspec_showcustom) THEN NULL
57221                         WHEN (flspec_custom_source='F') THEN findSpecialFinancial('E', flspec_type, pPeriodid) - findSpecialFinancial('S', flspec_type, pPeriodid)
57222                         WHEN (flspec_custom_source IN ('S', 'E', 'D', 'C', 'B')) THEN findSpecialFinancial(flspec_custom_source, flspec_type, pPeriodid)
57223                         ELSE 0.00
57224                    END AS custom,
57225                    CASE WHEN(flspec_showstartprcnt) THEN 0.00
57226                         ELSE NULL
57227                    END AS beginningprcnt,
57228                    CASE WHEN(flspec_showendprcnt) THEN 0.00
57229                         ELSE NULL
57230                    END AS endingprcnt,
57231                    CASE WHEN(flspec_showdeltaprcnt) THEN 0.00
57232                         ELSE NULL
57233                    END AS debitsprcnt,
57234                    CASE WHEN(flspec_showdeltaprcnt) THEN 0.00
57235                         ELSE NULL
57236                    END AS creditsprcnt,
57237                    CASE WHEN(flspec_showbudgetprcnt) THEN 0.00
57238                         ELSE NULL
57239                    END AS budgetprcnt,
57240                    CASE WHEN(flspec_showdiffprcnt) THEN 0.00
57241                         ELSE NULL
57242                    END AS diffprcnt,
57243                    CASE WHEN(flspec_showcustomprcnt) THEN 0.00
57244                         ELSE NULL
57245                    END AS customprcnt,
57246                    -1 AS accnt_id,
57247                    '' AS accnt_number
57248               FROM flspec
57249              WHERE ((flspec_flgrp_id=pFlgrpid)
57250                AND  (flspec_flhead_id=pFlheadid))
57251           ORDER BY orderby, accnt_number LOOP
57252
57253     IF (_r.type = 'G') THEN
57254
57255 -- Create a record for the items sub items to be attached to and be able to update the total
57256       INSERT INTO flrpt
57257              (flrpt_flhead_id, flrpt_period_id, flrpt_username,
57258               flrpt_order,
57259               flrpt_level, flrpt_type, flrpt_type_id,
57260               flrpt_beginning, flrpt_ending,
57261               flrpt_debits, flrpt_credits, flrpt_budget, flrpt_diff, flrpt_custom,
57262               flrpt_beginningprcnt, flrpt_endingprcnt,
57263               flrpt_debitsprcnt, flrpt_creditsprcnt, flrpt_budgetprcnt, flrpt_diffprcnt, flrpt_customprcnt,
57264               flrpt_parent_id, flrpt_interval)
57265       VALUES (pFlheadid, pPeriodid, getEffectiveXtUser(),
57266               (COALESCE(( SELECT MAX(flrpt_order)
57267                             FROM flrpt
57268                            WHERE ((flrpt_flhead_id=pFlheadid)
57269                              AND  (flrpt_period_id=pPeriodid)
57270                              AND (flrpt_interval=pInterval)
57271                              AND  (flrpt_username=getEffectiveXtUser()))
57272                         ), 1) + 1),
57273               pLevel, _r.type, _r.type_id,
57274               _r.beginning, _r.ending,
57275               _r.debits, _r.credits, _r.budget, _r.diff, _r.custom,
57276               _r.beginningprcnt, _r.endingprcnt,
57277               _r.debitsprcnt, _r.creditsprcnt, _r.budgetprcnt, _r.diffprcnt, _r.customprcnt,
57278               pFlgrpid, pInterval);
57279
57280       PERFORM insertFlGroup(pFlheadid, pPeriodid, _r.type_id, (pLevel + 1), (pSummarize OR _r.summarize), pInterval, pPrjid);
57281
57282 -- Update the parent item
57283       SELECT COALESCE(flrpt_beginning, 0.00) AS beginning,
57284              COALESCE(flrpt_ending, 0.00) AS ending,
57285              COALESCE(flrpt_debits, 0.00) AS debits,
57286              COALESCE(flrpt_credits, 0.00) AS credits,
57287              COALESCE(flrpt_budget, 0.00) AS budget,
57288              COALESCE(flrpt_diff, 0.00) AS diff,
57289              COALESCE(flrpt_custom, 0.00) AS custom INTO _g
57290         FROM flrpt
57291        WHERE ((flrpt_flhead_id=pFlheadid)
57292          AND  (flrpt_period_id=pPeriodid)
57293           AND (flrpt_interval=pInterval)
57294          AND  (flrpt_username=getEffectiveXtUser())
57295          AND  (flrpt_type=_r.type)
57296          AND  (flrpt_type_id=_r.type_id));
57297       IF (_r.subtract) THEN
57298         UPDATE flrpt
57299            SET flrpt_beginning = flrpt_beginning - _g.beginning,
57300                flrpt_ending    = flrpt_ending    - _g.ending,
57301                flrpt_debits    = flrpt_debits    - _g.debits,
57302                flrpt_credits   = flrpt_credits   - _g.credits,
57303                flrpt_budget    = flrpt_budget    - _g.budget,
57304                flrpt_diff      = flrpt_diff      - _g.diff,
57305                flrpt_custom    = flrpt_custom    - _g.custom
57306          WHERE ((flrpt_flhead_id=pFlheadid)
57307            AND  (flrpt_period_id=pPeriodid)
57308            AND  (flrpt_interval=pInterval)
57309            AND  (flrpt_username=getEffectiveXtUser())
57310            AND  (flrpt_type='G')
57311            AND  (flrpt_type_id=pFlgrpid));
57312       ELSE
57313         UPDATE flrpt
57314            SET flrpt_beginning = flrpt_beginning + _g.beginning,
57315                flrpt_ending    = flrpt_ending    + _g.ending,
57316                flrpt_debits    = flrpt_debits    + _g.debits,
57317                flrpt_credits   = flrpt_credits   + _g.credits,
57318                flrpt_budget    = flrpt_budget    + _g.budget,
57319                flrpt_diff      = flrpt_diff      + _g.diff,
57320                flrpt_custom    = flrpt_custom    + _g.custom
57321          WHERE ((flrpt_flhead_id=pFlheadid)
57322            AND  (flrpt_period_id=pPeriodid)
57323            AND  (flrpt_interval=pInterval)
57324            AND  (flrpt_username=getEffectiveXtUser())
57325            AND  (flrpt_type='G')
57326            AND  (flrpt_type_id=pFlgrpid));
57327       END IF;
57328
57329 -- If we are summarizing then we need to remove the record we created now that we have updated the total
57330       IF (pSummarize) THEN
57331         DELETE FROM flrpt
57332          WHERE ((flrpt_flhead_id=pFlheadid)
57333           AND  (flrpt_period_id=pPeriodid)
57334           AND  (flrpt_interval=pInterval)
57335           AND  (flrpt_username=getEffectiveXtUser())
57336           AND  (flrpt_type=_r.type)
57337           AND  (flrpt_type_id=_r.type_id));
57338       END IF;
57339
57340     ELSE
57341       IF (_r.type = 'I' OR _r.type = 'S' ) THEN
57342
57343 -- If we are not summarizing then create a new entry for this record
57344         IF (NOT pSummarize) THEN
57345           INSERT INTO flrpt
57346                  (flrpt_flhead_id, flrpt_period_id, flrpt_username,
57347                   flrpt_order,
57348                   flrpt_level, flrpt_type, flrpt_type_id,
57349                   flrpt_beginning, flrpt_ending,
57350                   flrpt_debits, flrpt_credits, flrpt_budget, flrpt_diff, flrpt_custom,
57351                   flrpt_beginningprcnt, flrpt_endingprcnt,
57352                   flrpt_debitsprcnt, flrpt_creditsprcnt, flrpt_budgetprcnt, flrpt_diffprcnt, flrpt_customprcnt,
57353                   flrpt_parent_id,flrpt_accnt_id,flrpt_interval)
57354           VALUES (pFlheadid, pPeriodid, getEffectiveXtUser(),
57355                   (COALESCE(( SELECT MAX(flrpt_order)
57356                                FROM flrpt
57357                               WHERE ((flrpt_flhead_id=pFlheadid)
57358                                 AND  (flrpt_period_id=pPeriodid)
57359                                 AND  (flrpt_interval=pInterval)
57360                                 AND  (flrpt_username=getEffectiveXtUser()))
57361                             ), 1) + 1),
57362                   pLevel, _r.type, _r.type_id,
57363                   _r.beginning, _r.ending,
57364                   _r.debits, _r.credits, _r.budget, _r.diff, _r.custom,
57365                   _r.beginningprcnt, _r.endingprcnt,
57366                   _r.debitsprcnt, _r.creditsprcnt, _r.budgetprcnt, _r.diffprcnt, _r.customprcnt,
57367                   pFlgrpid,_r.accnt_id,pInterval);
57368         END IF;
57369
57370 -- Update the parent item
57371         IF (_r.subtract) THEN
57372           UPDATE flrpt
57373              SET flrpt_beginning = flrpt_beginning - COALESCE(_r.beginning, 0.00),
57374                  flrpt_ending    = flrpt_ending    - COALESCE(_r.ending, 0.00),
57375                  flrpt_debits    = flrpt_debits    - COALESCE(_r.debits, 0.00),
57376                  flrpt_credits   = flrpt_credits   - COALESCE(_r.credits, 0.00),
57377                  flrpt_budget    = flrpt_budget    - COALESCE(_r.budget, 0.00),
57378                  flrpt_diff      = flrpt_diff      - COALESCE(_r.diff, 0.00),
57379                  flrpt_custom    = flrpt_custom    - COALESCE(_r.custom, 0.00)
57380            WHERE ((flrpt_flhead_id=pFlheadid)
57381              AND  (flrpt_period_id=pPeriodid)
57382              AND  (flrpt_interval=pInterval)
57383              AND  (flrpt_username=getEffectiveXtUser())
57384              AND  (flrpt_type='G')
57385              AND  (flrpt_type_id=pFlgrpid));
57386         ELSE
57387           UPDATE flrpt
57388              SET flrpt_beginning = flrpt_beginning + COALESCE(_r.beginning, 0.00),
57389                  flrpt_ending    = flrpt_ending    + COALESCE(_r.ending, 0.00),
57390                  flrpt_debits    = flrpt_debits    + COALESCE(_r.debits, 0.00),
57391                  flrpt_credits   = flrpt_credits   + COALESCE(_r.credits, 0.00),
57392                  flrpt_budget    = flrpt_budget    + COALESCE(_r.budget, 0.00),
57393                  flrpt_diff      = flrpt_diff      + COALESCE(_r.diff, 0.00),
57394                  flrpt_custom    = flrpt_custom    + COALESCE(_r.custom, 0.00)
57395            WHERE ((flrpt_flhead_id=pFlheadid)
57396              AND  (flrpt_interval=pInterval)
57397              AND  (flrpt_period_id=pPeriodid)
57398              AND  (flrpt_username=getEffectiveXtUser())
57399              AND  (flrpt_type='G')
57400              AND  (flrpt_type_id=pFlgrpid));
57401         END IF;
57402
57403       END IF;
57404     END IF;
57405
57406   END LOOP;
57407
57408   IF (NOT pSummarize) THEN
57409 -- If this group wants a summarized line create it here.
57410     IF (_subtotal) THEN
57411       INSERT INTO flrpt
57412              (flrpt_flhead_id, flrpt_period_id, flrpt_username,
57413               flrpt_order,
57414               flrpt_level, flrpt_type, flrpt_type_id,
57415               flrpt_beginning, flrpt_ending,
57416               flrpt_debits, flrpt_credits, flrpt_budget, flrpt_diff, flrpt_custom,
57417               flrpt_beginningprcnt, flrpt_endingprcnt,
57418               flrpt_debitsprcnt, flrpt_creditsprcnt, flrpt_budgetprcnt, flrpt_diffprcnt, flrpt_customprcnt,
57419               flrpt_parent_id, flrpt_altname,flrpt_interval )
57420       SELECT pFlheadid, pPeriodid, getEffectiveXtUser(),
57421              (COALESCE(( SELECT MAX(flrpt_order)
57422                            FROM flrpt
57423                           WHERE ((flrpt_flhead_id=pFlheadid)
57424                             AND  (flrpt_period_id=pPeriodid)
57425                             AND  (flrpt_interval=pInterval)
57426                             AND  (flrpt_username=getEffectiveXtUser()))
57427                        ), 1) + 1),
57428              pLevel, 'T', -1,
57429              CASE WHEN (flgrp_showstart) THEN flrpt_beginning
57430                   ELSE NULL
57431              END,
57432              CASE WHEN (flgrp_showend) THEN flrpt_ending
57433                   ELSE NULL
57434              END,
57435              CASE WHEN (flgrp_showdelta) THEN flrpt_debits
57436                   ELSE NULL
57437              END,
57438              CASE WHEN (flgrp_showdelta) THEN flrpt_credits
57439                   ELSE NULL
57440              END,
57441              CASE WHEN (flgrp_showbudget) THEN flrpt_budget
57442                   ELSE NULL
57443              END,
57444              CASE WHEN (flgrp_showdiff) THEN flrpt_diff
57445                   ELSE NULL
57446              END,
57447              CASE WHEN (flgrp_showcustom) THEN flrpt_custom
57448                   ELSE NULL
57449              END,
57450              CASE WHEN (flgrp_showstartprcnt) THEN flrpt_beginningprcnt
57451                   ELSE NULL
57452              END,
57453              CASE WHEN (flgrp_showendprcnt) THEN flrpt_endingprcnt
57454                   ELSE NULL
57455              END,
57456              CASE WHEN (flgrp_showdeltaprcnt) THEN flrpt_debitsprcnt
57457                   ELSE NULL
57458              END,
57459              CASE WHEN (flgrp_showdeltaprcnt) THEN flrpt_creditsprcnt
57460                   ELSE NULL
57461              END,
57462              CASE WHEN (flgrp_showbudgetprcnt) THEN flrpt_budgetprcnt
57463                   ELSE NULL
57464              END,
57465              CASE WHEN (flgrp_showdiffprcnt) THEN flrpt_diffprcnt
57466                   ELSE NULL
57467              END,
57468              CASE WHEN (flgrp_showcustomprcnt) THEN flrpt_customprcnt
57469                   ELSE NULL
57470              END,
57471              pFlgrpid,
57472              CASE WHEN (flgrp_usealtsubtotal) THEN flgrp_altsubtotal
57473                   ELSE NULL
57474              END, pInterval
57475         FROM flrpt, flgrp
57476        WHERE ((flrpt_flhead_id=flgrp_flhead_id)
57477          AND  (flrpt_type_id=flgrp_id)
57478          AND  (flrpt_flhead_id=pFlheadid)
57479          AND  (flrpt_period_id=pPeriodid)
57480          AND  (flrpt_interval=pInterval)
57481          AND  (flrpt_username=getEffectiveXtUser())
57482          AND  (flrpt_type='G')
57483          AND  (flrpt_type_id=pFlgrpid));
57484     END IF;
57485   END IF;
57486
57487   return TRUE;
57488 END;
57489 $_$;
57490
57491
57492 ALTER FUNCTION public.insertflgroup(integer, integer, integer, integer, boolean, character, integer) OWNER TO admin;
57493
57494 --
57495 -- TOC entry 1820 (class 1255 OID 146566563)
57496 -- Dependencies: 4536 8
57497 -- Name: insertgltransaction(text, text, text, text, integer, integer, integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
57498 --
57499
57500 CREATE FUNCTION insertgltransaction(text, text, text, text, integer, integer, integer, numeric, date) RETURNS integer
57501     LANGUAGE plpgsql
57502     AS $_$
57503 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57504 -- See www.xtuple.com/CPAL for the full text of the software license.
57505 DECLARE
57506   pSource ALIAS FOR $1;
57507   pDocType ALIAS FOR $2;
57508   pDocNumber ALIAS FOR $3;
57509   pNotes ALIAS FOR $4;
57510   pCreditid ALIAS FOR $5;
57511   pDebitid ALIAS FOR $6;
57512   pMiscid ALIAS FOR $7;
57513   pAmount ALIAS FOR $8;
57514   pDistDate ALIAS FOR $9;
57515   _return INTEGER;
57516
57517 BEGIN
57518
57519   SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'),
57520                               pSource, pDocType, pDocNumber, pNotes,
57521                               pCreditid, pDebitid, pMiscid, pAmount, pDistDate) INTO _return;
57522
57523   RETURN _return;
57524
57525 END;
57526 $_$;
57527
57528
57529 ALTER FUNCTION public.insertgltransaction(text, text, text, text, integer, integer, integer, numeric, date) OWNER TO admin;
57530
57531 --
57532 -- TOC entry 1821 (class 1255 OID 146566564)
57533 -- Dependencies: 4536 8
57534 -- Name: insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
57535 --
57536
57537 CREATE FUNCTION insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date) RETURNS integer
57538     LANGUAGE plpgsql
57539     AS $_$
57540 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57541 -- See www.xtuple.com/CPAL for the full text of the software license.
57542 DECLARE
57543   pJournalNumber ALIAS FOR $1;
57544   pSource ALIAS FOR $2;
57545   pDocType ALIAS FOR $3;
57546   pDocNumber ALIAS FOR $4;
57547   pNotes ALIAS FOR $5;
57548   pCreditid ALIAS FOR $6;
57549   pDebitid ALIAS FOR $7;
57550   pMiscid ALIAS FOR $8;
57551   pAmount ALIAS FOR $9;
57552   pDistDate ALIAS FOR $10;
57553   _return INTEGER;
57554
57555 BEGIN
57556
57557   SELECT insertGLTransaction( pJournalNumber, pSource, pDocType, pDocNumber, pNotes,
57558                               pCreditid, pDebitid, pMiscid, pAmount, pDistDate, TRUE) INTO _return;
57559
57560   RETURN _return;
57561
57562 END;
57563 $_$;
57564
57565
57566 ALTER FUNCTION public.insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date) OWNER TO admin;
57567
57568 --
57569 -- TOC entry 1822 (class 1255 OID 146566565)
57570 -- Dependencies: 4536 8
57571 -- Name: insertgltransaction(text, text, text, text, integer, integer, integer, numeric, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
57572 --
57573
57574 CREATE FUNCTION insertgltransaction(text, text, text, text, integer, integer, integer, numeric, date, boolean) RETURNS integer
57575     LANGUAGE plpgsql
57576     AS $_$
57577 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57578 -- See www.xtuple.com/CPAL for the full text of the software license.
57579 DECLARE
57580   pSource ALIAS FOR $1;
57581   pDocType ALIAS FOR $2;
57582   pDocNumber ALIAS FOR $3;
57583   pNotes ALIAS FOR $4;
57584   pCreditid ALIAS FOR $5;
57585   pDebitid ALIAS FOR $6;
57586   pMiscid ALIAS FOR $7;
57587   pAmount ALIAS FOR $8;
57588   pDistDate ALIAS FOR $9;
57589   pPostTrialBal ALIAS FOR $10;
57590   _return INTEGER;
57591
57592 BEGIN
57593
57594   SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'),
57595                               pSource, pDocType, pDocNumber, pNotes,
57596                               pCreditid, pDebitid, pMiscid, pAmount, pDistDate, pPostTrialBal) INTO _return;
57597
57598   RETURN _return;
57599
57600 END;
57601 $_$;
57602
57603
57604 ALTER FUNCTION public.insertgltransaction(text, text, text, text, integer, integer, integer, numeric, date, boolean) OWNER TO admin;
57605
57606 --
57607 -- TOC entry 1823 (class 1255 OID 146566566)
57608 -- Dependencies: 4536 8
57609 -- Name: insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
57610 --
57611
57612 CREATE FUNCTION insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date, boolean) RETURNS integer
57613     LANGUAGE plpgsql
57614     AS $_$
57615 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57616 -- See www.xtuple.com/CPAL for the full text of the software license.
57617 DECLARE
57618   pJournalNumber ALIAS FOR $1;
57619   pSource ALIAS FOR $2;
57620   pDocType ALIAS FOR $3;
57621   pDocNumber ALIAS FOR $4;
57622   pNotes ALIAS FOR $5;
57623   pCreditid ALIAS FOR $6;
57624   pDebitid ALIAS FOR $7;
57625   pMiscid ALIAS FOR $8;
57626   pAmount ALIAS FOR $9;
57627   pDistDate ALIAS FOR $10;
57628   pPostTrialBal ALIAS FOR $11;
57629   
57630   _return INTEGER;
57631
57632 BEGIN
57633
57634   SELECT insertGLTransaction( pJournalNumber, pSource, pDocType, pDocNumber, pNotes,
57635                               pCreditid, pDebitid, pMiscid, pAmount, pDistDate, pPostTrialBal, false) INTO _return;
57636
57637   RETURN _return;
57638
57639 END;
57640 $_$;
57641
57642
57643 ALTER FUNCTION public.insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date, boolean) OWNER TO admin;
57644
57645 --
57646 -- TOC entry 1824 (class 1255 OID 146566567)
57647 -- Dependencies: 4536 8
57648 -- Name: insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
57649 --
57650
57651 CREATE FUNCTION insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date, boolean, boolean) RETURNS integer
57652     LANGUAGE plpgsql
57653     AS $_$
57654 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57655 -- See www.xtuple.com/CPAL for the full text of the software license.
57656 DECLARE
57657   pJournalNumber ALIAS FOR $1;
57658   pSource ALIAS FOR $2;
57659   pDocType ALIAS FOR $3;
57660   pDocNumber ALIAS FOR $4;
57661   pNotes ALIAS FOR $5;
57662   pCreditid ALIAS FOR $6;
57663   pDebitid ALIAS FOR $7;
57664   pMiscid ALIAS FOR $8;
57665   pAmount ALIAS FOR $9;
57666   pDistDate ALIAS FOR $10;
57667   pPostTrialBal ALIAS FOR $11;
57668   pOnlyGL ALIAS FOR $12;
57669   _debitid INTEGER;
57670   _creditid INTEGER;
57671   _sequence INTEGER;
57672   _check INTEGER;
57673
57674 BEGIN
57675
57676 --  Check GL Interface metric
57677   IF (fetchMetricBool('InterfaceToGL') = false AND pSource IN ('I/M', 'P/D', 'S/R', 'W/O')) THEN
57678     RETURN 0;
57679   END IF;
57680   IF (fetchMetricBool('InterfaceAPToGL') = false AND pSource = 'A/P') THEN
57681     RETURN 0;
57682   END IF;
57683   IF (fetchMetricBool('InterfaceARToGL') = false AND pSource IN ('A/R', 'S/O', 'S/R')) THEN
57684     RETURN 0;
57685   END IF;
57686
57687 --  Is there anything to post?
57688 --  ToDo - 2 should really be the scale of the base currency
57689   IF (round(pAmount, 2) = 0) THEN
57690     RETURN -3;
57691   END IF;
57692
57693 /*  Make sure we don't create an imbalance across companies.
57694     The 'IgnoreCompanyBalance' metric is a back door mechanism to
57695     allow legacy users to create transactions accross companies if
57696     they have been using the company segment for something else
57697     and they MUST continue to be able to do so.  It can only be 
57698     implemented by direct sql update to the metric table and should 
57699     otherwise be discouraged.
57700 */ 
57701   IF (COALESCE(fetchMetricValue('GLCompanySize'),0) > 0 
57702     AND fetchMetricBool('IgnoreCompany') = false)  THEN
57703
57704     IF (SELECT (COALESCE(d.accnt_company,'') != COALESCE(c.accnt_company,''))
57705        FROM accnt d, accnt c
57706        WHERE ((d.accnt_id=pDebitid)
57707         AND (c.accnt_id=pCreditid))) THEN
57708       RAISE EXCEPTION 'G/L Transaction can not be posted because accounts % and % reference two differnt companies.',
57709         formatGlaccount(pDebitid), formatGlaccount(pCreditid);
57710     END IF;
57711   END IF;
57712
57713 --  Validate pDebitid
57714   IF (pDebitid IN (SELECT accnt_id FROM accnt)) THEN
57715     _debitid := pDebitid;
57716   ELSE
57717     SELECT getUnassignedAccntId() INTO _debitid;
57718   END IF;
57719
57720 --  Validate pCreditid
57721   IF (pCreditid IN (SELECT accnt_id FROM accnt)) THEN
57722     _creditid := pCreditid;
57723   ELSE
57724     SELECT getUnassignedAccntId() INTO _creditid;
57725   END IF;
57726
57727 -- refuse to accept postings into closed periods
57728   IF (SELECT BOOL_AND(COALESCE(period_closed, FALSE))
57729       FROM accnt LEFT OUTER JOIN
57730            period ON (pDistDate BETWEEN period_start AND period_end)
57731       WHERE (accnt_id IN (_creditid, _debitid))) THEN
57732     RAISE EXCEPTION 'Cannot post to closed period (%).', pDistDate;
57733     RETURN -4;  -- remove raise exception when all callers check return code
57734   END IF;
57735
57736 -- refuse to accept postings into frozen periods without proper priv
57737   IF (SELECT NOT BOOL_AND(checkPrivilege('PostFrozenPeriod')) AND
57738              BOOL_AND(COALESCE(period_freeze, FALSE))
57739       FROM accnt LEFT OUTER JOIN
57740            period ON (pDistDate BETWEEN period_start AND period_end)
57741       WHERE (accnt_id IN (_creditid, _debitid))) THEN
57742     RAISE EXCEPTION 'Cannot post to frozen period (%).', pDistDate;
57743     RETURN -4;  -- remove raise exception when all callers check return code
57744   END IF;
57745
57746 -- refuse to accept postings into nonexistent periods
57747   IF NOT EXISTS(SELECT period_id
57748                 FROM period
57749                 WHERE (pDistDate BETWEEN period_start AND period_end)) THEN
57750     RAISE EXCEPTION 'Cannot post to nonexistent period (%).', pDistDate;
57751   END IF;
57752
57753 --  Grab a sequence for the pair
57754   SELECT fetchGLSequence() INTO _sequence;
57755
57756   IF (NOT pOnlyGL AND fetchMetricBool('UseJournals')) THEN
57757   --  First the credit  
57758     INSERT INTO sltrans
57759     ( sltrans_journalnumber, sltrans_posted, sltrans_created, sltrans_date,
57760       sltrans_sequence, sltrans_accnt_id, sltrans_source,
57761       sltrans_doctype, sltrans_docnumber, sltrans_notes,
57762       sltrans_misc_id, sltrans_amount )
57763     VALUES
57764     ( pJournalNumber, FALSE, CURRENT_TIMESTAMP, pDistDate,
57765       _sequence, _creditid, pSource,
57766       pDocType, pDocNumber, pNotes,
57767       pMiscid, pAmount );
57768
57769   --  Now the debit
57770     INSERT INTO sltrans
57771     ( sltrans_journalnumber, sltrans_posted, sltrans_created, sltrans_date,
57772       sltrans_sequence, sltrans_accnt_id, sltrans_source,
57773       sltrans_doctype, sltrans_docnumber, sltrans_notes,
57774       sltrans_misc_id, sltrans_amount )
57775     VALUES
57776     ( pJournalNumber, FALSE, CURRENT_TIMESTAMP, pDistDate,
57777       _sequence, _debitid, pSource,
57778       pDocType, pDocNumber, pNotes,
57779       pMiscid, (pAmount * -1) );
57780   ELSE
57781   --  First the credit
57782     INSERT INTO gltrans
57783     ( gltrans_journalnumber, gltrans_posted, gltrans_exported, gltrans_created, gltrans_date,
57784       gltrans_sequence, gltrans_accnt_id, gltrans_source,
57785       gltrans_doctype, gltrans_docnumber, gltrans_notes,
57786       gltrans_misc_id, gltrans_amount )
57787     VALUES
57788     ( pJournalNumber, FALSE, FALSE, CURRENT_TIMESTAMP, pDistDate,
57789       _sequence, _creditid, pSource,
57790       pDocType, pDocNumber, pNotes,
57791       pMiscid, pAmount );
57792
57793   --  Now the debit
57794     INSERT INTO gltrans
57795     ( gltrans_journalnumber, gltrans_posted, gltrans_exported, gltrans_created, gltrans_date,
57796       gltrans_sequence, gltrans_accnt_id, gltrans_source,
57797       gltrans_doctype, gltrans_docnumber, gltrans_notes,
57798       gltrans_misc_id, gltrans_amount )
57799     VALUES
57800     ( pJournalNumber, FALSE, FALSE, CURRENT_TIMESTAMP, pDistDate,
57801       _sequence, _debitid, pSource,
57802       pDocType, pDocNumber, pNotes,
57803       pMiscid, (pAmount * -1) );
57804
57805     IF (pPostTrialBal) THEN
57806       PERFORM postIntoTrialBalance(_sequence);
57807     END IF;
57808   END IF;
57809
57810   RETURN _sequence;
57811
57812 END;
57813 $_$;
57814
57815
57816 ALTER FUNCTION public.insertgltransaction(integer, text, text, text, text, integer, integer, integer, numeric, date, boolean, boolean) OWNER TO admin;
57817
57818 --
57819 -- TOC entry 1825 (class 1255 OID 146566569)
57820 -- Dependencies: 4536 8
57821 -- Name: insertintoglseries(integer, text, text, text, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
57822 --
57823
57824 CREATE FUNCTION insertintoglseries(integer, text, text, text, integer, numeric) RETURNS integer
57825     LANGUAGE plpgsql
57826     AS $_$
57827 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57828 -- See www.xtuple.com/CPAL for the full text of the software license.
57829 DECLARE
57830   pSequence ALIAS FOR $1;
57831   pSource ALIAS FOR $2;
57832   pDocType ALIAS FOR $3;
57833   pDocNumber ALIAS FOR $4;
57834   pAccntid ALIAS FOR $5;
57835   pAmount ALIAS FOR $6;
57836   _returnValue INTEGER;
57837
57838 BEGIN
57839
57840   SELECT insertIntoGLSeries( pSequence, pSource, pDocType, pDocNumber,
57841                              pAccntid, pAmount, CURRENT_DATE, '' ) INTO _returnValue;
57842
57843   RETURN _returnValue;
57844
57845 END;
57846 $_$;
57847
57848
57849 ALTER FUNCTION public.insertintoglseries(integer, text, text, text, integer, numeric) OWNER TO admin;
57850
57851 --
57852 -- TOC entry 1826 (class 1255 OID 146566570)
57853 -- Dependencies: 4536 8
57854 -- Name: insertintoglseries(integer, text, text, text, integer, numeric, date); Type: FUNCTION; Schema: public; Owner: admin
57855 --
57856
57857 CREATE FUNCTION insertintoglseries(integer, text, text, text, integer, numeric, date) RETURNS integer
57858     LANGUAGE plpgsql
57859     AS $_$
57860 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57861 -- See www.xtuple.com/CPAL for the full text of the software license.
57862 DECLARE
57863   pSequence ALIAS FOR $1;
57864   pSource ALIAS FOR $2;
57865   pDocType ALIAS FOR $3;
57866   pDocNumber ALIAS FOR $4;
57867   pAccntid ALIAS FOR $5;
57868   pAmount ALIAS FOR $6;
57869   pDistDate ALIAS FOR $7;
57870   _returnValue INTEGER;
57871
57872 BEGIN
57873
57874   SELECT insertIntoGLSeries( pSequence, pSource, pDocType, pDocNumber,
57875                              pAccntid, pAmount, pDistDate, '' ) INTO _returnValue;
57876
57877   RETURN _returnValue;
57878
57879 END;
57880 $_$;
57881
57882
57883 ALTER FUNCTION public.insertintoglseries(integer, text, text, text, integer, numeric, date) OWNER TO admin;
57884
57885 --
57886 -- TOC entry 1827 (class 1255 OID 146566571)
57887 -- Dependencies: 4536 8
57888 -- Name: insertintoglseries(integer, text, text, text, integer, numeric, date, text); Type: FUNCTION; Schema: public; Owner: admin
57889 --
57890
57891 CREATE FUNCTION insertintoglseries(integer, text, text, text, integer, numeric, date, text) RETURNS integer
57892     LANGUAGE plpgsql
57893     AS $_$
57894 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57895 -- See www.xtuple.com/CPAL for the full text of the software license.
57896 DECLARE
57897   pSequence ALIAS FOR $1;
57898   pSource ALIAS FOR $2;
57899   pDocType ALIAS FOR $3;
57900   pDocNumber ALIAS FOR $4;
57901   pAccntid ALIAS FOR $5;
57902   pAmount ALIAS FOR $6;
57903   pDistDate ALIAS FOR $7;
57904   pNotes ALIAS FOR $8;
57905   _returnValue INTEGER;
57906
57907 BEGIN
57908
57909   SELECT insertIntoGLSeries( pSequence, pSource, pDocType, pDocNumber,
57910                              pAccntid, pAmount, pDistDate, pNotes, NULL ) INTO _returnValue;
57911
57912   RETURN _returnValue;
57913
57914 END;
57915 $_$;
57916
57917
57918 ALTER FUNCTION public.insertintoglseries(integer, text, text, text, integer, numeric, date, text) OWNER TO admin;
57919
57920 --
57921 -- TOC entry 1828 (class 1255 OID 146566572)
57922 -- Dependencies: 4536 8
57923 -- Name: insertintoglseries(integer, text, text, text, integer, numeric, date, text, integer); Type: FUNCTION; Schema: public; Owner: admin
57924 --
57925
57926 CREATE FUNCTION insertintoglseries(integer, text, text, text, integer, numeric, date, text, integer) RETURNS integer
57927     LANGUAGE plpgsql
57928     AS $_$
57929 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
57930 -- See www.xtuple.com/CPAL for the full text of the software license.
57931 DECLARE
57932   pSequence ALIAS FOR $1;
57933   pSource ALIAS FOR $2;
57934   pDocType ALIAS FOR $3;
57935   pDocNumber ALIAS FOR $4;
57936   pAccntid ALIAS FOR $5;
57937   pAmount ALIAS FOR $6;
57938   pDistDate ALIAS FOR $7;
57939   pNotes ALIAS FOR $8;
57940   pMiscid ALIAS FOR $9;
57941   _glseriesid INTEGER;
57942
57943 BEGIN
57944
57945 --  Check GL Interface metric
57946   IF (fetchMetricBool('InterfaceToGL') = false AND pSource IN ('I/M', 'P/D', 'S/R', 'W/O')) THEN
57947     RETURN 0;
57948   END IF;
57949   IF (fetchMetricBool('InterfaceAPToGL') = false AND pSource = 'A/P') THEN
57950     RETURN 0;
57951   END IF;
57952   IF (fetchMetricBool('InterfaceARToGL') = false AND pSource IN ('A/R', 'S/O', 'S/R')) THEN
57953     RETURN 0;
57954   END IF;
57955
57956 --  Verify the target accnt
57957   IF ( (pAccntid IS NULL) OR (pAccntid = -1) ) THEN
57958     RETURN -1;
57959   END IF;
57960
57961 -- refuse to accept postings into closed periods
57962   IF (SELECT BOOL_AND(COALESCE(period_closed, FALSE))
57963       FROM accnt LEFT OUTER JOIN
57964            period ON (pDistDate BETWEEN period_start AND period_end)
57965       WHERE (accnt_id = pAccntid)) THEN
57966     RAISE EXCEPTION 'Cannot post to closed period (%).', pDistDate;
57967     RETURN -4;  -- remove raise exception when all callers check return code
57968   END IF;
57969
57970 -- refuse to accept postings into frozen periods without proper priv
57971   IF (SELECT NOT BOOL_AND(checkPrivilege('PostFrozenPeriod')) AND
57972              BOOL_AND(COALESCE(period_freeze, FALSE))
57973       FROM accnt LEFT OUTER JOIN
57974            period ON (pDistDate BETWEEN period_start AND period_end)
57975       WHERE (accnt_id = pAccntid)) THEN
57976     RAISE EXCEPTION 'Cannot post to frozen period (%).', pDistDate;
57977     RETURN -4;  -- remove raise exception when all callers check return code
57978   END IF;
57979
57980 -- refuse to accept postings into nonexistent periods
57981   IF NOT EXISTS(SELECT period_id
57982                 FROM period
57983                 WHERE (pDistDate BETWEEN period_start AND period_end)) THEN
57984     RAISE EXCEPTION 'Cannot post to nonexistent period (%).', pDistDate;
57985   END IF;
57986
57987 -- Insert into the glseries
57988   SELECT NEXTVAL('glseries_glseries_id_seq') INTO _glseriesid;
57989   INSERT INTO glseries
57990   ( glseries_id, glseries_sequence, glseries_source, glseries_doctype, glseries_docnumber,
57991     glseries_accnt_id, glseries_amount, glseries_distdate, glseries_notes, glseries_misc_id )
57992   VALUES
57993   ( _glseriesid, pSequence, pSource, pDocType, pDocNumber,
57994     pAccntid, pAmount, pDistDate, pNotes, pMiscid );
57995
57996   RETURN _glseriesid;
57997
57998 END;
57999 $_$;
58000
58001
58002 ALTER FUNCTION public.insertintoglseries(integer, text, text, text, integer, numeric, date, text, integer) OWNER TO admin;
58003
58004 --
58005 -- TOC entry 224 (class 1259 OID 146566573)
58006 -- Dependencies: 6022 6023 6024 6026 8
58007 -- Name: invchead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
58008 --
58009
58010 CREATE TABLE invchead (
58011     invchead_id integer NOT NULL,
58012     invchead_cust_id integer NOT NULL,
58013     invchead_shipto_id integer,
58014     invchead_ordernumber text,
58015     invchead_orderdate date,
58016     invchead_posted boolean NOT NULL,
58017     invchead_printed boolean NOT NULL,
58018     invchead_invcnumber text NOT NULL,
58019     invchead_invcdate date NOT NULL,
58020     invchead_shipdate date,
58021     invchead_ponumber text,
58022     invchead_shipvia text,
58023     invchead_fob text,
58024     invchead_billto_name text,
58025     invchead_billto_address1 text,
58026     invchead_billto_address2 text,
58027     invchead_billto_address3 text,
58028     invchead_billto_city text,
58029     invchead_billto_state text,
58030     invchead_billto_zipcode text,
58031     invchead_billto_phone text,
58032     invchead_shipto_name text,
58033     invchead_shipto_address1 text,
58034     invchead_shipto_address2 text,
58035     invchead_shipto_address3 text,
58036     invchead_shipto_city text,
58037     invchead_shipto_state text,
58038     invchead_shipto_zipcode text,
58039     invchead_shipto_phone text,
58040     invchead_salesrep_id integer,
58041     invchead_commission numeric(20,10) NOT NULL,
58042     invchead_terms_id integer,
58043     invchead_freight numeric(16,2) NOT NULL,
58044     invchead_misc_amount numeric(16,2) NOT NULL,
58045     invchead_misc_descrip text,
58046     invchead_misc_accnt_id integer,
58047     invchead_payment numeric(16,2),
58048     invchead_paymentref text,
58049     invchead_notes text,
58050     invchead_billto_country text,
58051     invchead_shipto_country text,
58052     invchead_prj_id integer,
58053     invchead_curr_id integer DEFAULT basecurrid(),
58054     invchead_gldistdate date,
58055     invchead_recurring boolean DEFAULT false NOT NULL,
58056     invchead_recurring_interval integer,
58057     invchead_recurring_type text,
58058     invchead_recurring_until date,
58059     invchead_recurring_invchead_id integer,
58060     invchead_shipchrg_id integer,
58061     invchead_taxzone_id integer,
58062     invchead_void boolean DEFAULT false,
58063     invchead_saletype_id integer,
58064     invchead_shipzone_id integer,
58065     CONSTRAINT invchead_invchead_invcnumber_check CHECK ((invchead_invcnumber <> ''::text))
58066 );
58067
58068
58069 ALTER TABLE public.invchead OWNER TO admin;
58070
58071 --
58072 -- TOC entry 9039 (class 0 OID 0)
58073 -- Dependencies: 224
58074 -- Name: TABLE invchead; Type: COMMENT; Schema: public; Owner: admin
58075 --
58076
58077 COMMENT ON TABLE invchead IS 'Invoice header information';
58078
58079
58080 --
58081 -- TOC entry 9040 (class 0 OID 0)
58082 -- Dependencies: 224
58083 -- Name: COLUMN invchead.invchead_recurring; Type: COMMENT; Schema: public; Owner: admin
58084 --
58085
58086 COMMENT ON COLUMN invchead.invchead_recurring IS 'Deprecated.';
58087
58088
58089 --
58090 -- TOC entry 9041 (class 0 OID 0)
58091 -- Dependencies: 224
58092 -- Name: COLUMN invchead.invchead_recurring_interval; Type: COMMENT; Schema: public; Owner: admin
58093 --
58094
58095 COMMENT ON COLUMN invchead.invchead_recurring_interval IS 'Deprecated.';
58096
58097
58098 --
58099 -- TOC entry 9042 (class 0 OID 0)
58100 -- Dependencies: 224
58101 -- Name: COLUMN invchead.invchead_recurring_type; Type: COMMENT; Schema: public; Owner: admin
58102 --
58103
58104 COMMENT ON COLUMN invchead.invchead_recurring_type IS 'Deprecated.';
58105
58106
58107 --
58108 -- TOC entry 9043 (class 0 OID 0)
58109 -- Dependencies: 224
58110 -- Name: COLUMN invchead.invchead_recurring_until; Type: COMMENT; Schema: public; Owner: admin
58111 --
58112
58113 COMMENT ON COLUMN invchead.invchead_recurring_until IS 'Deprecated.';
58114
58115
58116 --
58117 -- TOC entry 9044 (class 0 OID 0)
58118 -- Dependencies: 224
58119 -- Name: COLUMN invchead.invchead_saletype_id; Type: COMMENT; Schema: public; Owner: admin
58120 --
58121
58122 COMMENT ON COLUMN invchead.invchead_saletype_id IS 'Associated sale type for invoice.';
58123
58124
58125 --
58126 -- TOC entry 9045 (class 0 OID 0)
58127 -- Dependencies: 224
58128 -- Name: COLUMN invchead.invchead_shipzone_id; Type: COMMENT; Schema: public; Owner: admin
58129 --
58130
58131 COMMENT ON COLUMN invchead.invchead_shipzone_id IS 'Associated shipping zone for invoice.';
58132
58133
58134 --
58135 -- TOC entry 225 (class 1259 OID 146566583)
58136 -- Dependencies: 6028 6029 8
58137 -- Name: prj; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
58138 --
58139
58140 CREATE TABLE prj (
58141     prj_id integer NOT NULL,
58142     prj_number text NOT NULL,
58143     prj_name text NOT NULL,
58144     prj_descrip text,
58145     prj_status character(1) NOT NULL,
58146     prj_so boolean,
58147     prj_wo boolean,
58148     prj_po boolean,
58149     prj_owner_username text,
58150     prj_start_date date,
58151     prj_due_date date,
58152     prj_assigned_date date,
58153     prj_completed_date date,
58154     prj_username text,
58155     prj_recurring_prj_id integer,
58156     prj_crmacct_id integer,
58157     prj_cntct_id integer,
58158     prj_prjtype_id integer,
58159     CONSTRAINT prj_prj_number_check CHECK ((prj_number <> ''::text)),
58160     CONSTRAINT prj_prj_status_check CHECK ((prj_status = ANY (ARRAY['P'::bpchar, 'O'::bpchar, 'C'::bpchar])))
58161 );
58162
58163
58164 ALTER TABLE public.prj OWNER TO admin;
58165
58166 --
58167 -- TOC entry 9047 (class 0 OID 0)
58168 -- Dependencies: 225
58169 -- Name: TABLE prj; Type: COMMENT; Schema: public; Owner: admin
58170 --
58171
58172 COMMENT ON TABLE prj IS 'Project information';
58173
58174
58175 --
58176 -- TOC entry 9048 (class 0 OID 0)
58177 -- Dependencies: 225
58178 -- Name: COLUMN prj.prj_recurring_prj_id; Type: COMMENT; Schema: public; Owner: admin
58179 --
58180
58181 COMMENT ON COLUMN prj.prj_recurring_prj_id IS 'The first prj record in the series if this is a recurring Project. If the prj_recurring_prj_id is the same as the prj_id, this record is the first in the series.';
58182
58183
58184 --
58185 -- TOC entry 226 (class 1259 OID 146566591)
58186 -- Dependencies: 6031 8
58187 -- Name: saletype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
58188 --
58189
58190 CREATE TABLE saletype (
58191     saletype_id integer NOT NULL,
58192     saletype_code text NOT NULL,
58193     saletype_descr text,
58194     saletype_active boolean DEFAULT true NOT NULL
58195 );
58196
58197
58198 ALTER TABLE public.saletype OWNER TO admin;
58199
58200 --
58201 -- TOC entry 9050 (class 0 OID 0)
58202 -- Dependencies: 226
58203 -- Name: TABLE saletype; Type: COMMENT; Schema: public; Owner: admin
58204 --
58205
58206 COMMENT ON TABLE saletype IS 'Type or Origination of Sale.';
58207
58208
58209 --
58210 -- TOC entry 9051 (class 0 OID 0)
58211 -- Dependencies: 226
58212 -- Name: COLUMN saletype.saletype_id; Type: COMMENT; Schema: public; Owner: admin
58213 --
58214
58215 COMMENT ON COLUMN saletype.saletype_id IS 'Sequence identifier for sale type.';
58216
58217
58218 --
58219 -- TOC entry 9052 (class 0 OID 0)
58220 -- Dependencies: 226
58221 -- Name: COLUMN saletype.saletype_code; Type: COMMENT; Schema: public; Owner: admin
58222 --
58223
58224 COMMENT ON COLUMN saletype.saletype_code IS 'User defined identifier for sale type.';
58225
58226
58227 --
58228 -- TOC entry 9053 (class 0 OID 0)
58229 -- Dependencies: 226
58230 -- Name: COLUMN saletype.saletype_descr; Type: COMMENT; Schema: public; Owner: admin
58231 --
58232
58233 COMMENT ON COLUMN saletype.saletype_descr IS 'Description for sale type.';
58234
58235
58236 --
58237 -- TOC entry 9054 (class 0 OID 0)
58238 -- Dependencies: 226
58239 -- Name: COLUMN saletype.saletype_active; Type: COMMENT; Schema: public; Owner: admin
58240 --
58241
58242 COMMENT ON COLUMN saletype.saletype_active IS 'Boolean to deactivate a sale type.';
58243
58244
58245 --
58246 -- TOC entry 227 (class 1259 OID 146566598)
58247 -- Dependencies: 6032 6033 8
58248 -- Name: shipzone; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
58249 --
58250
58251 CREATE TABLE shipzone (
58252     shipzone_id integer DEFAULT nextval(('shipzone_shipzone_id_seq'::text)::regclass) NOT NULL,
58253     shipzone_name text NOT NULL,
58254     shipzone_descrip text,
58255     CONSTRAINT shipzone_shipzone_name_check CHECK ((shipzone_name <> ''::text))
58256 );
58257
58258
58259 ALTER TABLE public.shipzone OWNER TO admin;
58260
58261 --
58262 -- TOC entry 9056 (class 0 OID 0)
58263 -- Dependencies: 227
58264 -- Name: TABLE shipzone; Type: COMMENT; Schema: public; Owner: admin
58265 --
58266
58267 COMMENT ON TABLE shipzone IS 'Shipping Zone information';
58268
58269
58270 SET search_path = api, pg_catalog;
58271
58272 --
58273 -- TOC entry 228 (class 1259 OID 146566606)
58274 -- Dependencies: 8475 6
58275 -- Name: invoice; Type: VIEW; Schema: api; Owner: admin
58276 --
58277
58278 CREATE VIEW invoice AS
58279     SELECT invchead.invchead_invcnumber AS invoice_number, invchead.invchead_ordernumber AS order_number, invchead.invchead_invcdate AS invoice_date, invchead.invchead_shipdate AS ship_date, invchead.invchead_orderdate AS order_date, saletype.saletype_code AS sale_type, salesrep.salesrep_number AS sales_rep, invchead.invchead_commission AS commission, COALESCE(taxzone.taxzone_code, 'None'::text) AS tax_zone, terms.terms_code AS terms, custinfo.cust_number AS customer_number, invchead.invchead_billto_name AS billto_name, invchead.invchead_billto_address1 AS billto_address1, invchead.invchead_billto_address2 AS billto_address2, invchead.invchead_billto_address3 AS billto_address3, invchead.invchead_billto_city AS billto_city, invchead.invchead_billto_state AS billto_state, invchead.invchead_billto_zipcode AS billto_postal_code, invchead.invchead_billto_country AS billto_country, invchead.invchead_billto_phone AS billto_phone, shiptoinfo.shipto_num AS shipto_number, invchead.invchead_shipto_name AS shipto_name, invchead.invchead_shipto_address1 AS shipto_address1, invchead.invchead_shipto_address2 AS shipto_address2, invchead.invchead_shipto_address3 AS shipto_address3, invchead.invchead_shipto_city AS shipto_city, invchead.invchead_shipto_state AS shipto_state, invchead.invchead_shipto_zipcode AS shipto_postal_code, invchead.invchead_shipto_country AS shipto_country, shipzone.shipzone_name AS shipto_shipzone, invchead.invchead_shipto_phone AS shipto_phone, invchead.invchead_ponumber AS po_number, invchead.invchead_shipvia AS ship_via, prj.prj_number AS project_number, invchead.invchead_fob AS fob, invchead.invchead_misc_descrip AS misc_charge_description, invchead.invchead_misc_amount AS misc_charge, CASE WHEN (invchead.invchead_misc_accnt_id = (-1)) THEN NULL::text ELSE public.formatglaccount(invchead.invchead_misc_accnt_id) END AS misc_charge_account_number, invchead.invchead_freight AS freight, curr.curr_abbr AS currency, invchead.invchead_payment AS payment, invchead.invchead_notes AS notes FROM (((((((((public.invchead LEFT JOIN public.custinfo ON ((custinfo.cust_id = invchead.invchead_cust_id))) LEFT JOIN public.shiptoinfo ON ((shiptoinfo.shipto_id = invchead.invchead_shipto_id))) LEFT JOIN public.prj ON ((prj.prj_id = invchead.invchead_prj_id))) LEFT JOIN public.curr_symbol curr ON ((curr.curr_id = invchead.invchead_curr_id))) LEFT JOIN public.salesrep ON ((salesrep.salesrep_id = invchead.invchead_salesrep_id))) LEFT JOIN public.terms ON ((terms.terms_id = invchead.invchead_terms_id))) LEFT JOIN public.taxzone ON ((taxzone.taxzone_id = invchead.invchead_taxzone_id))) LEFT JOIN public.saletype ON ((invchead.invchead_saletype_id = saletype.saletype_id))) LEFT JOIN public.shipzone ON ((invchead.invchead_shipzone_id = shipzone.shipzone_id)));
58280
58281
58282 ALTER TABLE api.invoice OWNER TO admin;
58283
58284 --
58285 -- TOC entry 9058 (class 0 OID 0)
58286 -- Dependencies: 228
58287 -- Name: VIEW invoice; Type: COMMENT; Schema: api; Owner: admin
58288 --
58289
58290 COMMENT ON VIEW invoice IS '
58291 This view can be used as an interface to import Invioce Header data directly  
58292 into the system.  Required fields will be checked and default values will be 
58293 populated';
58294
58295
58296 SET search_path = public, pg_catalog;
58297
58298 --
58299 -- TOC entry 1829 (class 1255 OID 146566611)
58300 -- Dependencies: 2868 4536 8
58301 -- Name: insertinvoice(api.invoice); Type: FUNCTION; Schema: public; Owner: admin
58302 --
58303
58304 CREATE FUNCTION insertinvoice(api.invoice) RETURNS boolean
58305     LANGUAGE plpgsql
58306     AS $_$
58307 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58308 -- See www.xtuple.com/CPAL for the full text of the software license.
58309 DECLARE
58310         pNew ALIAS FOR $1;
58311 BEGIN
58312         -- NOTE: (SELECT getCustId(...)) seems redundant, but it actually produces
58313         -- a HUGE performance increase because it makes the Postgres query planner
58314         -- use an index scan rather than an sequential table scan on cust_id
58315         INSERT INTO invchead (
58316                 invchead_invcnumber,
58317                 invchead_ordernumber,
58318                 invchead_invcdate,
58319                 invchead_shipdate,
58320                 invchead_orderdate,
58321                 invchead_printed,
58322                 invchead_posted,
58323                 invchead_salesrep_id,
58324                 invchead_commission,
58325                 invchead_taxzone_id,
58326                 invchead_terms_id,
58327                 invchead_cust_id,
58328                 invchead_billto_name,
58329                 invchead_billto_address1,
58330                 invchead_billto_address2,
58331                 invchead_billto_address3,
58332                 invchead_billto_city,
58333                 invchead_billto_state,
58334                 invchead_billto_zipcode,
58335                 invchead_billto_country,
58336                 invchead_billto_phone,
58337                 invchead_shipto_id,
58338                 invchead_shipto_name,
58339                 invchead_shipto_address1,
58340                 invchead_shipto_address2,
58341                 invchead_shipto_address3,
58342                 invchead_shipto_city,
58343                 invchead_shipto_state,
58344                 invchead_shipto_zipcode,
58345                 invchead_shipto_country,
58346                 invchead_shipto_phone,
58347                 invchead_ponumber,
58348                 invchead_shipvia,
58349                 invchead_prj_id,
58350                 invchead_fob,
58351                 invchead_misc_descrip,
58352                 invchead_misc_amount,
58353                 invchead_misc_accnt_id,
58354                 invchead_freight,
58355                 invchead_curr_id,
58356                 invchead_payment,
58357                 invchead_notes,
58358                 invchead_saletype_id,
58359                 invchead_shipzone_id
58360         ) SELECT
58361                 (CASE -- use a case here so we don't unnecessarily fetch a new invoice number
58362                         WHEN pNew.invoice_number IS NULL THEN CAST(fetchInvcNumber() AS TEXT)
58363                         WHEN pNew.invoice_number = '' THEN CAST(fetchInvcNumber() AS TEXT)
58364                         ELSE pNew.invoice_number
58365                 END),
58366                 pNew.order_number,
58367                 COALESCE(pNew.invoice_date, CURRENT_DATE),
58368                 pNew.ship_date,
58369                 pNew.order_date,
58370                 FALSE,
58371                 FALSE,
58372                 COALESCE(getSalesRepId(pNew.sales_rep),shipto_salesrep_id,cust_salesrep_id),
58373                 COALESCE(pNew.commission, 0),
58374                 CASE
58375                         WHEN pNew.tax_zone = 'None' THEN NULL
58376                         ELSE COALESCE(getTaxZoneId(pNew.tax_zone),shipto_taxzone_id,cust_taxzone_id)
58377                 END,
58378                 COALESCE(getTermsId(pNew.terms),cust_terms_id),
58379                 (SELECT getCustId(pNew.customer_number)),
58380                 COALESCE(pNew.billto_name, cohead_billtoname, cust_name),
58381                 COALESCE(pNew.billto_address1, cohead_billtoaddress1, addr_line1),
58382                 COALESCE(pNew.billto_address2, cohead_billtoaddress2, addr_line2),
58383                 COALESCE(pNew.billto_address3, cohead_billtoaddress3, addr_line3),
58384                 COALESCE(pNew.billto_city, cohead_billtocity, addr_city),
58385                 COALESCE(pNew.billto_state, cohead_billtostate, addr_state),
58386                 COALESCE(pNew.billto_postal_code, cohead_billtozipcode, addr_postalcode),
58387                 COALESCE(pNew.billto_country, cohead_billtocountry, addr_country),
58388                 COALESCE(pNew.billto_phone, ''),
58389                 COALESCE(shipto_id,-1),
58390                 pNew.shipto_name,
58391                 pNew.shipto_address1,
58392                 pNew.shipto_address2,
58393                 pNew.shipto_address3,
58394                 pNew.shipto_city,
58395                 pNew.shipto_state,
58396                 pNew.shipto_postal_code,
58397                 pNew.shipto_country,
58398                 pNew.shipto_phone,
58399                 COALESCE(pNew.po_number, ''),
58400                 COALESCE(pNew.ship_via,shipto_shipvia,cust_shipvia),
58401                 COALESCE(getPrjId(pNew.project_number),-1),
58402                 COALESCE(pNew.fob,fetchDefaultFob((
58403                         SELECT CAST(usrpref_value AS INTEGER) 
58404                         FROM usrpref, whsinfo
58405                         WHERE ((warehous_id=CAST(usrpref_value AS INTEGER))
58406                                 AND (warehous_shipping)
58407                                 AND (warehous_active)
58408                                 AND (usrpref_username=getEffectiveXtUser())
58409                                 AND (usrpref_name='PreferredWarehouse')
58410                         )
58411                 ))),
58412                 pNew.misc_charge_description,
58413                 COALESCE(pNew.misc_charge, 0),
58414                 COALESCE(getGlAccntId(pNew.misc_charge_account_number),-1),
58415                 COALESCE(pNew.freight, 0),
58416                 COALESCE(getCurrId(pNew.currency),(
58417                         SELECT cust_curr_id
58418                         FROM custinfo
58419                         WHERE (cust_id=(SELECT getCustId(pNew.customer_number)))
58420                 ),basecurrid()),
58421                 COALESCE(pNew.payment,0),
58422                 COALESCE(pNew.notes,''),
58423                 getSaleTypeId(pNew.sale_type),
58424                 getShipZoneId(pNew.shipto_shipzone)
58425         FROM custinfo
58426                 LEFT OUTER JOIN shiptoinfo ON (shipto_id=(SELECT CASE
58427                         WHEN getShiptoId(pNew.customer_number,pNew.shipto_number) IS NOT NULL
58428                                 THEN getShiptoId(pNew.customer_number,pNew.shipto_number)
58429                         ELSE (SELECT shipto_id FROM shiptoinfo WHERE shipto_cust_id=cust_id AND shipto_default)
58430                 END))
58431                LEFT OUTER JOIN cohead ON (cohead_number=pNEW.order_number)
58432                LEFT OUTER JOIN cntct ON (cntct_id=cust_cntct_id)
58433                LEFT OUTER JOIN addr ON (addr_id=cntct_addr_id)
58434         WHERE cust_id = (SELECT getCustId(pNew.customer_number));
58435         RETURN TRUE;
58436 END;
58437 $_$;
58438
58439
58440 ALTER FUNCTION public.insertinvoice(api.invoice) OWNER TO admin;
58441
58442 --
58443 -- TOC entry 229 (class 1259 OID 146566612)
58444 -- Dependencies: 6035 6036 8
58445 -- Name: invcitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
58446 --
58447
58448 CREATE TABLE invcitem (
58449     invcitem_id integer NOT NULL,
58450     invcitem_invchead_id integer NOT NULL,
58451     invcitem_linenumber integer,
58452     invcitem_item_id integer,
58453     invcitem_warehous_id integer DEFAULT (-1),
58454     invcitem_custpn text,
58455     invcitem_number text,
58456     invcitem_descrip text,
58457     invcitem_ordered numeric(20,6) NOT NULL,
58458     invcitem_billed numeric(20,6) NOT NULL,
58459     invcitem_custprice numeric(20,4),
58460     invcitem_price numeric(20,4) NOT NULL,
58461     invcitem_notes text,
58462     invcitem_salescat_id integer,
58463     invcitem_taxtype_id integer,
58464     invcitem_qty_uom_id integer,
58465     invcitem_qty_invuomratio numeric(20,10) NOT NULL,
58466     invcitem_price_uom_id integer,
58467     invcitem_price_invuomratio numeric(20,10) NOT NULL,
58468     invcitem_coitem_id integer,
58469     invcitem_updateinv boolean DEFAULT false,
58470     invcitem_rev_accnt_id integer
58471 );
58472
58473
58474 ALTER TABLE public.invcitem OWNER TO admin;
58475
58476 --
58477 -- TOC entry 9060 (class 0 OID 0)
58478 -- Dependencies: 229
58479 -- Name: TABLE invcitem; Type: COMMENT; Schema: public; Owner: admin
58480 --
58481
58482 COMMENT ON TABLE invcitem IS 'Invoice Line Item information';
58483
58484
58485 SET search_path = api, pg_catalog;
58486
58487 --
58488 -- TOC entry 230 (class 1259 OID 146566620)
58489 -- Dependencies: 8476 6
58490 -- Name: invoiceline; Type: VIEW; Schema: api; Owner: admin
58491 --
58492
58493 CREATE VIEW invoiceline AS
58494     SELECT invchead.invchead_invcnumber AS invoice_number, invcitem.invcitem_linenumber AS line_number, item.item_number, invcitem.invcitem_number AS misc_item_number, whsinfo.warehous_code AS site, invcitem.invcitem_descrip AS misc_item_description, salescat.salescat_name AS sales_category, invcitem.invcitem_custpn AS customer_part_number, invcitem.invcitem_ordered AS qty_ordered, invcitem.invcitem_billed AS qty_billed, invcitem.invcitem_updateinv AS update_inventory, invcitem.invcitem_price AS net_unit_price, COALESCE(taxtype.taxtype_name, 'None'::text) AS tax_type, COALESCE(qty_uom.uom_name, 'None'::text) AS qty_uom, COALESCE(price_uom.uom_name, 'None'::text) AS price_uom, invcitem.invcitem_notes AS notes, CASE WHEN (invcitem.invcitem_rev_accnt_id IS NOT NULL) THEN public.formatglaccount(invcitem.invcitem_rev_accnt_id) ELSE NULL::text END AS alternate_rev_account FROM (((((((public.invcitem LEFT JOIN public.invchead ON ((invcitem.invcitem_invchead_id = invchead.invchead_id))) LEFT JOIN public.item ON ((item.item_id = invcitem.invcitem_item_id))) LEFT JOIN public.whsinfo ON ((invcitem.invcitem_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.salescat ON ((salescat.salescat_id = invcitem.invcitem_salescat_id))) LEFT JOIN public.taxtype ON ((taxtype.taxtype_id = invcitem.invcitem_taxtype_id))) LEFT JOIN public.uom qty_uom ON ((qty_uom.uom_id = invcitem.invcitem_qty_uom_id))) LEFT JOIN public.uom price_uom ON ((price_uom.uom_id = invcitem.invcitem_price_uom_id)));
58495
58496
58497 ALTER TABLE api.invoiceline OWNER TO admin;
58498
58499 --
58500 -- TOC entry 9062 (class 0 OID 0)
58501 -- Dependencies: 230
58502 -- Name: VIEW invoiceline; Type: COMMENT; Schema: api; Owner: admin
58503 --
58504
58505 COMMENT ON VIEW invoiceline IS '
58506 This view can be used as an interface to import Invoice Line Items data directly
58507 into the system.  Required fields will be checked and default values will be
58508 populated';
58509
58510
58511 SET search_path = public, pg_catalog;
58512
58513 --
58514 -- TOC entry 1830 (class 1255 OID 146566625)
58515 -- Dependencies: 2875 4536 8
58516 -- Name: insertinvoicelineitem(api.invoiceline); Type: FUNCTION; Schema: public; Owner: admin
58517 --
58518
58519 CREATE FUNCTION insertinvoicelineitem(api.invoiceline) RETURNS boolean
58520     LANGUAGE plpgsql
58521     AS $_$
58522 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58523 -- See www.xtuple.com/CPAL for the full text of the software license.
58524 DECLARE
58525         pNew ALIAS FOR $1;
58526         _r RECORD;
58527 BEGIN
58528         INSERT INTO invcitem (
58529                 invcitem_invchead_id,
58530                 invcitem_linenumber,
58531                 invcitem_item_id,
58532                 invcitem_warehous_id,
58533                 invcitem_custpn,
58534                 invcitem_number,
58535                 invcitem_descrip,
58536                 invcitem_ordered,
58537                 invcitem_billed,
58538                 invcitem_updateinv,
58539                 invcitem_custprice,
58540                 invcitem_price,
58541                 invcitem_notes,
58542                 invcitem_salescat_id,
58543                 invcitem_taxtype_id,
58544                 invcitem_qty_uom_id,
58545                 invcitem_qty_invuomratio,
58546                 invcitem_price_uom_id,
58547                 invcitem_price_invuomratio,
58548                 invcitem_rev_accnt_id
58549         ) SELECT
58550                 invchead_id,
58551                 COALESCE(pNew.line_number,(
58552                         SELECT (COALESCE(MAX(invcitem_linenumber), 0) + 1)
58553                         FROM invcitem WHERE (invcitem_invchead_id=invchead_id)
58554                 )),
58555                 COALESCE(item_id, -1),
58556                 COALESCE(getwarehousid(pNew.site,'ALL'),-1),
58557                 pNew.customer_part_number,
58558                 (CASE WHEN item_id IS NULL THEN pNew.misc_item_number ELSE NULL END),
58559                 (CASE WHEN item_id IS NULL THEN pNew.misc_item_description ELSE NULL END),
58560                 pNew.qty_ordered,
58561                 COALESCE(pNew.qty_billed, 0),
58562                 COALESCE(pNew.update_inventory,FALSE),
58563                 0, -- invcitem_custprice
58564                 COALESCE(pNew.net_unit_price,itemPrice(item_id,invchead_cust_id,
58565                         invchead_shipto_id,pNew.qty_ordered,invchead_curr_id,invchead_orderdate)),
58566                 COALESCE(pNew.notes,''),
58567                 CASE
58568                         WHEN item_id IS NULL THEN
58569                                 (SELECT salescat_id FROM salescat WHERE salescat_name = pNew.sales_category)
58570                         ELSE NULL
58571                 END,
58572                 taxtype_id,
58573                 CASE
58574                         WHEN item_id IS NOT NULL THEN
58575                                 COALESCE((SELECT uom_id FROM uom WHERE (uom_name=pNew.qty_uom)), item_price_uom_id)
58576                         ELSE NULL
58577                 END,
58578                 CASE
58579                         WHEN item_id IS NOT NULL THEN
58580                                 itemuomtouomratio(item_id,
58581                                         COALESCE((SELECT uom_id FROM uom WHERE uom_name=pNew.qty_uom),item_price_uom_id),
58582                                         item_price_uom_id
58583                                 )
58584                         ELSE 1
58585                 END,
58586                 CASE
58587                         WHEN item_id IS NOT NULL THEN
58588                                 COALESCE((SELECT uom_id FROM uom WHERE uom_name=pNew.price_uom),item_price_uom_id)
58589                         ELSE NULL
58590                 END,
58591                 CASE
58592                         WHEN item_id IS NOT NULL THEN
58593                                 itemuomtouomratio(item_id,
58594                                         COALESCE((SELECT uom_id FROM uom WHERE uom_name=pNew.price_uom),item_price_uom_id),
58595                                         item_price_uom_id
58596                                 )
58597                         ELSE 1
58598                 END,
58599                 getGlAccntId(pNew.alternate_rev_account)
58600         FROM invchead
58601                 LEFT OUTER JOIN item ON (item_id=getItemId(pNew.item_number))
58602                 LEFT OUTER JOIN taxtype ON (taxtype_id=CASE
58603                         WHEN pNew.tax_type IS NULL THEN getItemTaxType(item_id,invchead_taxzone_id)
58604                         WHEN pNew.tax_type = 'None' THEN NULL
58605                         ELSE (SELECT taxtype_id FROM taxtype WHERE taxtype_name=pNew.tax_type)
58606                 END)
58607         WHERE (invchead_invcnumber=pNew.invoice_number) AND (invchead_posted=FALSE);
58608         RETURN TRUE;
58609 END;
58610 $_$;
58611
58612
58613 ALTER FUNCTION public.insertinvoicelineitem(api.invoiceline) OWNER TO admin;
58614
58615 --
58616 -- TOC entry 1831 (class 1255 OID 146566626)
58617 -- Dependencies: 4536 8
58618 -- Name: insertitemcost(integer, integer, integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
58619 --
58620
58621 CREATE FUNCTION insertitemcost(integer, integer, integer, numeric, boolean) RETURNS integer
58622     LANGUAGE plpgsql
58623     AS $_$
58624 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58625 -- See www.xtuple.com/CPAL for the full text of the software license.
58626 DECLARE
58627 pItemId ALIAS FOR $1;
58628 pCostElemId ALIAS FOR $2;
58629 pCurrId ALIAS FOR $3;
58630 pCost ALIAS FOR $4;
58631 pPostToStandard ALIAS FOR $5;
58632 _itemcost_id INTEGER;
58633 _update_return INTEGER;
58634 _postcost_return BOOLEAN;
58635
58636 --This function is used with the api.itemcost View for updating and inserting
58637 --into the itemcosts table
58638
58639 BEGIN
58640   IF (pCost IS NULL OR pCost < 0) THEN
58641     RAISE EXCEPTION 'itemcost Actual Cost Invalid ', pCost;
58642   END IF;
58643
58644 -- Check for uniqueness
58645   SELECT itemcost_id INTO _itemcost_id
58646   FROM itemcost
58647   WHERE ( (itemcost_item_id = pItemId)
58648     AND   (itemcost_costelem_id = pCostElemId)
58649     AND   (NOT itemcost_lowlevel) );
58650   IF (FOUND) THEN
58651     RAISE EXCEPTION 'itemcost already exists for this Item and Cost Element';
58652   END IF;
58653
58654 -- Check for valid combination of item_type and costelem_type
58655   IF (SELECT (COUNT(*) > 0)
58656       FROM item, costelem
58657       WHERE (item_id=pItemId)
58658         AND (costelem_id=pCostElemId)
58659         AND (item_type IN ('M', 'F', 'B', 'C', 'T'))
58660         AND (costelem_type IN ('Material'))) THEN
58661     RAISE EXCEPTION 'itemcost of this type is invalid for Manufactured Item';
58662   END IF;
58663   
58664   IF (SELECT (COUNT(*) > 0)
58665       FROM item, costelem
58666       WHERE (item_id=pItemId)
58667         AND (costelem_id=pCostElemId)
58668         AND (item_type IN ('O', 'P'))
58669         AND (costelem_type IN ('Direct Labor', 'Overhead', 'Machine Overhead'))) THEN
58670     RAISE EXCEPTION 'itemcost of this type is invalid for Purchased Item';
58671   END IF;
58672   
58673   IF (pCost > 0) THEN
58674     SELECT NEXTVAL('itemcost_itemcost_id_seq') INTO _itemcost_id;
58675     INSERT INTO itemcost
58676       ( itemcost_id, itemcost_item_id, itemcost_costelem_id, itemcost_lowlevel,
58677         itemcost_stdcost, itemcost_posted, itemcost_actcost, itemcost_updated, itemcost_curr_id )
58678     VALUES
58679       ( _itemcost_id, pItemId, pCostElemId, FALSE,
58680         0, startOfTime(), pCost, CURRENT_DATE, pCurrId );
58681
58682     --Only Post Cost to standard if the parameter is set to true
58683     IF (pPostToStandard) THEN
58684       IF (NOT checkPrivilege('PostStandardCosts')) THEN
58685         RAISE EXCEPTION 'You do not have privileges to poststandard itemcosts. Set api.itemcost post_to_standard to false';
58686       END IF;
58687       SELECT postcost(_itemcost_id) INTO _postcost_return;       
58688       IF (NOT _postcost_return) THEN
58689         RETURN -2;
58690       END IF;
58691     END IF;
58692   ELSE 
58693     RETURN -1;
58694   END IF;
58695
58696   RETURN _itemcost_id;
58697   
58698 END;
58699 $_$;
58700
58701
58702 ALTER FUNCTION public.insertitemcost(integer, integer, integer, numeric, boolean) OWNER TO admin;
58703
58704 --
58705 -- TOC entry 1832 (class 1255 OID 146566627)
58706 -- Dependencies: 2767 4536 8
58707 -- Name: insertsalesline(api.salesline); Type: FUNCTION; Schema: public; Owner: admin
58708 --
58709
58710 CREATE FUNCTION insertsalesline(api.salesline) RETURNS boolean
58711     LANGUAGE plpgsql
58712     AS $_$
58713 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
58714 -- See www.xtuple.com/CPAL for the full text of the software license.
58715 DECLARE
58716   pNEW ALIAS FOR $1;
58717   _r RECORD;
58718
58719 BEGIN
58720
58721   IF (NOT EXISTS (SELECT cohead_id FROM cohead WHERE cohead_number=pNEW.order_number)) THEN
58722     RAISE EXCEPTION 'Function insertSalesLine failed because Sales Order % not found', pNEW.order_number;
58723   END IF;
58724
58725   IF (NOT EXISTS (SELECT item_id FROM item WHERE item_number=pNEW.item_number)) THEN
58726     RAISE EXCEPTION 'Function insertSalesLine failed because Item Number % not found', pNEW.item_number;
58727   END IF;
58728
58729   SELECT * INTO _r
58730   FROM cohead, itemsite, item, whsinfo
58731   WHERE ((cohead_number=pNEW.order_number)
58732   AND (itemsite_warehous_id=warehous_id
58733   AND (itemsite_item_id=item_id)
58734   AND (itemsite_active)
58735   AND (item_number=pNEW.item_number)
58736   AND (warehous_active)
58737   AND (warehous_id=COALESCE(getWarehousId(pNEW.sold_from_site,'ALL'),cohead_warehous_id,fetchprefwarehousid()))));
58738
58739   IF (NOT FOUND) THEN
58740     RAISE EXCEPTION 'Function insertSalesLine failed with unknown failure to retrieve Sales Order';
58741   END IF;
58742
58743   INSERT INTO coitem (
58744     coitem_cohead_id,
58745     coitem_linenumber,
58746     coitem_itemsite_id,
58747     coitem_status,
58748     coitem_scheddate,
58749     coitem_promdate,
58750     coitem_qtyord,
58751     coitem_qty_uom_id,
58752     coitem_qty_invuomratio,
58753     coitem_qtyshipped,
58754     coitem_unitcost,
58755     coitem_price,
58756     coitem_price_uom_id,
58757     coitem_price_invuomratio,
58758     coitem_custprice,
58759     coitem_order_id,
58760     coitem_memo,
58761     coitem_imported,
58762     coitem_qtyreturned,
58763     coitem_custpn,
58764     coitem_order_type,
58765     coitem_substitute_item_id,
58766     coitem_prcost,
58767     coitem_taxtype_id,
58768     coitem_warranty,
58769     coitem_cos_accnt_id,
58770     coitem_rev_accnt_id)
58771   VALUES (
58772     _r.cohead_id,
58773     pNEW.line_number::INTEGER,
58774     _r.itemsite_id,
58775     pNEW.status,
58776     pNEW.scheduled_date,
58777     pNEW.promise_date,
58778     pNEW.qty_ordered,
58779     COALESCE(getUomId(pNEW.qty_uom),_r.item_inv_uom_id),
58780     itemuomtouomratio(_r.item_id,COALESCE(getUomId(pNEW.qty_uom),_r.item_inv_uom_id),_r.item_inv_uom_id),
58781     0,
58782     stdCost(_r.item_id),
58783     COALESCE(pNEW.net_unit_price,itemPrice(_r.item_id,_r.cohead_cust_id,
58784              _r.cohead_shipto_id,pNEW.qty_ordered,_r.cohead_curr_id,_r.cohead_orderdate)),
58785     COALESCE(getUomId(pNEW.price_uom),_r.item_price_uom_id),
58786     itemuomtouomratio(_r.item_id,COALESCE(getUomId(pNEW.price_uom),_r.item_price_uom_id),_r.item_price_uom_id),
58787     itemPrice(_r.item_id,_r.cohead_cust_id,_r.cohead_shipto_id,pNEW.qty_ordered,_r.cohead_curr_id,_r.cohead_orderdate),
58788     -1,
58789     pNEW.notes,
58790     true,
58791     0,
58792     pNEW.customer_pn,
58793     CASE
58794       WHEN ((pNEW.create_order  AND (_r.item_type = 'M')) OR 
58795            ((pNEW.create_order IS NULL) AND _r.itemsite_createwo)) THEN
58796         'W'
58797       WHEN ((pNEW.create_order AND (_r.item_type = 'P')) OR 
58798            ((pNEW.create_order IS NULL) AND _r.itemsite_createsopr)) THEN
58799         'R'
58800       WHEN ((pNEW.create_order AND (_r.item_type = 'P') AND (_r.itemsite_createsopo)) OR 
58801            ((pNEW.create_order IS NULL) AND _r.itemsite_createsopo)) THEN
58802         'P'
58803     END,
58804     getitemid(pNEW.substitute_for),
58805     pNEW.overwrite_po_price,
58806     COALESCE(getTaxTypeId(pNEW.tax_type), getItemTaxType(_r.itemsite_item_id, _r.cohead_taxzone_id)),
58807     pNEW.warranty,
58808     getGlAccntId(pNEW.alternate_cos_account),
58809     getGlAccntId(pNEW.alternate_rev_account)
58810     );
58811
58812   RETURN TRUE;
58813 END;
58814 $_$;
58815
58816
58817 ALTER FUNCTION public.insertsalesline(api.salesline) OWNER TO admin;
58818
58819 --
58820 -- TOC entry 1833 (class 1255 OID 146566628)
58821 -- Dependencies: 8
58822 -- Name: intervaltominutes(interval); Type: FUNCTION; Schema: public; Owner: admin
58823 --
58824
58825 CREATE FUNCTION intervaltominutes(interval) RETURNS numeric
58826     LANGUAGE sql
58827     AS $_$
58828 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
58829 -- See www.xtuple.com/CPAL for the full text of the software license.
58830   SELECT (EXTRACT(DAY FROM $1) * 24 * 60 +
58831           EXTRACT(HOUR FROM $1) * 60 +
58832           EXTRACT(MINUTE FROM $1) +
58833           ROUND((EXTRACT(SECOND FROM $1) / 60)::NUMERIC, 4))::NUMERIC AS result
58834 $_$;
58835
58836
58837 ALTER FUNCTION public.intervaltominutes(interval) OWNER TO admin;
58838
58839 --
58840 -- TOC entry 1834 (class 1255 OID 146566629)
58841 -- Dependencies: 4536 8
58842 -- Name: invadjustment(integer, numeric, text, text); Type: FUNCTION; Schema: public; Owner: admin
58843 --
58844
58845 CREATE FUNCTION invadjustment(integer, numeric, text, text) RETURNS integer
58846     LANGUAGE plpgsql
58847     AS $_$
58848 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58849 -- See www.xtuple.com/CPAL for the full text of the software license.
58850 BEGIN
58851   RETURN invAdjustment($1, $2, $3, $4, CURRENT_TIMESTAMP, NULL);
58852 END;
58853 $_$;
58854
58855
58856 ALTER FUNCTION public.invadjustment(integer, numeric, text, text) OWNER TO admin;
58857
58858 --
58859 -- TOC entry 1835 (class 1255 OID 146566630)
58860 -- Dependencies: 4536 8
58861 -- Name: invadjustment(integer, numeric, text, text, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
58862 --
58863
58864 CREATE FUNCTION invadjustment(integer, numeric, text, text, timestamp with time zone) RETURNS integer
58865     LANGUAGE plpgsql
58866     AS $_$
58867 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58868 -- See www.xtuple.com/CPAL for the full text of the software license.
58869 BEGIN
58870   RETURN invAdjustment($1, $2, $3, $4, $5, NULL);
58871 END;
58872 $_$;
58873
58874
58875 ALTER FUNCTION public.invadjustment(integer, numeric, text, text, timestamp with time zone) OWNER TO admin;
58876
58877 --
58878 -- TOC entry 1837 (class 1255 OID 146566631)
58879 -- Dependencies: 4536 8
58880 -- Name: invadjustment(integer, numeric, text, text, timestamp with time zone, numeric); Type: FUNCTION; Schema: public; Owner: admin
58881 --
58882
58883 CREATE FUNCTION invadjustment(integer, numeric, text, text, timestamp with time zone, numeric) RETURNS integer
58884     LANGUAGE plpgsql
58885     AS $_$
58886 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58887 -- See www.xtuple.com/CPAL for the full text of the software license.
58888 DECLARE
58889   pItemsiteid     ALIAS FOR $1;
58890   pQty            ALIAS FOR $2;
58891   pDocumentNumber ALIAS FOR $3;
58892   pComments       ALIAS FOR $4;
58893   pGlDistTS       ALIAS FOR $5;
58894   pCostValue      ALIAS FOR $6;
58895   _invhistid      INTEGER;
58896   _itemlocSeries  INTEGER;
58897
58898 BEGIN
58899
58900 --  Make sure the passed itemsite points to a real item
58901   IF ( ( SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
58902          FROM itemsite, item
58903          WHERE ( (itemsite_item_id=item_id)
58904           AND (itemsite_id=pItemsiteid) ) ) ) THEN
58905     RETURN 0;
58906   END IF;
58907
58908   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
58909   SELECT postInvTrans( itemsite_id, 'AD', pQty,
58910                        'I/M', 'AD', pDocumentNumber, '',
58911                        ('Miscellaneous Adjustment for item ' || item_number || E'\n' ||  pComments),
58912                        costcat_asset_accnt_id, costcat_adjustment_accnt_id,
58913                        _itemlocSeries, pGlDistTS, pCostValue) INTO _invhistid
58914   FROM itemsite, item, costcat
58915   WHERE ( (itemsite_item_id=item_id)
58916    AND (itemsite_costcat_id=costcat_id)
58917    AND (itemsite_id=pItemsiteid) );
58918
58919   RETURN _itemlocSeries;
58920
58921 END;
58922 $_$;
58923
58924
58925 ALTER FUNCTION public.invadjustment(integer, numeric, text, text, timestamp with time zone, numeric) OWNER TO admin;
58926
58927 --
58928 -- TOC entry 1838 (class 1255 OID 146566632)
58929 -- Dependencies: 4536 8
58930 -- Name: invexpense(integer, numeric, integer, text, text, timestamp with time zone, integer); Type: FUNCTION; Schema: public; Owner: admin
58931 --
58932
58933 CREATE FUNCTION invexpense(pitemsiteid integer, pqty numeric, pexpcatid integer, pdocumentnumber text, pcomments text, pgldistts timestamp with time zone DEFAULT now(), pprjid integer DEFAULT NULL::integer) RETURNS integer
58934     LANGUAGE plpgsql
58935     AS $$
58936 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58937 -- See www.xtuple.com/CPAL for the full text of the software license.
58938 DECLARE
58939   _invhistid INTEGER;
58940   _itemlocSeries INTEGER;
58941
58942 BEGIN
58943
58944   --  Make sure the passed itemsite points to a real item
58945   IF ( ( SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
58946          FROM itemsite, item
58947          WHERE ( (itemsite_item_id=item_id)
58948           AND (itemsite_id=pItemsiteid) ) ) ) THEN
58949     RETURN 0;
58950   END IF;
58951
58952   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
58953   SELECT postInvTrans( itemsite_id, 'EX', pQty,
58954                        'I/M', 'EX', pDocumentNumber, '',
58955                        CASE WHEN (pQty < 0) THEN ('Reverse Material Expense for item ' || item_number || E'\n' ||  pComments)
58956                             ELSE  ('Material Expense for item ' || item_number || E'\n' ||  pComments)
58957                        END,
58958                        getPrjAccntId(pPrjid, expcat_exp_accnt_id), costcat_asset_accnt_id,
58959                        _itemlocSeries, pGlDistTS) INTO _invhistid
58960   FROM itemsite, item, costcat, expcat
58961   WHERE ( (itemsite_item_id=item_id)
58962    AND (itemsite_costcat_id=costcat_id)
58963    AND (itemsite_id=pItemsiteid)
58964    AND (expcat_id=pExpcatid) );
58965
58966   INSERT INTO invhistexpcat (invhistexpcat_invhist_id, invhistexpcat_expcat_id)
58967                      VALUES (_invhistid,               pExpcatid);
58968
58969   RETURN _itemlocSeries;
58970
58971 END;
58972 $$;
58973
58974
58975 ALTER FUNCTION public.invexpense(pitemsiteid integer, pqty numeric, pexpcatid integer, pdocumentnumber text, pcomments text, pgldistts timestamp with time zone, pprjid integer) OWNER TO admin;
58976
58977 --
58978 -- TOC entry 1839 (class 1255 OID 146566633)
58979 -- Dependencies: 4536 8
58980 -- Name: invhistsense(integer); Type: FUNCTION; Schema: public; Owner: admin
58981 --
58982
58983 CREATE FUNCTION invhistsense(integer) RETURNS integer
58984     LANGUAGE plpgsql
58985     AS $_$
58986 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
58987 -- See www.xtuple.com/CPAL for the full text of the software license.
58988 DECLARE
58989   pInvhistId ALIAS FOR $1;
58990   _count INTEGER;
58991   _row RECORD;
58992   _sense INTEGER;
58993 BEGIN
58994
58995   SELECT invhist_transtype, invhist_ordnumber, itemsite_warehous_id
58996   INTO _row 
58997   FROM invhist 
58998     JOIN itemsite ON (itemsite_id=invhist_itemsite_id)
58999   WHERE (invhist_id=pInvhistId);
59000
59001   GET DIAGNOSTICS _count = ROW_COUNT;
59002   IF (_count = 0) THEN
59003     RAISE EXCEPTION 'Record not found for invhist_id=%',pInvhistId;
59004   END IF;
59005   
59006   -- increase inventory: AD RM RT RP RR RS RX RB TR
59007   -- decrease inventory: IM IB IT SH SI EX RI
59008   -- TS and TR are special: shipShipment and recallShipment should not change
59009   -- QOH at the Transfer Order src whs (as this was done by issueToShipping)
59010   -- but postReceipt should change QOH at the transit whs
59011   IF (_row.invhist_transtype='TS') THEN
59012        _sense := CASE WHEN (SELECT tohead_trns_warehous_id=_row.itemsite_warehous_id
59013                                   FROM tohead
59014                                   WHERE (tohead_number=_row.invhist_ordnumber)) THEN -1
59015                 ELSE 0
59016                 END;
59017   ELSIF (_row.invhist_transtype='TR') THEN
59018       _sense := CASE WHEN (SELECT tohead_src_warehous_id=_row.itemsite_warehous_id
59019                                   FROM tohead
59020                                   WHERE (tohead_number=_row.invhist_ordnumber)) THEN 0
59021                 ELSE 1
59022                 END;
59023   ELSIF (_row.invhist_transtype IN ('IM', 'IB', 'IT', 'SH', 'SI', 'EX', 'RI')) THEN
59024       _sense := -1;
59025     ELSE
59026       _sense := 1;
59027     END IF;
59028
59029   RETURN _sense;
59030 END;
59031 $_$;
59032
59033
59034 ALTER FUNCTION public.invhistsense(integer) OWNER TO admin;
59035
59036 --
59037 -- TOC entry 1840 (class 1255 OID 146566634)
59038 -- Dependencies: 4536 8
59039 -- Name: invhisttrig(); Type: FUNCTION; Schema: public; Owner: admin
59040 --
59041
59042 CREATE FUNCTION invhisttrig() RETURNS trigger
59043     LANGUAGE plpgsql
59044     AS $$
59045 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59046 -- See www.xtuple.com/CPAL for the full text of the software license.
59047 BEGIN
59048
59049 --  Need to allow 'temporary' negative for average costed item that has been frozen.
59050 --  Check at itemsite after all of the transactions have been thawed will ensure
59051 --  that final Qty On Hand is positive. 
59052 --  IF (NEW.invhist_qoh_after < 0 AND NEW.invhist_costmethod = 'A') THEN
59053 --    RAISE EXCEPTION 'Invhist (%) is recording with average costing and is not allowed to have a negative quantity on hand.', NEW.invhist_id;
59054 --  END IF;
59055
59056   IF ( ( SELECT itemsite_freeze
59057          FROM itemsite
59058          WHERE (itemsite_id=NEW.invhist_itemsite_id) ) ) THEN
59059     NEW.invhist_posted = FALSE;
59060   END IF;
59061
59062   -- never change the created timestamp, which defaults to CURRENT_TIMESTAMP
59063   IF (TG_OP != 'INSERT') THEN
59064     NEW.invhist_created = OLD.invhist_created;
59065   ELSE
59066     -- Always need a series id for distribution posting
59067     IF (NEW.invhist_series IS NULL) THEN
59068       RAISE EXCEPTION 'Column invhist_series may not be null.';
59069     END IF;
59070   END IF;
59071
59072   RETURN NEW;
59073
59074 END;
59075 $$;
59076
59077
59078 ALTER FUNCTION public.invhisttrig() OWNER TO admin;
59079
59080 --
59081 -- TOC entry 1841 (class 1255 OID 146566635)
59082 -- Dependencies: 4536 8
59083 -- Name: invoicetotal(integer); Type: FUNCTION; Schema: public; Owner: admin
59084 --
59085
59086 CREATE FUNCTION invoicetotal(integer) RETURNS numeric
59087     LANGUAGE plpgsql
59088     AS $_$
59089 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59090 -- See www.xtuple.com/CPAL for the full text of the software license.
59091 DECLARE
59092   pInvoiceId ALIAS FOR $1;
59093   _linesum   NUMERIC;
59094   _linetax   NUMERIC;
59095   _result    NUMERIC;
59096   _allocated NUMERIC;
59097   _posted    BOOLEAN;
59098
59099 BEGIN
59100
59101   SELECT SUM(ROUND(COALESCE((invcitem_billed * invcitem_qty_invuomratio) *
59102                              (invcitem_price / COALESCE(invcitem_price_invuomratio,1)), 0),2))
59103                           INTO _linesum
59104   FROM invcitem
59105   WHERE (invcitem_invchead_id=pInvoiceId);
59106
59107   -- TODO: why sum on the result of select round(sum(), 2)?
59108   SELECT SUM(tax) INTO _linetax
59109     FROM (SELECT ROUND(SUM(COALESCE(taxdetail_tax, 0)),2) AS tax 
59110             FROM tax 
59111             JOIN calculateTaxDetailSummary('I', pInvoiceId, 'T') ON (taxdetail_tax_id=tax_id)
59112           GROUP BY tax_id) AS data;
59113
59114   SELECT noNeg(invchead_freight + invchead_misc_amount + COALESCE(_linetax, 0) + COALESCE(_linesum, 0)),
59115          invchead_posted INTO _result, _posted
59116   FROM invchead
59117   WHERE (invchead_id=pInvoiceId);
59118
59119   IF NOT FOUND THEN
59120     RETURN 0;
59121   END IF;
59122
59123   IF (_posted) THEN
59124     SELECT COALESCE(SUM(currToCurr(arapply_curr_id, aropen_curr_id,
59125                                    arapply_applied, aropen_docdate)),0) INTO _allocated
59126      FROM arapply, aropen, invchead
59127     WHERE ( (invchead_posted)
59128       AND   (invchead_id=pInvoiceId)
59129       AND   (aropen_docnumber=invchead_invcnumber)
59130       AND   (aropen_doctype='I')
59131       AND   (arapply_target_aropen_id=aropen_id)
59132       AND   (arapply_reftype='S')
59133       AND   (invchead_posted) ) ;
59134   ELSE
59135     SELECT COALESCE(SUM(CASE WHEN((aropen_amount - aropen_paid) >=
59136                        currToCurr(aropenalloc_curr_id, aropen_curr_id,
59137                           aropenalloc_amount, aropen_docdate))
59138            THEN currToCurr(aropenalloc_curr_id, invchead_curr_id,
59139                    aropenalloc_amount, aropen_docdate)
59140            ELSE currToCurr(aropen_curr_id, invchead_curr_id,
59141                    aropen_amount - aropen_paid, aropen_docdate)
59142            END),0) INTO _allocated
59143      FROM invchead LEFT OUTER JOIN cohead ON (cohead_number=invchead_ordernumber)
59144                    JOIN aropenalloc ON ((aropenalloc_doctype='I' AND aropenalloc_doc_id=invchead_id) OR
59145                                         (aropenalloc_doctype='S' AND aropenalloc_doc_id=cohead_id))
59146                    JOIN aropen ON (aropen_id=aropenalloc_aropen_id AND (aropen_amount - aropen_paid) > 0.0)
59147     WHERE ( (NOT invchead_posted)
59148       AND   (invchead_id=pInvoiceId) );
59149   END IF;
59150   
59151   RETURN _result - COALESCE(_allocated, 0);
59152
59153 END;
59154 $_$;
59155
59156
59157 ALTER FUNCTION public.invoicetotal(integer) OWNER TO admin;
59158
59159 --
59160 -- TOC entry 1811 (class 1255 OID 146566636)
59161 -- Dependencies: 4536 8
59162 -- Name: invreceipt(integer, numeric, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
59163 --
59164
59165 CREATE FUNCTION invreceipt(integer, numeric, text, text, text) RETURNS integer
59166     LANGUAGE plpgsql
59167     AS $_$
59168 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59169 -- See www.xtuple.com/CPAL for the full text of the software license.
59170 BEGIN
59171   RETURN invReceipt($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, NULL);
59172 END;
59173 $_$;
59174
59175
59176 ALTER FUNCTION public.invreceipt(integer, numeric, text, text, text) OWNER TO admin;
59177
59178 --
59179 -- TOC entry 1836 (class 1255 OID 146566637)
59180 -- Dependencies: 4536 8
59181 -- Name: invreceipt(integer, numeric, text, text, text, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
59182 --
59183
59184 CREATE FUNCTION invreceipt(integer, numeric, text, text, text, timestamp with time zone) RETURNS integer
59185     LANGUAGE plpgsql
59186     AS $_$
59187 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59188 -- See www.xtuple.com/CPAL for the full text of the software license.
59189 BEGIN
59190   RETURN invReceipt($1, $2, $3, $4, $5, $6, NULL);
59191 END;
59192 $_$;
59193
59194
59195 ALTER FUNCTION public.invreceipt(integer, numeric, text, text, text, timestamp with time zone) OWNER TO admin;
59196
59197 --
59198 -- TOC entry 1842 (class 1255 OID 146566638)
59199 -- Dependencies: 4536 8
59200 -- Name: invreceipt(integer, numeric, text, text, text, timestamp with time zone, numeric); Type: FUNCTION; Schema: public; Owner: admin
59201 --
59202
59203 CREATE FUNCTION invreceipt(integer, numeric, text, text, text, timestamp with time zone, numeric) RETURNS integer
59204     LANGUAGE plpgsql
59205     AS $_$
59206 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59207 -- See www.xtuple.com/CPAL for the full text of the software license.
59208 DECLARE
59209   pItemsiteid ALIAS FOR $1;
59210   pQty ALIAS FOR $2;
59211   pOrdernumber ALIAS FOR $3;
59212   pDocumentNumber ALIAS FOR $4;
59213   pComments ALIAS FOR $5;
59214   pGlDistTS     ALIAS FOR $6;
59215   pCostValue ALIAS FOR $7;
59216   _invhistid INTEGER;
59217   _itemlocSeries INTEGER;
59218
59219 BEGIN
59220
59221 --  Make sure the passed itemsite points to a real item
59222   IF ( ( SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
59223          FROM itemsite, item
59224          WHERE ( (itemsite_item_id=item_id)
59225           AND (itemsite_id=pItemsiteid) ) ) ) THEN
59226     RETURN 0;
59227   END IF;
59228
59229   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
59230   SELECT postInvTrans( itemsite_id, 'RX', pQty,
59231                        'I/M', 'RX', pDocumentNumber, '',
59232                        ('Miscellaneous Receipt for item ' || item_number || E'\n' ||  pComments),
59233                        costcat_asset_accnt_id, costcat_liability_accnt_id,
59234                        _itemlocSeries, pGlDistTS, pCostValue) INTO _invhistid
59235   FROM itemsite, item, costcat
59236   WHERE ( (itemsite_item_id=item_id)
59237    AND (itemsite_costcat_id=costcat_id)
59238    AND (itemsite_id=pItemsiteid) );
59239
59240   RETURN _itemlocSeries;
59241
59242 END;
59243 $_$;
59244
59245
59246 ALTER FUNCTION public.invreceipt(integer, numeric, text, text, text, timestamp with time zone, numeric) OWNER TO admin;
59247
59248 --
59249 -- TOC entry 1843 (class 1255 OID 146566639)
59250 -- Dependencies: 4536 8
59251 -- Name: invscrap(integer, numeric, text, text); Type: FUNCTION; Schema: public; Owner: admin
59252 --
59253
59254 CREATE FUNCTION invscrap(integer, numeric, text, text) RETURNS integer
59255     LANGUAGE plpgsql
59256     AS $_$
59257 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59258 -- See www.xtuple.com/CPAL for the full text of the software license.
59259 BEGIN
59260   RETURN invScrap($1, $2, $3, $4, CURRENT_TIMESTAMP);
59261 END;
59262 $_$;
59263
59264
59265 ALTER FUNCTION public.invscrap(integer, numeric, text, text) OWNER TO admin;
59266
59267 --
59268 -- TOC entry 1844 (class 1255 OID 146566640)
59269 -- Dependencies: 4536 8
59270 -- Name: invscrap(integer, numeric, text, text, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
59271 --
59272
59273 CREATE FUNCTION invscrap(integer, numeric, text, text, timestamp with time zone) RETURNS integer
59274     LANGUAGE plpgsql
59275     AS $_$
59276 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59277 -- See www.xtuple.com/CPAL for the full text of the software license.
59278 BEGIN
59279   RETURN invScrap($1, $2, $3, $4, $5, NULL);
59280 END;
59281 $_$;
59282
59283
59284 ALTER FUNCTION public.invscrap(integer, numeric, text, text, timestamp with time zone) OWNER TO admin;
59285
59286 --
59287 -- TOC entry 1845 (class 1255 OID 146566641)
59288 -- Dependencies: 4536 8
59289 -- Name: invscrap(integer, numeric, text, text, timestamp with time zone, integer); Type: FUNCTION; Schema: public; Owner: admin
59290 --
59291
59292 CREATE FUNCTION invscrap(integer, numeric, text, text, timestamp with time zone, integer) RETURNS integer
59293     LANGUAGE plpgsql
59294     AS $_$
59295 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59296 -- See www.xtuple.com/CPAL for the full text of the software license.
59297 BEGIN
59298   RETURN invScrap($1, $2, $3, $4, $5, $6, NULL);
59299 END;
59300 $_$;
59301
59302
59303 ALTER FUNCTION public.invscrap(integer, numeric, text, text, timestamp with time zone, integer) OWNER TO admin;
59304
59305 --
59306 -- TOC entry 1846 (class 1255 OID 146566642)
59307 -- Dependencies: 4536 8
59308 -- Name: invscrap(integer, numeric, text, text, timestamp with time zone, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
59309 --
59310
59311 CREATE FUNCTION invscrap(integer, numeric, text, text, timestamp with time zone, integer, integer) RETURNS integer
59312     LANGUAGE plpgsql
59313     AS $_$
59314 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59315 -- See www.xtuple.com/CPAL for the full text of the software license.
59316 DECLARE
59317   pItemsiteid ALIAS FOR $1;
59318   pQty ALIAS FOR $2;
59319   pDocumentNumber ALIAS FOR $3;
59320   pComments ALIAS FOR $4;
59321   pGlDistTS ALIAS FOR $5;
59322   pInvHistId ALIAS FOR $6;
59323   pPrjid ALIAS FOR $7;
59324   _invhistid INTEGER;
59325   _itemlocSeries INTEGER;
59326
59327 BEGIN
59328
59329 --  Make sure the passed itemsite points to a real item
59330   IF ( ( SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
59331          FROM itemsite, item
59332          WHERE ( (itemsite_item_id=item_id)
59333           AND (itemsite_id=pItemsiteid) ) ) ) THEN
59334     RETURN 0;
59335   END IF;
59336
59337   IF (pInvHistId IS NOT NULL) THEN
59338     SELECT invhist_series INTO _itemlocSeries
59339     FROM invhist
59340     WHERE invhist_id=pInvHistId;
59341   ELSE
59342     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
59343   END IF;
59344   
59345   SELECT postInvTrans( itemsite_id, 'SI', pQty,
59346                        'I/M', 'SI', pDocumentNumber, '',
59347                        CASE WHEN (pQty < 0) THEN ('Reverse Material Scrap for item ' || item_number || E'\n' ||  pComments)
59348                             ELSE ('Material Scrap for item ' || item_number || E'\n' ||  pComments)
59349                        END,
59350                        getPrjAccntId(pPrjid, costcat_scrap_accnt_id), costcat_asset_accnt_id,
59351                        _itemlocSeries, pGlDistTS, NULL, pInvHistId) INTO _invhistid
59352   FROM itemsite, item, costcat
59353   WHERE ( (itemsite_item_id=item_id)
59354    AND (itemsite_costcat_id=costcat_id)
59355    AND (itemsite_id=pItemsiteid) );
59356
59357   RETURN _itemlocSeries;
59358
59359 END;
59360 $_$;
59361
59362
59363 ALTER FUNCTION public.invscrap(integer, numeric, text, text, timestamp with time zone, integer, integer) OWNER TO admin;
59364
59365 --
59366 -- TOC entry 1847 (class 1255 OID 146566643)
59367 -- Dependencies: 8
59368 -- Name: isdba(text); Type: FUNCTION; Schema: public; Owner: admin
59369 --
59370
59371 CREATE FUNCTION isdba(text DEFAULT NULL::text) RETURNS boolean
59372     LANGUAGE sql
59373     AS $_$
59374   SELECT (datdba=pg_roles.oid OR rolsuper) AS issuper
59375     FROM pg_database, pg_roles
59376   WHERE ((datname=current_database())
59377      AND (rolname=COALESCE($1, getEffectiveXtUser())));
59378 $_$;
59379
59380
59381 ALTER FUNCTION public.isdba(text) OWNER TO admin;
59382
59383 --
59384 -- TOC entry 1848 (class 1255 OID 146566644)
59385 -- Dependencies: 4536 8
59386 -- Name: ismulticurr(); Type: FUNCTION; Schema: public; Owner: admin
59387 --
59388
59389 CREATE FUNCTION ismulticurr() RETURNS boolean
59390     LANGUAGE plpgsql IMMUTABLE
59391     AS $$
59392 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59393 -- See www.xtuple.com/CPAL for the full text of the software license.
59394 BEGIN
59395   RETURN (SELECT (count(*) > 1)
59396           FROM curr_symbol);
59397 END;
59398 $$;
59399
59400
59401 ALTER FUNCTION public.ismulticurr() OWNER TO admin;
59402
59403 --
59404 -- TOC entry 1849 (class 1255 OID 146566645)
59405 -- Dependencies: 4536 8
59406 -- Name: isnumeric(text); Type: FUNCTION; Schema: public; Owner: admin
59407 --
59408
59409 CREATE FUNCTION isnumeric(text) RETURNS boolean
59410     LANGUAGE plpgsql IMMUTABLE
59411     AS $_$
59412 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59413 -- See www.xtuple.com/CPAL for the full text of the software license.
59414 DECLARE
59415   pText ALIAS FOR $1;
59416   _cursor INTEGER;
59417
59418 BEGIN
59419
59420   IF ( (LENGTH(pText) = 0) OR (pText IS NULL) ) THEN
59421     RETURN FALSE;
59422   END IF;
59423
59424   FOR _cursor IN 1..LENGTH(pText) LOOP
59425     IF (SUBSTRING(pText FROM _cursor FOR 1) NOT IN ( '0', '1', '2', '3', '4',
59426                                                      '5' ,'6' ,'7' ,'8' ,'9' )) THEN
59427       RETURN FALSE;
59428     END IF;
59429   END LOOP;
59430
59431   RETURN TRUE;
59432
59433 END;
59434 $_$;
59435
59436
59437 ALTER FUNCTION public.isnumeric(text) OWNER TO admin;
59438
59439 --
59440 -- TOC entry 1850 (class 1255 OID 146566646)
59441 -- Dependencies: 4536 8
59442 -- Name: issueallbalancetoshipping(integer); Type: FUNCTION; Schema: public; Owner: admin
59443 --
59444
59445 CREATE FUNCTION issueallbalancetoshipping(integer) RETURNS integer
59446     LANGUAGE plpgsql
59447     AS $_$
59448 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59449 -- See www.xtuple.com/CPAL for the full text of the software license.
59450 BEGIN
59451   RETURN issueAllBalanceToShipping('SO', $1, 0, NULL);
59452 END;
59453 $_$;
59454
59455
59456 ALTER FUNCTION public.issueallbalancetoshipping(integer) OWNER TO admin;
59457
59458 --
59459 -- TOC entry 1855 (class 1255 OID 146566647)
59460 -- Dependencies: 4536 8
59461 -- Name: issueallbalancetoshipping(text, integer, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
59462 --
59463
59464 CREATE FUNCTION issueallbalancetoshipping(text, integer, integer, timestamp with time zone) RETURNS integer
59465     LANGUAGE plpgsql
59466     AS $_$
59467 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59468 -- See www.xtuple.com/CPAL for the full text of the software license.
59469 DECLARE
59470   pordertype            ALIAS FOR $1;
59471   pheadid               ALIAS FOR $2;
59472   _itemlocSeries        INTEGER                  := $3;
59473   _timestamp            TIMESTAMP WITH TIME ZONE := $4;
59474   _s                    RECORD;
59475
59476 BEGIN
59477   IF (pordertype = 'SO') THEN
59478     FOR _s IN SELECT coitem_id,
59479                      CASE WHEN (fetchMetricBool('RequireSOReservations'))
59480                           THEN coitem_qtyreserved
59481                           ELSE noNeg( coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned - qtyAtShipping('SO', coitem_id) )
59482                      END AS _balance
59483               FROM coitem LEFT OUTER JOIN (itemsite JOIN item ON (itemsite_item_id=item_id)) ON (coitem_itemsite_id=itemsite_id)
59484               WHERE ( (coitem_status NOT IN ('C','X'))
59485                 AND (item_type != 'K')
59486                AND (coitem_cohead_id=pheadid) ) LOOP
59487
59488       IF (_s.balance <> 0) THEN
59489         _itemlocSeries := issueToShipping(pordertype, _s.coitem_id, _s.balance, _itemlocSeries, _timestamp);
59490         IF (_itemlocSeries < 0) THEN
59491           EXIT;
59492         END IF;
59493       END IF;
59494     END LOOP;
59495
59496   ELSEIF (pordertype = 'TO') THEN
59497     FOR _s IN SELECT toitem_id,
59498                      noNeg( toitem_qty_ordered - toitem_qty_shipped - qtyAtShipping('TO', toitem_id) )
59499                       AS balance
59500               FROM toitem
59501               WHERE ( (toitem_status NOT IN ('C','X'))
59502                AND (toitem_tohead_id=pheadid) ) LOOP
59503
59504       IF (_s.balance <> 0) THEN
59505         _itemlocSeries := issueToShipping(pordertype, _s.toitem_id, _s.balance, _itemlocSeries, _timestamp);
59506         IF (_itemlocSeries < 0) THEN
59507           EXIT;
59508         END IF;
59509       END IF;
59510     END LOOP;
59511
59512   ELSE
59513     RETURN -1;
59514   END IF;
59515
59516   RETURN _itemlocSeries;
59517
59518 END;
59519 $_$;
59520
59521
59522 ALTER FUNCTION public.issueallbalancetoshipping(text, integer, integer, timestamp with time zone) OWNER TO admin;
59523
59524 --
59525 -- TOC entry 1856 (class 1255 OID 146566648)
59526 -- Dependencies: 4536 8
59527 -- Name: issuelinebalancetoshipping(integer); Type: FUNCTION; Schema: public; Owner: admin
59528 --
59529
59530 CREATE FUNCTION issuelinebalancetoshipping(integer) RETURNS integer
59531     LANGUAGE plpgsql
59532     AS $_$
59533 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59534 -- See www.xtuple.com/CPAL for the full text of the software license.
59535 BEGIN
59536   RETURN issueLineBalanceToShipping('SO', $1, NULL);
59537 END;
59538 $_$;
59539
59540
59541 ALTER FUNCTION public.issuelinebalancetoshipping(integer) OWNER TO admin;
59542
59543 --
59544 -- TOC entry 1857 (class 1255 OID 146566649)
59545 -- Dependencies: 4536 8
59546 -- Name: issuelinebalancetoshipping(text, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
59547 --
59548
59549 CREATE FUNCTION issuelinebalancetoshipping(text, integer, timestamp with time zone) RETURNS integer
59550     LANGUAGE plpgsql
59551     AS $_$
59552 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59553 -- See www.xtuple.com/CPAL for the full text of the software license.
59554 BEGIN
59555   RETURN issueLineBalanceToShipping($1, $2, $3, 0, NULL);
59556 END;
59557 $_$;
59558
59559
59560 ALTER FUNCTION public.issuelinebalancetoshipping(text, integer, timestamp with time zone) OWNER TO admin;
59561
59562 --
59563 -- TOC entry 1858 (class 1255 OID 146566650)
59564 -- Dependencies: 4536 8
59565 -- Name: issuelinebalancetoshipping(text, integer, timestamp with time zone, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
59566 --
59567
59568 CREATE FUNCTION issuelinebalancetoshipping(text, integer, timestamp with time zone, integer, integer) RETURNS integer
59569     LANGUAGE plpgsql
59570     AS $_$
59571 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59572 -- See www.xtuple.com/CPAL for the full text of the software license.
59573 DECLARE
59574   pordertype            ALIAS FOR $1;
59575   pitemid               ALIAS FOR $2;
59576   ptimestamp            ALIAS FOR $3;
59577   pitemlocseries        ALIAS FOR $4;
59578   pinvhistid            ALIAS FOR $5;
59579   _itemlocSeries        INTEGER := 0;
59580   _qty                  NUMERIC;
59581
59582 BEGIN
59583   _itemlocSeries := COALESCE(pitemlocseries,0);
59584   
59585   IF (pordertype = 'SO') THEN
59586     SELECT CASE WHEN (fetchMetricBool('RequireSOReservations'))
59587                 THEN coitem_qtyreserved
59588                 ELSE noNeg( coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned - qtyAtShipping('SO', coitem_id) )
59589            END INTO _qty
59590     FROM coitem
59591     WHERE (coitem_id=pitemid);
59592   ELSEIF (pordertype = 'TO') THEN
59593     SELECT noNeg( toitem_qty_ordered - toitem_qty_shipped - qtyAtShipping('TO', toitem_id) )
59594                INTO _qty
59595     FROM toitem
59596     WHERE (toitem_id=pitemid);
59597   ELSE
59598     RETURN -1;
59599   END IF;
59600
59601   IF (_qty > 0) THEN
59602     _itemlocSeries := issueToShipping(pordertype, pitemid, _qty, _itemlocSeries, ptimestamp, pinvhistid);
59603   END IF;
59604
59605   RETURN _itemlocSeries;
59606
59607 END;
59608 $_$;
59609
59610
59611 ALTER FUNCTION public.issuelinebalancetoshipping(text, integer, timestamp with time zone, integer, integer) OWNER TO admin;
59612
59613 --
59614 -- TOC entry 1859 (class 1255 OID 146566651)
59615 -- Dependencies: 4536 8
59616 -- Name: issues(text); Type: FUNCTION; Schema: public; Owner: admin
59617 --
59618
59619 CREATE FUNCTION issues(text) RETURNS boolean
59620     LANGUAGE plpgsql
59621     AS $_$
59622 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59623 -- See www.xtuple.com/CPAL for the full text of the software license.
59624 DECLARE
59625   pTransType ALIAS FOR $1;
59626
59627 BEGIN
59628   IF (pTransType IN ('IM', 'IB', 'IT')) THEN
59629     RETURN TRUE;
59630   ELSE
59631     RETURN FALSE;
59632   END IF;
59633
59634 END;
59635 $_$;
59636
59637
59638 ALTER FUNCTION public.issues(text) OWNER TO admin;
59639
59640 --
59641 -- TOC entry 1860 (class 1255 OID 146566652)
59642 -- Dependencies: 4536 8
59643 -- Name: issuetoshipping(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
59644 --
59645
59646 CREATE FUNCTION issuetoshipping(integer, numeric) RETURNS integer
59647     LANGUAGE plpgsql
59648     AS $_$
59649 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59650 -- See www.xtuple.com/CPAL for the full text of the software license.
59651 BEGIN
59652   RETURN issueToShipping('SO', $1, $2, 0, CURRENT_TIMESTAMP);
59653 END;
59654 $_$;
59655
59656
59657 ALTER FUNCTION public.issuetoshipping(integer, numeric) OWNER TO admin;
59658
59659 --
59660 -- TOC entry 1861 (class 1255 OID 146566653)
59661 -- Dependencies: 4536 8
59662 -- Name: issuetoshipping(integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
59663 --
59664
59665 CREATE FUNCTION issuetoshipping(integer, numeric, integer) RETURNS integer
59666     LANGUAGE plpgsql
59667     AS $_$
59668 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59669 -- See www.xtuple.com/CPAL for the full text of the software license.
59670 BEGIN
59671   RETURN issueToShipping('SO', $1, $2, $3, CURRENT_TIMESTAMP);
59672 END;
59673 $_$;
59674
59675
59676 ALTER FUNCTION public.issuetoshipping(integer, numeric, integer) OWNER TO admin;
59677
59678 --
59679 -- TOC entry 1862 (class 1255 OID 146566654)
59680 -- Dependencies: 4536 8
59681 -- Name: issuetoshipping(text, integer, numeric, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
59682 --
59683
59684 CREATE FUNCTION issuetoshipping(text, integer, numeric, integer, timestamp with time zone) RETURNS integer
59685     LANGUAGE plpgsql
59686     AS $_$
59687 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59688 -- See www.xtuple.com/CPAL for the full text of the software license.
59689 BEGIN
59690   RETURN issueToShipping($1, $2, $3, $4, $5, NULL);
59691 END;
59692 $_$;
59693
59694
59695 ALTER FUNCTION public.issuetoshipping(text, integer, numeric, integer, timestamp with time zone) OWNER TO admin;
59696
59697 --
59698 -- TOC entry 1863 (class 1255 OID 146566655)
59699 -- Dependencies: 4536 8
59700 -- Name: issuetoshipping(text, integer, numeric, integer, timestamp with time zone, integer); Type: FUNCTION; Schema: public; Owner: admin
59701 --
59702
59703 CREATE FUNCTION issuetoshipping(text, integer, numeric, integer, timestamp with time zone, integer) RETURNS integer
59704     LANGUAGE plpgsql
59705     AS $_$
59706 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59707 -- See www.xtuple.com/CPAL for the full text of the software license.
59708 DECLARE
59709   pordertype            ALIAS FOR $1;
59710   pitemid               ALIAS FOR $2;
59711   pQty                  ALIAS FOR $3;
59712   _itemlocSeries        INTEGER := $4;
59713   _timestamp            TIMESTAMP WITH TIME ZONE := $5;
59714   pinvhistid            ALIAS FOR $6;
59715   _coholdtype           TEXT;
59716   _invhistid            INTEGER;
59717   _shipheadid           INTEGER;
59718   _shipnumber           INTEGER;
59719   _cntctid              INTEGER;
59720   _p                    RECORD;
59721   _m                    RECORD;
59722   _value                NUMERIC;
59723   _warehouseid          INTEGER;
59724   _shipitemid           INTEGER;
59725   _freight              NUMERIC;
59726
59727 BEGIN
59728
59729   IF (_timestamp IS NULL) THEN
59730     _timestamp := CURRENT_TIMESTAMP;
59731   END IF;
59732
59733   IF (_itemlocSeries = 0) THEN
59734     _itemlocSeries := NEXTVAL('itemloc_series_seq');
59735   END IF;
59736
59737   IF (pordertype = 'SO') THEN
59738
59739     -- Check site security
59740     SELECT warehous_id INTO _warehouseid
59741     FROM coitem,itemsite,site()
59742     WHERE ((coitem_id=pitemid)
59743     AND (itemsite_id=coitem_itemsite_id)
59744     AND (warehous_id=itemsite_warehous_id));
59745           
59746     IF (NOT FOUND) THEN
59747       RETURN 0;
59748     END IF;
59749
59750     -- Check for average cost items going negative
59751     IF ( SELECT ( (itemsite_costmethod='A') AND
59752                   ((itemsite_qtyonhand - round(pQty * coitem_qty_invuomratio, 6)) < 0.0) )
59753          FROM coitem JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
59754          WHERE (coitem_id=pitemid) ) THEN
59755       RETURN -20;
59756     END IF;
59757
59758     -- Check auto registration
59759     IF ( SELECT COALESCE(itemsite_autoreg, FALSE)
59760          FROM coitem JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
59761          WHERE (coitem_id=pitemid) ) THEN
59762       SELECT COALESCE(crmacct_cntct_id_1, -1) INTO _cntctid
59763       FROM coitem JOIN cohead ON (cohead_id=coitem_cohead_id)
59764                   JOIN crmacct ON (crmacct_cust_id=cohead_cust_id)
59765       WHERE (coitem_id=pitemid);
59766       IF (_cntctid = -1) THEN
59767         RETURN -15;
59768       END IF;
59769     END IF; 
59770   
59771     SELECT shiphead_id INTO _shipheadid
59772     FROM shiphead, coitem JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
59773     WHERE ( (coitem_id=pitemid)
59774       AND   (shiphead_number=getOpenShipment(pordertype, coitem_cohead_id, itemsite_warehous_id)) );
59775     IF (NOT FOUND) THEN
59776       SELECT NEXTVAL('shiphead_shiphead_id_seq') INTO _shipheadid;
59777
59778       _shipnumber := fetchShipmentNumber();
59779       IF (_shipnumber < 0) THEN
59780         RETURN -10;
59781       END IF;
59782
59783       SELECT cohead_holdtype INTO _coholdtype
59784       FROM cohead, coitem
59785       WHERE ((cohead_id=coitem_cohead_id)
59786         AND  (coitem_id=pitemid));
59787
59788       IF (_coholdtype = 'C') THEN
59789         RETURN -12;
59790       ELSIF (_coholdtype = 'P') THEN
59791         RETURN -13;
59792       ELSIF (_coholdtype = 'R') THEN
59793         RETURN -14;
59794       END IF;
59795
59796       INSERT INTO shiphead
59797       ( shiphead_id, shiphead_number, shiphead_order_id, shiphead_order_type,
59798         shiphead_shipped,
59799         shiphead_sfstatus, shiphead_shipvia, shiphead_shipchrg_id,
59800         shiphead_freight, shiphead_freight_curr_id,
59801         shiphead_shipdate, shiphead_notes, shiphead_shipform_id )
59802       SELECT _shipheadid, _shipnumber, coitem_cohead_id, pordertype,
59803              FALSE,
59804              'N', cohead_shipvia,
59805              CASE WHEN (cohead_shipchrg_id <= 0) THEN NULL
59806                   ELSE cohead_shipchrg_id
59807              END,
59808              cohead_freight, cohead_curr_id,
59809              _timestamp::DATE, cohead_shipcomments,
59810              CASE WHEN cohead_shipform_id = -1 THEN NULL
59811                   ELSE cohead_shipform_id
59812              END
59813       FROM cohead, coitem
59814       WHERE ((coitem_cohead_id=cohead_id)
59815          AND (coitem_id=pitemid) );
59816
59817       UPDATE pack
59818       SET pack_shiphead_id = _shipheadid,
59819           pack_printed = FALSE
59820       FROM coitem
59821       WHERE ((pack_head_id=coitem_cohead_id)
59822         AND  (pack_shiphead_id IS NULL)
59823         AND  (pack_head_type='SO')
59824         AND  (coitem_id=pitemid));
59825
59826     ELSE
59827       UPDATE pack
59828       SET pack_printed = FALSE
59829       FROM coitem
59830       WHERE ((pack_head_id=coitem_cohead_id)
59831         AND  (pack_shiphead_id=_shipheadid)
59832         AND  (pack_head_type='SO')
59833         AND  (coitem_id=pitemid));
59834     END IF;
59835
59836     -- Handle g/l transaction
59837     SELECT postInvTrans( itemsite_id, 'SH', (pQty * coitem_qty_invuomratio),
59838                            'S/R', porderType,
59839                            formatSoNumber(coitem_id), shiphead_number,
59840                            ('Issue ' || item_number || ' to Shipping for customer ' || cohead_billtoname),
59841                            getPrjAccntId(cohead_prj_id, costcat_shipasset_accnt_id), costcat_asset_accnt_id,
59842                            _itemlocSeries, _timestamp, NULL, pinvhistid ) INTO _invhistid
59843     FROM coitem, cohead, itemsite, item, costcat, shiphead
59844     WHERE ( (coitem_cohead_id=cohead_id)
59845      AND (coitem_itemsite_id=itemsite_id)
59846      AND (itemsite_item_id=item_id)
59847      AND (itemsite_costcat_id=costcat_id)
59848      AND (coitem_id=pitemid)
59849      AND (shiphead_id=_shipheadid) );
59850
59851     SELECT (invhist_unitcost * invhist_invqty) INTO _value
59852     FROM invhist
59853     WHERE (invhist_id=_invhistid);
59854
59855     _shipitemid := nextval('shipitem_shipitem_id_seq');
59856     INSERT INTO shipitem
59857     ( shipitem_id, shipitem_shiphead_id, shipitem_orderitem_id, shipitem_qty,
59858       shipitem_transdate, shipitem_trans_username, shipitem_invoiced,
59859       shipitem_value, shipitem_invhist_id )
59860     VALUES
59861     ( _shipitemid, _shipheadid, pitemid, pQty,
59862       _timestamp, getEffectiveXtUser(), FALSE,
59863       _value, 
59864       CASE WHEN _invhistid = -1 THEN
59865         NULL
59866       ELSE 
59867         _invhistid
59868       END );
59869
59870     -- Handle reservation
59871     IF (fetchmetricbool('EnableSOReservations')) THEN
59872       -- Remember what was reserved so we can re-reserve if this issue is returned
59873       INSERT INTO shipitemrsrv 
59874         (shipitemrsrv_shipitem_id, shipitemrsrv_qty)
59875       SELECT _shipitemid, least(pQty,coitem_qtyreserved)
59876       FROM coitem
59877       WHERE ((coitem_id=pitemid)
59878       AND (coitem_qtyreserved > 0));
59879
59880       -- Update sales order
59881       UPDATE coitem
59882         SET coitem_qtyreserved = noNeg(coitem_qtyreserved - pQty)
59883       WHERE(coitem_id=pitemid);
59884     END IF;
59885
59886     -- Calculate shipment freight
59887     SELECT calcShipFreight(_shipheadid) INTO _freight;
59888     UPDATE shiphead SET shiphead_freight=_freight
59889     WHERE (shiphead_id=_shipheadid);
59890
59891   ELSEIF (pordertype = 'TO') THEN
59892
59893     -- Check site security
59894     IF (fetchMetricBool('MultiWhs')) THEN
59895       SELECT warehous_id INTO _warehouseid
59896       FROM toitem, tohead, site()
59897       WHERE ( (toitem_id=pitemid)
59898         AND   (tohead_id=toitem_tohead_id)
59899         AND   (warehous_id=tohead_src_warehous_id) );
59900           
59901       IF (NOT FOUND) THEN
59902         RETURN 0;
59903       END IF;
59904     END IF;
59905
59906     SELECT postInvTrans( itemsite_id, 'SH', pQty, 'S/R',
59907                          pordertype, formatToNumber(toitem_id), '', 'Issue to Shipping',
59908                          costcat_shipasset_accnt_id, costcat_asset_accnt_id,
59909                          _itemlocSeries, _timestamp) INTO _invhistid
59910     FROM tohead, toitem, itemsite, costcat
59911     WHERE ((tohead_id=toitem_tohead_id)
59912       AND  (itemsite_item_id=toitem_item_id)
59913       AND  (itemsite_warehous_id=tohead_src_warehous_id)
59914       AND  (itemsite_costcat_id=costcat_id)
59915       AND  (toitem_id=pitemid) );
59916
59917     SELECT (invhist_unitcost * invhist_invqty) INTO _value
59918     FROM invhist
59919     WHERE (invhist_id=_invhistid);
59920
59921     SELECT shiphead_id INTO _shipheadid
59922     FROM shiphead, toitem JOIN tohead ON (tohead_id=toitem_tohead_id)
59923     WHERE ( (toitem_id=pitemid)
59924       AND   (shiphead_number=getOpenShipment(pordertype, tohead_id, tohead_src_warehous_id)) );
59925
59926     IF (NOT FOUND) THEN
59927       _shipheadid := NEXTVAL('shiphead_shiphead_id_seq');
59928
59929       _shipnumber := fetchShipmentNumber();
59930       IF (_shipnumber < 0) THEN
59931         RETURN -10;
59932       END IF;
59933
59934       INSERT INTO shiphead
59935       ( shiphead_id, shiphead_number, shiphead_order_id, shiphead_order_type,
59936         shiphead_shipped,
59937         shiphead_sfstatus, shiphead_shipvia, shiphead_shipchrg_id,
59938         shiphead_freight, shiphead_freight_curr_id,
59939         shiphead_shipdate, shiphead_notes, shiphead_shipform_id )
59940       SELECT _shipheadid, _shipnumber, tohead_id, pordertype,
59941              FALSE,
59942              'N', tohead_shipvia, tohead_shipchrg_id,
59943              tohead_freight + SUM(toitem_freight), tohead_freight_curr_id,
59944              _timestamp::DATE, tohead_shipcomments, tohead_shipform_id
59945       FROM tohead, toitem
59946       WHERE ((toitem_tohead_id=tohead_id)
59947          AND (tohead_id IN (SELECT toitem_tohead_id
59948                             FROM toitem
59949                             WHERE (toitem_id=pitemid))) )
59950       GROUP BY tohead_id, tohead_shipvia, tohead_shipchrg_id, tohead_freight,
59951                tohead_freight_curr_id, tohead_shipcomments, tohead_shipform_id;
59952     END IF;
59953
59954     INSERT INTO shipitem
59955     ( shipitem_shiphead_id, shipitem_orderitem_id, shipitem_qty,
59956       shipitem_transdate, shipitem_trans_username, shipitem_invoiced,
59957       shipitem_value, shipitem_invhist_id )
59958     VALUES
59959     ( _shipheadid, pitemid, pQty,
59960       _timestamp, getEffectiveXtUser(), FALSE,
59961       _value, 
59962       CASE WHEN _invhistid = -1 THEN NULL
59963            ELSE _invhistid
59964       END
59965     );
59966
59967   ELSE
59968     RETURN -11;
59969   END IF;
59970
59971   RETURN _itemlocSeries;
59972
59973 END;
59974 $_$;
59975
59976
59977 ALTER FUNCTION public.issuetoshipping(text, integer, numeric, integer, timestamp with time zone, integer) OWNER TO admin;
59978
59979 --
59980 -- TOC entry 1867 (class 1255 OID 146566660)
59981 -- Dependencies: 4536 8
59982 -- Name: issuewomaterial(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
59983 --
59984
59985 CREATE FUNCTION issuewomaterial(integer, numeric) RETURNS integer
59986     LANGUAGE plpgsql
59987     AS $_$
59988 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
59989 -- See www.xtuple.com/CPAL for the full text of the software license.
59990 DECLARE
59991   pWomatlid ALIAS FOR $1;
59992   pQty ALIAS FOR $2;
59993   _itemlocSeries INTEGER;
59994
59995 BEGIN
59996
59997   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
59998   RETURN issueWoMaterial(pWomatlid, pQty, _itemlocSeries);
59999
60000 END;
60001 $_$;
60002
60003
60004 ALTER FUNCTION public.issuewomaterial(integer, numeric) OWNER TO admin;
60005
60006 --
60007 -- TOC entry 1865 (class 1255 OID 146566658)
60008 -- Dependencies: 4536 8
60009 -- Name: issuewomaterial(integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
60010 --
60011
60012 CREATE FUNCTION issuewomaterial(integer, numeric, integer) RETURNS integer
60013     LANGUAGE plpgsql
60014     AS $_$
60015 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60016 -- See www.xtuple.com/CPAL for the full text of the software license.
60017 DECLARE
60018   pWomatlid ALIAS FOR $1;
60019   pQty ALIAS FOR $2;
60020   pItemlocSeries ALIAS FOR $3;
60021   _p RECORD;
60022   _invhistid INTEGER;
60023   _itemlocSeries INTEGER;
60024
60025 BEGIN
60026   RETURN issueWoMaterial(pWomatlid, pQty, pItemlocSeries, now());
60027 END;
60028 $_$;
60029
60030
60031 ALTER FUNCTION public.issuewomaterial(integer, numeric, integer) OWNER TO admin;
60032
60033 --
60034 -- TOC entry 1866 (class 1255 OID 146566659)
60035 -- Dependencies: 4536 8
60036 -- Name: issuewomaterial(integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
60037 --
60038
60039 CREATE FUNCTION issuewomaterial(integer, numeric, boolean) RETURNS integer
60040     LANGUAGE plpgsql
60041     AS $_$
60042 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60043 -- See www.xtuple.com/CPAL for the full text of the software license.
60044 DECLARE
60045   pWomatlid ALIAS FOR $1;
60046   pQty ALIAS FOR $2;
60047   pMarkPush ALIAS FOR $3;
60048   _itemlocSeries INTEGER;
60049
60050 BEGIN
60051   RETURN issueWoMaterial(pWomatlid, pQty, pMarkPush, now());
60052 END;
60053 $_$;
60054
60055
60056 ALTER FUNCTION public.issuewomaterial(integer, numeric, boolean) OWNER TO admin;
60057
60058 --
60059 -- TOC entry 1864 (class 1255 OID 146566657)
60060 -- Dependencies: 4536 8
60061 -- Name: issuewomaterial(integer, numeric, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
60062 --
60063
60064 CREATE FUNCTION issuewomaterial(integer, numeric, integer, boolean) RETURNS integer
60065     LANGUAGE plpgsql
60066     AS $_$
60067 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60068 -- See www.xtuple.com/CPAL for the full text of the software license.
60069 DECLARE
60070   pWomatlid ALIAS FOR $1;
60071   pQty ALIAS FOR $2;
60072   pItemlocSeries ALIAS FOR $3;
60073   pMarkPush ALIAS FOR $4;
60074   _itemlocSeries INTEGER;
60075
60076 BEGIN
60077   RETURN issueWoMaterial(pWomatlid, pQty, pItemlocSeries,now());
60078 END;
60079 $_$;
60080
60081
60082 ALTER FUNCTION public.issuewomaterial(integer, numeric, integer, boolean) OWNER TO admin;
60083
60084 --
60085 -- TOC entry 1852 (class 1255 OID 146566662)
60086 -- Dependencies: 4536 8
60087 -- Name: issuewomaterial(integer, numeric, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
60088 --
60089
60090 CREATE FUNCTION issuewomaterial(integer, numeric, integer, timestamp with time zone) RETURNS integer
60091     LANGUAGE plpgsql
60092     AS $_$
60093 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60094 -- See www.xtuple.com/CPAL for the full text of the software license.
60095 BEGIN
60096   RETURN issueWoMaterial($1, $2, $3, $4, NULL);
60097 END;
60098 $_$;
60099
60100
60101 ALTER FUNCTION public.issuewomaterial(integer, numeric, integer, timestamp with time zone) OWNER TO admin;
60102
60103 --
60104 -- TOC entry 1869 (class 1255 OID 146566663)
60105 -- Dependencies: 4536 8
60106 -- Name: issuewomaterial(integer, numeric, boolean, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
60107 --
60108
60109 CREATE FUNCTION issuewomaterial(integer, numeric, boolean, timestamp with time zone) RETURNS integer
60110     LANGUAGE plpgsql
60111     AS $_$
60112 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60113 -- See www.xtuple.com/CPAL for the full text of the software license.
60114 DECLARE
60115   pWomatlid ALIAS FOR $1;
60116   pQty ALIAS FOR $2;
60117   pMarkPush ALIAS FOR $3;
60118   pGlDistTS ALIAS FOR $4;
60119   _itemlocSeries INTEGER;
60120
60121 BEGIN
60122
60123   SELECT issueWoMaterial(pWomatlid, pQty, 0, pGlDistTS) INTO _itemlocSeries;
60124   IF (_itemlocSeries < 0) THEN
60125     RETURN _itemlocSeries;
60126   END IF;
60127
60128   IF (pMarkPush) THEN
60129     UPDATE womatl
60130     SET womatl_issuemethod='S'
60131     WHERE ((womatl_issuemethod='M')
60132      AND (womatl_id=pWomatlid));
60133   END IF;
60134
60135   RETURN _itemlocSeries;
60136
60137 END;
60138 $_$;
60139
60140
60141 ALTER FUNCTION public.issuewomaterial(integer, numeric, boolean, timestamp with time zone) OWNER TO admin;
60142
60143 --
60144 -- TOC entry 1851 (class 1255 OID 146566661)
60145 -- Dependencies: 4536 8
60146 -- Name: issuewomaterial(integer, numeric, integer, boolean, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
60147 --
60148
60149 CREATE FUNCTION issuewomaterial(integer, numeric, integer, boolean, timestamp with time zone) RETURNS integer
60150     LANGUAGE plpgsql
60151     AS $_$
60152 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60153 -- See www.xtuple.com/CPAL for the full text of the software license.
60154 DECLARE
60155   pWomatlid ALIAS FOR $1;
60156   pQty ALIAS FOR $2;
60157   pItemlocSeries ALIAS FOR $3;
60158   pMarkPush ALIAS FOR $4;
60159   pGlDistTS ALIAS FOR $5;
60160   _itemlocSeries INTEGER;
60161
60162 BEGIN
60163
60164   SELECT issueWoMaterial(pWomatlid, pQty, pItemlocSeries, pGlDistTS) INTO _itemlocSeries;
60165
60166   IF (pMarkPush) THEN
60167     UPDATE womatl
60168     SET womatl_issuemethod='S'
60169     WHERE ((womatl_issuemethod='M')
60170      AND (womatl_id=pWomatlid));
60171   END IF;
60172
60173   RETURN _itemlocSeries;
60174
60175 END;
60176 $_$;
60177
60178
60179 ALTER FUNCTION public.issuewomaterial(integer, numeric, integer, boolean, timestamp with time zone) OWNER TO admin;
60180
60181 --
60182 -- TOC entry 1870 (class 1255 OID 146566664)
60183 -- Dependencies: 4536 8
60184 -- Name: issuewomaterial(integer, numeric, integer, timestamp with time zone, integer); Type: FUNCTION; Schema: public; Owner: admin
60185 --
60186
60187 CREATE FUNCTION issuewomaterial(integer, numeric, integer, timestamp with time zone, integer) RETURNS integer
60188     LANGUAGE plpgsql
60189     AS $_$
60190 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60191 -- See www.xtuple.com/CPAL for the full text of the software license.
60192 DECLARE
60193   pWomatlid ALIAS FOR $1;
60194   pQty ALIAS FOR $2;
60195   pItemlocSeries ALIAS FOR $3;
60196   pGlDistTS ALIAS FOR $4;
60197   pInvhistid ALIAS FOR $5;
60198   _p RECORD;
60199   _invhistid INTEGER;
60200   _itemlocSeries INTEGER;
60201
60202 BEGIN
60203
60204   SELECT item_id,
60205          itemsite_id AS c_itemsite_id,
60206          wo_itemsite_id AS p_itemsite_id,
60207          itemsite_loccntrl, itemsite_controlmethod,
60208          womatl_wo_id, womatl_qtyreq, itemsite_item_id, womatl_uom_id, wo_prj_id,
60209          roundQty(item_fractional, itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, pQty)) AS qty,
60210          formatWoNumber(wo_id) AS woNumber,
60211          CASE WHEN(itemsite_costmethod='J' AND item_type='P' AND poitem_id IS NOT NULL) THEN poitem_unitprice
60212               WHEN(itemsite_costmethod IN ('A','J')) THEN avgcost(itemsite_id)
60213               WHEN(itemsite_costmethod='S') THEN stdcost(itemsite_item_id)
60214               ELSE 0.0
60215          END AS cost,
60216          womatl_issuemethod AS issueMethod INTO _p
60217   FROM womatl JOIN wo ON (wo_id=womatl_wo_id)
60218               JOIN itemsite ON (itemsite_id=womatl_itemsite_id)
60219               JOIN item ON (item_id=itemsite_item_id)
60220               LEFT OUTER JOIN poitem ON (poitem_order_id=womatl_id AND poitem_order_type='W')
60221   WHERE (womatl_id=pWomatlid);
60222
60223   IF (pQty < 0) THEN
60224     RETURN pItemlocSeries;
60225   END IF;
60226
60227   IF (pItemlocSeries <> 0) THEN
60228     _itemlocSeries := pItemlocSeries;
60229   ELSE
60230     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
60231   END IF;
60232   SELECT postInvTrans( ci.itemsite_id, 'IM', _p.qty,
60233                       'W/O', 'WO', _p.woNumber, '',
60234                       ('Material ' || item_number || ' Issue to Work Order'),
60235                       getPrjAccntId(_p.wo_prj_id, pc.costcat_wip_accnt_id),
60236                       cc.costcat_asset_accnt_id, _itemlocSeries, pGlDistTS,
60237                       NULL, pInvhistid ) INTO _invhistid
60238   FROM itemsite AS ci, itemsite AS pi,
60239        costcat AS cc, costcat AS pc,
60240        item
60241   WHERE ( (ci.itemsite_costcat_id=cc.costcat_id)
60242    AND (pi.itemsite_costcat_id=pc.costcat_id)
60243    AND (ci.itemsite_id=_p.c_itemsite_id)
60244    AND (pi.itemsite_id=_p.p_itemsite_id)
60245    AND (ci.itemsite_item_id=item_id) );
60246
60247 --  Create linkage to the transaction created
60248   IF (_invhistid != -1) THEN
60249     INSERT INTO womatlpost (womatlpost_womatl_id,womatlpost_invhist_id)
60250                 VALUES (pWomatlid,_invhistid);
60251   END IF;
60252
60253 --  Increase the parent W/O's WIP value by the value of the issued components
60254   UPDATE wo
60255   SET wo_wipvalue = (wo_wipvalue + (_p.cost * _p.qty)),
60256       wo_postedvalue = (wo_postedvalue + (_p.cost * _p.qty))
60257   WHERE (wo_id=_p.womatl_wo_id);
60258
60259   UPDATE womatl
60260   SET womatl_qtyiss = (womatl_qtyiss + itemuomtouom(_p.itemsite_item_id, NULL, _p.womatl_uom_id, _p.qty)),
60261       womatl_lastissue = pGlDistTS::DATE
60262   WHERE (womatl_id=pWomatlid);
60263
60264   UPDATE wo
60265   SET wo_status='I'
60266   WHERE ( (wo_status <> 'I')
60267    AND (wo_id=_p.womatl_wo_id) );
60268
60269   RETURN _itemlocSeries;
60270
60271 END;
60272 $_$;
60273
60274
60275 ALTER FUNCTION public.issuewomaterial(integer, numeric, integer, timestamp with time zone, integer) OWNER TO admin;
60276
60277 --
60278 -- TOC entry 1871 (class 1255 OID 146566665)
60279 -- Dependencies: 4536 8
60280 -- Name: issuewomaterialbatch(integer); Type: FUNCTION; Schema: public; Owner: admin
60281 --
60282
60283 CREATE FUNCTION issuewomaterialbatch(integer) RETURNS integer
60284     LANGUAGE plpgsql
60285     AS $_$
60286 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60287 -- See www.xtuple.com/CPAL for the full text of the software license.
60288 DECLARE
60289   pWoid ALIAS FOR $1;
60290   _itemlocSeries INTEGER;
60291   _r RECORD;
60292   _woNumber TEXT;
60293
60294 BEGIN
60295
60296   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
60297
60298   FOR _r IN SELECT womatl_id, 
60299               CASE WHEN (womatl_qtyreq >= 0) THEN
60300                 roundQty(itemuomfractionalbyuom(item_id, womatl_uom_id), noNeg(womatl_qtyreq - womatl_qtyiss))
60301               ELSE
60302                 roundQty(itemuomfractionalbyuom(item_id, womatl_uom_id), noNeg(womatl_qtyiss * -1)) 
60303               END AS qty
60304             FROM womatl, itemsite, item
60305             WHERE ( (womatl_itemsite_id=itemsite_id)
60306              AND (itemsite_item_id=item_id)
60307              AND (womatl_issuemethod IN ('S', 'M'))
60308              AND (womatl_wo_id=pWoid) ) LOOP
60309
60310     IF (_r.qty > 0) THEN
60311       SELECT issueWoMaterial(_r.womatl_id, _r.qty, _itemlocSeries, TRUE) INTO _itemlocSeries;
60312     END IF;
60313
60314   END LOOP;
60315
60316   RETURN _itemlocSeries;
60317
60318 END;
60319 $_$;
60320
60321
60322 ALTER FUNCTION public.issuewomaterialbatch(integer) OWNER TO admin;
60323
60324 --
60325 -- TOC entry 1872 (class 1255 OID 146566666)
60326 -- Dependencies: 4536 8
60327 -- Name: itemaltcapinvrat(integer); Type: FUNCTION; Schema: public; Owner: admin
60328 --
60329
60330 CREATE FUNCTION itemaltcapinvrat(integer) RETURNS numeric
60331     LANGUAGE plpgsql STABLE
60332     AS $_$
60333 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60334 -- See www.xtuple.com/CPAL for the full text of the software license.
60335 DECLARE
60336   pItemid ALIAS FOR $1;
60337
60338 BEGIN
60339   RETURN itemUOMRatioByType(pItemid, 'AltCapacity');
60340 END;
60341 $_$;
60342
60343
60344 ALTER FUNCTION public.itemaltcapinvrat(integer) OWNER TO admin;
60345
60346 --
60347 -- TOC entry 1873 (class 1255 OID 146566667)
60348 -- Dependencies: 4536 8
60349 -- Name: itemaltcapuom(integer); Type: FUNCTION; Schema: public; Owner: admin
60350 --
60351
60352 CREATE FUNCTION itemaltcapuom(integer) RETURNS text
60353     LANGUAGE plpgsql STABLE
60354     AS $_$
60355 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60356 -- See www.xtuple.com/CPAL for the full text of the software license.
60357 DECLARE
60358   pItemid ALIAS FOR $1;
60359
60360 BEGIN
60361   RETURN itemUOMByType(pItemid, 'AltCapacity');
60362 END;
60363 $_$;
60364
60365
60366 ALTER FUNCTION public.itemaltcapuom(integer) OWNER TO admin;
60367
60368 --
60369 -- TOC entry 1874 (class 1255 OID 146566668)
60370 -- Dependencies: 4536 8
60371 -- Name: itemcapinvrat(integer); Type: FUNCTION; Schema: public; Owner: admin
60372 --
60373
60374 CREATE FUNCTION itemcapinvrat(integer) RETURNS numeric
60375     LANGUAGE plpgsql STABLE
60376     AS $_$
60377 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60378 -- See www.xtuple.com/CPAL for the full text of the software license.
60379 DECLARE
60380   pItemid ALIAS FOR $1;
60381
60382 BEGIN
60383   RETURN itemUOMRatioByType(pItemid, 'Capacity');
60384 END;
60385 $_$;
60386
60387
60388 ALTER FUNCTION public.itemcapinvrat(integer) OWNER TO admin;
60389
60390 --
60391 -- TOC entry 1875 (class 1255 OID 146566669)
60392 -- Dependencies: 4536 8
60393 -- Name: itemcapuom(integer); Type: FUNCTION; Schema: public; Owner: admin
60394 --
60395
60396 CREATE FUNCTION itemcapuom(integer) RETURNS text
60397     LANGUAGE plpgsql STABLE
60398     AS $_$
60399 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60400 -- See www.xtuple.com/CPAL for the full text of the software license.
60401 DECLARE
60402   pItemid ALIAS FOR $1;
60403
60404 BEGIN
60405   RETURN itemUOMByType(pItemid, 'Capacity');
60406 END;
60407 $_$;
60408
60409
60410 ALTER FUNCTION public.itemcapuom(integer) OWNER TO admin;
60411
60412 --
60413 -- TOC entry 1877 (class 1255 OID 146566671)
60414 -- Dependencies: 4536 8
60415 -- Name: itemcharprice(integer, integer, text, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
60416 --
60417
60418 CREATE FUNCTION itemcharprice(integer, integer, text, integer, numeric) RETURNS numeric
60419     LANGUAGE plpgsql
60420     AS $_$
60421 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60422 -- See www.xtuple.com/CPAL for the full text of the software license.
60423 DECLARE
60424   pItemid ALIAS FOR $1;
60425   pCharid ALIAS FOR $2;
60426   pCharValue ALIAS FOR $3;
60427   pCustid ALIAS FOR $4;
60428   pQty ALIAS FOR $5;
60429
60430 BEGIN
60431   RETURN itemCharPrice(pItemid, pCharid, pCharValue, pCustid, -1, pQty, baseCurrId(), CURRENT_DATE);
60432 END;
60433 $_$;
60434
60435
60436 ALTER FUNCTION public.itemcharprice(integer, integer, text, integer, numeric) OWNER TO admin;
60437
60438 --
60439 -- TOC entry 1878 (class 1255 OID 146566672)
60440 -- Dependencies: 4536 8
60441 -- Name: itemcharprice(integer, integer, text, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
60442 --
60443
60444 CREATE FUNCTION itemcharprice(integer, integer, text, integer, integer, numeric) RETURNS numeric
60445     LANGUAGE plpgsql
60446     AS $_$
60447 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60448 -- See www.xtuple.com/CPAL for the full text of the software license.
60449 DECLARE
60450   pItemid ALIAS FOR $1;
60451   pCharid ALIAS FOR $2;
60452   pCharValue ALIAS FOR $3;
60453   pCustid ALIAS FOR $4;
60454   pShiptoid ALIAS FOR $5;
60455   pQty ALIAS FOR $6;
60456
60457 BEGIN
60458   RETURN itemCharPrice(pItemid, pCharid, pCharValue, pCustid, pShiptoid, pQty, baseCurrId(), CURRENT_DATE);
60459 END;
60460 $_$;
60461
60462
60463 ALTER FUNCTION public.itemcharprice(integer, integer, text, integer, integer, numeric) OWNER TO admin;
60464
60465 --
60466 -- TOC entry 1879 (class 1255 OID 146566673)
60467 -- Dependencies: 4536 8
60468 -- Name: itemcharprice(integer, integer, text, integer, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
60469 --
60470
60471 CREATE FUNCTION itemcharprice(integer, integer, text, integer, integer, numeric, integer) RETURNS numeric
60472     LANGUAGE plpgsql
60473     AS $_$
60474 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60475 -- See www.xtuple.com/CPAL for the full text of the software license.
60476 DECLARE
60477   pItemid ALIAS FOR $1;
60478   pCharid ALIAS FOR $2;
60479   pCharValue ALIAS FOR $3;
60480   pCustid ALIAS FOR $4;
60481   pShiptoid ALIAS FOR $5;
60482   pQty ALIAS FOR $6;
60483   pCurrid ALIAS FOR $7;
60484
60485 BEGIN
60486   RETURN itemCharPrice(pItemid, pCharid, pCharValue, pCustid, pShiptoid, pQty, pCurrid, CURRENT_DATE);
60487 END;
60488 $_$;
60489
60490
60491 ALTER FUNCTION public.itemcharprice(integer, integer, text, integer, integer, numeric, integer) OWNER TO admin;
60492
60493 --
60494 -- TOC entry 1876 (class 1255 OID 146566670)
60495 -- Dependencies: 4536 8
60496 -- Name: itemcharprice(integer, integer, text, integer, integer, numeric, integer, date); Type: FUNCTION; Schema: public; Owner: admin
60497 --
60498
60499 CREATE FUNCTION itemcharprice(integer, integer, text, integer, integer, numeric, integer, date) RETURNS numeric
60500     LANGUAGE plpgsql
60501     AS $_$
60502 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60503 -- See www.xtuple.com/CPAL for the full text of the software license.
60504 DECLARE
60505   pItemid ALIAS FOR $1;
60506   pCharid ALIAS FOR $2;
60507   pCharValue ALIAS FOR $3;
60508   pCustid ALIAS FOR $4;
60509   pShiptoid ALIAS FOR $5;
60510   pQty ALIAS FOR $6;
60511   pCurrid ALIAS FOR $7;
60512   pEffective ALIAS FOR $8;
60513
60514 BEGIN
60515   RETURN itemCharPrice(pItemid, pCharid, pCharValue, pCustid, pShiptoid, pQty, pCurrid, CURRENT_DATE, CURRENT_DATE);
60516 END;
60517 $_$;
60518
60519
60520 ALTER FUNCTION public.itemcharprice(integer, integer, text, integer, integer, numeric, integer, date) OWNER TO admin;
60521
60522 --
60523 -- TOC entry 1880 (class 1255 OID 146566674)
60524 -- Dependencies: 4536 8
60525 -- Name: itemcharprice(integer, integer, text, integer, integer, numeric, integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
60526 --
60527
60528 CREATE FUNCTION itemcharprice(integer, integer, text, integer, integer, numeric, integer, date, date) RETURNS numeric
60529     LANGUAGE plpgsql
60530     AS $_$
60531 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60532 -- See www.xtuple.com/CPAL for the full text of the software license.
60533 DECLARE
60534   pItemid ALIAS FOR $1;
60535   pCharid ALIAS FOR $2;
60536   pCharValue ALIAS FOR $3;
60537   pCustid ALIAS FOR $4;
60538   pShiptoid ALIAS FOR $5;
60539   pQty ALIAS FOR $6;
60540   pCurrid ALIAS FOR $7;
60541   pEffective ALIAS FOR $8;
60542   pAsOf ALIAS FOR $9;
60543   _price NUMERIC;
60544   _sales NUMERIC;
60545   _item RECORD;
60546   _iteminvpricerat NUMERIC;
60547
60548 BEGIN
60549 -- If the charass_value passed in is NULL, we can skip this function
60550   IF (pCharValue IS NULL) THEN 
60551     RETURN 0;
60552   END IF;
60553
60554 -- Return the itemCharPrice in the currency passed in as pCurrid
60555
60556 -- Get a value here so we do not have to call the function several times
60557   SELECT iteminvpricerat(pItemid)
60558     INTO _iteminvpricerat;
60559
60560 -- First get a sales price if any so we when we find other prices
60561 -- we can determine if we want that price or this price.
60562 --  Check for a Sale Price
60563   SELECT currToCurr(ipshead_curr_id, pCurrid,
60564                       ipsprice_price - (ipsprice_price * cust_discntprcnt),
60565                       pEffective) INTO _sales
60566   FROM (
60567   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id,
60568          itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak) AS ipsprice_qtybreak,
60569          (ipsitemchar_price * itemuomtouomratio(ipsitem_item_id, NULL, ipsitem_price_uom_id)) * _iteminvpricerat AS ipsprice_price
60570     FROM ipsiteminfo,ipsitemchar
60571    WHERE((ipsitem_item_id=pItemid)
60572     AND (ipsitemchar_char_id=pCharid)
60573     AND (ipsitemchar_value=pCharValue)
60574     AND (ipsitemchar_ipsitem_id=ipsitem_id))
60575        ) AS
60576         ipsprice, ipshead, sale, custinfo
60577   WHERE ( (ipsprice_ipshead_id=ipshead_id)
60578    AND (sale_ipshead_id=ipshead_id)
60579    AND (pAsOf BETWEEN sale_startdate AND sale_enddate)
60580    AND (ipsprice_qtybreak <= pQty)
60581    AND (cust_id=pCustid) )
60582   ORDER BY ipsprice_qtybreak DESC, ipsprice_price ASC
60583   LIMIT 1;
60584
60585 --  Check for a Customer Shipto Price
60586   SELECT currToCurr(ipshead_curr_id, pCurrid, ipsprice_price, pEffective) INTO _price
60587   FROM (
60588   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id,
60589          itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak) AS ipsprice_qtybreak,
60590          (ipsitemchar_price * itemuomtouomratio(ipsitem_item_id, NULL, ipsitem_price_uom_id)) * _iteminvpricerat AS ipsprice_price
60591     FROM ipsiteminfo,ipsitemchar
60592    WHERE ((ipsitem_item_id=pItemid)
60593     AND (ipsitemchar_char_id=pCharid)
60594     AND (ipsitemchar_value=pCharValue)
60595     AND (ipsitemchar_ipsitem_id=ipsitem_id))
60596        ) AS
60597         ipsprice, ipshead, ipsass
60598   WHERE ( (ipsprice_ipshead_id=ipshead_id)
60599    AND (ipsass_ipshead_id=ipshead_id)
60600    AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
60601    AND (ipsprice_qtybreak <= pQty)
60602    AND (ipsass_shipto_id != -1)
60603    AND (ipsass_shipto_id=pShiptoid) )
60604   ORDER BY ipsprice_qtybreak DESC, ipsprice_price ASC
60605   LIMIT 1;
60606
60607   IF (_price IS NOT NULL) THEN
60608     IF ((_sales IS NOT NULL) AND (_sales < _price)) THEN
60609       RETURN _sales;
60610     END IF;
60611     RETURN _price;
60612   END IF;
60613
60614 --  Check for a Customer Shipto Pattern Price
60615   SELECT currToCurr(ipshead_curr_id, pCurrid, ipsprice_price, pEffective) INTO _price
60616   FROM (
60617   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id,
60618          itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak) AS ipsprice_qtybreak,
60619          (ipsitemchar_price * itemuomtouomratio(ipsitem_item_id, NULL, ipsitem_price_uom_id)) * _iteminvpricerat AS ipsprice_price
60620     FROM ipsiteminfo,ipsitemchar
60621    WHERE ((ipsitem_item_id=pItemid)
60622     AND (ipsitemchar_char_id=pCharid)
60623     AND (ipsitemchar_value=pCharValue)
60624     AND (ipsitemchar_ipsitem_id=ipsitem_id))
60625        ) AS
60626         ipsprice, ipshead, ipsass, shiptoinfo
60627   WHERE ( (ipsprice_ipshead_id=ipshead_id)
60628    AND (ipsass_ipshead_id=ipshead_id)
60629    AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
60630    AND (ipsprice_qtybreak <= pQty)
60631    AND (COALESCE(length(ipsass_shipto_pattern), 0) > 0)
60632    AND (shipto_num ~ ipsass_shipto_pattern)
60633    AND (ipsass_cust_id=pCustid)
60634    AND (shipto_id=pShiptoid) )
60635   ORDER BY ipsprice_qtybreak DESC, ipsprice_price ASC
60636   LIMIT 1;
60637
60638   IF (_price IS NOT NULL) THEN
60639     IF ((_sales IS NOT NULL) AND (_sales < _price)) THEN
60640       RETURN _sales;
60641     END IF;
60642     RETURN _price;
60643   END IF;
60644
60645 --  Check for a Customer Price
60646   SELECT currToCurr(ipshead_curr_id, pCurrid, ipsprice_price, pEffective) INTO _price
60647   FROM (
60648   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id,
60649          itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak) AS ipsprice_qtybreak,
60650          (ipsitemchar_price * itemuomtouomratio(ipsitem_item_id, NULL, ipsitem_price_uom_id)) * _iteminvpricerat AS ipsprice_price
60651     FROM ipsiteminfo,ipsitemchar
60652    WHERE ((ipsitem_item_id=pItemid)
60653     AND (ipsitemchar_char_id=pCharid)
60654     AND (ipsitemchar_value=pCharValue)
60655     AND (ipsitemchar_ipsitem_id=ipsitem_id))
60656        ) AS
60657         ipsprice, ipshead, ipsass
60658   WHERE ( (ipsprice_ipshead_id=ipshead_id)
60659    AND (ipsass_ipshead_id=ipshead_id)
60660    AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
60661    AND (ipsprice_qtybreak <= pQty)
60662    AND (COALESCE(length(ipsass_shipto_pattern), 0) = 0)
60663    AND (ipsass_cust_id=pCustid) )
60664   ORDER BY ipsprice_qtybreak DESC, ipsprice_price ASC
60665   LIMIT 1;
60666
60667   IF (_price IS NOT NULL) THEN
60668     IF ((_sales IS NOT NULL) AND (_sales < _price)) THEN
60669       RETURN _sales;
60670     END IF;
60671     RETURN _price;
60672   END IF;
60673
60674 --  Check for a Customer Type Price
60675   SELECT currToCurr(ipshead_curr_id, pCurrid, ipsprice_price, pEffective) INTO _price
60676   FROM (
60677   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id,
60678          itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak) AS ipsprice_qtybreak,
60679          (ipsitemchar_price * itemuomtouomratio(ipsitem_item_id, NULL, ipsitem_price_uom_id)) * _iteminvpricerat AS ipsprice_price
60680     FROM ipsiteminfo,ipsitemchar
60681    WHERE((ipsitem_item_id=pItemid)
60682     AND (ipsitemchar_char_id=pCharid)
60683     AND (ipsitemchar_value=pCharValue)
60684     AND (ipsitemchar_ipsitem_id=ipsitem_id))
60685        ) AS
60686         ipsprice, ipshead, ipsass, custinfo
60687   WHERE ( (ipsprice_ipshead_id=ipshead_id)
60688    AND (ipsass_ipshead_id=ipshead_id)
60689    AND (ipsass_custtype_id=cust_custtype_id)
60690    AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
60691    AND (ipsprice_qtybreak <= pQty)
60692    AND (cust_id=pCustid) )
60693   ORDER BY ipsprice_qtybreak DESC, ipsprice_price ASC
60694   LIMIT 1;
60695
60696   IF (_price IS NOT NULL) THEN
60697     IF ((_sales IS NOT NULL) AND (_sales < _price)) THEN
60698       RETURN _sales;
60699     END IF;
60700     RETURN _price;
60701   END IF;
60702
60703 --  Check for a Customer Type Pattern Price
60704   SELECT currToCurr(ipshead_curr_id, pCurrid, ipsprice_price, pEffective) INTO _price
60705   FROM (
60706   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id,
60707          itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak) AS ipsprice_qtybreak,
60708          (ipsitemchar_price * itemuomtouomratio(ipsitem_item_id, NULL, ipsitem_price_uom_id)) * _iteminvpricerat AS ipsprice_price
60709     FROM ipsiteminfo,ipsitemchar
60710    WHERE ((ipsitem_item_id=pItemid)
60711     AND (ipsitemchar_char_id=pCharid)
60712     AND (ipsitemchar_value=pCharValue)
60713     AND (ipsitemchar_ipsitem_id=ipsitem_id))
60714        ) AS
60715         ipsprice, ipshead, ipsass, custtype, custinfo
60716   WHERE ( (ipsprice_ipshead_id=ipshead_id)
60717    AND (ipsass_ipshead_id=ipshead_id)
60718    AND (coalesce(length(ipsass_custtype_pattern), 0) > 0)
60719    AND (custtype_code ~ ipsass_custtype_pattern)
60720    AND (cust_custtype_id=custtype_id)
60721    AND (pAsOf BETWEEN ipshead_effective AND (ipshead_expires - 1))
60722    AND (ipsprice_qtybreak <= pQty)
60723    AND (cust_id=pCustid) )
60724   ORDER BY ipsprice_qtybreak DESC, ipsprice_price ASC
60725   LIMIT 1;
60726
60727   IF (_price IS NOT NULL) THEN
60728     IF ((_sales IS NOT NULL) AND (_sales < _price)) THEN
60729       RETURN _sales;
60730     END IF;
60731     RETURN _price;
60732   END IF;
60733
60734 -- If we have not found another price yet and we have a
60735 -- sales price we will use that.
60736   IF (_sales IS NOT NULL) THEN
60737     RETURN _sales;
60738   END IF;
60739
60740 --  Check for a list price
60741   SELECT MIN(currToLocal(pCurrid,
60742                        charass_price - (charass_price * COALESCE(cust_discntprcnt, 0)),
60743                        pEffective)) AS price,
60744          item_exclusive INTO _item
60745   FROM charass,item LEFT OUTER JOIN custinfo ON (cust_id=pCustid)
60746   WHERE ((item_id=pItemid)
60747    AND (charass_char_id=pCharid)
60748    AND (charass_value=pCharValue)
60749    AND (charass_target_type='I')
60750    AND (charass_target_id=item_id))
60751   GROUP BY item_exclusive;
60752   IF (FOUND) THEN
60753     IF (NOT _item.item_exclusive) THEN
60754       IF (_item.price < 0) THEN
60755         RETURN 0;
60756       ELSE
60757         RETURN _item.price;
60758       END IF;
60759     ELSE
60760       RETURN 0;
60761     END IF;
60762   ELSE
60763     RETURN 0;
60764   END IF;
60765
60766 END;
60767 $_$;
60768
60769
60770 ALTER FUNCTION public.itemcharprice(integer, integer, text, integer, integer, numeric, integer, date, date) OWNER TO admin;
60771
60772 --
60773 -- TOC entry 1881 (class 1255 OID 146566675)
60774 -- Dependencies: 4536 8
60775 -- Name: itemcharvalue(integer, text); Type: FUNCTION; Schema: public; Owner: admin
60776 --
60777
60778 CREATE FUNCTION itemcharvalue(integer, text) RETURNS text
60779     LANGUAGE plpgsql
60780     AS $_$
60781 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60782 -- See www.xtuple.com/CPAL for the full text of the software license.
60783 DECLARE
60784   pItemid ALIAS FOR $1;
60785   pCharName ALIAS FOR $2;
60786   _value TEXT;
60787
60788 BEGIN
60789
60790   SELECT charass_value INTO _value
60791   FROM charass, char
60792   WHERE ( (charass_char_id=char_id)
60793    AND (charass_target_type='I')
60794    AND (charass_target_id=pItemid)
60795    AND (char_name=pCharName) );
60796   IF (NOT FOUND) THEN
60797     _value = '';
60798   END IF;
60799
60800   RETURN _value;
60801
60802 END;
60803 $_$;
60804
60805
60806 ALTER FUNCTION public.itemcharvalue(integer, text) OWNER TO admin;
60807
60808 --
60809 -- TOC entry 1882 (class 1255 OID 146566676)
60810 -- Dependencies: 4536 8
60811 -- Name: itemcost(integer); Type: FUNCTION; Schema: public; Owner: admin
60812 --
60813
60814 CREATE FUNCTION itemcost(integer) RETURNS numeric
60815     LANGUAGE plpgsql STABLE
60816     AS $_$
60817 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60818 -- See www.xtuple.com/CPAL for the full text of the software license.
60819 DECLARE
60820   pItemsiteid ALIAS FOR $1;
60821   _cost NUMERIC;
60822 BEGIN
60823   SELECT CASE WHEN (itemsite_costmethod='A' AND itemsite_qtyonhand != 0.0) THEN (itemsite_value / itemsite_qtyonhand)
60824               WHEN (itemsite_costmethod='A' AND itemsite_qtyonhand = 0.0) THEN 0.0
60825               WHEN (itemsite_costmethod='N') THEN 0.0
60826               ELSE stdCost(itemsite_item_id)
60827          END INTO _cost
60828     FROM itemsite
60829    WHERE(itemsite_id=pItemsiteid);
60830   RETURN _cost;
60831 END;
60832 $_$;
60833
60834
60835 ALTER FUNCTION public.itemcost(integer) OWNER TO admin;
60836
60837 --
60838 -- TOC entry 1883 (class 1255 OID 146566677)
60839 -- Dependencies: 4536 8
60840 -- Name: iteminventoryuominuse(integer); Type: FUNCTION; Schema: public; Owner: admin
60841 --
60842
60843 CREATE FUNCTION iteminventoryuominuse(integer) RETURNS boolean
60844     LANGUAGE plpgsql
60845     AS $_$
60846 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60847 -- See www.xtuple.com/CPAL for the full text of the software license.
60848 DECLARE
60849   pItemid ALIAS FOR $1;
60850   _uomid INTEGER;
60851   _result INTEGER;
60852 BEGIN
60853   SELECT item_inv_uom_id INTO _uomid
60854     FROM item
60855    WHERE(item_id=pItemid);
60856
60857   SELECT itemuomconv_id INTO _result
60858     FROM itemuomconv
60859    WHERE(itemuomconv_item_id=pItemid)
60860    LIMIT 1;
60861   IF (FOUND) THEN
60862     RETURN TRUE;
60863   END IF;
60864
60865   SELECT itemsite_id INTO _result
60866   FROM itemsite WHERE ( (itemsite_item_id=pItemid)
60867                   AND   ((itemsite_qtyonhand <> 0) OR (itemsite_nnqoh <> 0)) )
60868   LIMIT 1;
60869   IF (FOUND) THEN
60870     RETURN TRUE;
60871   END IF;
60872
60873   RETURN FALSE;
60874 END;
60875 $_$;
60876
60877
60878 ALTER FUNCTION public.iteminventoryuominuse(integer) OWNER TO admin;
60879
60880 --
60881 -- TOC entry 1884 (class 1255 OID 146566678)
60882 -- Dependencies: 4536 8
60883 -- Name: iteminvpricerat(integer); Type: FUNCTION; Schema: public; Owner: admin
60884 --
60885
60886 CREATE FUNCTION iteminvpricerat(integer) RETURNS numeric
60887     LANGUAGE plpgsql STABLE
60888     AS $_$
60889 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60890 -- See www.xtuple.com/CPAL for the full text of the software license.
60891 DECLARE
60892   pItemid ALIAS FOR $1;
60893   _fromUomid INTEGER;
60894   _toUomid INTEGER;
60895   _ratio NUMERIC;
60896 BEGIN
60897
60898   IF(pItemid IS NULL) THEN
60899     RETURN 1.0;
60900   END IF;
60901
60902   SELECT item_inv_uom_id, item_price_uom_id
60903     INTO _fromUomid, _toUomid
60904     FROM item
60905    WHERE(item_id=pItemid);
60906
60907   IF(NOT FOUND) THEN
60908     RAISE EXCEPTION 'No item record found for item_id %', pItemid;
60909   END IF;
60910
60911   IF(_fromUomid = _toUomid) THEN
60912     RETURN 1.0;
60913   END IF;
60914
60915   -- Return the ration as inventory / price
60916   SELECT CASE WHEN(itemuomconv_from_uom_id=_fromUomid) THEN itemuomconv_from_value / itemuomconv_to_value
60917               ELSE itemuomconv_to_value / itemuomconv_from_value
60918          END
60919     INTO _ratio
60920     FROM itemuomconv
60921    WHERE((((itemuomconv_from_uom_id=_fromUomid) AND (itemuomconv_to_uom_id=_toUomid))
60922        OR ((itemuomconv_from_uom_id=_toUomid) AND (itemuomconv_to_uom_id=_fromUomid)))
60923      AND (itemuomconv_item_id=pItemid));
60924
60925   IF(NOT FOUND) THEN
60926     RAISE EXCEPTION 'No itemuomconv record found for item_id % to item_price_uomid %', pItemid, _toUomid;
60927   END IF;
60928   
60929   RETURN _ratio;
60930 END;
60931 $_$;
60932
60933
60934 ALTER FUNCTION public.iteminvpricerat(integer) OWNER TO admin;
60935
60936 --
60937 -- TOC entry 1885 (class 1255 OID 146566679)
60938 -- Dependencies: 2684 4536 8
60939 -- Name: itemipsprice(integer, integer, integer, numeric, integer, integer, integer, date, date, integer); Type: FUNCTION; Schema: public; Owner: admin
60940 --
60941
60942 CREATE FUNCTION itemipsprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date, pasof date, psiteid integer) RETURNS SETOF itemprice
60943     LANGUAGE plpgsql
60944     AS $$
60945 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
60946 -- See www.xtuple.com/CPAL for the full text of the software license.
60947 DECLARE
60948   _row  itemprice%ROWTYPE;
60949   _sale RECORD;
60950   _ips RECORD;
60951   _item RECORD;
60952   _cust RECORD;
60953   _shipto RECORD;
60954   _iteminvpricerat NUMERIC := 1.0;
60955   _listprice NUMERIC := 0.0;
60956   _qty NUMERIC;
60957   _asof DATE;
60958   _wholesalepricecosting BOOLEAN := false;
60959   _long30markups BOOLEAN := false;
60960   _itempricingprecedence BOOLEAN := false;
60961
60962 BEGIN
60963   _wholesalepricecosting := fetchMetricBool('WholesalePriceCosting');
60964   _long30markups := fetchMetricBool('Long30Markups');
60965   _itempricingprecedence := fetchMetricBool('ItemPricingPrecedence');
60966
60967 -- Return the itemPrice in the currency passed in as pCurrid
60968   _qty := itemuomtouom(pItemid, pQtyUOM, NULL, pQty);
60969
60970 -- If no as of passed, use current date
60971   _asof := COALESCE(pAsOf, CURRENT_DATE);
60972
60973 --  Cache Item, Customer and Shipto
60974   SELECT item.*, itemCost(itemsite_id) AS invcost INTO _item
60975   FROM item LEFT OUTER JOIN itemsite ON (itemsite_item_id=item_id AND itemsite_warehous_id=pSiteid)
60976   WHERE (item_id=pItemid);
60977
60978   SELECT * INTO _cust
60979   FROM custinfo JOIN custtype ON (custtype_id=cust_custtype_id)
60980   WHERE (cust_id=pCustid);
60981
60982   SELECT * INTO _shipto
60983   FROM shiptoinfo
60984   WHERE (shipto_id=pShiptoid);
60985
60986 -- Get a value here so we do not have to call the function several times
60987   SELECT itemuomtouomratio(pItemid, pPriceUOM, _item.item_price_uom_id) AS ratio
60988     INTO _iteminvpricerat;
60989
60990 -- First get a sales price if any so we when we find other prices
60991 -- we can determine if we want that price or this price.
60992 --  Check for a Sale Price
60993   SELECT INTO _sale
60994     currToCurr(ipshead_curr_id, pCurrid, ipsprice_price, pEffective) AS rightprice, ipsitem_type AS righttype
60995   FROM (
60996   SELECT ipsitem_ipshead_id AS ipsprice_ipshead_id, ipsitem_type,
60997          CASE WHEN (ipsitem_type = 'N') THEN
60998                (ipsitem_price * itemuomtouomratio(_item.item_id, pPriceUOM, ipsitem_price_uom_id))
60999               WHEN (ipsitem_type = 'D') THEN
61000                noNeg(_item.item_listprice - (_item.item_listprice * ipsitem_discntprcnt) - ipsitem_fixedamtdiscount) * _iteminvpricerat
61001               WHEN ((ipsitem_type = 'M') AND _long30markups AND _wholesalepricecosting) THEN
61002                (_item.item_listcost / (1.0 - ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61003               WHEN ((ipsitem_type = 'M') AND _long30markups) THEN
61004                (_item.invcost / (1.0 - ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61005               WHEN (ipsitem_type = 'M' AND _wholesalepricecosting) THEN
61006                (_item.item_listcost + (_item.item_listcost * ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61007               WHEN (ipsitem_type = 'M') THEN
61008                (_item.invcost + (_item.invcost * ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61009               ELSE 0.00
61010          END AS ipsprice_price,
61011          CASE WHEN (ipsitem_item_id=_item.item_id) THEN itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak)
61012               ELSE ipsitem_qtybreak
61013          END AS ipsprice_qtybreak,
61014          (COALESCE(ipsitem_price_uom_id, -1)=COALESCE(pPriceUOM,-1)) AS uommatched,
61015          CASE WHEN (_itempricingprecedence) THEN (COALESCE(ipsitem_item_id, -1)=_item.item_id)
61016               ELSE true END AS itemmatched
61017     FROM ipsiteminfo
61018    WHERE(ipsitem_item_id=_item.item_id) OR (ipsitem_prodcat_id=_item.item_prodcat_id) ) AS
61019         ipsprice, ipshead, ipsass, sale
61020   WHERE ( (ipsprice_ipshead_id=ipshead_id)
61021     AND   (sale_ipshead_id=ipsprice_ipshead_id)
61022     AND   (_asof BETWEEN sale_startdate AND sale_enddate)
61023     AND   (ipsprice_qtybreak <= _qty)
61024     AND   (ipsass_ipshead_id=ipshead_id)
61025     AND ( (ipsass_shipto_id=_shipto.shipto_id)
61026      OR   ((COALESCE(LENGTH(ipsass_shipto_pattern), 0) > 0) AND (_shipto.shipto_num ~ ipsass_shipto_pattern))
61027      OR   (ipsass_cust_id=_cust.cust_id)
61028      OR   (ipsass_custtype_id=_cust.cust_custtype_id)
61029      OR   ((COALESCE(LENGTH(ipsass_custtype_pattern), 0) > 0) AND (_cust.custtype_code ~ ipsass_custtype_pattern)) )
61030         )
61031   ORDER BY itemmatched DESC, uommatched DESC, ipsprice_qtybreak DESC, ipsprice_price ASC
61032   LIMIT 1;
61033
61034 -- Find the best Price Schedule Price
61035  
61036   SELECT INTO _ips
61037     currToCurr(ipshead_curr_id, pCurrid, protoprice, pEffective) AS rightprice, ipsitem_type AS righttype
61038   
61039   FROM (
61040     SELECT *,
61041            CASE WHEN (COALESCE(ipsass_shipto_id, -1) > 0) THEN 1
61042              WHEN (COALESCE(LENGTH(ipsass_shipto_pattern), 0) > 0) THEN 2
61043              WHEN (COALESCE(ipsass_cust_id, -1) > 0) THEN 3
61044              WHEN (COALESCE(ipsass_custtype_id, -1) > 0) THEN 4
61045              WHEN (COALESCE(LENGTH(ipsass_custtype_pattern), 0) > 0) THEN 5
61046              ELSE 99
61047            END AS assignseq,
61048            CASE WHEN (ipsitem_type = 'N') THEN
61049                  (ipsitem_price * itemuomtouomratio(_item.item_id, pPriceUOM, ipsitem_price_uom_id))
61050                 WHEN (ipsitem_type = 'D') THEN
61051                  noNeg(_item.item_listprice - (_item.item_listprice * ipsitem_discntprcnt) - ipsitem_fixedamtdiscount) * _iteminvpricerat
61052                 WHEN ((ipsitem_type = 'M') AND _long30markups AND _wholesalepricecosting) THEN
61053                  (_item.item_listcost / (1.0 - ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61054                 WHEN ((ipsitem_type = 'M') AND _long30markups) THEN
61055                  (_item.invcost / (1.0 - ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61056                 WHEN (ipsitem_type = 'M' AND _wholesalepricecosting) THEN
61057                  (_item.item_listcost + (_item.item_listcost * ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61058                 WHEN (ipsitem_type = 'M') THEN
61059                  (_item.invcost + (_item.invcost * ipsitem_discntprcnt) + ipsitem_fixedamtdiscount) * _iteminvpricerat
61060                 ELSE 0.00
61061            END AS protoprice,
61062            CASE WHEN (ipsitem_item_id=_item.item_id) THEN itemuomtouom(ipsitem_item_id, ipsitem_qty_uom_id, NULL, ipsitem_qtybreak)
61063                 ELSE ipsitem_qtybreak
61064            END AS protoqtybreak,
61065            (COALESCE(ipsitem_price_uom_id, -1)=COALESCE(pPriceUOM,-1)) AS uommatched,
61066            CASE WHEN (_itempricingprecedence) THEN (COALESCE(ipsitem_item_id, -1)=_item.item_id)
61067                 ELSE true END AS itemmatched
61068     FROM ipsass JOIN ipshead ON (ipshead_id=ipsass_ipshead_id)
61069                 JOIN ipsiteminfo ON (ipsitem_ipshead_id=ipshead_id)
61070     WHERE ((ipsitem_item_id=_item.item_id) OR (ipsitem_prodcat_id=_item.item_prodcat_id))
61071       AND (_asof BETWEEN ipshead_effective AND ipshead_expires)
61072       AND ((ipsitem_warehous_id=pSiteid) OR (ipsitem_warehous_id IS NULL))
61073       AND ( (ipsass_shipto_id=_shipto.shipto_id)
61074        OR   ((COALESCE(LENGTH(ipsass_shipto_pattern), 0) > 0) AND (_shipto.shipto_num ~ ipsass_shipto_pattern))
61075        OR   (ipsass_cust_id=_cust.cust_id)
61076        OR   (ipsass_custtype_id=_cust.cust_custtype_id)
61077        OR   ((COALESCE(LENGTH(ipsass_custtype_pattern), 0) > 0) AND (_cust.custtype_code ~ ipsass_custtype_pattern))
61078           )
61079   ) AS proto
61080   WHERE (protoqtybreak <= pQty)
61081   ORDER BY assignseq, itemmatched DESC, protoqtybreak DESC, rightprice
61082   LIMIT 1;
61083  
61084   IF (_ips.rightprice IS NOT NULL) THEN
61085     IF ((_sale.rightprice IS NOT NULL) AND (_sale.rightprice < _ips.rightprice)) THEN
61086       RAISE DEBUG 'itemprice, item=%, cust=%, shipto=%, sale price= %', pItemid, pCustid, pShiptoid, _sale.rightprice;
61087       _row.itemprice_price := _sale.rightprice;
61088       _row.itemprice_type := _sale.righttype;
61089       RETURN NEXT _row;
61090     END IF;
61091     RAISE DEBUG 'itemprice, item=%, cust=%, shipto=%, schedule price= %', pItemid, pCustid, pShiptoid, _ips.rightprice;
61092     _row.itemprice_price := _ips.rightprice;
61093     _row.itemprice_type := _ips.righttype;
61094     RETURN NEXT _row;
61095   END IF;
61096
61097 --  If item is exclusive then list list price does not apply
61098   IF (_item.item_exclusive) THEN
61099     RAISE DEBUG 'itemprice, item=%, cust=%, shipto=%, item exclusive, price=-9999', pItemid, pCustid, pShiptoid;
61100     _row.itemprice_price := -9999.0;
61101     _row.itemprice_type := '';
61102     RETURN NEXT _row;
61103   END IF;
61104
61105 --  Check for a list price
61106   _listprice := noNeg(currToLocal(pCurrid, _item.item_listprice - (_item.item_listprice * COALESCE(_cust.cust_discntprcnt, 0.0)), pEffective)
61107                       * itemuomtouomratio(pItemid, pPriceUOM, _item.item_price_uom_id));
61108
61109   RAISE DEBUG 'itemprice, item=%, cust=%, shipto=%, list price= %', pItemid, pCustid, pShiptoid, _listprice;
61110
61111   _row.itemprice_price := _listprice;
61112   _row.itemprice_type := 'P';
61113   RETURN NEXT _row;
61114
61115   RETURN;
61116
61117 END;
61118 $$;
61119
61120
61121 ALTER FUNCTION public.itemipsprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date, pasof date, psiteid integer) OWNER TO admin;
61122
61123 --
61124 -- TOC entry 1887 (class 1255 OID 146566682)
61125 -- Dependencies: 4536 8
61126 -- Name: itemlocdistqty(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
61127 --
61128
61129 CREATE FUNCTION itemlocdistqty(integer, integer) RETURNS numeric
61130     LANGUAGE plpgsql
61131     AS $_$
61132 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61133 -- See www.xtuple.com/CPAL for the full text of the software license.
61134 DECLARE
61135   pLocationid ALIAS FOR $1;
61136   pParentid ALIAS FOR $2;
61137   _qty NUMERIC;
61138   _tempQty NUMERIC;
61139
61140 BEGIN
61141
61142   SELECT COALESCE(SUM(itemlocdist_qty), 0) INTO _qty
61143   FROM itemlocdist
61144   WHERE ( (itemlocdist_source_type='L')
61145    AND (itemlocdist_source_id=pLocationid)
61146    AND (itemlocdist_itemlocdist_id=pParentid) );
61147
61148   SELECT COALESCE(SUM(itemlocdist_qty), 0) INTO _tempQty
61149   FROM itemlocdist, itemloc
61150   WHERE ( (itemlocdist_source_type='I')
61151    AND (itemlocdist_source_id=itemloc_id)
61152    AND (itemloc_location_id=pLocationid)
61153    AND (itemlocdist_itemlocdist_id=pParentid) );
61154
61155   _qty := (_qty + _tempQty);
61156
61157   RETURN _qty;
61158
61159 END;
61160 $_$;
61161
61162
61163 ALTER FUNCTION public.itemlocdistqty(integer, integer) OWNER TO admin;
61164
61165 --
61166 -- TOC entry 1886 (class 1255 OID 146566681)
61167 -- Dependencies: 4536 8
61168 -- Name: itemlocdistqty(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
61169 --
61170
61171 CREATE FUNCTION itemlocdistqty(text, integer, integer) RETURNS numeric
61172     LANGUAGE plpgsql
61173     AS $_$
61174 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61175 -- See www.xtuple.com/CPAL for the full text of the software license.
61176 DECLARE
61177   pTypes ALIAS FOR $1;
61178   pLocationid ALIAS FOR $2;
61179   pParentid ALIAS FOR $3;
61180   _qty NUMERIC := 0;
61181   _tempQty NUMERIC;
61182
61183 BEGIN
61184
61185   IF (strpos(pTypes, 'L') > 0) THEN
61186     SELECT COALESCE(SUM(itemlocdist_qty), 0) INTO _tempQty
61187     FROM itemlocdist
61188     WHERE ( (itemlocdist_source_type='L')
61189      AND (itemlocdist_source_id=pLocationid)
61190      AND (itemlocdist_itemlocdist_id=pParentid) );
61191
61192     _qty := (_qty + _tempQty);
61193   END IF;
61194
61195   IF (strpos(pTypes, 'I') > 0) THEN
61196     SELECT COALESCE(SUM(itemlocdist_qty), 0) INTO _tempQty
61197     FROM itemlocdist, itemloc
61198     WHERE ( (itemlocdist_source_type='I')
61199      AND (itemlocdist_source_id=itemloc_id)
61200      AND (itemloc_location_id=pLocationid)
61201      AND (itemlocdist_itemlocdist_id=pParentid) );
61202
61203     _qty := (_qty + _tempQty);
61204   END IF;
61205
61206   RETURN _qty;
61207
61208 END;
61209 $_$;
61210
61211
61212 ALTER FUNCTION public.itemlocdistqty(text, integer, integer) OWNER TO admin;
61213
61214 --
61215 -- TOC entry 1888 (class 1255 OID 146566683)
61216 -- Dependencies: 4536 8
61217 -- Name: itemprice(integer, integer, integer, numeric, integer, date); Type: FUNCTION; Schema: public; Owner: admin
61218 --
61219
61220 CREATE FUNCTION itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pcurrid integer, peffective date) RETURNS numeric
61221     LANGUAGE plpgsql
61222     AS $$
61223 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61224 -- See www.xtuple.com/CPAL for the full text of the software license.
61225 DECLARE
61226   _item RECORD;
61227
61228 BEGIN
61229   SELECT item_inv_uom_id, item_price_uom_id
61230     INTO _item
61231     FROM item
61232    WHERE(item_id=pItemid);
61233   IF (FOUND) THEN
61234     RETURN itemPrice(pItemid, pCustid, pShiptoid, pQty, _item.item_inv_uom_id, _item.item_price_uom_id, pCurrid, pEffective);
61235   END IF;
61236   RETURN -9999;
61237 END;
61238 $$;
61239
61240
61241 ALTER FUNCTION public.itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pcurrid integer, peffective date) OWNER TO admin;
61242
61243 --
61244 -- TOC entry 1889 (class 1255 OID 146566684)
61245 -- Dependencies: 4536 8
61246 -- Name: itemprice(integer, integer, integer, numeric, integer, integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
61247 --
61248
61249 CREATE FUNCTION itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date) RETURNS numeric
61250     LANGUAGE plpgsql
61251     AS $$
61252 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61253 -- See www.xtuple.com/CPAL for the full text of the software license.
61254 DECLARE
61255
61256 BEGIN
61257   RETURN itemPrice(pItemid, pCustid, pShiptoid, pQty, pQtyUOM, pPriceUOM, pCurrid, pEffective, CURRENT_DATE);
61258 END;
61259 $$;
61260
61261
61262 ALTER FUNCTION public.itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date) OWNER TO admin;
61263
61264 --
61265 -- TOC entry 1890 (class 1255 OID 146566685)
61266 -- Dependencies: 4536 8
61267 -- Name: itemprice(integer, integer, integer, numeric, integer, integer, integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
61268 --
61269
61270 CREATE FUNCTION itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date, pasof date) RETURNS numeric
61271     LANGUAGE plpgsql
61272     AS $$
61273 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61274 -- See www.xtuple.com/CPAL for the full text of the software license.
61275 DECLARE
61276
61277 BEGIN
61278   RETURN itemPrice(pItemid, pCustid, pShiptoid, pQty, pQtyUOM, pPriceUOM, pCurrid, pEffective, pAsOf, NULL);
61279 END;
61280 $$;
61281
61282
61283 ALTER FUNCTION public.itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date, pasof date) OWNER TO admin;
61284
61285 --
61286 -- TOC entry 1891 (class 1255 OID 146566686)
61287 -- Dependencies: 4536 8
61288 -- Name: itemprice(integer, integer, integer, numeric, integer, integer, integer, date, date, integer); Type: FUNCTION; Schema: public; Owner: admin
61289 --
61290
61291 CREATE FUNCTION itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date, pasof date, psiteid integer) RETURNS numeric
61292     LANGUAGE plpgsql
61293     AS $$
61294 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61295 -- See www.xtuple.com/CPAL for the full text of the software license.
61296 DECLARE
61297   _r RECORD;
61298
61299 BEGIN
61300   SELECT * FROM itemIpsPrice(pItemid, pCustid, pShiptoid, pQty, pQtyUOM, pPriceUOM,
61301                              pCurrid, pEffective, pAsOf, pSiteid) INTO _r;
61302   RETURN _r.itemprice_price;
61303 END;
61304 $$;
61305
61306
61307 ALTER FUNCTION public.itemprice(pitemid integer, pcustid integer, pshiptoid integer, pqty numeric, pqtyuom integer, ppriceuom integer, pcurrid integer, peffective date, pasof date, psiteid integer) OWNER TO admin;
61308
61309 --
61310 -- TOC entry 1892 (class 1255 OID 146566687)
61311 -- Dependencies: 4536 8
61312 -- Name: itemsellinguom(integer); Type: FUNCTION; Schema: public; Owner: admin
61313 --
61314
61315 CREATE FUNCTION itemsellinguom(integer) RETURNS text
61316     LANGUAGE plpgsql
61317     AS $_$
61318 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61319 -- See www.xtuple.com/CPAL for the full text of the software license.
61320 DECLARE
61321   pItemid ALIAS FOR $1;
61322
61323 BEGIN
61324   RETURN itemUOMByType(pItemid, 'Selling');
61325 END;
61326 $_$;
61327
61328
61329 ALTER FUNCTION public.itemsellinguom(integer) OWNER TO admin;
61330
61331 --
61332 -- TOC entry 1893 (class 1255 OID 146566688)
61333 -- Dependencies: 4536 8
61334 -- Name: itemsrcprice(integer, numeric, integer, date); Type: FUNCTION; Schema: public; Owner: admin
61335 --
61336
61337 CREATE FUNCTION itemsrcprice(pitemsrcid integer, pqty numeric, pcurrid integer, peffective date) RETURNS numeric
61338     LANGUAGE plpgsql
61339     AS $$
61340 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61341 -- See www.xtuple.com/CPAL for the full text of the software license.
61342 DECLARE
61343   _price NUMERIC := 0.0;
61344
61345 BEGIN
61346
61347   SELECT itemsrcPrice(pItemsrcid, -1, FALSE, pQty, pCurrid, pEffective) INTO _price;
61348
61349   RETURN _price;
61350
61351 END;
61352 $$;
61353
61354
61355 ALTER FUNCTION public.itemsrcprice(pitemsrcid integer, pqty numeric, pcurrid integer, peffective date) OWNER TO admin;
61356
61357 --
61358 -- TOC entry 1894 (class 1255 OID 146566689)
61359 -- Dependencies: 4536 8
61360 -- Name: itemsrcprice(integer, integer, boolean, numeric, integer, date); Type: FUNCTION; Schema: public; Owner: admin
61361 --
61362
61363 CREATE FUNCTION itemsrcprice(pitemsrcid integer, psiteid integer, pdropship boolean, pqty numeric, pcurrid integer, peffective date) RETURNS numeric
61364     LANGUAGE plpgsql
61365     AS $$
61366 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61367 -- See www.xtuple.com/CPAL for the full text of the software license.
61368 DECLARE
61369   _price NUMERIC := 0.0;
61370   _r RECORD;
61371   _effective DATE;
61372
61373 BEGIN
61374 -- If no pEffective passed, use current date
61375   _effective := COALESCE(pEffective, CURRENT_DATE);
61376
61377 --  Cache Itemsrc and Item
61378   SELECT *
61379   INTO _r
61380   FROM itemsrc JOIN item ON (item_id=itemsrc_item_id)
61381   WHERE (itemsrc_id=pItemsrcid);
61382   IF (NOT FOUND) THEN
61383     RAISE EXCEPTION 'itemsrc % not found.', pItemsrcid;
61384   END IF;
61385
61386 --  Determine price
61387   SELECT currToCurr(itemsrcp_curr_id, pCurrid, price, _effective) INTO _price
61388   FROM (
61389     SELECT *,
61390            CASE itemsrcp_type WHEN ('N') THEN itemsrcp_price
61391                               WHEN ('D') THEN (_r.item_listcost - (_r.item_listcost * itemsrcp_discntprcnt) - itemsrcp_fixedamtdiscount)
61392                               ELSE 0.0
61393            END AS price
61394     FROM itemsrcp
61395     WHERE ( (itemsrcp_itemsrc_id=_r.itemsrc_id)
61396       AND   ((itemsrcp_warehous_id=pSiteid) OR (itemsrcp_warehous_id=-1))
61397       AND   ((itemsrcp_dropship=pDropship) OR (NOT itemsrcp_dropship))
61398       AND   (itemsrcp_qtybreak <= pQty) )
61399     ORDER BY itemsrcp_qtybreak DESC
61400     LIMIT 1
61401        ) AS data
61402   ;
61403
61404   RETURN _price;
61405
61406 END;
61407 $$;
61408
61409
61410 ALTER FUNCTION public.itemsrcprice(pitemsrcid integer, psiteid integer, pdropship boolean, pqty numeric, pcurrid integer, peffective date) OWNER TO admin;
61411
61412 --
61413 -- TOC entry 1895 (class 1255 OID 146566690)
61414 -- Dependencies: 4536 8
61415 -- Name: itemuombytype(integer, text); Type: FUNCTION; Schema: public; Owner: admin
61416 --
61417
61418 CREATE FUNCTION itemuombytype(integer, text) RETURNS text
61419     LANGUAGE plpgsql STABLE
61420     AS $_$
61421 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61422 -- See www.xtuple.com/CPAL for the full text of the software license.
61423 DECLARE
61424   pItemid ALIAS FOR $1;
61425   pUomtype ALIAS FOR $2;
61426   _uom TEXT;
61427 BEGIN
61428   SELECT uom_name INTO _uom FROM (
61429   SELECT uom_name
61430     FROM item
61431     JOIN itemuomconv ON (itemuomconv_item_id=item_id)
61432     JOIN itemuom ON (itemuom_itemuomconv_id=itemuomconv_id)
61433     JOIN uomtype ON (itemuom_uomtype_id=uomtype_id)
61434     JOIN uom ON (itemuomconv_to_uom_id=uom_id)
61435    WHERE((item_id=pItemid)
61436      AND (uomtype_name=pUomtype)
61437      AND (item_inv_uom_id != itemuomconv_to_uom_id))
61438   UNION
61439   SELECT uom_name
61440     FROM item
61441     JOIN itemuomconv ON (itemuomconv_item_id=item_id)
61442     JOIN itemuom ON (itemuom_itemuomconv_id=itemuomconv_id)
61443     JOIN uomtype ON (itemuom_uomtype_id=uomtype_id)
61444     JOIN uom ON (itemuomconv_from_uom_id=uom_id)
61445    WHERE((item_id=pItemid)
61446      AND (uomtype_name=pUomtype)
61447      AND (item_inv_uom_id != itemuomconv_from_uom_id))) data
61448    LIMIT 1;
61449
61450   IF (NOT FOUND) THEN
61451     SELECT uom_name
61452       INTO _uom
61453       FROM item
61454       JOIN uom ON (item_inv_uom_id=uom_id)
61455      WHERE(item_id=pItemid);
61456   END IF;
61457
61458   RETURN _uom;
61459 END;
61460 $_$;
61461
61462
61463 ALTER FUNCTION public.itemuombytype(integer, text) OWNER TO admin;
61464
61465 --
61466 -- TOC entry 1896 (class 1255 OID 146566691)
61467 -- Dependencies: 4536 8
61468 -- Name: itemuomfractionalbytype(integer, text); Type: FUNCTION; Schema: public; Owner: admin
61469 --
61470
61471 CREATE FUNCTION itemuomfractionalbytype(integer, text) RETURNS boolean
61472     LANGUAGE plpgsql
61473     AS $_$
61474 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61475 -- See www.xtuple.com/CPAL for the full text of the software license.
61476 DECLARE
61477   pItemid ALIAS FOR $1;
61478   pUomtype ALIAS FOR $2;
61479   _frac BOOLEAN;
61480 BEGIN
61481   SELECT itemuomconv_fractional
61482     INTO _frac
61483     FROM item
61484     JOIN itemuomconv ON (itemuomconv_item_id=item_id)
61485     JOIN itemuom ON (itemuom_itemuomconv_id=itemuomconv_id)
61486     JOIN uomtype ON (itemuom_uomtype_id=uomtype_id)
61487    WHERE((item_id=pItemid)
61488      AND (uomtype_name=pUomtype))
61489    LIMIT 1;
61490
61491   IF (NOT FOUND) THEN
61492     SELECT item_fractional
61493       INTO _frac
61494       FROM item
61495       JOIN uom ON (item_inv_uom_id=uom_id)
61496      WHERE(item_id=pItemid);
61497   END IF;
61498
61499   RETURN _frac;
61500 END;
61501 $_$;
61502
61503
61504 ALTER FUNCTION public.itemuomfractionalbytype(integer, text) OWNER TO admin;
61505
61506 --
61507 -- TOC entry 1898 (class 1255 OID 146566692)
61508 -- Dependencies: 4536 8
61509 -- Name: itemuomfractionalbyuom(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
61510 --
61511
61512 CREATE FUNCTION itemuomfractionalbyuom(integer, integer) RETURNS boolean
61513     LANGUAGE plpgsql
61514     AS $_$
61515 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61516 -- See www.xtuple.com/CPAL for the full text of the software license.
61517 DECLARE
61518   pItemid ALIAS FOR $1;
61519   pUomid ALIAS FOR $2;
61520   _frac BOOLEAN;
61521 BEGIN
61522   SELECT itemuomconv_fractional
61523     INTO _frac
61524     FROM item
61525     JOIN itemuomconv ON (itemuomconv_item_id=item_id)
61526    WHERE((item_id=pItemid)
61527      AND ((itemuomconv_from_uom_id=item_inv_uom_id AND itemuomconv_to_uom_id=pUomid)
61528        OR (itemuomconv_to_uom_id=item_inv_uom_id AND itemuomconv_from_uom_id=pUomid)))
61529    LIMIT 1;
61530
61531   IF (NOT FOUND) THEN
61532     SELECT item_fractional
61533       INTO _frac
61534       FROM item
61535       JOIN uom ON (item_inv_uom_id=uom_id)
61536      WHERE(item_id=pItemid);
61537   END IF;
61538
61539   RETURN _frac;
61540 END;
61541 $_$;
61542
61543
61544 ALTER FUNCTION public.itemuomfractionalbyuom(integer, integer) OWNER TO admin;
61545
61546 --
61547 -- TOC entry 1899 (class 1255 OID 146566693)
61548 -- Dependencies: 4536 8
61549 -- Name: itemuomratiobytype(integer, text); Type: FUNCTION; Schema: public; Owner: admin
61550 --
61551
61552 CREATE FUNCTION itemuomratiobytype(integer, text) RETURNS numeric
61553     LANGUAGE plpgsql STABLE
61554     AS $_$
61555 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61556 -- See www.xtuple.com/CPAL for the full text of the software license.
61557 DECLARE
61558   pItemid ALIAS FOR $1;
61559   pUomtype ALIAS FOR $2;
61560   _ratio NUMERIC;
61561 BEGIN
61562   -- Return the ration as alternate / inventory uom
61563   SELECT CASE WHEN(itemuomconv_from_uom_id=item_inv_uom_id) THEN itemuomconv_to_value / itemuomconv_from_value
61564               ELSE itemuomconv_from_value / itemuomconv_to_value
61565          END
61566     INTO _ratio
61567     FROM item
61568     JOIN itemuomconv ON (itemuomconv_item_id=item_id)
61569     JOIN itemuom ON (itemuom_itemuomconv_id=itemuomconv_id)
61570     JOIN uomtype ON (itemuom_uomtype_id=uomtype_id)
61571    WHERE((item_id=pItemid)
61572      AND (uomtype_name=pUomtype))
61573    LIMIT 1;
61574
61575   IF (NOT FOUND) THEN
61576     _ratio := 1.0;
61577   END IF;
61578
61579   RETURN _ratio;
61580 END;
61581 $_$;
61582
61583
61584 ALTER FUNCTION public.itemuomratiobytype(integer, text) OWNER TO admin;
61585
61586 --
61587 -- TOC entry 1900 (class 1255 OID 146566694)
61588 -- Dependencies: 4536 8
61589 -- Name: itemuomtouom(integer, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
61590 --
61591
61592 CREATE FUNCTION itemuomtouom(integer, integer, integer, numeric) RETURNS numeric
61593     LANGUAGE plpgsql STABLE
61594     AS $_$
61595 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61596 -- See www.xtuple.com/CPAL for the full text of the software license.
61597 BEGIN
61598   RETURN itemuomtouom($1, $2, $3, $4, 'qty');
61599 END;
61600 $_$;
61601
61602
61603 ALTER FUNCTION public.itemuomtouom(integer, integer, integer, numeric) OWNER TO admin;
61604
61605 --
61606 -- TOC entry 1901 (class 1255 OID 146566695)
61607 -- Dependencies: 4536 8
61608 -- Name: itemuomtouom(integer, integer, integer, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
61609 --
61610
61611 CREATE FUNCTION itemuomtouom(pitemid integer, puomidfrom integer, puomidto integer, pqtyfrom numeric, plocale text) RETURNS numeric
61612     LANGUAGE plpgsql STABLE
61613     AS $$
61614 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61615 -- See www.xtuple.com/CPAL for the full text of the software license.
61616 DECLARE
61617   _uomidFrom INTEGER;
61618   _uomidTo   INTEGER;
61619   _uomidInv  INTEGER;
61620   _valueFrom NUMERIC := 0.0;
61621   _valueTo   NUMERIC := 0.0;
61622   _value     NUMERIC := 0.0;
61623   _item      RECORD;
61624   _conv      RECORD;
61625   _frac      BOOLEAN := FALSE;
61626 BEGIN
61627
61628   SELECT item_inv_uom_id, item_fractional
61629     INTO _item
61630     FROM item
61631    WHERE(item_id=pItemid);
61632   IF(NOT FOUND) THEN
61633     RAISE EXCEPTION 'No item record was found for item id %', pItemid;
61634   END IF;
61635
61636   _uomidFrom := COALESCE(pUomidFrom, _item.item_inv_uom_id);
61637   _uomidTo   := COALESCE(pUomidTo,   _item.item_inv_uom_id);
61638   _uomidInv  := _item.item_inv_uom_id;
61639
61640   -- Should we round the qty here or not?
61641   IF(_uomidFrom = _uomidTo) THEN
61642     -- Both from/to are the same. If it is the item inv uom
61643     -- then use the item fractional value otherwise assume
61644     -- it is fractional for now so the user gets the same value back.
61645     IF(_uomidFrom = _item.item_inv_uom_id) THEN
61646       _frac := _item.item_fractional;
61647     ELSE
61648       _frac := true;
61649     END IF;
61650     RETURN roundLocale(_frac, pQtyFrom, pLocale);
61651   END IF;
61652
61653   -- Try a direct conversion
61654   SELECT itemuomconv_from_uom_id, itemuomconv_from_value,
61655          itemuomconv_to_uom_id, itemuomconv_to_value,
61656          itemuomconv_fractional
61657     INTO _conv
61658     FROM itemuomconv
61659    WHERE(((itemuomconv_from_uom_id=_uomidFrom AND itemuomconv_to_uom_id=_uomidTo)
61660        OR (itemuomconv_from_uom_id=_uomidTo AND itemuomconv_to_uom_id=_uomidFrom))
61661      AND (itemuomconv_item_id=pItemid));
61662   IF(FOUND) THEN
61663     IF(_conv.itemuomconv_from_uom_id=_uomidFrom) THEN
61664       _valueFrom := _conv.itemuomconv_from_value;
61665       _valueTo := _conv.itemuomconv_to_value;
61666     ELSE
61667       _valueFrom := _conv.itemuomconv_to_value;
61668       _valueTo := _conv.itemuomconv_from_value;
61669     END IF;
61670
61671     -- If we are converting to the item inv uom use the item fractional value
61672     -- otherwise use the conversion fractional value.
61673     if(_uomidTo = _uomidInv) THEN
61674       _frac := _item.item_fractional;
61675     ELSE
61676       _frac := _conv.itemuomconv_fractional;
61677     END IF;
61678     _value := roundLocale(_frac, ((_valueTo/_valueFrom) * pQtyFrom), pLocale);
61679   ELSE
61680     -- Try to convert the from uom to the inventory uom
61681     SELECT itemuomconv_from_uom_id, itemuomconv_from_value,
61682            itemuomconv_to_uom_id, itemuomconv_to_value,
61683            itemuomconv_fractional
61684       INTO _conv
61685       FROM itemuomconv
61686      WHERE(((itemuomconv_from_uom_id=_uomidFrom AND itemuomconv_to_uom_id=_uomidInv)
61687          OR (itemuomconv_from_uom_id=_uomidInv AND itemuomconv_to_uom_id=_uomidFrom))
61688        AND (itemuomconv_item_id=pItemid));
61689     IF(NOT FOUND) THEN
61690       RAISE EXCEPTION 'A conversion for item_id % from uom_id % to inv_uom_id % was not found.', pItemid, _uomidFrom, _uomidInv;
61691     END IF;
61692     IF(_conv.itemuomconv_from_uom_id=_uomidInv) THEN
61693       _valueFrom := _conv.itemuomconv_from_value;
61694       _valueTo := _conv.itemuomconv_to_value;
61695     ELSE
61696       _valueFrom := _conv.itemuomconv_to_value;
61697       _valueTo := _conv.itemuomconv_from_value;
61698     END IF;
61699     _value := (_valueTo / _valueFrom);
61700     IF (_conv.itemuomconv_fractional OR _item.item_fractional) THEN
61701       _frac := TRUE;
61702     END IF;
61703     -- Try to convert the to uom to the inventory uom
61704     SELECT itemuomconv_from_uom_id, itemuomconv_from_value,
61705            itemuomconv_to_uom_id, itemuomconv_to_value,
61706            itemuomconv_fractional
61707       INTO _conv
61708       FROM itemuomconv
61709      WHERE(((itemuomconv_from_uom_id=_uomidInv AND itemuomconv_to_uom_id=_uomidTo)
61710          OR (itemuomconv_from_uom_id=_uomidTo AND itemuomconv_to_uom_id=_uomidInv))
61711        AND (itemuomconv_item_id=pItemid));
61712     IF(NOT FOUND) THEN
61713       RAISE EXCEPTION 'A conversion for item_id % from uom_id % to inv_uom_id % was not found.', pItemid, _uomidTo, _uomidInv;
61714     END IF;
61715     IF(_conv.itemuomconv_from_uom_id=_uomidInv) THEN
61716       _valueFrom := _conv.itemuomconv_from_value;
61717       _valueTo := _conv.itemuomconv_to_value;
61718     ELSE
61719       _valueFrom := _conv.itemuomconv_to_value;
61720       _valueTo := _conv.itemuomconv_from_value;
61721     END IF;
61722     _value := _value * (_valueTo / _valueFrom);
61723     IF (_conv.itemuomconv_fractional OR _item.item_fractional) THEN
61724       _frac := TRUE;
61725     END IF;
61726     _value := roundLocale(_frac, (_value * pQtyFrom), pLocale);
61727   END IF;
61728
61729   RETURN _value;
61730 END;
61731 $$;
61732
61733
61734 ALTER FUNCTION public.itemuomtouom(pitemid integer, puomidfrom integer, puomidto integer, pqtyfrom numeric, plocale text) OWNER TO admin;
61735
61736 --
61737 -- TOC entry 1902 (class 1255 OID 146566696)
61738 -- Dependencies: 4536 8
61739 -- Name: itemuomtouomratio(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
61740 --
61741
61742 CREATE FUNCTION itemuomtouomratio(pitemid integer, puomidfrom integer, puomidto integer) RETURNS numeric
61743     LANGUAGE plpgsql STABLE
61744     AS $$
61745 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61746 -- See www.xtuple.com/CPAL for the full text of the software license.
61747 DECLARE
61748   _uomidFrom INTEGER;
61749   _uomidTo   INTEGER;
61750   _uomidInv  INTEGER;
61751   _valueFrom NUMERIC := 0.0;
61752   _valueTo   NUMERIC := 0.0;
61753   _value     NUMERIC := 0.0;
61754   _item      RECORD;
61755   _conv      RECORD;
61756 BEGIN
61757
61758   SELECT item_inv_uom_id
61759     INTO _item
61760     FROM item
61761    WHERE(item_id=pItemid);
61762   IF(NOT FOUND) THEN
61763     RAISE EXCEPTION 'No item record was found for item id %', pItemid;
61764   END IF;
61765
61766   _uomidFrom := COALESCE(pUomidFrom, _item.item_inv_uom_id);
61767   _uomidTo   := COALESCE(pUomidTo,   _item.item_inv_uom_id);
61768   _uomidInv  := _item.item_inv_uom_id;
61769
61770   IF(_uomidFrom = _uomidTo) THEN
61771     RETURN 1.0;
61772   END IF;
61773
61774   -- Try a direct conversion
61775   SELECT itemuomconv_from_uom_id, itemuomconv_from_value,
61776          itemuomconv_to_uom_id, itemuomconv_to_value
61777     INTO _conv
61778     FROM itemuomconv
61779    WHERE(((itemuomconv_from_uom_id=_uomidFrom AND itemuomconv_to_uom_id=_uomidTo)
61780        OR (itemuomconv_from_uom_id=_uomidTo AND itemuomconv_to_uom_id=_uomidFrom))
61781      AND (itemuomconv_item_id=pItemid));
61782   IF(FOUND) THEN
61783     IF(_conv.itemuomconv_from_uom_id=_uomidFrom) THEN
61784       _valueFrom := _conv.itemuomconv_from_value;
61785       _valueTo := _conv.itemuomconv_to_value;
61786     ELSE
61787       _valueFrom := _conv.itemuomconv_to_value;
61788       _valueTo := _conv.itemuomconv_from_value;
61789     END IF;
61790     _value := (_valueTo / _valueFrom);
61791   ELSE
61792     -- Try to convert the from uom to the inventory uom
61793     SELECT itemuomconv_from_uom_id, itemuomconv_from_value,
61794            itemuomconv_to_uom_id, itemuomconv_to_value
61795       INTO _conv
61796       FROM itemuomconv
61797      WHERE(((itemuomconv_from_uom_id=_uomidFrom AND itemuomconv_to_uom_id=_uomidInv)
61798          OR (itemuomconv_from_uom_id=_uomidInv AND itemuomconv_to_uom_id=_uomidFrom))
61799        AND (itemuomconv_item_id=pItemid));
61800     IF(NOT FOUND) THEN
61801       RAISE EXCEPTION 'A conversion for item_id % from uom_id % to inv_uom_id % was not found.', pItemid, _uomidFrom, _uomidInv;
61802     END IF;
61803     IF(_conv.itemuomconv_from_uom_id=_uomidInv) THEN
61804       _valueFrom := _conv.itemuomconv_from_value;
61805       _valueTo := _conv.itemuomconv_to_value;
61806     ELSE
61807       _valueFrom := _conv.itemuomconv_to_value;
61808       _valueTo := _conv.itemuomconv_from_value;
61809     END IF;
61810     _value := (_valueTo / _valueFrom);
61811     -- Try to convert the to uom to the inventory uom
61812     SELECT itemuomconv_from_uom_id, itemuomconv_from_value,
61813            itemuomconv_to_uom_id, itemuomconv_to_value
61814       INTO _conv
61815       FROM itemuomconv
61816      WHERE(((itemuomconv_from_uom_id=_uomidInv AND itemuomconv_to_uom_id=_uomidTo)
61817          OR (itemuomconv_from_uom_id=_uomidTo AND itemuomconv_to_uom_id=_uomidInv))
61818        AND (itemuomconv_item_id=pItemid));
61819     IF(NOT FOUND) THEN
61820       RAISE EXCEPTION 'A conversion for item_id % from uom_id % to inv_uom_id % was not found.', pItemid, _uomidTo, _uomidInv;
61821     END IF;
61822     IF(_conv.itemuomconv_from_uom_id=_uomidInv) THEN
61823       _valueFrom := _conv.itemuomconv_from_value;
61824       _valueTo := _conv.itemuomconv_to_value;
61825     ELSE
61826       _valueFrom := _conv.itemuomconv_to_value;
61827       _valueTo := _conv.itemuomconv_from_value;
61828     END IF;
61829     _value := _value * (_valueTo / _valueFrom);
61830   END IF;
61831
61832   RETURN _value;
61833 END;
61834 $$;
61835
61836
61837 ALTER FUNCTION public.itemuomtouomratio(pitemid integer, puomidfrom integer, puomidto integer) OWNER TO admin;
61838
61839 --
61840 -- TOC entry 1903 (class 1255 OID 146566697)
61841 -- Dependencies: 8
61842 -- Name: last_agg(anyelement, anyelement); Type: FUNCTION; Schema: public; Owner: admin
61843 --
61844
61845 CREATE FUNCTION last_agg(anyelement, anyelement) RETURNS anyelement
61846     LANGUAGE sql STABLE
61847     AS $_$
61848   SELECT $2;
61849 $_$;
61850
61851
61852 ALTER FUNCTION public.last_agg(anyelement, anyelement) OWNER TO admin;
61853
61854 --
61855 -- TOC entry 1904 (class 1255 OID 146566698)
61856 -- Dependencies: 4536 8
61857 -- Name: login(); Type: FUNCTION; Schema: public; Owner: admin
61858 --
61859
61860 CREATE FUNCTION login() RETURNS integer
61861     LANGUAGE plpgsql
61862     AS $$
61863 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61864 -- See www.xtuple.com/CPAL for the full text of the software license.
61865 DECLARE 
61866   _p RECORD;
61867
61868 BEGIN
61869
61870   RETURN login(false);
61871
61872 END;
61873 $$;
61874
61875
61876 ALTER FUNCTION public.login() OWNER TO admin;
61877
61878 --
61879 -- TOC entry 1905 (class 1255 OID 146566699)
61880 -- Dependencies: 4536 8
61881 -- Name: login(boolean); Type: FUNCTION; Schema: public; Owner: admin
61882 --
61883
61884 CREATE FUNCTION login(boolean) RETURNS integer
61885     LANGUAGE plpgsql
61886     AS $_$
61887 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61888 -- See www.xtuple.com/CPAL for the full text of the software license.
61889 DECLARE 
61890   _setSearchPath ALIAS FOR $1;
61891   _p RECORD;
61892
61893 BEGIN
61894   -- added support for PostgreSQL 9.2.0, Incident 21852
61895   IF (compareversion('9.2.0') <= 0)
61896   THEN
61897     PERFORM pg_try_advisory_lock(datid::integer, pid)
61898      FROM pg_stat_activity
61899     WHERE(pid = pg_backend_pid());
61900   ELSE
61901     PERFORM pg_try_advisory_lock(datid::integer, procpid)
61902      FROM pg_stat_activity
61903     WHERE(procpid = pg_backend_pid());
61904   END IF;
61905
61906   -- This is new to version 9.0 and higher and will error on older versions
61907   IF (compareversion('9.0.0') <= 0) THEN
61908     SET bytea_output TO escape;
61909   END IF;
61910
61911   -- this is temporary until either qt fixes the postgres driver or we find &
61912   -- fix all of the places in our app that can write strings with backslashes
61913   SET standard_conforming_strings TO false;
61914
61915   SELECT usr_id, userCanLogin(usr_username) AS usr_active INTO _p
61916   FROM usr
61917   WHERE (usr_username=getEffectiveXtUser());
61918
61919   IF (NOT FOUND) THEN
61920     RETURN -1;
61921
61922   ELSIF (NOT _p.usr_active) THEN
61923     IF(SELECT metric_value='AdminOnly'
61924          FROM metric
61925         WHERE metric_name='AllowedUserLogins') THEN
61926       RETURN -3;
61927     END IF;
61928     RETURN -2;
61929   END IF;
61930
61931   IF (_setSearchPath) THEN
61932     IF EXISTS(SELECT 1
61933                 FROM pg_proc
61934                 JOIN pg_namespace ON (pronamespace=pg_namespace.oid)
61935                WHERE nspname='public'
61936                  AND proname='buildsearchpath') THEN
61937       EXECUTE 'SET SEARCH_PATH TO ' || public.buildSearchPath();
61938     END IF;
61939   END IF;
61940
61941   RETURN 1;
61942
61943 END;
61944 $_$;
61945
61946
61947 ALTER FUNCTION public.login(boolean) OWNER TO admin;
61948
61949 --
61950 -- TOC entry 1906 (class 1255 OID 146566700)
61951 -- Dependencies: 4536 8
61952 -- Name: logout(); Type: FUNCTION; Schema: public; Owner: admin
61953 --
61954
61955 CREATE FUNCTION logout() RETURNS integer
61956     LANGUAGE plpgsql
61957     AS $$
61958 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61959 -- See www.xtuple.com/CPAL for the full text of the software license.
61960 BEGIN
61961   PERFORM pg_advisory_unlock(datid::integer, procpid)
61962      FROM pg_stat_activity
61963     WHERE(procpid = pg_backend_pid());
61964
61965   RETURN 0;
61966 END;
61967 $$;
61968
61969
61970 ALTER FUNCTION public.logout() OWNER TO admin;
61971
61972 --
61973 -- TOC entry 1907 (class 1255 OID 146566701)
61974 -- Dependencies: 4536 8
61975 -- Name: lowercost(integer, text); Type: FUNCTION; Schema: public; Owner: admin
61976 --
61977
61978 CREATE FUNCTION lowercost(integer, text) RETURNS numeric
61979     LANGUAGE plpgsql
61980     AS $_$
61981 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
61982 -- See www.xtuple.com/CPAL for the full text of the software license.
61983 DECLARE
61984   pItemid       ALIAS FOR $1;
61985   pCosttype     ALIAS FOR $2;
61986
61987 BEGIN
61988     RETURN lowerCost(pItemid, pCosttype, TRUE);
61989 END;
61990 $_$;
61991
61992
61993 ALTER FUNCTION public.lowercost(integer, text) OWNER TO admin;
61994
61995 --
61996 -- TOC entry 1908 (class 1255 OID 146566702)
61997 -- Dependencies: 4536 8
61998 -- Name: lowercost(integer, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
61999 --
62000
62001 CREATE FUNCTION lowercost(integer, text, boolean) RETURNS numeric
62002     LANGUAGE plpgsql
62003     AS $_$
62004 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62005 -- See www.xtuple.com/CPAL for the full text of the software license.
62006 DECLARE
62007   pItemid ALIAS FOR $1;
62008   pCosttype ALIAS FOR $2;
62009   pActual       ALIAS FOR $3;
62010   _type CHAR(1);
62011   _actCost      NUMERIC;
62012   _actCost1     NUMERIC;
62013   _actCost2     NUMERIC;
62014   _stdCost      NUMERIC;
62015   _stdCost1     NUMERIC;
62016   _stdCost2     NUMERIC;
62017   _cost         NUMERIC;
62018   _cost1        NUMERIC;
62019   _cost2        NUMERIC;
62020   _batchsize    NUMERIC;
62021
62022 BEGIN
62023
62024   SELECT item_type INTO _type
62025   FROM item
62026   WHERE (item_id=pItemid);
62027
62028   _batchsize := COALESCE( (
62029     SELECT bomhead_batchsize
62030     FROM bomhead
62031     WHERE ((bomhead_item_id=pItemId)
62032      AND  (bomhead_rev_id=getActiveRevId('BOM',pItemId))) LIMIT 1), 1);
62033
62034   -- find the lowercost in the base currency at the current conversion rate
62035   IF (_type IN ('M', 'F', 'B', 'T')) THEN
62036
62037     IF (pActual) THEN
62038       SELECT SUM( CASE WHEN (bomitemcost_id IS NOT NULL AND bc.costelem_id IS NOT NULL) THEN
62039                   round(currToBase(bomitemcost_curr_id, bomitemcost_actcost, CURRENT_DATE),6) *
62040                     itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper')
62041                   ELSE
62042                   round(currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE),6) *
62043                     itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper')
62044                   END )
62045           INTO _cost
62046       FROM bomitem(pItemid)
62047         JOIN item ON (item_id=bomitem_item_id AND item_type <> 'T')
62048         JOIN itemcost ON (itemcost_item_id=bomitem_item_id)
62049         JOIN costelem ic ON (ic.costelem_id=itemcost_costelem_id AND ic.costelem_type=pCosttype)
62050         LEFT OUTER JOIN bomitemcost ON (bomitemcost_bomitem_id=bomitem_id)
62051         LEFT OUTER JOIN costelem bc ON (bc.costelem_id=bomitemcost_costelem_id AND bc.costelem_type=pCosttype)
62052       WHERE ( CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1) );
62053     ELSE
62054       SELECT SUM( CASE WHEN (bomitemcost_id IS NOT NULL AND bc.costelem_id IS NOT NULL) THEN
62055                   bomitemcost_stdcost *
62056                     itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper')
62057                   ELSE
62058                   itemcost_stdcost *
62059                     itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper')
62060                   END )
62061           INTO _cost
62062       FROM bomitem(pItemid)
62063         JOIN item ON (item_id=bomitem_item_id AND item_type <> 'T')
62064         JOIN itemcost ON (itemcost_item_id=bomitem_item_id)
62065         JOIN costelem ON (costelem_id=itemcost_costelem_id AND costelem_type=pCosttype)
62066         LEFT OUTER JOIN bomitemcost ON (bomitemcost_bomitem_id=bomitem_id)
62067         LEFT OUTER JOIN costelem bc ON (bc.costelem_id=bomitemcost_costelem_id AND bc.costelem_type=pCosttype)
62068       WHERE ( CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1) ); 
62069     END IF;
62070     
62071     IF (NOT FOUND) THEN
62072       _cost := NULL;
62073     END IF;
62074
62075   ELSIF (_type IN ('C')) THEN
62076     SELECT SUM(CASE WHEN (bbomitem_qtyper = 0) THEN 0
62077                     ELSE currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE) / bbomitem_qtyper * bbomitem_costabsorb
62078                END),
62079            SUM(CASE WHEN (bbomitem_qtyper = 0) THEN 0
62080                     ELSE itemcost_stdcost / bbomitem_qtyper * bbomitem_costabsorb
62081                END)
62082         INTO _actCost1, _stdCost1
62083     FROM itemcost
62084          JOIN costelem       ON (itemcost_costelem_id=costelem_id)
62085          JOIN xtmfg.bbomitem ON (bbomitem_parent_item_id=itemcost_item_id)
62086     WHERE ( (bbomitem_item_id=pItemid)
62087      AND (CURRENT_DATE BETWEEN bbomitem_effective AND (bbomitem_expires - 1))
62088      AND (costelem_type=pCosttype) );
62089
62090     SELECT SUM(CASE WHEN (t.bbomitem_qtyper = 0) THEN 0
62091                     ELSE currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE) * s.bbomitem_qtyper / t.bbomitem_qtyper * t.bbomitem_costabsorb
62092                END),
62093            SUM(CASE WHEN (t.bbomitem_qtyper = 0) THEN 0
62094                     ELSE itemcost_stdcost * s.bbomitem_qtyper / t.bbomitem_qtyper * t.bbomitem_costabsorb
62095                END)
62096         INTO _actCost2, _stdCost2
62097     FROM costelem
62098          JOIN itemcost            ON (costelem_id=itemcost_costelem_id)
62099          JOIN xtmfg.bbomitem AS s ON (itemcost_item_id=s.bbomitem_item_id)
62100          JOIN xtmfg.bbomitem AS t ON (s.bbomitem_parent_item_id=t.bbomitem_parent_item_id)
62101          JOIN  item               ON (s.bbomitem_item_id=item_id)
62102     WHERE ( (t.bbomitem_item_id=pItemid)
62103      AND ( CURRENT_DATE BETWEEN s.bbomitem_effective
62104                         AND (s.bbomitem_expires - 1) )
62105      AND ( CURRENT_DATE BETWEEN t.bbomitem_effective
62106                         AND (t.bbomitem_expires - 1) )
62107      AND (item_type='Y')
62108      AND (costelem_type=pCosttype) );
62109
62110     IF (pActual) THEN
62111         _cost  = _actCost;
62112         _cost1 = _actCost1;
62113         _cost2 = _actCost2;
62114     ELSE
62115         _cost  = _stdCost;
62116         _cost1 = _stdCost1;
62117         _cost2 = _stdCost2;     -- should this be std or act?
62118     END IF;
62119
62120     IF (_cost1 IS NULL AND _cost2 IS NULL) THEN
62121         _cost = NULL;
62122     ELSE
62123         _cost = COALESCE(_cost1, 0) + COALESCE(_cost2, 0);
62124     END IF;
62125
62126   ELSE
62127     RETURN NULL;
62128   END IF;
62129
62130   RETURN round(_cost,6);
62131
62132 END;
62133 $_$;
62134
62135
62136 ALTER FUNCTION public.lowercost(integer, text, boolean) OWNER TO admin;
62137
62138 --
62139 -- TOC entry 1909 (class 1255 OID 146566703)
62140 -- Dependencies: 4536 8
62141 -- Name: maintainbomworkspace(); Type: FUNCTION; Schema: public; Owner: admin
62142 --
62143
62144 CREATE FUNCTION maintainbomworkspace() RETURNS integer
62145     LANGUAGE plpgsql
62146     AS $$
62147 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62148 -- See www.xtuple.com/CPAL for the full text of the software license.
62149 DECLARE
62150   _test TEXT;
62151
62152 BEGIN
62153
62154   SELECT tablename INTO _test
62155   FROM pg_tables
62156   WHERE (tablename='bomwork');
62157   IF (NOT FOUND) THEN
62158     CREATE TEMPORARY TABLE bomwork
62159     ( bomwork_id INTEGER, bomwork_set_id INTEGER, bomwork_parent_id INTEGER,
62160       bomwork_seqnumber INTEGER, bomwork_parent_seqnumber INTEGER,
62161       bomwork_item_id INTEGER, bomwork_item_type CHARACTER(1), bomwork_status CHARACTER(1),
62162       bomwork_qtyper NUMERIC(20, 8), bomwork_scrap NUMERIC(20, 10),
62163       bomwork_level INTEGER, bomwork_effective DATE, bomwork_expires DATE,
62164       bomwork_stdunitcost NUMERIC(16, 4), bomwork_actunitcost NUMERIC(16, 4),
62165       bomwork_createwo BOOLEAN, bomwork_issuemethod CHARACTER(1) );
62166     CREATE INDEX bomwork_set_id_idx ON bomwork(bomwork_set_id);
62167   END IF;
62168
62169   RETURN 1;
62170
62171 END;
62172 $$;
62173
62174
62175 ALTER FUNCTION public.maintainbomworkspace() OWNER TO admin;
62176
62177 --
62178 -- TOC entry 1910 (class 1255 OID 146566704)
62179 -- Dependencies: 4536 8
62180 -- Name: markapcheckasposted(integer); Type: FUNCTION; Schema: public; Owner: admin
62181 --
62182
62183 CREATE FUNCTION markapcheckasposted(integer) RETURNS integer
62184     LANGUAGE plpgsql
62185     AS $_$
62186 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62187 -- See www.xtuple.com/CPAL for the full text of the software license.
62188 BEGIN
62189   RAISE NOTICE 'markAPCheckAsPosted() is deprecated - use markCheckAsPosted() instead';
62190   RETURN markCheckAsPosted($1);
62191
62192 END;
62193 $_$;
62194
62195
62196 ALTER FUNCTION public.markapcheckasposted(integer) OWNER TO admin;
62197
62198 --
62199 -- TOC entry 1911 (class 1255 OID 146566705)
62200 -- Dependencies: 4536 8
62201 -- Name: markapcheckasprinted(integer); Type: FUNCTION; Schema: public; Owner: admin
62202 --
62203
62204 CREATE FUNCTION markapcheckasprinted(integer) RETURNS integer
62205     LANGUAGE plpgsql
62206     AS $_$
62207 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62208 -- See www.xtuple.com/CPAL for the full text of the software license.
62209 BEGIN
62210   RAISE NOTICE 'markAPCheckAsPrinted() is deprecated - use markCheckAsPrinted()';
62211   RETURN markCheckAsPrinted($1);
62212 END;
62213 $_$;
62214
62215
62216 ALTER FUNCTION public.markapcheckasprinted(integer) OWNER TO admin;
62217
62218 --
62219 -- TOC entry 1912 (class 1255 OID 146566706)
62220 -- Dependencies: 4536 8
62221 -- Name: markcheckasposted(integer); Type: FUNCTION; Schema: public; Owner: admin
62222 --
62223
62224 CREATE FUNCTION markcheckasposted(integer) RETURNS integer
62225     LANGUAGE plpgsql
62226     AS $_$
62227 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62228 -- See www.xtuple.com/CPAL for the full text of the software license.
62229 DECLARE
62230   pCheckid ALIAS FOR $1;
62231
62232 BEGIN
62233
62234   UPDATE checkhead
62235   SET checkhead_posted=TRUE
62236   WHERE (checkhead_id=pCheckid);
62237
62238   RETURN 1;
62239
62240 END;
62241 $_$;
62242
62243
62244 ALTER FUNCTION public.markcheckasposted(integer) OWNER TO admin;
62245
62246 --
62247 -- TOC entry 1913 (class 1255 OID 146566707)
62248 -- Dependencies: 4536 8
62249 -- Name: markcheckasprinted(integer); Type: FUNCTION; Schema: public; Owner: admin
62250 --
62251
62252 CREATE FUNCTION markcheckasprinted(integer) RETURNS integer
62253     LANGUAGE plpgsql
62254     AS $_$
62255 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62256 -- See www.xtuple.com/CPAL for the full text of the software license.
62257 DECLARE
62258   pCheckid ALIAS FOR $1;
62259
62260 BEGIN
62261
62262   UPDATE checkhead
62263   SET checkhead_printed=TRUE
62264   WHERE (checkhead_id=pCheckid);
62265
62266   RETURN 1;
62267
62268 END;
62269 $_$;
62270
62271
62272 ALTER FUNCTION public.markcheckasprinted(integer) OWNER TO admin;
62273
62274 --
62275 -- TOC entry 1914 (class 1255 OID 146566708)
62276 -- Dependencies: 4536 8
62277 -- Name: massexpirebomitem(integer, date, text); Type: FUNCTION; Schema: public; Owner: admin
62278 --
62279
62280 CREATE FUNCTION massexpirebomitem(integer, date, text) RETURNS boolean
62281     LANGUAGE plpgsql
62282     AS $_$
62283 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62284 -- See www.xtuple.com/CPAL for the full text of the software license.
62285 DECLARE
62286   pItemid ALIAS FOR $1;
62287   pExpireDate ALIAS FOR $2;
62288   pECN ALIAS FOR $3;
62289
62290 BEGIN
62291
62292   UPDATE bomitem
62293   SET bomitem_expires=pExpireDate
62294   WHERE ( (bomitem_expires >= CURRENT_DATE)
62295    AND (bomitem_item_id=pItemid)
62296    AND (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id)) );
62297
62298   RETURN TRUE;
62299 END;
62300 $_$;
62301
62302
62303 ALTER FUNCTION public.massexpirebomitem(integer, date, text) OWNER TO admin;
62304
62305 --
62306 -- TOC entry 1915 (class 1255 OID 146566709)
62307 -- Dependencies: 4536 8
62308 -- Name: massreplacebomitem(integer, integer, date, text); Type: FUNCTION; Schema: public; Owner: admin
62309 --
62310
62311 CREATE FUNCTION massreplacebomitem(integer, integer, date, text) RETURNS integer
62312     LANGUAGE plpgsql
62313     AS $_$
62314 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62315 -- See www.xtuple.com/CPAL for the full text of the software license.
62316 DECLARE
62317   pNewItemid ALIAS FOR $1;
62318   pOriginalItemid ALIAS FOR $2;
62319   pEffectiveDate ALIAS FOR $3;
62320   pECN ALIAS FOR $4;
62321   _effectiveDate DATE;
62322   _result               INTEGER;
62323
62324 BEGIN
62325
62326   _effectiveDate := COALESCE(pEffectiveDate, CURRENT_DATE);
62327
62328   IF (BOMContains(pOriginalItemid, pNewItemid) OR
62329       BOMContains(pNewItemid, pOriginalItemid)) THEN
62330     RETURN -1;
62331   END IF;
62332
62333   INSERT INTO bomitem
62334   ( bomitem_parent_item_id, bomitem_seqnumber,
62335     bomitem_item_id, bomitem_qtyfxd, bomitem_qtyper, bomitem_uom_id,
62336     bomitem_scrap, bomitem_effective, bomitem_expires, bomitem_ecn,
62337     bomitem_createwo, bomitem_issuemethod, bomitem_subtype,
62338     bomitem_booitem_seq_id, bomitem_schedatwooper, bomitem_moddate, bomitem_rev_id,
62339     bomitem_char_id, bomitem_value )
62340   SELECT bomitem_parent_item_id, bomitem_seqnumber,
62341          pNewItemid, bomitem_qtyfxd, bomitem_qtyper, bomitem_uom_id,
62342          bomitem_scrap, _effectiveDate, endOfTime(), pECN,
62343          bomitem_createwo, bomitem_issuemethod, 'I',
62344          bomitem_booitem_seq_id, bomitem_schedatwooper, CURRENT_DATE, getActiveRevId('BOM',bomitem_parent_item_id),
62345          bomitem_char_id, bomitem_value
62346   FROM bomitem
62347   WHERE ( (_effectiveDate < bomitem_expires)
62348    AND (bomitem_item_id=pOriginalItemid)
62349    AND (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id)) );
62350
62351   UPDATE bomitem
62352   SET bomitem_expires=_effectiveDate
62353   WHERE ( (_effectiveDate < bomitem_expires)
62354    AND (bomitem_item_id=pOriginalItemid)
62355    AND (bomitem_rev_id=getActiveRevid('BOM',bomitem_parent_item_id)) );
62356
62357   RETURN 1;
62358 END;
62359 $_$;
62360
62361
62362 ALTER FUNCTION public.massreplacebomitem(integer, integer, date, text) OWNER TO admin;
62363
62364 --
62365 -- TOC entry 1916 (class 1255 OID 146566710)
62366 -- Dependencies: 4536 8
62367 -- Name: merge2crmaccts(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
62368 --
62369
62370 CREATE FUNCTION merge2crmaccts(integer, integer, boolean) RETURNS integer
62371     LANGUAGE plpgsql
62372     AS $_$
62373 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62374 -- See www.xtuple.com/CPAL for the full text of the software license.
62375 DECLARE
62376   pSourceId ALIAS FOR $1;
62377   pTargetId ALIAS FOR $2;
62378   _purge    BOOLEAN := COALESCE($3, FALSE);
62379
62380   _coldesc    RECORD;
62381   _count      INTEGER := 0;
62382   _hassubtype BOOLEAN;
62383   _mrgcol     BOOLEAN;
62384   _result     INTEGER := 0;
62385   _sel        RECORD;
62386   _colname    TEXT;
62387   _tmpid      INTEGER;
62388
62389 BEGIN
62390   -- Validate
62391   IF (pSourceId = pTargetId) THEN
62392     RAISE NOTICE 'Tried to merge a CRM Account with itself: %.', pSourceId;
62393     RETURN 0;
62394   ELSIF (pSourceId IS NULL) THEN
62395     RAISE EXCEPTION 'Merge source id cannot be null [xtuple: merge, -1]';
62396   ELSIF NOT(EXISTS(SELECT 1 FROM crmacct WHERE crmacct_id=pSourceId)) THEN
62397     RAISE EXCEPTION 'Merge source % not found [xtuple: merge, -2, %]',
62398                     pSourceId, pSourceId;
62399   ELSIF (pTargetId IS NULL) THEN
62400     RAISE EXCEPTION 'Merge target id cannot be null [xtuple: merge, -3]';
62401   ELSIF NOT(EXISTS(SELECT 1 FROM crmacct WHERE crmacct_id=pTargetId)) THEN
62402     RAISE EXCEPTION 'Merge target % not found [xtuple: merge, -4, %]',
62403                     pTargetId, pTargetId;
62404   ELSIF NOT(EXISTS(SELECT 1
62405                      FROM crmacctsel
62406                     WHERE (crmacctsel_src_crmacct_id=pSourceId)
62407                       AND (crmacctsel_dest_crmacct_id=pTargetId))) THEN
62408     RAISE EXCEPTION 'Source % and target % have not been selected for merging [xtuple: merge, -5, %, %]',
62409                     pSourceId, pTargetId, pSourceId, pTargetId;
62410   END IF;
62411
62412   _result:= changeFkeyPointers('public', 'crmacct', pSourceId, pTargetId,
62413                                ARRAY[ 'crmacctsel', 'crmacctmrgd' ], _purge)
62414           + changePseudoFKeyPointers('public', 'alarm', 'alarm_source_id',
62415                                      pSourceId, 'public', 'crmacct', pTargetId,
62416                                      'alarm_source', 'CRMA', _purge)
62417           + changePseudoFKeyPointers('public', 'charass', 'charass_target_id',
62418                                      pSourceId, 'public', 'crmacct', pTargetId,
62419                                      'charass_target_type', 'CRMACCT', _purge)
62420           + changePseudoFKeyPointers('public', 'comment', 'comment_source_id',
62421                                      pSourceId, 'public', 'crmacct', pTargetId,
62422                                      'comment_source', 'CRMA', _purge)
62423           + changePseudoFKeyPointers('public', 'docass', 'docass_source_id',
62424                                      pSourceId, 'public', 'crmacct', pTargetId,
62425                                      'docass_source_type', 'CRMA', _purge)
62426           + changePseudoFKeyPointers('public', 'docass', 'docass_target_id',
62427                                      pSourceId, 'public', 'crmacct', pTargetId,
62428                                      'docass_target_type', 'CRMA', _purge)
62429           + changePseudoFKeyPointers('public', 'imageass', 'imageass_source_id',
62430                                      pSourceId, 'public', 'crmacct', pTargetId,
62431                                      'imageass_source', 'CRMA', _purge)
62432           ;
62433
62434   -- TODO: find a generic way to handle pseudofkeys in packages - see 9401
62435   IF (fetchMetricBool('EnableBatchManager') AND packageIsEnabled('xtbatch')) THEN
62436     _result:= _result
62437             + changePseudoFKeyPointers('xtbatch', 'emlassc', 'emlassc_assc_id',
62438                                        pSourceId, 'public', 'crmacct', pTargetId,
62439                                        'emlassc_type', 'CRMA', _purge);
62440   END IF;
62441
62442   -- back up all of the values in the target record that are about to be changed
62443   FOR _coldesc IN SELECT attname, typname
62444                     FROM pg_attribute
62445                     JOIN pg_type      ON (atttypid=pg_type.oid)
62446                     JOIN pg_class     ON (attrelid=pg_class.oid)
62447                     JOIN pg_namespace ON (relnamespace=pg_namespace.oid)
62448                    WHERE (attnum >= 0)
62449                      AND (relname='crmacct')
62450                      AND (nspname='public')
62451                      AND (attname NOT IN ('crmacct_id', 'crmacct_number'))
62452   LOOP
62453
62454     -- if we're supposed to merge this column at all
62455     EXECUTE 'SELECT ' || quote_ident('crmacctsel_mrg_' || _coldesc.attname) || '
62456                FROM crmacctsel
62457               WHERE ((crmacctsel_src_crmacct_id='  || pSourceId || ')
62458                  AND (crmacctsel_dest_crmacct_id=' || pTargetId || '))' INTO _mrgcol;
62459
62460     IF (_mrgcol) THEN
62461       _colname := REPLACE(_coldesc.attname, 'crmacctsel_mrg_', '');
62462
62463       -- optionally back up the old value from the destination
62464       -- we'll back up the old value from the source further down
62465       IF (NOT _purge) THEN
62466         BEGIN
62467           EXECUTE 'INSERT INTO mrgundo (
62468                        mrgundo_schema,      mrgundo_table,
62469                        mrgundo_pkey_col,    mrgundo_pkey_id,
62470                        mrgundo_col,         mrgundo_value,      mrgundo_type,
62471                        mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id
62472                  ) SELECT ''public'',     ''crmacct'',
62473                           ''crmacct_id'', crmacct_id, '   ||
62474                           quote_literal(_colname)         || ', ' ||
62475                           quote_ident(_colname)           || ', ' ||
62476                           quote_literal(_coldesc.typname) || ',
62477                           ''public'', ''crmacct'', crmacct_id
62478                      FROM crmacct
62479                     WHERE (crmacct_id=' || pTargetId || ');' ;
62480         EXCEPTION WHEN unique_violation THEN
62481           RAISE EXCEPTION 'Could not make a backup copy of % when merging % into % [xtuple: merge, -8, %, %, public, crmacct, %]',
62482                        _colname, pSourceId, pTargetId,
62483                        _colname, pSourceId, pTargetId;
62484         END;
62485       END IF;
62486
62487       -- TODO: what do we do about users?
62488       /* update the destination crmacct in one of 3 different ways:
62489          - crmacct_notes might be concatenated from more than one source record
62490          - foreign keys to crm account subtype records (e.g. crmacct_cust_id)
62491            must not leave orphaned records and must avoid uniqueness violations
62492          - some fields can simply be updated in place
62493        */
62494       IF (_colname = 'crmacct_notes') THEN
62495         EXECUTE 'UPDATE crmacct dest
62496                     SET '      || quote_ident(_colname) ||
62497                       '=dest.' || quote_ident(_colname) ||
62498                       E' || E''\\n'' || src.' || _colname || '
62499                   FROM crmacct src
62500                   JOIN crmacctsel ON (src.crmacct_id=crmacctsel_src_crmacct_id)
62501                  WHERE ((dest.crmacct_id=crmacctsel_dest_crmacct_id)
62502                     AND (dest.crmacct_id!=crmacctsel_src_crmacct_id));';
62503
62504       ELSIF (_colname IN ('crmacct_cust_id', 'crmacct_prospect_id', 
62505                           'crmacct_vend_id', 'crmacct_taxauth_id',
62506                           'crmacct_emp_id',  'crmacct_salesrep_id')) THEN
62507         IF (_colname IN ('crmacct_cust_id', 'crmacct_prospect_id')) THEN
62508           EXECUTE 'SELECT src.' || quote_ident(_colname) || ' IS NOT NULL
62509                       AND (dest.crmacct_prospect_id IS NOT NULL OR
62510                            dest.crmacct_cust_id IS NOT NULL)
62511                      FROM crmacct src
62512                      JOIN crmacctsel ON (src.crmacct_id=crmacctsel_src_crmacct_id)
62513                      JOIN crmacct dest ON (crmacctsel_dest_crmacct_id=dest.crmacct_id)
62514                     WHERE ((src.crmacct_id='  || pSourceId || ')
62515                        AND (dest.crmacct_id=' || pTargetId || '))' INTO _hassubtype;
62516           IF (_hassubtype) THEN
62517             RAISE EXCEPTION 'Cannot merge two CRM Accounts that both refer to Customers and/or Prospects [xtuple: merge, -6, %, %]',
62518                             pSourceId, pTargetId;
62519           END IF;
62520         ELSE
62521           EXECUTE 'SELECT src.' || quote_ident(_colname) || ' IS NOT NULL
62522                       AND dest.'|| quote_ident(_colname) || ' IS NOT NULL
62523                      FROM crmacct src
62524                      JOIN crmacctsel ON (src.crmacct_id=crmacctsel_src_crmacct_id)
62525                      JOIN crmacct dest ON (crmacctsel_dest_crmacct_id=dest.crmacct_id)
62526                     WHERE ((src.crmacct_id='  || pSourceId || ')
62527                        AND (dest.crmacct_id=' || pTargetId || '))' INTO _hassubtype;
62528
62529           IF (_hassubtype) THEN
62530             RAISE EXCEPTION 'Cannot merge CRM Accounts until the % child records have been merged [xtuple: merge, -7, %, %, %]',
62531                             _colname, _colname, pSourceId, pTargetId;
62532           END IF;
62533
62534         END IF;
62535
62536         /* clearing the source separately from setting the target avoids
62537            problems with triggers updating the wrong records */
62538         EXECUTE 'SELECT ' || quote_ident(_colname) || ' FROM crmacct
62539                   WHERE crmacct_id=' || pSourceId
62540         INTO _tmpid;
62541
62542         -- now we have the data to back up the source
62543         IF (NOT _purge) THEN
62544           BEGIN
62545             EXECUTE 'INSERT INTO mrgundo (
62546                          mrgundo_schema,      mrgundo_table,
62547                          mrgundo_pkey_col,    mrgundo_pkey_id,
62548                          mrgundo_col,         mrgundo_value,      mrgundo_type,
62549                          mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id
62550                    ) SELECT ''public'',     ''crmacct'',
62551                             ''crmacct_id'', crmacct_id, '   ||
62552                             quote_literal(_colname)         || ', ' ||
62553                             quote_ident(_colname)           || ', ' ||
62554                             quote_literal(_coldesc.typname) || ',
62555                             ''public'', ''crmacct'', '      || pTargetId || '
62556                        FROM crmacct
62557                       WHERE (crmacct_id=' || pSourceId || ');' ;
62558           EXCEPTION WHEN unique_violation THEN
62559             RAISE EXCEPTION 'Could not make a backup copy of % when merging % into % [xtuple: merge, -8, %, %, public, crmacct, %]',
62560                          _colname, pSourceId, pTargetId,
62561                          _colname, pSourceId, pTargetId;
62562           END;
62563         END IF;
62564
62565         EXECUTE 'UPDATE crmacct SET ' || quote_ident(_colname) || '=NULL
62566               WHERE (crmacct_id=' || pSourceId || ');';
62567
62568         EXECUTE 'UPDATE crmacct
62569                     SET ' || quote_ident(_colname) || '=' || quote_literal(_tmpid) || '
62570               WHERE (crmacct_id=' || pTargetId || ');';
62571
62572       ELSE
62573         EXECUTE 'UPDATE crmacct dest
62574                     SET '      || quote_ident(_colname) || '
62575                         =src.' || quote_ident(_colname) || '
62576                   FROM crmacct src
62577                  WHERE ((dest.crmacct_id=' || pTargetId || ')
62578                     AND (src.crmacct_id='  || pSourceId || '));';
62579       END IF;
62580
62581       GET DIAGNOSTICS _count = ROW_COUNT;
62582       _result := _result + _count;
62583     END IF;
62584
62585   END LOOP;
62586
62587   IF (_purge) THEN
62588     DELETE FROM crmacct WHERE crmacct = pSourceId;
62589   ELSE
62590     INSERT INTO mrgundo (
62591            mrgundo_schema,      mrgundo_table,
62592            mrgundo_pkey_col,    mrgundo_pkey_id,
62593            mrgundo_col,         mrgundo_value,      mrgundo_type,
62594            mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id
62595     ) SELECT 'public',         'crmacct',
62596              'crmacct_id',     pSourceId,
62597              'crmacct_active', crmacct_active, 'bool',
62598              'public',         'crmacct',       pTargetId
62599         FROM crmacct
62600        WHERE crmacct_active AND (crmacct_id = pSourceId);
62601     GET DIAGNOSTICS _count = ROW_COUNT;
62602     IF (_count > 0) THEN
62603       _result := _result + _count;
62604       UPDATE crmacct SET crmacct_active = false WHERE (crmacct_id=pSourceId);
62605     END IF;
62606
62607     -- make a special record of the source crm account so we can delete it later
62608     INSERT INTO mrgundo (
62609            mrgundo_schema,      mrgundo_table,
62610            mrgundo_pkey_col,    mrgundo_pkey_id,
62611            mrgundo_col,         mrgundo_value,      mrgundo_type,
62612            mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id
62613      ) VALUES (
62614            'public',     'crmacct',
62615            'crmacct_id', pSourceId,
62616            NULL,         NULL,       NULL,
62617            'public',     'crmacct', pTargetId);
62618   END IF;
62619
62620   DELETE FROM crmacctsel WHERE (crmacctsel_src_crmacct_id=pSourceId);
62621
62622   RETURN _result;
62623 END;
62624 $_$;
62625
62626
62627 ALTER FUNCTION public.merge2crmaccts(integer, integer, boolean) OWNER TO admin;
62628
62629 --
62630 -- TOC entry 9064 (class 0 OID 0)
62631 -- Dependencies: 1916
62632 -- Name: FUNCTION merge2crmaccts(integer, integer, boolean); Type: COMMENT; Schema: public; Owner: admin
62633 --
62634
62635 COMMENT ON FUNCTION merge2crmaccts(integer, integer, boolean) IS 'This function merges two crmacct records as decribed in crmacctsel records. For each field in the crmacctsel record marked TRUE, the data are copied from the crmacct record with crmacct_id=pSourceId to the record with crmacct_id=pTargetId. If the purge argument is TRUE, the source record is deleted. If it is FALSE, then mrgundo records are created so the merge can later be undone.';
62636
62637
62638 --
62639 -- TOC entry 1919 (class 1255 OID 146566712)
62640 -- Dependencies: 4536 8
62641 -- Name: mergecrmaccts(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
62642 --
62643
62644 CREATE FUNCTION mergecrmaccts(integer, boolean) RETURNS integer
62645     LANGUAGE plpgsql
62646     AS $_$
62647 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62648 -- See www.xtuple.com/CPAL for the full text of the software license.
62649 DECLARE
62650   pTargetId     ALIAS FOR $1;
62651   _purge        BOOLEAN := COALESCE($2, FALSE);
62652
62653   _retval       INTEGER;
62654 BEGIN
62655
62656   /* if crmacctsel says the target should not keep its original
62657      notes, clear them.  notes are special because the merge allows
62658      concatenating them from multiple sources. this needs to be
62659      kept in sync with merge2crmaccts' similar check.
62660    */
62661   IF NOT (SELECT crmacctsel_mrg_crmacct_notes
62662             FROM crmacctsel
62663            WHERE crmacctsel_src_crmacct_id=crmacctsel_dest_crmacct_id
62664              AND crmacctsel_dest_crmacct_id=pTargetId) THEN
62665     IF (NOT _purge) THEN
62666       INSERT INTO mrgundo (
62667              mrgundo_schema,      mrgundo_table,
62668              mrgundo_pkey_col,    mrgundo_pkey_id,
62669              mrgundo_col,         mrgundo_value,      mrgundo_type,
62670              mrgundo_base_schema, mrgundo_base_table, mrgundo_base_id)
62671       SELECT 'public', 'crmacct', crmacct_id,
62672              'public', 'crmacct', 'crmacct_id', crmacct_id,
62673              'crmacct_notes', crmacct_notes, 'text',
62674              'public', 'crmacct', crmacct_id
62675         FROM crmacct
62676        WHERE (crmacct_id=pTargetId);
62677     END IF;
62678
62679     UPDATE crmacct
62680        SET crmacct_notes = ''
62681      WHERE (crmacct_id=pTargetId);
62682   END IF;
62683
62684   -- merge the data from the various source records
62685   SELECT SUM(merge2crmaccts(crmacctsel_src_crmacct_id, pTargetId, _purge))
62686          INTO _retval
62687     FROM crmacctsel
62688    WHERE ((crmacctsel_dest_crmacct_id=pTargetId)
62689       AND (crmacctsel_dest_crmacct_id!=crmacctsel_src_crmacct_id));
62690
62691   DELETE FROM crmacctsel WHERE crmacctsel_dest_crmacct_id=pTargetId;
62692
62693   RETURN COALESCE(_retval, 0);
62694
62695 END;
62696 $_$;
62697
62698
62699 ALTER FUNCTION public.mergecrmaccts(integer, boolean) OWNER TO admin;
62700
62701 --
62702 -- TOC entry 9065 (class 0 OID 0)
62703 -- Dependencies: 1919
62704 -- Name: FUNCTION mergecrmaccts(integer, boolean); Type: COMMENT; Schema: public; Owner: admin
62705 --
62706
62707 COMMENT ON FUNCTION mergecrmaccts(integer, boolean) IS 'This function uses the crmacctsel table to merge multiple crmacct records together. Only the merges into the specified target account are performed. Most of the work is done by repeated calls to the merge2crmaccts function. If the purge argument is FALSE, data are kept to allow reversing the merge.';
62708
62709
62710 --
62711 -- TOC entry 1920 (class 1255 OID 146566713)
62712 -- Dependencies: 4536 8
62713 -- Name: movebomitemdown(integer); Type: FUNCTION; Schema: public; Owner: admin
62714 --
62715
62716 CREATE FUNCTION movebomitemdown(integer) RETURNS integer
62717     LANGUAGE plpgsql
62718     AS $_$
62719 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62720 -- See www.xtuple.com/CPAL for the full text of the software license.
62721 DECLARE
62722   pBomitemid ALIAS FOR $1;
62723   _nextBomitem RECORD;
62724
62725 BEGIN
62726
62727   SELECT nextbomitem.bomitem_seqnumber AS next_seqnumber,
62728          thisbomitem.bomitem_seqnumber AS this_seqnumber,
62729          thisbomitem.bomitem_parent_item_id AS parent_item_id,
62730          thisbomitem.bomitem_rev_id AS rev_id
62731           INTO _nextBomitem
62732   FROM bomitem AS nextbomitem, bomitem AS thisbomitem
62733   WHERE ((nextbomitem.bomitem_seqnumber > thisbomitem.bomitem_seqnumber)
62734    AND (nextbomitem.bomitem_parent_item_id=thisbomitem.bomitem_parent_item_id)
62735    AND (nextbomitem.bomitem_rev_id=thisbomitem.bomitem_rev_id)
62736    AND (thisbomitem.bomitem_id=pBomitemid))
62737   ORDER BY next_seqnumber
62738   LIMIT 1;
62739
62740   IF (FOUND) THEN
62741 --  Swap the seqnumber of the current bomitem and the next bomitem
62742 --  There is the potential for multiple bomitems with the same seqnumber
62743
62744     UPDATE bomitem
62745     SET bomitem_seqnumber=0
62746     WHERE (bomitem_seqnumber=_nextBomitem.next_seqnumber)
62747       AND (bomitem_parent_item_id=_nextBomitem.parent_item_id)
62748       AND (bomitem_rev_id=_nextBomitem.rev_id);
62749
62750     UPDATE bomitem 
62751     SET bomitem_seqnumber=_nextBomitem.next_seqnumber
62752     WHERE (bomitem_seqnumber=_nextBomitem.this_seqnumber)
62753       AND (bomitem_parent_item_id=_nextBomitem.parent_item_id)
62754       AND (bomitem_rev_id=_nextBomitem.rev_id);
62755
62756     UPDATE bomitem
62757     SET bomitem_seqnumber=_nextBomitem.this_seqnumber
62758     WHERE (bomitem_seqnumber=0)
62759       AND (bomitem_parent_item_id=_nextBomitem.parent_item_id)
62760       AND (bomitem_rev_id=_nextBomitem.rev_id);
62761   END IF;
62762
62763   RETURN 1;
62764
62765 END;
62766 $_$;
62767
62768
62769 ALTER FUNCTION public.movebomitemdown(integer) OWNER TO admin;
62770
62771 --
62772 -- TOC entry 1921 (class 1255 OID 146566714)
62773 -- Dependencies: 4536 8
62774 -- Name: movebomitemup(integer); Type: FUNCTION; Schema: public; Owner: admin
62775 --
62776
62777 CREATE FUNCTION movebomitemup(integer) RETURNS integer
62778     LANGUAGE plpgsql
62779     AS $_$
62780 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62781 -- See www.xtuple.com/CPAL for the full text of the software license.
62782 DECLARE
62783   pBomitemid ALIAS FOR $1;
62784   _nextBomitem RECORD;
62785
62786 BEGIN
62787
62788   SELECT nextbomitem.bomitem_seqnumber AS next_seqnumber,
62789          thisbomitem.bomitem_seqnumber AS this_seqnumber,
62790          thisbomitem.bomitem_parent_item_id AS parent_item_id,
62791          thisbomitem.bomitem_rev_id AS rev_id
62792           INTO _nextBomitem
62793   FROM bomitem AS nextbomitem, bomitem AS thisbomitem
62794   WHERE ((nextbomitem.bomitem_seqnumber < thisbomitem.bomitem_seqnumber)
62795    AND (nextbomitem.bomitem_parent_item_id=thisbomitem.bomitem_parent_item_id)
62796    AND (nextbomitem.bomitem_rev_id=thisbomitem.bomitem_rev_id)
62797    AND (thisbomitem.bomitem_id=pBomitemid))
62798   ORDER BY next_seqnumber DESC
62799   LIMIT 1;
62800
62801   IF (FOUND) THEN
62802 --  Swap the seqnumber of the current bomitem and the next bomitem
62803 --  There is the potential for multiple bomitems with the same seqnumber
62804
62805     UPDATE bomitem
62806     SET bomitem_seqnumber=0
62807     WHERE (bomitem_seqnumber=_nextBomitem.next_seqnumber)
62808       AND (bomitem_parent_item_id=_nextBomitem.parent_item_id)
62809       AND (bomitem_rev_id=_nextBomitem.rev_id);
62810
62811     UPDATE bomitem 
62812     SET bomitem_seqnumber=_nextBomitem.next_seqnumber
62813     WHERE (bomitem_seqnumber=_nextBomitem.this_seqnumber)
62814       AND (bomitem_parent_item_id=_nextBomitem.parent_item_id)
62815       AND (bomitem_rev_id=_nextBomitem.rev_id);
62816
62817     UPDATE bomitem
62818     SET bomitem_seqnumber=_nextBomitem.this_seqnumber
62819     WHERE (bomitem_seqnumber=0)
62820       AND (bomitem_parent_item_id=_nextBomitem.parent_item_id)
62821       AND (bomitem_rev_id=_nextBomitem.rev_id);
62822   END IF;
62823
62824   RETURN 1;
62825
62826 END;
62827 $_$;
62828
62829
62830 ALTER FUNCTION public.movebomitemup(integer) OWNER TO admin;
62831
62832 --
62833 -- TOC entry 1922 (class 1255 OID 146566715)
62834 -- Dependencies: 4536 8
62835 -- Name: moveccarddown(integer); Type: FUNCTION; Schema: public; Owner: admin
62836 --
62837
62838 CREATE FUNCTION moveccarddown(integer) RETURNS integer
62839     LANGUAGE plpgsql
62840     AS $_$
62841 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62842 -- See www.xtuple.com/CPAL for the full text of the software license.
62843 DECLARE
62844   pCcardid ALIAS FOR $1;
62845   _nextCcard RECORD;
62846
62847 BEGIN
62848
62849   SELECT nextCcard.ccard_id, nextCcard.ccard_seq AS next_seqnumber,
62850          thisCcard.ccard_seq AS this_seqnumber INTO _nextCcard
62851   FROM Ccard AS nextCcard, Ccard AS thisCcard
62852   WHERE ((nextCcard.ccard_seq > thisCcard.ccard_seq)
62853    AND (nextCcard.ccard_cust_id=thisCcard.ccard_cust_id)
62854    AND (thisCcard.ccard_id=pCcardid))
62855   ORDER BY next_seqnumber
62856   LIMIT 1;
62857
62858   IF (FOUND) THEN
62859 --  Swap the seqnumber of the current Ccard and the next Ccard
62860
62861     UPDATE Ccard
62862     SET ccard_seq=_nextCcard.next_seqnumber
62863     WHERE (ccard_id=pCcardid);
62864
62865     UPDATE Ccard
62866     SET ccard_seq=_nextCcard.this_seqnumber
62867     WHERE (ccard_id=_nextCcard.ccard_id);
62868   END IF;
62869
62870   RETURN 1;
62871
62872 END;
62873 $_$;
62874
62875
62876 ALTER FUNCTION public.moveccarddown(integer) OWNER TO admin;
62877
62878 --
62879 -- TOC entry 1923 (class 1255 OID 146566716)
62880 -- Dependencies: 4536 8
62881 -- Name: moveccardup(integer); Type: FUNCTION; Schema: public; Owner: admin
62882 --
62883
62884 CREATE FUNCTION moveccardup(integer) RETURNS integer
62885     LANGUAGE plpgsql
62886     AS $_$
62887 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62888 -- See www.xtuple.com/CPAL for the full text of the software license.
62889 DECLARE
62890   pCcardid ALIAS FOR $1;
62891   _nextCcard RECORD;
62892
62893 BEGIN
62894
62895   SELECT nextCcard.ccard_id AS ccard_id, nextCcard.ccard_seq AS next_seqnumber,
62896          thisCcard.ccard_seq AS this_seqnumber INTO _nextCcard
62897   FROM ccard AS nextCcard, ccard AS thisCcard
62898   WHERE ((nextCcard.ccard_seq < thisCcard.ccard_seq)
62899    AND (nextCcard.ccard_cust_id=thisCcard.ccard_cust_id)
62900    AND (thisCcard.ccard_id=pCcardid))
62901   ORDER BY next_seqnumber DESC
62902   LIMIT 1;
62903
62904   IF (FOUND) THEN
62905 --  Swap the seqnumber of the current Ccard and the next Ccard
62906
62907     UPDATE Ccard 
62908     SET ccard_seq=_nextCcard.next_seqnumber
62909     WHERE (ccard_id=pCcardid);
62910
62911     UPDATE Ccard
62912     SET ccard_seq=_nextCcard.this_seqnumber
62913     WHERE (ccard_id=_nextCcard.ccard_id);
62914   END IF;
62915
62916   RETURN 1;
62917
62918 END;
62919 $_$;
62920
62921
62922 ALTER FUNCTION public.moveccardup(integer) OWNER TO admin;
62923
62924 --
62925 -- TOC entry 1925 (class 1255 OID 146566717)
62926 -- Dependencies: 4536 8
62927 -- Name: moveflgroupdown(integer); Type: FUNCTION; Schema: public; Owner: admin
62928 --
62929
62930 CREATE FUNCTION moveflgroupdown(integer) RETURNS integer
62931     LANGUAGE plpgsql
62932     AS $_$
62933 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
62934 -- See www.xtuple.com/CPAL for the full text of the software license.
62935 DECLARE
62936   pFlgrpid ALIAS FOR $1;
62937   _from RECORD;
62938   _to RECORD;
62939
62940 BEGIN
62941
62942   SELECT flgrp_id AS id,
62943          flgrp_flhead_id AS flhead_id,
62944          flgrp_flgrp_id AS flgrp_id,
62945          flgrp_order AS ord INTO _from
62946     FROM flgrp
62947    WHERE (flgrp_id=pFlgrpid);
62948   IF (NOT FOUND) THEN
62949     RETURN -1;
62950   END IF;
62951
62952   SELECT id, type, ord INTO _to
62953     FROM (SELECT flitem_id AS id, 'I' AS type, flitem_order AS ord
62954             FROM flitem
62955            WHERE ((flitem_flgrp_id=_from.flgrp_id)
62956              AND  (flitem_flhead_id=_from.flhead_id))
62957            UNION
62958           SELECT flgrp_id AS id, 'G' AS type, flgrp_order AS ord
62959             FROM flgrp
62960            WHERE ((flgrp_flgrp_id=_from.flgrp_id)
62961              AND  (flgrp_flhead_id=_from.flhead_id))
62962            UNION
62963           SELECT flspec_id AS id, 'S' AS type, flspec_order AS ord
62964             FROM flspec
62965            WHERE ((flspec_flgrp_id=_from.flgrp_id)
62966              AND  (flspec_flhead_id=_from.flhead_id)) ) AS data
62967    WHERE (ord > _from.ord)
62968    ORDER BY ord
62969    LIMIT 1;
62970   IF (FOUND) THEN
62971     UPDATE flgrp
62972        SET flgrp_order=_to.ord
62973      WHERE (flgrp_id=_from.id);
62974
62975     IF (_to.type='I') THEN
62976       UPDATE flitem
62977          SET flitem_order=_from.ord
62978        WHERE (flitem_id=_to.id);
62979     ELSE
62980       IF (_to.type='G') THEN
62981         UPDATE flgrp
62982            SET flgrp_order=_from.ord
62983          WHERE (flgrp_id=_to.id);
62984       ELSE
62985         IF (_to.type='S') THEN
62986           UPDATE flspec
62987              SET flspec_order=_from.ord
62988            WHERE (flspec_id=_to.id);
62989         END IF;
62990       END IF;
62991     END IF;
62992   END IF;
62993
62994   RETURN 0;
62995
62996 END;
62997 $_$;
62998
62999
63000 ALTER FUNCTION public.moveflgroupdown(integer) OWNER TO admin;
63001
63002 --
63003 -- TOC entry 1926 (class 1255 OID 146566718)
63004 -- Dependencies: 4536 8
63005 -- Name: moveflgroupup(integer); Type: FUNCTION; Schema: public; Owner: admin
63006 --
63007
63008 CREATE FUNCTION moveflgroupup(integer) RETURNS integer
63009     LANGUAGE plpgsql
63010     AS $_$
63011 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63012 -- See www.xtuple.com/CPAL for the full text of the software license.
63013 DECLARE
63014   pFlgrpid ALIAS FOR $1;
63015   _from RECORD;
63016   _to RECORD;
63017
63018 BEGIN
63019
63020   SELECT flgrp_id AS id,
63021          flgrp_flhead_id AS flhead_id,
63022          flgrp_flgrp_id AS flgrp_id,
63023          flgrp_order AS ord INTO _from
63024     FROM flgrp
63025    WHERE (flgrp_id=pFlgrpid);
63026   IF (NOT FOUND) THEN
63027     RETURN -1;
63028   END IF;
63029
63030   SELECT id, type, ord INTO _to
63031     FROM (SELECT flitem_id AS id, 'I' AS type, flitem_order AS ord
63032             FROM flitem
63033            WHERE ((flitem_flgrp_id=_from.flgrp_id)
63034              AND  (flitem_flhead_id=_from.flhead_id))
63035            UNION
63036           SELECT flgrp_id AS id, 'G' AS type, flgrp_order AS ord
63037             FROM flgrp
63038            WHERE ((flgrp_flgrp_id=_from.flgrp_id)
63039              AND  (flgrp_flhead_id=_from.flhead_id))
63040            UNION
63041           SELECT flspec_id AS id, 'S' AS type, flspec_order AS ord
63042             FROM flspec
63043            WHERE ((flspec_flgrp_id=_from.flgrp_id)
63044              AND  (flspec_flhead_id=_from.flhead_id)) ) AS data
63045    WHERE (ord < _from.ord)
63046    ORDER BY ord DESC
63047    LIMIT 1;
63048   IF (FOUND) THEN
63049     UPDATE flgrp
63050        SET flgrp_order=_to.ord
63051      WHERE (flgrp_id=_from.id);
63052
63053     IF (_to.type='I') THEN
63054       UPDATE flitem
63055          SET flitem_order=_from.ord
63056        WHERE (flitem_id=_to.id);
63057     ELSE
63058       IF (_to.type='G') THEN
63059         UPDATE flgrp
63060            SET flgrp_order=_from.ord
63061          WHERE (flgrp_id=_to.id);
63062       ELSE
63063         IF (_to.type='S') THEN
63064           UPDATE flspec
63065              SET flspec_order=_from.ord
63066            WHERE (flspec_id=_to.id);
63067         END IF;
63068       END IF;
63069     END IF;
63070   END IF;
63071
63072   RETURN 0;
63073
63074 END;
63075 $_$;
63076
63077
63078 ALTER FUNCTION public.moveflgroupup(integer) OWNER TO admin;
63079
63080 --
63081 -- TOC entry 1927 (class 1255 OID 146566719)
63082 -- Dependencies: 4536 8
63083 -- Name: moveflitemdown(integer); Type: FUNCTION; Schema: public; Owner: admin
63084 --
63085
63086 CREATE FUNCTION moveflitemdown(integer) RETURNS integer
63087     LANGUAGE plpgsql
63088     AS $_$
63089 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63090 -- See www.xtuple.com/CPAL for the full text of the software license.
63091 DECLARE
63092   pFlitemid ALIAS FOR $1;
63093   _from RECORD;
63094   _to RECORD;
63095
63096 BEGIN
63097
63098   SELECT flitem_id AS id,
63099          flitem_flhead_id AS flhead_id,
63100          flitem_flgrp_id AS flgrp_id,
63101          flitem_order AS ord INTO _from
63102     FROM flitem
63103    WHERE (flitem_id=pFlitemid);
63104   IF (NOT FOUND) THEN
63105     RETURN -1;
63106   END IF;
63107
63108   SELECT id, type, ord INTO _to
63109     FROM (SELECT flitem_id AS id, 'I' AS type, flitem_order AS ord
63110             FROM flitem
63111            WHERE ((flitem_flgrp_id=_from.flgrp_id)
63112              AND  (flitem_flhead_id=_from.flhead_id))
63113            UNION
63114           SELECT flgrp_id AS id, 'G' AS type, flgrp_order AS ord
63115             FROM flgrp
63116            WHERE ((flgrp_flgrp_id=_from.flgrp_id)
63117              AND  (flgrp_flhead_id=_from.flhead_id))
63118            UNION
63119           SELECT flspec_id AS id, 'S' AS type, flspec_order AS ord
63120             FROM flspec
63121            WHERE ((flspec_flgrp_id=_from.flgrp_id)
63122              AND  (flspec_flhead_id=_from.flhead_id)) ) AS data
63123    WHERE (ord > _from.ord)
63124    ORDER BY ord
63125    LIMIT 1;
63126   IF (FOUND) THEN
63127     UPDATE flitem
63128        SET flitem_order=_to.ord
63129      WHERE (flitem_id=_from.id);
63130
63131     IF (_to.type='I') THEN
63132       UPDATE flitem
63133          SET flitem_order=_from.ord
63134        WHERE (flitem_id=_to.id);
63135     ELSE
63136       IF (_to.type='G') THEN
63137         UPDATE flgrp
63138            SET flgrp_order=_from.ord
63139          WHERE (flgrp_id=_to.id);
63140       ELSE
63141         IF (_to.type='S') THEN
63142           UPDATE flspec
63143              SET flspec_order=_from.ord
63144            WHERE (flspec_id=_to.id);
63145         END IF;
63146       END IF;
63147     END IF;
63148   END IF;
63149
63150   RETURN 0;
63151
63152 END;
63153 $_$;
63154
63155
63156 ALTER FUNCTION public.moveflitemdown(integer) OWNER TO admin;
63157
63158 --
63159 -- TOC entry 1928 (class 1255 OID 146566720)
63160 -- Dependencies: 4536 8
63161 -- Name: moveflitemup(integer); Type: FUNCTION; Schema: public; Owner: admin
63162 --
63163
63164 CREATE FUNCTION moveflitemup(integer) RETURNS integer
63165     LANGUAGE plpgsql
63166     AS $_$
63167 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63168 -- See www.xtuple.com/CPAL for the full text of the software license.
63169 DECLARE
63170   pFlitemid ALIAS FOR $1;
63171   _from RECORD;
63172   _to RECORD;
63173
63174 BEGIN
63175
63176   SELECT flitem_id AS id,
63177          flitem_flhead_id AS flhead_id,
63178          flitem_flgrp_id AS flgrp_id,
63179          flitem_order AS ord INTO _from
63180     FROM flitem
63181    WHERE (flitem_id=pFlitemid);
63182   IF (NOT FOUND) THEN
63183     RETURN -1;
63184   END IF;
63185
63186   SELECT id, type, ord INTO _to
63187     FROM (SELECT flitem_id AS id, 'I' AS type, flitem_order AS ord
63188             FROM flitem
63189            WHERE ((flitem_flgrp_id=_from.flgrp_id)
63190              AND  (flitem_flhead_id=_from.flhead_id))
63191            UNION
63192           SELECT flgrp_id AS id, 'G' AS type, flgrp_order AS ord
63193             FROM flgrp
63194            WHERE ((flgrp_flgrp_id=_from.flgrp_id)
63195              AND  (flgrp_flhead_id=_from.flhead_id))
63196            UNION
63197           SELECT flspec_id AS id, 'S' AS type, flspec_order AS ord
63198             FROM flspec
63199            WHERE ((flspec_flgrp_id=_from.flgrp_id)
63200              AND  (flspec_flhead_id=_from.flhead_id)) ) AS data
63201    WHERE (ord < _from.ord)
63202    ORDER BY ord DESC
63203    LIMIT 1;
63204   IF (FOUND) THEN
63205     UPDATE flitem
63206        SET flitem_order=_to.ord
63207      WHERE (flitem_id=_from.id);
63208
63209     IF (_to.type='I') THEN
63210       UPDATE flitem
63211          SET flitem_order=_from.ord
63212        WHERE (flitem_id=_to.id);
63213     ELSE
63214       IF (_to.type='G') THEN
63215         UPDATE flgrp
63216            SET flgrp_order=_from.ord
63217          WHERE (flgrp_id=_to.id);
63218       ELSE
63219         IF (_to.type='S') THEN
63220           UPDATE flspec
63221              SET flspec_order=_from.ord
63222            WHERE (flspec_id=_to.id);
63223         END IF;
63224       END IF;
63225     END IF;
63226   END IF;
63227
63228   RETURN 0;
63229
63230 END;
63231 $_$;
63232
63233
63234 ALTER FUNCTION public.moveflitemup(integer) OWNER TO admin;
63235
63236 --
63237 -- TOC entry 1930 (class 1255 OID 146566721)
63238 -- Dependencies: 4536 8
63239 -- Name: moveflspecdown(integer); Type: FUNCTION; Schema: public; Owner: admin
63240 --
63241
63242 CREATE FUNCTION moveflspecdown(integer) RETURNS integer
63243     LANGUAGE plpgsql
63244     AS $_$
63245 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63246 -- See www.xtuple.com/CPAL for the full text of the software license.
63247 DECLARE
63248   pFlspecid ALIAS FOR $1;
63249   _from RECORD;
63250   _to RECORD;
63251
63252 BEGIN
63253
63254   SELECT flspec_id AS id,
63255          flspec_flhead_id AS flhead_id,
63256          flspec_flgrp_id AS flgrp_id,
63257          flspec_order AS ord INTO _from
63258     FROM flspec
63259    WHERE (flspec_id=pFlspecid);
63260   IF (NOT FOUND) THEN
63261     RETURN -1;
63262   END IF;
63263
63264   SELECT id, type, ord INTO _to
63265     FROM (SELECT flitem_id AS id, 'I' AS type, flitem_order AS ord
63266             FROM flitem
63267            WHERE ((flitem_flgrp_id=_from.flgrp_id)
63268              AND  (flitem_flhead_id=_from.flhead_id))
63269            UNION
63270           SELECT flgrp_id AS id, 'G' AS type, flgrp_order AS ord
63271             FROM flgrp
63272            WHERE ((flgrp_flgrp_id=_from.flgrp_id)
63273              AND  (flgrp_flhead_id=_from.flhead_id))
63274            UNION
63275           SELECT flspec_id AS id, 'S' AS type, flspec_order AS ord
63276             FROM flspec
63277            WHERE ((flspec_flgrp_id=_from.flgrp_id)
63278              AND  (flspec_flhead_id=_from.flhead_id)) ) AS data
63279    WHERE (ord > _from.ord)
63280    ORDER BY ord
63281    LIMIT 1;
63282   IF (FOUND) THEN
63283     UPDATE flspec
63284        SET flspec_order=_to.ord
63285      WHERE (flspec_id=_from.id);
63286
63287     IF (_to.type='I') THEN
63288       UPDATE flitem
63289          SET flitem_order=_from.ord
63290        WHERE (flitem_id=_to.id);
63291     ELSE
63292       IF (_to.type='G') THEN
63293         UPDATE flgrp
63294            SET flgrp_order=_from.ord
63295          WHERE (flgrp_id=_to.id);
63296       ELSE
63297         IF (_to.type='S') THEN
63298           UPDATE flspec
63299              SET flspec_order=_from.ord
63300            WHERE (flspec_id=_to.id);
63301         END IF;
63302       END IF;
63303     END IF;
63304   END IF;
63305
63306   RETURN 0;
63307
63308 END;
63309 $_$;
63310
63311
63312 ALTER FUNCTION public.moveflspecdown(integer) OWNER TO admin;
63313
63314 --
63315 -- TOC entry 1931 (class 1255 OID 146566722)
63316 -- Dependencies: 4536 8
63317 -- Name: moveflspecup(integer); Type: FUNCTION; Schema: public; Owner: admin
63318 --
63319
63320 CREATE FUNCTION moveflspecup(integer) RETURNS integer
63321     LANGUAGE plpgsql
63322     AS $_$
63323 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63324 -- See www.xtuple.com/CPAL for the full text of the software license.
63325 DECLARE
63326   pFlspecid ALIAS FOR $1;
63327   _from RECORD;
63328   _to RECORD;
63329
63330 BEGIN
63331
63332   SELECT flspec_id AS id,
63333          flspec_flhead_id AS flhead_id,
63334          flspec_flgrp_id AS flgrp_id,
63335          flspec_order AS ord INTO _from
63336     FROM flspec
63337    WHERE (flspec_id=pFlspecid);
63338   IF (NOT FOUND) THEN
63339     RETURN -1;
63340   END IF;
63341
63342   SELECT id, type, ord INTO _to
63343     FROM (SELECT flitem_id AS id, 'I' AS type, flitem_order AS ord
63344             FROM flitem
63345            WHERE ((flitem_flgrp_id=_from.flgrp_id)
63346              AND  (flitem_flhead_id=_from.flhead_id))
63347            UNION
63348           SELECT flgrp_id AS id, 'G' AS type, flgrp_order AS ord
63349             FROM flgrp
63350            WHERE ((flgrp_flgrp_id=_from.flgrp_id)
63351              AND  (flgrp_flhead_id=_from.flhead_id))
63352            UNION
63353           SELECT flspec_id AS id, 'S' AS type, flspec_order AS ord
63354             FROM flspec
63355            WHERE ((flspec_flgrp_id=_from.flgrp_id)
63356              AND  (flspec_flhead_id=_from.flhead_id)) ) AS data
63357    WHERE (ord < _from.ord)
63358    ORDER BY ord DESC
63359    LIMIT 1;
63360   IF (FOUND) THEN
63361     UPDATE flspec
63362        SET flspec_order=_to.ord
63363      WHERE (flspec_id=_from.id);
63364
63365     IF (_to.type='I') THEN
63366       UPDATE flitem
63367          SET flitem_order=_from.ord
63368        WHERE (flitem_id=_to.id);
63369     ELSE
63370       IF (_to.type='G') THEN
63371         UPDATE flgrp
63372            SET flgrp_order=_from.ord
63373          WHERE (flgrp_id=_to.id);
63374       ELSE
63375         IF (_to.type='S') THEN
63376           UPDATE flspec
63377              SET flspec_order=_from.ord
63378            WHERE (flspec_id=_to.id);
63379         END IF;
63380       END IF;
63381     END IF;
63382   END IF;
63383
63384   RETURN 0;
63385
63386 END;
63387 $_$;
63388
63389
63390 ALTER FUNCTION public.moveflspecup(integer) OWNER TO admin;
63391
63392 --
63393 -- TOC entry 1932 (class 1255 OID 146566723)
63394 -- Dependencies: 4536 8
63395 -- Name: movescript(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
63396 --
63397
63398 CREATE FUNCTION movescript(integer, integer, integer) RETURNS integer
63399     LANGUAGE plpgsql
63400     AS $_$
63401 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63402 -- See www.xtuple.com/CPAL for the full text of the software license.
63403 DECLARE
63404   pscriptid ALIAS FOR $1;
63405   poldpkgid ALIAS FOR $2;
63406   pnewpkgid ALIAS FOR $3;
63407
63408   _deletestr    TEXT;
63409   _destination  TEXT;
63410   _insertstr    TEXT;
63411   _rows         INTEGER;
63412   _selectstr    TEXT;
63413   _source       TEXT;
63414   _record       RECORD;
63415
63416 BEGIN
63417   IF (poldpkgid = pnewpkgid) THEN
63418     RETURN 0;
63419   END IF;
63420
63421   IF (poldpkgid = -1) THEN
63422     _source = 'public.script';
63423   ELSE
63424     SELECT pkghead_name || '.pkgscript' INTO _source
63425     FROM pkghead
63426     WHERE pkghead_id=poldpkgid;
63427
63428     IF NOT FOUND THEN
63429       RETURN -1;
63430     END IF;
63431   END IF;
63432
63433   IF (pnewpkgid = -1) THEN
63434     _destination = 'public.script';
63435   ELSE
63436     SELECT pkghead_name || '.pkgscript' INTO _destination
63437     FROM pkghead
63438     WHERE pkghead_id=pnewpkgid;
63439
63440     IF NOT FOUND THEN
63441       RETURN -2;
63442     END IF;
63443   END IF;
63444
63445   _selectstr := ' SELECT * FROM ' || _source ||
63446                 ' WHERE script_id = ' || pscriptid;
63447   EXECUTE _selectstr INTO _record;
63448
63449   _deletestr := 'DELETE FROM ONLY ' || _source || 
63450                 ' WHERE script_id = ' || pscriptid;
63451   EXECUTE _deletestr;
63452   GET DIAGNOSTICS _rows = ROW_COUNT;
63453   RAISE NOTICE '% rows from %', _rows, _deletestr;
63454   IF (_rows < 1) THEN
63455     RETURN -3;
63456   ELSIF (_rows > 1) THEN
63457     RAISE EXCEPTION 'Tried to delete % scripts with the id % when there should be exactly 1',
63458                     _rows, pscriptid;
63459   END IF;
63460
63461   _insertstr := 'INSERT INTO ' || _destination ||
63462                 ' (script_id, script_name, script_order, script_enabled, ' ||
63463                 '  script_source, script_notes) VALUES ('
63464                 || _record.script_id      || ','
63465                 || quote_literal(_record.script_name)    || ','
63466                 || _record.script_order   || ','
63467                 || _record.script_enabled || ','
63468                 || quote_literal(_record.script_source)  || ','
63469                 || quote_literal(_record.script_notes )  || ');'
63470                 ;
63471   EXECUTE _insertstr;
63472   GET DIAGNOSTICS _rows = ROW_COUNT;
63473   RAISE NOTICE '% rows from %', _rows, _insertstr;
63474   IF (_rows < 1) THEN
63475     RETURN -4;
63476   ELSIF (_rows > 1) THEN
63477     RAISE EXCEPTION 'Tried to insert % scripts with the id % when there should be exactly 1',
63478                     _rows, pscriptid;
63479   END IF;
63480
63481   RETURN pscriptid;
63482
63483 END;
63484 $_$;
63485
63486
63487 ALTER FUNCTION public.movescript(integer, integer, integer) OWNER TO admin;
63488
63489 --
63490 -- TOC entry 1933 (class 1255 OID 146566724)
63491 -- Dependencies: 4536 8
63492 -- Name: moveuiform(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
63493 --
63494
63495 CREATE FUNCTION moveuiform(integer, integer, integer) RETURNS integer
63496     LANGUAGE plpgsql
63497     AS $_$
63498 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63499 -- See www.xtuple.com/CPAL for the full text of the software license.
63500 DECLARE
63501   puiformid ALIAS FOR $1;
63502   poldpkgid ALIAS FOR $2;
63503   pnewpkgid ALIAS FOR $3;
63504
63505   _deletestr    TEXT;
63506   _destination  TEXT;
63507   _insertstr    TEXT;
63508   _rows         INTEGER;
63509   _selectstr    TEXT;
63510   _source       TEXT;
63511   _record       RECORD;
63512
63513 BEGIN
63514   IF (poldpkgid = pnewpkgid) THEN
63515     RETURN 0;
63516   END IF;
63517
63518   IF (poldpkgid = -1) THEN
63519     _source = 'public.uiform';
63520   ELSE
63521     SELECT pkghead_name || '.pkguiform' INTO _source
63522     FROM pkghead
63523     WHERE pkghead_id=poldpkgid;
63524
63525     IF NOT FOUND THEN
63526       RETURN -1;
63527     END IF;
63528   END IF;
63529
63530   IF (pnewpkgid = -1) THEN
63531     _destination = 'public.uiform';
63532   ELSE
63533     SELECT pkghead_name || '.pkguiform' INTO _destination
63534     FROM pkghead
63535     WHERE pkghead_id=pnewpkgid;
63536
63537     IF NOT FOUND THEN
63538       RETURN -2;
63539     END IF;
63540   END IF;
63541
63542   _selectstr := ' SELECT * FROM ' || _source ||
63543                 ' WHERE uiform_id = ' || puiformid;
63544   EXECUTE _selectstr INTO _record;
63545
63546   _deletestr := 'DELETE FROM ONLY ' || _source || 
63547                 ' WHERE uiform_id = ' || puiformid;
63548   EXECUTE _deletestr;
63549   GET DIAGNOSTICS _rows = ROW_COUNT;
63550   RAISE NOTICE '% rows from %', _rows, _deletestr;
63551   IF (_rows < 1) THEN
63552     RETURN -3;
63553   ELSIF (_rows > 1) THEN
63554     RAISE EXCEPTION 'Tried to delete % uiforms with the id % when there should be exactly 1',
63555                     _rows, puiformid;
63556   END IF;
63557
63558   _insertstr := 'INSERT INTO ' || _destination ||
63559                 ' (uiform_id, uiform_name, uiform_order, uiform_enabled, ' ||
63560                 '  uiform_source, uiform_notes) VALUES ('
63561                 || _record.uiform_id      || ','
63562                 || quote_literal(_record.uiform_name)    || ','
63563                 || _record.uiform_order   || ','
63564                 || _record.uiform_enabled || ','
63565                 || quote_literal(_record.uiform_source)  || ','
63566                 || quote_literal(_record.uiform_notes )  || ');'
63567                 ;
63568   EXECUTE _insertstr;
63569   GET DIAGNOSTICS _rows = ROW_COUNT;
63570   RAISE NOTICE '% rows from %', _rows, _insertstr;
63571   IF (_rows < 1) THEN
63572     RETURN -4;
63573   ELSIF (_rows > 1) THEN
63574     RAISE EXCEPTION 'Tried to insert % uiforms with the id % when there should be exactly 1',
63575                     _rows, puiformid;
63576   END IF;
63577
63578   RETURN puiformid;
63579
63580 END;
63581 $_$;
63582
63583
63584 ALTER FUNCTION public.moveuiform(integer, integer, integer) OWNER TO admin;
63585
63586 --
63587 -- TOC entry 1934 (class 1255 OID 146566725)
63588 -- Dependencies: 4536 8
63589 -- Name: moveupdown(integer, text, text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
63590 --
63591
63592 CREATE FUNCTION moveupdown(pid integer, pschema text, ptable text, pseqcol text, pjoincol text, pextra text, pdir text) RETURNS integer
63593     LANGUAGE plpgsql
63594     AS $_$
63595 DECLARE
63596   _keyfield TEXT;
63597   _keysize  INTEGER;
63598   _qry      TEXT;
63599   _r        RECORD;
63600   _rowcnt   INTEGER;
63601   _schema   TEXT := COALESCE(pSchema, 'public');
63602 BEGIN
63603   RAISE DEBUG 'moveUpDown(%, %, %, %, %, %, %) entered',
63604               pId, pSchema, pTable, pSeqCol, pJoinCol, pExtra, pDir;
63605
63606   IF (UPPER(pDir) NOT IN ('UP', 'DOWN')) THEN
63607      RAISE EXCEPTION 'Cannot change the order of records; unsure what % means for sequencing [xtuple: moveUpDown, -1, %, %.%]',
63608                      pDir, pDir, _schema, pTable;
63609   END IF;
63610
63611   SELECT attname, ARRAY_UPPER(conkey, 1) INTO _keyfield, _keysize
63612     FROM pg_attribute
63613     JOIN pg_constraint ON (attrelid=conrelid AND attnum=conkey[1])
63614     JOIN pg_class      ON (conrelid=pg_class.oid)
63615     JOIN pg_namespace  ON (relnamespace=pg_namespace.oid)
63616    WHERE ((contype='p')
63617       AND (nspname=_schema)
63618       AND (relname=pTable));
63619
63620   RAISE DEBUG 'SELECT attname... returned %, %', _keyfield, _keysize;
63621
63622   IF (_keysize > 1) THEN
63623     RAISE EXCEPTION 'Cannot change the order of records because %.% has a composite primary key [xtuple: moveUpDown, -2, %.%]',
63624                      _schema, pTable,
63625                      _schema, pTable;
63626   END IF;
63627
63628   /* SELECT next._keyfield AS nextid,
63629             next.pSeqCol   AS nextseq,
63630             this.pSeqCol   AS thisseq
63631        FROM _schema.pTable AS next,
63632             _schema.pTable AS this
63633       WHERE (this._keyfield=$1)
63634           AND (next.pSeqCol [> or <] this.pSeqCol)
63635         [ AND (next.pJoinCol=this.pJoinCol) ]
63636         [ AND (pExtra) ]
63637       ORDER BY nextseq [ DESC or ASC ]
63638       LIMIT 1;
63639   */
63640
63641   _qry := 'SELECT next.' || quote_ident(_keyfield) || ' AS nextid,
63642                   next.' || quote_ident(pSeqCol)   || ' AS nextseq,
63643                   this.' || quote_ident(pSeqCol)   || ' AS thisseq
63644              FROM ' || _schema || '.' || quote_ident(pTable) || ' AS next,
63645                   ' || _schema || '.' || quote_ident(pTable) || ' AS this
63646             WHERE ((this.' || quote_ident(_keyfield)  || '=$1)
63647                AND (next.' || quote_ident(pSeqCol)    ||
63648                     CASE pDir WHEN 'UP' THEN ' < ' ELSE ' > ' END ||
63649                    'this.' || quote_ident(pSeqCol) || ')' ||
63650                CASE WHEN pJoinCol IS NULL THEN ''
63651                     ELSE ' AND (next.' || quote_ident(pJoinCol)  ||
63652                          '=this.' || quote_ident(pJoinCol) || ')'
63653                END ||
63654           '     AND (' || COALESCE(pExtra, 'TRUE') || '))
63655             ORDER BY nextseq ' ||
63656                CASE pDir WHEN 'UP' THEN 'DESC' ELSE 'ASC' END ||
63657           ' LIMIT 1;';
63658   RAISE DEBUG 'moveUpDown about to use % when running %', pId, _qry;
63659
63660   EXECUTE _qry INTO _r USING pId;
63661   GET DIAGNOSTICS _rowcnt = ROW_COUNT;
63662   RAISE DEBUG 'next id %, next seq %, this id %, this seq %',
63663                _r.nextid, _r.nextseq, pId, _r.thisseq;
63664
63665   IF (_rowcnt > 0) THEN
63666     _qry := 'UPDATE ' || _schema || '.' || quote_ident(pTable)  ||
63667               ' SET ' || pSeqCol || '=CAST($1 AS INTEGER)
63668              WHERE (' || quote_ident(_keyfield) || '=$2);';
63669
63670     EXECUTE _qry USING -1,         _r.nextid;
63671     EXECUTE _qry USING _r.nextseq, pId;
63672     EXECUTE _qry USING _r.thisseq, _r.nextid;
63673     RETURN _r.nextid;
63674   END IF;
63675
63676   RETURN pId;
63677 END;
63678 $_$;
63679
63680
63681 ALTER FUNCTION public.moveupdown(pid integer, pschema text, ptable text, pseqcol text, pjoincol text, pextra text, pdir text) OWNER TO admin;
63682
63683 --
63684 -- TOC entry 9066 (class 0 OID 0)
63685 -- Dependencies: 1934
63686 -- Name: FUNCTION moveupdown(pid integer, pschema text, ptable text, pseqcol text, pjoincol text, pextra text, pdir text); Type: COMMENT; Schema: public; Owner: admin
63687 --
63688
63689 COMMENT ON FUNCTION moveupdown(pid integer, pschema text, ptable text, pseqcol text, pjoincol text, pextra text, pdir text) IS 'moveUpDown moves a particular record up or down in an ordered list.
63690       pId argument names the record to move.
63691       pSchema (uses public if NULL) and pTable name the table holding the list.
63692       pSeqCol is the column that holds the sequence number.
63693       pJoinCol is the column that distinguishes one list from another in the same table, or NULL if the table holds only one list.
63694       pExtra is an extra join clause that may be required, or NULL.
63695       pDir is either UP, meaning move the pId record closer to the beginning,
63696                 or DOWN.
63697 Returns the id of the record with which pId was swapped,
63698       or pId if the record was already at the end in the specified direction.';
63699
63700
63701 --
63702 -- TOC entry 1897 (class 1255 OID 146566726)
63703 -- Dependencies: 4536 8
63704 -- Name: nextperiodbyinterval(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
63705 --
63706
63707 CREATE FUNCTION nextperiodbyinterval(integer, integer) RETURNS integer
63708     LANGUAGE plpgsql
63709     AS $_$
63710 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63711 -- See www.xtuple.com/CPAL for the full text of the software license.
63712 DECLARE
63713   pPeriodid ALIAS FOR $1;
63714   pInterval ALIAS FOR $2;
63715   _periodid INTEGER;
63716 BEGIN
63717   SELECT b.period_id INTO _periodid
63718     FROM period AS a, period AS b
63719    WHERE ((a.period_id=pPeriodid)
63720      AND  (b.period_start >= a.period_start))
63721    ORDER BY b.period_start
63722    LIMIT 1 OFFSET pInterval;
63723   IF (NOT FOUND) THEN
63724     RETURN -1;
63725   END IF;
63726   RETURN _periodid;
63727 END;
63728 $_$;
63729
63730
63731 ALTER FUNCTION public.nextperiodbyinterval(integer, integer) OWNER TO admin;
63732
63733 --
63734 -- TOC entry 1917 (class 1255 OID 146566727)
63735 -- Dependencies: 4536 8
63736 -- Name: nextprsubnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
63737 --
63738
63739 CREATE FUNCTION nextprsubnumber(integer) RETURNS integer
63740     LANGUAGE plpgsql
63741     AS $_$
63742 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63743 -- See www.xtuple.com/CPAL for the full text of the software license.
63744 DECLARE
63745   pPrNumber ALIAS FOR $1;
63746   _subNumber INTEGER;
63747
63748 BEGIN
63749
63750   SELECT MAX(pr_subnumber) INTO _subNumber
63751   FROM pr
63752   WHERE (pr_number=pPrNumber);
63753
63754   IF (_subNumber IS NULL)
63755     THEN _subNumber := 0;
63756   END IF;
63757
63758   RETURN (_subNumber + 1);
63759
63760 END;
63761 $_$;
63762
63763
63764 ALTER FUNCTION public.nextprsubnumber(integer) OWNER TO admin;
63765
63766 --
63767 -- TOC entry 1918 (class 1255 OID 146566728)
63768 -- Dependencies: 8
63769 -- Name: nextwosubnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
63770 --
63771
63772 CREATE FUNCTION nextwosubnumber(integer) RETURNS integer
63773     LANGUAGE sql
63774     AS $_$
63775 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63776 -- See www.xtuple.com/CPAL for the full text of the software license.
63777 SELECT COALESCE((MAX(wo_subnumber) + 1), 1)
63778 FROM wo
63779 WHERE (wo_number=($1));
63780 $_$;
63781
63782
63783 ALTER FUNCTION public.nextwosubnumber(integer) OWNER TO admin;
63784
63785 --
63786 -- TOC entry 1924 (class 1255 OID 146566729)
63787 -- Dependencies: 4536 8
63788 -- Name: noneg(numeric); Type: FUNCTION; Schema: public; Owner: admin
63789 --
63790
63791 CREATE FUNCTION noneg(numeric) RETURNS numeric
63792     LANGUAGE plpgsql IMMUTABLE
63793     AS $_$
63794 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63795 -- See www.xtuple.com/CPAL for the full text of the software license.
63796 DECLARE
63797   pValue ALIAS FOR $1;
63798
63799 BEGIN
63800
63801   IF (pValue < 0) THEN
63802     RETURN 0;
63803   ELSE
63804    RETURN pValue;
63805   END IF;
63806
63807 END;
63808 $_$;
63809
63810
63811 ALTER FUNCTION public.noneg(numeric) OWNER TO admin;
63812
63813 --
63814 -- TOC entry 1929 (class 1255 OID 146566730)
63815 -- Dependencies: 4536 8
63816 -- Name: nopos(numeric); Type: FUNCTION; Schema: public; Owner: admin
63817 --
63818
63819 CREATE FUNCTION nopos(numeric) RETURNS numeric
63820     LANGUAGE plpgsql IMMUTABLE
63821     AS $_$
63822 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63823 -- See www.xtuple.com/CPAL for the full text of the software license.
63824 DECLARE
63825   pValue ALIAS FOR $1;
63826
63827 BEGIN
63828
63829   IF (pValue > 0) THEN
63830     RETURN 0;
63831   ELSE
63832    RETURN pValue;
63833   END IF;
63834
63835 END;
63836 $_$;
63837
63838
63839 ALTER FUNCTION public.nopos(numeric) OWNER TO admin;
63840
63841 --
63842 -- TOC entry 1936 (class 1255 OID 146566731)
63843 -- Dependencies: 4536 8
63844 -- Name: normalizetrialbal(integer, character); Type: FUNCTION; Schema: public; Owner: admin
63845 --
63846
63847 CREATE FUNCTION normalizetrialbal(integer, character) RETURNS numeric
63848     LANGUAGE plpgsql STABLE
63849     AS $_$
63850 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63851 -- See www.xtuple.com/CPAL for the full text of the software license.
63852 DECLARE
63853   pTrialbalid ALIAS FOR $1;
63854   pSide ALIAS FOR $2;
63855   _value NUMERIC;
63856   _r RECORD;
63857
63858 BEGIN
63859
63860   SELECT accnt_type, trialbal_beginning, trialbal_ending INTO _r
63861   FROM trialbal, accnt
63862   WHERE ( (trialbal_accnt_id=accnt_id)
63863    AND (trialbal_id=pTrialbalid) );
63864   IF (NOT FOUND) THEN
63865     RETURN -1;
63866   END IF;
63867
63868 -- If we are looking for the Ending Balance, cache it
63869   IF (pSide = 'E') THEN
63870     _value = _r.trialbal_ending;
63871
63872 --  We had better been looking for the Beginning Balance!
63873   ELSE
63874     _value = _r.trialbal_beginning;
63875   END IF;
63876
63877 --  If the accnt_type is Asset or Expense, swap the sense
63878   IF (_r.accnt_type IN ('A', 'E')) THEN
63879     _value := (_value * -1);
63880   END IF;
63881
63882   RETURN _value;
63883
63884 END;
63885 $_$;
63886
63887
63888 ALTER FUNCTION public.normalizetrialbal(integer, character) OWNER TO admin;
63889
63890 --
63891 -- TOC entry 1937 (class 1255 OID 146566732)
63892 -- Dependencies: 4536 8
63893 -- Name: numofdatabaseusers(); Type: FUNCTION; Schema: public; Owner: admin
63894 --
63895
63896 CREATE FUNCTION numofdatabaseusers() RETURNS integer
63897     LANGUAGE plpgsql
63898     AS $$
63899 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63900 -- See www.xtuple.com/CPAL for the full text of the software license.
63901 DECLARE
63902   _count INTEGER;
63903
63904 BEGIN
63905
63906   -- in version 9.2.0 the column "procpid" was changed to just "pid" Incident #21852
63907   IF (compareversion('9.2.0') <= 0)
63908   THEN
63909   SELECT count(*)
63910     INTO _count
63911     FROM pg_stat_activity, pg_locks
63912    WHERE((database=datid)
63913      AND (classid=datid)
63914      AND (objsubid=2)
63915      AND (pg_stat_activity.pid = pg_backend_pid()));
63916   ELSE
63917   SELECT count(*)
63918     INTO _count
63919     FROM pg_stat_activity, pg_locks
63920    WHERE((database=datid)
63921      AND (classid=datid)
63922      AND (objsubid=2)
63923      AND (procpid = pg_backend_pid()));
63924   END IF;
63925
63926   IF (_count IS NULL) THEN
63927     _count := 0;
63928   END IF;
63929
63930   RETURN _count;
63931
63932 END;
63933 $$;
63934
63935
63936 ALTER FUNCTION public.numofdatabaseusers() OWNER TO admin;
63937
63938 --
63939 -- TOC entry 1938 (class 1255 OID 146566733)
63940 -- Dependencies: 4536 8
63941 -- Name: numofserverusers(); Type: FUNCTION; Schema: public; Owner: admin
63942 --
63943
63944 CREATE FUNCTION numofserverusers() RETURNS integer
63945     LANGUAGE plpgsql
63946     AS $$
63947 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63948 -- See www.xtuple.com/CPAL for the full text of the software license.
63949 DECLARE
63950   _count INTEGER;
63951
63952 BEGIN
63953
63954   SELECT COUNT(*) INTO _count
63955   FROM pg_stat_activity;
63956   IF (_count IS NULL) THEN
63957     _count := 0;
63958   END IF;
63959
63960   RETURN _count;
63961
63962 END;
63963 $$;
63964
63965
63966 ALTER FUNCTION public.numofserverusers() OWNER TO admin;
63967
63968 --
63969 -- TOC entry 1939 (class 1255 OID 146566734)
63970 -- Dependencies: 4536 8
63971 -- Name: openaccountingperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
63972 --
63973
63974 CREATE FUNCTION openaccountingperiod(integer) RETURNS integer
63975     LANGUAGE plpgsql
63976     AS $_$
63977 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
63978 -- See www.xtuple.com/CPAL for the full text of the software license.
63979 DECLARE
63980   pPeriodid ALIAS FOR $1;
63981   _r RECORD;
63982
63983 BEGIN
63984
63985 --  Check to make use that the period is closed
63986   IF ( ( SELECT (NOT period_closed)
63987          FROM period
63988          WHERE (period_id=pPeriodid) ) ) THEN
63989     RETURN -1;
63990   END IF;
63991
63992   IF ( ( SELECT (count(period_id) > 0)
63993            FROM period
63994           WHERE ((period_end > (
63995             SELECT period_end 
63996             FROM period 
63997             WHERE (period_id=pPeriodId))
63998           )
63999            AND (period_closed)) ) ) THEN
64000     RETURN -3;
64001   END IF;
64002   
64003 --  Make sure the year is open
64004   IF ( ( SELECT (yearperiod_closed)
64005          FROM yearperiod
64006            JOIN period ON (period_yearperiod_id=yearperiod_id)
64007          WHERE (period_id=pPeriodid) ) ) THEN
64008     RETURN -4;
64009   END IF;
64010
64011 --  Reset the period_closed flag
64012   UPDATE period
64013   SET period_closed=FALSE
64014   WHERE (period_id=pPeriodid);
64015
64016 --  Post any unposted G/L Transactions into the new period
64017   FOR _r IN SELECT DISTINCT gltrans_sequence
64018             FROM gltrans, period
64019             WHERE ( (NOT gltrans_posted)
64020              AND (gltrans_date BETWEEN period_start AND period_end)
64021              AND (period_id=pPeriodid) ) LOOP
64022     PERFORM postIntoTrialBalance(_r.gltrans_sequence);
64023   END LOOP;
64024
64025   RETURN pPeriodid;
64026
64027 END;
64028 $_$;
64029
64030
64031 ALTER FUNCTION public.openaccountingperiod(integer) OWNER TO admin;
64032
64033 --
64034 -- TOC entry 1940 (class 1255 OID 146566735)
64035 -- Dependencies: 4536 8
64036 -- Name: openaccountingyearperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
64037 --
64038
64039 CREATE FUNCTION openaccountingyearperiod(integer) RETURNS integer
64040     LANGUAGE plpgsql
64041     AS $_$
64042 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64043 -- See www.xtuple.com/CPAL for the full text of the software license.
64044 DECLARE
64045   pYearPeriodId ALIAS FOR $1;
64046   _r RECORD;
64047
64048 BEGIN
64049
64050 --  Check to make use that the yearperiod is closed
64051   IF ( ( SELECT (NOT yearperiod_closed)
64052          FROM yearperiod
64053          WHERE (yearperiod_id=pYearPeriodId) ) ) THEN
64054     RETURN -1;
64055   END IF;
64056
64057   IF ( ( SELECT (count(yearperiod_id) > 0)
64058            FROM yearperiod
64059           WHERE ((yearperiod_end> (
64060             SELECT yearperiod_end 
64061             FROM yearperiod 
64062             WHERE (yearperiod_id=pYearPeriodId))
64063           )
64064            AND (yearperiod_closed)) ) ) THEN
64065     RETURN -2;
64066   END IF;
64067
64068 --  Reset the yearperiod_closed flag
64069   UPDATE yearperiod
64070   SET yearperiod_closed=FALSE
64071   WHERE (yearperiod_id=pYearPeriodId);
64072
64073   RETURN pYearPeriodid;
64074
64075 END;
64076 $_$;
64077
64078
64079 ALTER FUNCTION public.openaccountingyearperiod(integer) OWNER TO admin;
64080
64081 --
64082 -- TOC entry 1941 (class 1255 OID 146566736)
64083 -- Dependencies: 4536 8
64084 -- Name: openapitemsvalue(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
64085 --
64086
64087 CREATE FUNCTION openapitemsvalue(pvendid integer, pperiodid integer) RETURNS numeric
64088     LANGUAGE plpgsql
64089     AS $$
64090 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64091 -- See www.xtuple.com/CPAL for the full text of the software license.
64092 DECLARE
64093   _value NUMERIC;
64094
64095 BEGIN
64096
64097   SELECT SUM( (apopen_amount - apopen_paid) / apopen_curr_rate *
64098                CASE WHEN (apopen_doctype IN ('D', 'V')) THEN 1 ELSE -1 END )
64099                INTO _value
64100   FROM apopen
64101   WHERE ( (apopen_open)
64102     AND   (apopen_vend_id=pVendid)
64103     AND   (apopen_duedate BETWEEN findPeriodStart(pPeriodid) AND findPeriodEnd(pPeriodid)) );
64104
64105   RETURN COALESCE(_value, 0.0);
64106
64107 END;
64108 $$;
64109
64110
64111 ALTER FUNCTION public.openapitemsvalue(pvendid integer, pperiodid integer) OWNER TO admin;
64112
64113 --
64114 -- TOC entry 1942 (class 1255 OID 146566737)
64115 -- Dependencies: 4536 8
64116 -- Name: openaritemsvalue(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
64117 --
64118
64119 CREATE FUNCTION openaritemsvalue(integer, integer) RETURNS numeric
64120     LANGUAGE plpgsql
64121     AS $_$
64122 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64123 -- See www.xtuple.com/CPAL for the full text of the software license.
64124 DECLARE
64125   pCustid ALIAS FOR $1;
64126   pPeriodid ALIAS FOR $2;
64127   _value NUMERIC;
64128
64129 BEGIN
64130
64131   SELECT SUM( CASE WHEN (aropen_doctype IN ('C', 'R')) THEN ((aropen_amount - aropen_paid) * -1)
64132                    ELSE (aropen_amount - aropen_paid)
64133               END )  INTO _value
64134   FROM aropen
64135   WHERE ( (aropen_open)
64136     AND (aropen_cust_id=pCustid)
64137     AND (aropen_duedate BETWEEN findPeriodStart(pPeriodid) AND findPeriodEnd(pPeriodid)) );
64138
64139   IF (_value IS NULL) THEN
64140     _value := 0;
64141   END IF;
64142
64143   RETURN _value;
64144
64145 END;
64146 $_$;
64147
64148
64149 ALTER FUNCTION public.openaritemsvalue(integer, integer) OWNER TO admin;
64150
64151 --
64152 -- TOC entry 1943 (class 1255 OID 146566738)
64153 -- Dependencies: 4536 8
64154 -- Name: openrecurringitems(integer, text, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
64155 --
64156
64157 CREATE FUNCTION openrecurringitems(integer, text, timestamp with time zone) RETURNS integer
64158     LANGUAGE plpgsql
64159     AS $_$
64160 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64161 -- See www.xtuple.com/CPAL for the full text of the software license.
64162 DECLARE
64163   pParentid  ALIAS FOR $1;
64164   pType      TEXT := UPPER($2);
64165   pDatetime  TIMESTAMP WITH TIME ZONE := COALESCE($3, CURRENT_TIMESTAMP);
64166
64167   _count     INTEGER := -1;
64168   _countstmt TEXT;
64169   _rt        RECORD;
64170
64171 BEGIN
64172   IF (pParentid IS NULL) THEN
64173     RETURN -11;
64174   END IF;
64175   
64176   SELECT * INTO _rt FROM recurtype WHERE (UPPER(recurtype_type)=pType);
64177   GET DIAGNOSTICS _count = ROW_COUNT;
64178   IF (_count <= 0) THEN
64179     RETURN -10;
64180   END IF;
64181
64182   _countstmt := 'SELECT COUNT(*) FROM [fulltable]'
64183              || ' WHERE (NOT ([done])'
64184              || '    AND ([schedcol]>=''$1'')'
64185              || '    AND ([table]_recurring_[table]_id=''$2''));';
64186   _countstmt := REPLACE(_countstmt, '[fulltable]',    _rt.recurtype_table);
64187   _countstmt := REPLACE(_countstmt, '[table]',
64188                         REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
64189   _countstmt := REPLACE(_countstmt, '[done]',     _rt.recurtype_donecheck);
64190   _countstmt := REPLACE(_countstmt, '[schedcol]', _rt.recurtype_schedcol);
64191
64192   -- 8.4+: EXECUTE _countstmt INTO _count USING pDatetime, pParentid;
64193   EXECUTE REPLACE(REPLACE(_countstmt, '$1', pDatetime::TEXT),
64194                                       '$2', pParentid::TEXT) INTO _count;
64195
64196   RETURN _count;
64197 END;
64198 $_$;
64199
64200
64201 ALTER FUNCTION public.openrecurringitems(integer, text, timestamp with time zone) OWNER TO admin;
64202
64203 --
64204 -- TOC entry 231 (class 1259 OID 146566739)
64205 -- Dependencies: 6038 6039 8
64206 -- Name: ophead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
64207 --
64208
64209 CREATE TABLE ophead (
64210     ophead_id integer NOT NULL,
64211     ophead_name text NOT NULL,
64212     ophead_crmacct_id integer,
64213     ophead_owner_username text,
64214     ophead_opstage_id integer,
64215     ophead_opsource_id integer,
64216     ophead_optype_id integer,
64217     ophead_probability_prcnt integer,
64218     ophead_amount numeric(20,4),
64219     ophead_target_date date,
64220     ophead_actual_date date,
64221     ophead_notes text,
64222     ophead_curr_id integer,
64223     ophead_active boolean DEFAULT true,
64224     ophead_cntct_id integer,
64225     ophead_username text,
64226     ophead_start_date date,
64227     ophead_assigned_date date,
64228     ophead_priority_id integer,
64229     ophead_number text NOT NULL,
64230     CONSTRAINT ophead_ophead_number_check CHECK ((ophead_number <> ''::text))
64231 );
64232
64233
64234 ALTER TABLE public.ophead OWNER TO admin;
64235
64236 --
64237 -- TOC entry 9067 (class 0 OID 0)
64238 -- Dependencies: 231
64239 -- Name: TABLE ophead; Type: COMMENT; Schema: public; Owner: admin
64240 --
64241
64242 COMMENT ON TABLE ophead IS 'Opportunity header.';
64243
64244
64245 --
64246 -- TOC entry 1944 (class 1255 OID 146566747)
64247 -- Dependencies: 2878 4536 8
64248 -- Name: ophead(); Type: FUNCTION; Schema: public; Owner: admin
64249 --
64250
64251 CREATE FUNCTION ophead() RETURNS SETOF ophead
64252     LANGUAGE plpgsql
64253     AS $$
64254 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64255 -- See www.xtuple.com/CPAL for the full text of the software license.
64256 DECLARE
64257   _row ophead%ROWTYPE;
64258   _priv TEXT;
64259   _grant BOOLEAN;
64260
64261 BEGIN
64262   -- This query will give us the most permissive privilege the user has been granted
64263   SELECT privilege, granted INTO _priv, _grant
64264   FROM privgranted 
64265   WHERE privilege IN ('MaintainAllOpportunities','ViewAllOpportunities','MaintainPersonalOpportunities','ViewPersonalOpportunities')
64266   ORDER BY granted DESC, sequence
64267   LIMIT 1;
64268
64269   -- If have an 'All' privilege return all results
64270   IF (_priv ~ 'All' AND _grant) THEN
64271     FOR _row IN 
64272       SELECT * FROM ophead
64273     LOOP
64274       RETURN NEXT _row;
64275     END LOOP;
64276   -- Otherwise if have any other grant, must be personal privilege.
64277   ELSIF (_grant) THEN
64278     FOR _row IN 
64279       SELECT * FROM ophead 
64280       WHERE getEffectiveXtUser() IN (ophead_owner_username, ophead_username)
64281     LOOP
64282       RETURN NEXT _row;
64283     END LOOP;
64284   END IF;
64285
64286   RETURN;
64287
64288 END;
64289 $$;
64290
64291
64292 ALTER FUNCTION public.ophead() OWNER TO admin;
64293
64294 --
64295 -- TOC entry 9069 (class 0 OID 0)
64296 -- Dependencies: 1944
64297 -- Name: FUNCTION ophead(); Type: COMMENT; Schema: public; Owner: admin
64298 --
64299
64300 COMMENT ON FUNCTION ophead() IS 'A table function that returns Opportunity results according to privilege settings.';
64301
64302
64303 --
64304 -- TOC entry 1946 (class 1255 OID 146566749)
64305 -- Dependencies: 4536 8
64306 -- Name: orderedbypo(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
64307 --
64308
64309 CREATE FUNCTION orderedbypo(integer, integer) RETURNS numeric
64310     LANGUAGE plpgsql
64311     AS $_$
64312 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64313 -- See www.xtuple.com/CPAL for the full text of the software license.
64314 DECLARE
64315   pItemsiteid ALIAS FOR $1;
64316   pLookAhead ALIAS FOR $2;
64317   _qty NUMERIC;
64318
64319 BEGIN
64320
64321   SELECT orderedByPo(pItemsiteid, startOfTime(), (CURRENT_DATE + pLookAhead)) INTO _qty;
64322   RETURN _qty;
64323
64324 END;
64325 $_$;
64326
64327
64328 ALTER FUNCTION public.orderedbypo(integer, integer) OWNER TO admin;
64329
64330 --
64331 -- TOC entry 1945 (class 1255 OID 146566748)
64332 -- Dependencies: 4536 8
64333 -- Name: orderedbypo(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
64334 --
64335
64336 CREATE FUNCTION orderedbypo(integer, date, date) RETURNS numeric
64337     LANGUAGE plpgsql
64338     AS $_$
64339 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64340 -- See www.xtuple.com/CPAL for the full text of the software license.
64341 DECLARE
64342   pItemsiteid ALIAS FOR $1;
64343   pStartDate ALIAS FOR $2;
64344   pEndDate ALIAS FOR $3;
64345   _qty NUMERIC;
64346
64347 BEGIN
64348
64349   SELECT COALESCE(SUM(noNeg(poitem_qty_ordered - poitem_qty_received) * poitem_invvenduomratio), 0.0) INTO _qty
64350   FROM poitem
64351   WHERE ( (poitem_itemsite_id=pItemsiteid)
64352     AND (poitem_status <> 'C')
64353     AND (poitem_duedate BETWEEN pStartDate AND pEndDate) );
64354
64355   RETURN _qty;
64356
64357 END;
64358 $_$;
64359
64360
64361 ALTER FUNCTION public.orderedbypo(integer, date, date) OWNER TO admin;
64362
64363 --
64364 -- TOC entry 1947 (class 1255 OID 146566750)
64365 -- Dependencies: 4536 8
64366 -- Name: orderedbywo(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
64367 --
64368
64369 CREATE FUNCTION orderedbywo(integer, integer) RETURNS numeric
64370     LANGUAGE plpgsql
64371     AS $_$
64372 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64373 -- See www.xtuple.com/CPAL for the full text of the software license.
64374 DECLARE
64375   pItemsiteid ALIAS FOR $1;
64376   pLookAheadDays ALIAS FOR $2;
64377
64378 BEGIN
64379
64380   RETURN orderedByWo(pItemsiteid, startOfTime(), (CURRENT_DATE + pLookAheadDays));
64381
64382 END;
64383 $_$;
64384
64385
64386 ALTER FUNCTION public.orderedbywo(integer, integer) OWNER TO admin;
64387
64388 --
64389 -- TOC entry 1948 (class 1255 OID 146566751)
64390 -- Dependencies: 4536 8
64391 -- Name: orderedbywo(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
64392 --
64393
64394 CREATE FUNCTION orderedbywo(integer, date, date) RETURNS numeric
64395     LANGUAGE plpgsql
64396     AS $_$
64397 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64398 -- See www.xtuple.com/CPAL for the full text of the software license.
64399 DECLARE
64400   pItemsiteid ALIAS FOR $1;
64401   pStartDate ALIAS FOR $2;
64402   pEndDate ALIAS FOR $3;
64403   _itemType CHARACTER(1);
64404   _qty NUMERIC := 0;
64405
64406 BEGIN
64407   SELECT item_type INTO _itemType
64408   FROM itemsite, item
64409   WHERE ( (itemsite_item_id=item_id)
64410    AND (itemsite_id=pItemsiteid) );
64411   
64412   IF (_itemType NOT IN ('C','T')) THEN
64413     SELECT COALESCE(SUM(noNeg(wo_qtyord - wo_qtyrcv)), 0.0) INTO _qty
64414     FROM wo
64415     WHERE ( (wo_status <> 'C')
64416      AND (wo_itemsite_id=pItemsiteid)
64417      AND (wo_duedate BETWEEN pStartDate AND pEndDate) );
64418   ELSIF (_itemType = 'C') THEN
64419     SELECT COALESCE(SUM((noNeg(wo_qtyord - wo_qtyrcv) * brddist_stdqtyper)), 0.0) INTO _qty
64420     FROM wo, xtmfg.brddist
64421     WHERE ( (wo_status <> 'C')
64422      AND (brddist_wo_id=wo_id)
64423      AND (brddist_itemsite_id=pItemsiteid)
64424      AND (wo_duedate BETWEEN pStartDate AND pEndDate) );
64425   ELSIF (_itemType = 'T' AND fetchMetricBool('Routings')) THEN -- Tooling:  Determine quantity already returned
64426     SELECT
64427       -- Qty Required
64428       COALESCE(SUM(noNeg(womatl_qtyreq)),0)  - 
64429       -- Qty Returned
64430      (SELECT COALESCE(SUM(abs(invhist_invqty)),0) 
64431       FROM wo
64432         JOIN womatl ON (womatl_wo_id=wo_id)
64433         JOIN womatlpost ON (womatl_id=womatlpost_womatl_id)
64434         JOIN invhist ON ((womatlpost_invhist_id=invhist_id)
64435                      AND (invhist_invqty < 0))   
64436       LEFT OUTER JOIN xtmfg.wooper ON (womatl_wooper_id=wooper_id)
64437     WHERE ( NOT (COALESCE(wooper_rncomplete,wo_status = 'C'))
64438      AND (womatl_itemsite_id=pItemsiteid)
64439      AND (wo_duedate BETWEEN pStartDate AND pEndDate) )
64440        )
64441    INTO _qty
64442     FROM wo
64443       JOIN womatl ON (womatl_wo_id=wo_id)
64444       LEFT OUTER JOIN xtmfg.wooper ON (womatl_wooper_id=wooper_id)
64445     WHERE ( NOT (COALESCE(wooper_rncomplete,wo_status = 'C'))
64446      AND (womatl_itemsite_id=pItemsiteid)
64447      AND (wo_duedate BETWEEN pStartDate AND pEndDate) )
64448     GROUP BY womatl_qtyreq;   
64449   ELSIF (_itemType = 'T') THEN -- Tooling:  Determine quantity already returned
64450     SELECT
64451       -- Qty Required
64452       COALESCE(SUM(noNeg(womatl_qtyreq)),0)  - 
64453       -- Qty Returned
64454      (SELECT COALESCE(SUM(abs(invhist_invqty)),0) 
64455       FROM wo
64456         JOIN womatl ON (womatl_wo_id=wo_id)
64457         JOIN womatlpost ON (womatl_id=womatlpost_womatl_id)
64458         JOIN invhist ON ((womatlpost_invhist_id=invhist_id)
64459                      AND (invhist_invqty < 0))
64460     WHERE ( NOT (wo_status = 'C')
64461      AND (womatl_itemsite_id=pItemsiteid)
64462      AND (wo_duedate BETWEEN pStartDate AND pEndDate) )
64463        )
64464    INTO _qty
64465     FROM wo
64466       JOIN womatl ON (womatl_wo_id=wo_id)
64467     WHERE ( NOT (wo_status = 'C')
64468      AND (womatl_itemsite_id=pItemsiteid)
64469      AND (wo_duedate BETWEEN pStartDate AND pEndDate) )
64470     GROUP BY womatl_qtyreq;   
64471   END IF;
64472
64473   RETURN COALESCE(_qty,0);
64474
64475 END;
64476 $_$;
64477
64478
64479 ALTER FUNCTION public.orderedbywo(integer, date, date) OWNER TO admin;
64480
64481 --
64482 -- TOC entry 1949 (class 1255 OID 146566752)
64483 -- Dependencies: 2690 4536 8
64484 -- Name: orderhead(); Type: FUNCTION; Schema: public; Owner: admin
64485 --
64486
64487 CREATE FUNCTION orderhead() RETURNS SETOF ordhead
64488     LANGUAGE plpgsql
64489     AS $$
64490 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64491 -- See www.xtuple.com/CPAL for the full text of the software license.
64492 DECLARE
64493   _row ordhead%ROWTYPE;
64494   _query TEXT;
64495 BEGIN
64496
64497   _query := '
64498   SELECT DISTINCT * FROM (
64499   SELECT pohead_id              AS orderhead_id,
64500          ''PO''                 AS orderhead_type,
64501          pohead_number          AS orderhead_number,
64502          pohead_status          AS orderhead_status,
64503          pohead_orderdate       AS orderhead_orderdate,
64504          (SELECT count(*)
64505            FROM poitem
64506            WHERE poitem_pohead_id=pohead_id) AS orderhead_linecount,
64507          pohead_vend_id         AS orderhead_from_id,
64508          vend_name              AS orderhead_from,
64509          NULL                   AS orderhead_to_id,
64510          ''''                   AS orderhead_to,
64511          pohead_curr_id         AS orderhead_curr_id,
64512          pohead_agent_username  AS orderhead_agent_username,
64513          pohead_shipvia         AS orderhead_shipvia
64514   FROM pohead LEFT OUTER JOIN vendinfo ON (pohead_vend_id=vend_id)
64515   UNION
64516   SELECT cohead_id              AS orderhead_id,
64517          ''SO''                 AS orderhead_type,
64518          cohead_number          AS orderhead_number,
64519          COALESCE(coitem_status,''C'') AS orderhead_status,
64520          cohead_orderdate       AS orderhead_orderdate,
64521          (SELECT count(*)
64522            FROM coitem
64523            WHERE coitem_cohead_id=cohead_id) AS orderhead_linecount,
64524          NULL                   AS orderhead_from_id,
64525          ''''                   AS orderhead_from,
64526          cohead_cust_id         AS orderhead_to_id,
64527          cust_name              AS orderhead_to,
64528          cohead_curr_id         AS orderhead_curr_id,
64529          ''''                   AS orderhead_agent_username,
64530          cohead_shipvia         AS orderhead_shipvia
64531   FROM cohead LEFT OUTER JOIN custinfo ON (cohead_cust_id=cust_id)
64532               LEFT OUTER JOIN coitem ON ((cohead_id=coitem_cohead_id)
64533                                      AND (coitem_status=''O''))';
64534
64535   IF (fetchmetricbool('MultiWhs')) THEN
64536     _query := _query || '
64537     UNION
64538     SELECT tohead_id            AS orderhead_id,
64539          ''TO''                 AS orderhead_type,
64540          tohead_number          AS orderhead_number,
64541          tohead_status          AS orderhead_status,
64542          tohead_orderdate       AS orderhead_orderdate,
64543          (SELECT count(*)
64544            FROM toitem
64545            WHERE toitem_tohead_id=tohead_id) AS orderhead_linecount,
64546          tohead_src_warehous_id  AS orderhead_from_id,
64547          tohead_srcname         AS orderhead_from,
64548          tohead_dest_warehous_id AS orderhead_to_id,
64549          tohead_destname        AS orderhead_to,
64550          tohead_freight_curr_id AS orderhead_curr_id,
64551          tohead_agent_username  AS orderhead_agent_username,
64552          tohead_shipvia         AS orderhead_shipvia
64553     FROM tohead';
64554   END IF;
64555
64556   IF (fetchmetricbool('EnableReturnAuth')) THEN
64557     _query := _query || '
64558   UNION
64559     SELECT rahead_id            AS orderhead_id,
64560          ''RA''                 AS orderhead_type,
64561          rahead_number          AS orderhead_number,
64562          COALESCE(raitem_status,''C'') AS orderhead_status,
64563          rahead_authdate        AS orderhead_orderdate,
64564          (SELECT count(*)
64565            FROM raitem
64566            WHERE raitem_rahead_id=rahead_id) AS orderhead_linecount,
64567          rahead_cust_id         AS orderhead_from_id,
64568          cust_name              AS orderhead_from,
64569          NULL                   AS orderhead_to_id,
64570          ''''                   AS orderhead_to,
64571          rahead_curr_id         AS orderhead_curr_id,
64572          ''''                   AS orderhead_agent_username,
64573          ''''                   AS orderhead_shipvia
64574     FROM rahead LEFT OUTER JOIN custinfo ON (rahead_cust_id=cust_id)
64575               LEFT OUTER JOIN raitem ON ((rahead_id=raitem_rahead_id)
64576                                      AND (raitem_status=''O''))';
64577   END IF;
64578
64579   _query := _query || ') AS data ORDER BY orderhead_type, orderhead_number ;';
64580   
64581   FOR _row IN EXECUTE _query
64582   LOOP
64583     RETURN NEXT _row;
64584   END LOOP;
64585
64586   RETURN;
64587 END;
64588 $$;
64589
64590
64591 ALTER FUNCTION public.orderhead() OWNER TO admin;
64592
64593 --
64594 -- TOC entry 1950 (class 1255 OID 146566753)
64595 -- Dependencies: 2693 4536 8
64596 -- Name: orderitem(); Type: FUNCTION; Schema: public; Owner: admin
64597 --
64598
64599 CREATE FUNCTION orderitem() RETURNS SETOF orditem
64600     LANGUAGE plpgsql
64601     AS $$
64602 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64603 -- See www.xtuple.com/CPAL for the full text of the software license.
64604 DECLARE
64605   _row orditem%ROWTYPE;
64606   _query TEXT;
64607 BEGIN
64608
64609   _query := '
64610   SELECT poitem_id              AS orderitem_id,
64611          ''PO''                 AS orderitem_orderhead_type,
64612          poitem_pohead_id       AS orderitem_orderhead_id,
64613          poitem_linenumber      AS orderitem_linenumber,
64614          poitem_status          AS orderitem_status,
64615          poitem_itemsite_id     AS orderitem_itemsite_id,
64616          poitem_duedate         AS orderitem_scheddate,
64617          poitem_qty_ordered     AS orderitem_qty_ordered,
64618          poitem_qty_returned    AS orderitem_qty_shipped,
64619          poitem_qty_received    AS orderitem_qty_received,
64620          uom_id                 AS orderitem_qty_uom_id,
64621          poitem_invvenduomratio AS orderitem_qty_invuomratio,
64622          poitem_unitprice       AS orderitem_unitcost,
64623          pohead_curr_id         AS orderitem_unitcost_curr_id,
64624          poitem_freight         AS orderitem_freight,
64625          poitem_freight_received AS orderitem_freight_received,
64626          pohead_curr_id         AS orderitem_freight_curr_id
64627
64628   FROM poitem LEFT OUTER JOIN pohead ON (poitem_pohead_id=pohead_id)
64629               LEFT OUTER JOIN uom ON (uom_name=poitem_vend_uom)
64630   UNION
64631   SELECT coitem_id              AS orderitem_id,
64632          ''SO''                 AS orderitem_orderhead_type,
64633          coitem_cohead_id       AS orderitem_orderhead_id,
64634          coitem_linenumber      AS orderitem_linenumber,
64635          coitem_status          AS orderitem_status,
64636          coitem_itemsite_id     AS orderitem_itemsite_id,
64637          coitem_scheddate       AS orderitem_scheddate,
64638          coitem_qtyord          AS orderitem_qty_ordered,
64639          coitem_qtyshipped      AS orderitem_qty_shipped,
64640          coitem_qtyreturned     AS orderitem_qty_received,
64641          coitem_qty_uom_id      AS orderitem_qty_uom_id,
64642          coitem_qty_invuomratio AS orderitem_qty_invuomratio,
64643          coitem_unitcost        AS orderitem_unitcost,
64644          basecurrid()           AS orderitem_unitcost_curr_id,
64645          NULL                   AS orderitem_freight,
64646          NULL                   AS orderitem_freight_received,
64647          basecurrid()           AS orderitem_freight_curr_id
64648   FROM coitem';
64649
64650   IF (fetchmetricbool('MultiWhs')) THEN
64651     _query := _query || '
64652     UNION
64653     SELECT toitem_id            AS orderitem_id,
64654       ''TO''                    AS orderitem_orderhead_type,
64655       toitem_tohead_id  AS orderitem_orderhead_id,
64656       toitem_linenumber AS orderitem_linenumber,
64657       toitem_status             AS orderitem_status,
64658       itemsite_id               AS orderitem_itemsite_id,
64659       toitem_duedate            AS orderitem_scheddate,
64660       toitem_qty_ordered        AS orderitem_qty_ordered,
64661       toitem_qty_shipped        AS orderitem_qty_shipped,
64662       toitem_qty_received       AS orderitem_qty_received,
64663       uom_id                    AS orderitem_qty_uom_id,
64664       1                 AS orderitem_qty_invuomratio,
64665       toitem_stdcost            AS orderitem_unitcost,
64666       basecurrid()              AS orderitem_unitcost_curr_id,
64667       toitem_freight            AS orderitem_freight,
64668       toitem_freight_received AS orderitem_freight_received,
64669       toitem_freight_curr_id    AS orderitem_freight_curr_id
64670     FROM tohead, itemsite, toitem LEFT OUTER JOIN uom ON (uom_name=toitem_uom)
64671     WHERE ((toitem_tohead_id=tohead_id)
64672      AND  (tohead_src_warehous_id=itemsite_warehous_id)
64673      AND  (toitem_item_id=itemsite_item_id)) ';
64674   END IF;
64675
64676   IF (fetchmetricbool('EnableReturnAuth')) THEN
64677     _query := _query || '
64678     UNION
64679     SELECT raitem_id            AS orderitem_id,
64680       ''RA''                    AS orderitem_orderhead_type,
64681       raitem_rahead_id  AS orderitem_orderhead_id,
64682       raitem_linenumber AS orderitem_linenumber,
64683       raitem_status             AS orderitem_status,
64684       raitem_itemsite_id        AS orderitem_itemsite_id,
64685       raitem_scheddate  AS orderitem_scheddate,
64686       raitem_qtyauthorized      AS orderitem_qty_ordered,
64687       0                 AS orderitem_qty_shipped,
64688       raitem_qtyreceived        AS orderitem_qty_received,
64689       raitem_qty_uom_id AS orderitem_qty_uom_id,
64690       raitem_qty_invuomratio    AS orderitem_qty_invuomratio,
64691       raitem_unitprice  AS orderitem_unitcost,
64692       basecurrid()              AS orderitem_unitcost_curr_id,
64693       NULL                      AS orderitem_freight,
64694       NULL                      AS orderitem_freight_received,
64695       basecurrid()              AS orderitem_freight_curr_id
64696     FROM raitem';
64697   END IF;
64698   
64699   FOR _row IN EXECUTE _query
64700   LOOP
64701     RETURN NEXT _row;
64702   END LOOP;
64703
64704   RETURN;
64705 END;
64706 $$;
64707
64708
64709 ALTER FUNCTION public.orderitem() OWNER TO admin;
64710
64711 --
64712 -- TOC entry 1955 (class 1255 OID 146566754)
64713 -- Dependencies: 2687 4536 8
64714 -- Name: orderitemdata(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
64715 --
64716
64717 CREATE FUNCTION orderitemdata(text, integer, integer) RETURNS SETOF orderitemtype
64718     LANGUAGE plpgsql
64719     AS $_$
64720 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64721 -- See www.xtuple.com/CPAL for the full text of the software license.
64722 DECLARE
64723   pOrdertype ALIAS FOR $1;
64724   pOrderheadid ALIAS FOR $2;
64725   pOrderitemid ALIAS FOR $3;
64726   _row orderitemtype%ROWTYPE;
64727   _set RECORD;
64728
64729 BEGIN
64730
64731   IF(UPPER(pOrdertype)='PO') THEN
64732     FOR _set IN 
64733       SELECT poitem_id              AS orderitem_id,
64734              'PO'                   AS orderitem_orderhead_type,
64735              poitem_pohead_id       AS orderitem_orderhead_id,
64736              poitem_linenumber      AS orderitem_linenumber,
64737              poitem_status          AS orderitem_status,
64738              poitem_itemsite_id     AS orderitem_itemsite_id,
64739              poitem_duedate         AS orderitem_scheddate,
64740              poitem_qty_ordered     AS orderitem_qty_ordered,
64741              poitem_qty_returned    AS orderitem_qty_shipped,
64742              poitem_qty_received    AS orderitem_qty_received,
64743              uom_id                 AS orderitem_qty_uom_id,
64744              poitem_invvenduomratio AS orderitem_qty_invuomratio,
64745              poitem_unitprice       AS orderitem_unitcost,
64746              (SELECT pohead_curr_id FROM pohead WHERE pohead_id=poitem_pohead_id)
64747                                     AS orderitem_unitcost_curr_id,
64748              poitem_freight         AS orderitem_freight,
64749              poitem_freight_received AS orderitem_freight_received,
64750              (SELECT pohead_curr_id FROM pohead WHERE pohead_id=poitem_pohead_id)
64751                                     AS orderitem_freight_curr_id
64752         FROM poitem LEFT OUTER JOIN uom ON (uom_name=poitem_vend_uom)
64753        WHERE(((pOrderheadid IS NULL) OR (poitem_pohead_id=pOrderheadid))
64754          AND ((pOrderitemid IS NULL) OR (poitem_id=pOrderitemid))) LOOP
64755   
64756       _row.orderitem_id := _set.orderitem_id;
64757       _row.orderitem_orderhead_type := _set.orderitem_orderhead_type;
64758       _row.orderitem_orderhead_id := _set.orderitem_orderhead_id;
64759       _row.orderitem_linenumber := _set.orderitem_linenumber;
64760       _row.orderitem_status := _set.orderitem_status;
64761       _row.orderitem_itemsite_id := _set.orderitem_itemsite_id;
64762       _row.orderitem_scheddate := _set.orderitem_scheddate;
64763       _row.orderitem_qty_ordered := _set.orderitem_qty_ordered;
64764       _row.orderitem_qty_shipped := _set.orderitem_qty_shipped;
64765       _row.orderitem_qty_received := _set.orderitem_qty_received;
64766       _row.orderitem_qty_uom_id := _set.orderitem_qty_uom_id;
64767       _row.orderitem_qty_invuomratio := _set.orderitem_qty_invuomratio;
64768       _row.orderitem_unitcost := _set.orderitem_unitcost;
64769       _row.orderitem_unitcost_curr_id := _set.orderitem_unitcost_curr_id;
64770       _row.orderitem_freight := _set.orderitem_freight;
64771       _row.orderitem_freight_received := _set.orderitem_freight_received;
64772       _row.orderitem_freight_curr_id := _set.orderitem_freight_curr_id;
64773
64774       RETURN NEXT _row;
64775     END LOOP;
64776   ELSEIF(UPPER(pOrdertype)='SO') THEN
64777     FOR _set IN 
64778       SELECT coitem_id              AS orderitem_id,
64779              'SO'                   AS orderitem_orderhead_type,
64780              coitem_cohead_id       AS orderitem_orderhead_id,
64781              coitem_linenumber      AS orderitem_linenumber,
64782              coitem_status          AS orderitem_status,
64783              coitem_itemsite_id     AS orderitem_itemsite_id,
64784              coitem_scheddate       AS orderitem_scheddate,
64785              coitem_qtyord          AS orderitem_qty_ordered,
64786              coitem_qtyshipped      AS orderitem_qty_shipped,
64787              coitem_qtyreturned     AS orderitem_qty_received,
64788              coitem_qty_uom_id      AS orderitem_qty_uom_id,
64789              coitem_qty_invuomratio AS orderitem_qty_invuomratio,
64790              coitem_unitcost        AS orderitem_unitcost,
64791              basecurrid()           AS orderitem_unitcost_curr_id,
64792              NULL                   AS orderitem_freight,
64793              NULL                   AS orderitem_freight_received,
64794              basecurrid()           AS orderitem_freight_curr_id
64795         FROM coitem
64796        WHERE(((pOrderheadid IS NULL) OR (coitem_cohead_id=pOrderheadid))
64797          AND ((pOrderitemid IS NULL) OR (coitem_id=pOrderitemid))) LOOP
64798   
64799       _row.orderitem_id := _set.orderitem_id;
64800       _row.orderitem_orderhead_type := _set.orderitem_orderhead_type;
64801       _row.orderitem_orderhead_id := _set.orderitem_orderhead_id;
64802       _row.orderitem_linenumber := _set.orderitem_linenumber;
64803       _row.orderitem_status := _set.orderitem_status;
64804       _row.orderitem_itemsite_id := _set.orderitem_itemsite_id;
64805       _row.orderitem_scheddate := _set.orderitem_scheddate;
64806       _row.orderitem_qty_ordered := _set.orderitem_qty_ordered;
64807       _row.orderitem_qty_shipped := _set.orderitem_qty_shipped;
64808       _row.orderitem_qty_received := _set.orderitem_qty_received;
64809       _row.orderitem_qty_uom_id := _set.orderitem_qty_uom_id;
64810       _row.orderitem_qty_invuomratio := _set.orderitem_qty_invuomratio;
64811       _row.orderitem_unitcost := _set.orderitem_unitcost;
64812       _row.orderitem_unitcost_curr_id := _set.orderitem_unitcost_curr_id;
64813       _row.orderitem_freight := _set.orderitem_freight;
64814       _row.orderitem_freight_received := _set.orderitem_freight_received;
64815       _row.orderitem_freight_curr_id := _set.orderitem_freight_curr_id;
64816
64817       RETURN NEXT _row;
64818     END LOOP;
64819   ELSEIF(UPPER(pOrdertype)='RA') THEN
64820     FOR _set IN 
64821       SELECT raitem_id              AS orderitem_id,
64822              'RA'                   AS orderitem_orderhead_type,
64823              raitem_rahead_id       AS orderitem_orderhead_id,
64824              raitem_linenumber      AS orderitem_linenumber,
64825              raitem_status          AS orderitem_status,
64826              raitem_itemsite_id     AS orderitem_itemsite_id,
64827              raitem_scheddate       AS orderitem_scheddate,
64828              raitem_qtyauthorized   AS orderitem_qty_ordered,
64829              0                      AS orderitem_qty_shipped,
64830              raitem_qtyreceived     AS orderitem_qty_received,
64831              raitem_qty_uom_id      AS orderitem_qty_uom_id,
64832              raitem_qty_invuomratio AS orderitem_qty_invuomratio,
64833              raitem_unitprice       AS orderitem_unitcost,
64834              basecurrid()           AS orderitem_unitcost_curr_id,
64835              NULL                   AS orderitem_freight,
64836              NULL                   AS orderitem_freight_received,
64837              basecurrid()           AS orderitem_freight_curr_id
64838         FROM raitem
64839        WHERE(((pOrderheadid IS NULL) OR (raitem_rahead_id=pOrderheadid))
64840          AND ((pOrderitemid IS NULL) OR (raitem_id=pOrderitemid))) LOOP
64841   
64842       _row.orderitem_id := _set.orderitem_id;
64843       _row.orderitem_orderhead_type := _set.orderitem_orderhead_type;
64844       _row.orderitem_orderhead_id := _set.orderitem_orderhead_id;
64845       _row.orderitem_linenumber := _set.orderitem_linenumber;
64846       _row.orderitem_status := _set.orderitem_status;
64847       _row.orderitem_itemsite_id := _set.orderitem_itemsite_id;
64848       _row.orderitem_scheddate := _set.orderitem_scheddate;
64849       _row.orderitem_qty_ordered := _set.orderitem_qty_ordered;
64850       _row.orderitem_qty_shipped := _set.orderitem_qty_shipped;
64851       _row.orderitem_qty_received := _set.orderitem_qty_received;
64852       _row.orderitem_qty_uom_id := _set.orderitem_qty_uom_id;
64853       _row.orderitem_qty_invuomratio := _set.orderitem_qty_invuomratio;
64854       _row.orderitem_unitcost := _set.orderitem_unitcost;
64855       _row.orderitem_unitcost_curr_id := _set.orderitem_unitcost_curr_id;
64856       _row.orderitem_freight := _set.orderitem_freight;
64857       _row.orderitem_freight_received := _set.orderitem_freight_received;
64858       _row.orderitem_freight_curr_id := _set.orderitem_freight_curr_id;
64859
64860       RETURN NEXT _row;
64861     END LOOP;
64862   ELSEIF(UPPER(pOrdertype)='TO') THEN
64863     FOR _set IN 
64864       SELECT toitem_id              AS orderitem_id,
64865              'TO'                   AS orderitem_orderhead_type,
64866              toitem_tohead_id       AS orderitem_orderhead_id,
64867              toitem_linenumber      AS orderitem_linenumber,
64868              toitem_status          AS orderitem_status,
64869              itemsite_id            AS orderitem_itemsite_id,
64870              toitem_duedate         AS orderitem_scheddate,
64871              toitem_qty_ordered     AS orderitem_qty_ordered,
64872              toitem_qty_shipped     AS orderitem_qty_shipped,
64873              toitem_qty_received    AS orderitem_qty_received,
64874              uom_id                 AS orderitem_qty_uom_id,
64875              1                      AS orderitem_qty_invuomratio,
64876              toitem_stdcost         AS orderitem_unitcost,
64877              basecurrid()           AS orderitem_unitcost_curr_id,
64878              toitem_freight         AS orderitem_freight,
64879              toitem_freight_received AS orderitem_freight_received,
64880              toitem_freight_curr_id AS orderitem_freight_curr_id
64881         FROM tohead, itemsite, toitem LEFT OUTER JOIN uom ON (uom_name=toitem_uom)
64882        WHERE((toitem_tohead_id=tohead_id)
64883          AND (tohead_src_warehous_id=itemsite_warehous_id)
64884          AND (toitem_item_id=itemsite_item_id)
64885          AND ((pOrderheadid IS NULL) OR (toitem_tohead_id=pOrderheadid))
64886          AND ((pOrderitemid IS NULL) OR (toitem_id=pOrderitemid))) LOOP
64887   
64888       _row.orderitem_id := _set.orderitem_id;
64889       _row.orderitem_orderhead_type := _set.orderitem_orderhead_type;
64890       _row.orderitem_orderhead_id := _set.orderitem_orderhead_id;
64891       _row.orderitem_linenumber := _set.orderitem_linenumber;
64892       _row.orderitem_status := _set.orderitem_status;
64893       _row.orderitem_itemsite_id := _set.orderitem_itemsite_id;
64894       _row.orderitem_scheddate := _set.orderitem_scheddate;
64895       _row.orderitem_qty_ordered := _set.orderitem_qty_ordered;
64896       _row.orderitem_qty_shipped := _set.orderitem_qty_shipped;
64897       _row.orderitem_qty_received := _set.orderitem_qty_received;
64898       _row.orderitem_qty_uom_id := _set.orderitem_qty_uom_id;
64899       _row.orderitem_qty_invuomratio := _set.orderitem_qty_invuomratio;
64900       _row.orderitem_unitcost := _set.orderitem_unitcost;
64901       _row.orderitem_unitcost_curr_id := _set.orderitem_unitcost_curr_id;
64902       _row.orderitem_freight := _set.orderitem_freight;
64903       _row.orderitem_freight_received := _set.orderitem_freight_received;
64904       _row.orderitem_freight_curr_id := _set.orderitem_freight_curr_id;
64905
64906       RETURN NEXT _row;
64907     END LOOP;
64908   END IF;
64909
64910   RETURN;
64911 END;
64912 $_$;
64913
64914
64915 ALTER FUNCTION public.orderitemdata(text, integer, integer) OWNER TO admin;
64916
64917 --
64918 -- TOC entry 1956 (class 1255 OID 146566755)
64919 -- Dependencies: 8
64920 -- Name: packageisenabled(integer); Type: FUNCTION; Schema: public; Owner: admin
64921 --
64922
64923 CREATE FUNCTION packageisenabled(integer) RETURNS boolean
64924     LANGUAGE sql
64925     AS $_$
64926 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64927 -- See www.xtuple.com/CPAL for the full text of the software license.
64928   SELECT COUNT(*) >= 8
64929   FROM pg_inherits, pg_class, pg_namespace, pkghead
64930   WHERE ((inhrelid=pg_class.oid)
64931      AND (relnamespace=pg_namespace.oid)
64932      AND  (nspname=lower(pkghead_name))
64933      AND  (pkghead_id=$1));
64934 $_$;
64935
64936
64937 ALTER FUNCTION public.packageisenabled(integer) OWNER TO admin;
64938
64939 --
64940 -- TOC entry 1957 (class 1255 OID 146566756)
64941 -- Dependencies: 8
64942 -- Name: packageisenabled(text); Type: FUNCTION; Schema: public; Owner: admin
64943 --
64944
64945 CREATE FUNCTION packageisenabled(text) RETURNS boolean
64946     LANGUAGE sql
64947     AS $_$
64948 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
64949 -- See www.xtuple.com/CPAL for the full text of the software license.
64950   SELECT COUNT(*) >= 8
64951   FROM pg_inherits, pg_class, pg_namespace
64952   WHERE ((inhrelid=pg_class.oid)
64953      AND (relnamespace=pg_namespace.oid)
64954      AND  (nspname=lower($1)));
64955 $_$;
64956
64957
64958 ALTER FUNCTION public.packageisenabled(text) OWNER TO admin;
64959
64960 --
64961 -- TOC entry 1958 (class 1255 OID 146566757)
64962 -- Dependencies: 8
64963 -- Name: pgp_key_id(bytea); Type: FUNCTION; Schema: public; Owner: admin
64964 --
64965
64966 CREATE FUNCTION pgp_key_id(bytea) RETURNS text
64967     LANGUAGE c IMMUTABLE STRICT
64968     AS '$libdir/pgcrypto', 'pgp_key_id_w';
64969
64970
64971 ALTER FUNCTION public.pgp_key_id(bytea) OWNER TO admin;
64972
64973 --
64974 -- TOC entry 1959 (class 1255 OID 146566758)
64975 -- Dependencies: 8
64976 -- Name: pgp_pub_decrypt(bytea, bytea); Type: FUNCTION; Schema: public; Owner: admin
64977 --
64978
64979 CREATE FUNCTION pgp_pub_decrypt(bytea, bytea) RETURNS text
64980     LANGUAGE c IMMUTABLE STRICT
64981     AS '$libdir/pgcrypto', 'pgp_pub_decrypt_text';
64982
64983
64984 ALTER FUNCTION public.pgp_pub_decrypt(bytea, bytea) OWNER TO admin;
64985
64986 --
64987 -- TOC entry 1960 (class 1255 OID 146566759)
64988 -- Dependencies: 8
64989 -- Name: pgp_pub_decrypt(bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
64990 --
64991
64992 CREATE FUNCTION pgp_pub_decrypt(bytea, bytea, text) RETURNS text
64993     LANGUAGE c IMMUTABLE STRICT
64994     AS '$libdir/pgcrypto', 'pgp_pub_decrypt_text';
64995
64996
64997 ALTER FUNCTION public.pgp_pub_decrypt(bytea, bytea, text) OWNER TO admin;
64998
64999 --
65000 -- TOC entry 1961 (class 1255 OID 146566760)
65001 -- Dependencies: 8
65002 -- Name: pgp_pub_decrypt(bytea, bytea, text, text); Type: FUNCTION; Schema: public; Owner: admin
65003 --
65004
65005 CREATE FUNCTION pgp_pub_decrypt(bytea, bytea, text, text) RETURNS text
65006     LANGUAGE c IMMUTABLE STRICT
65007     AS '$libdir/pgcrypto', 'pgp_pub_decrypt_text';
65008
65009
65010 ALTER FUNCTION public.pgp_pub_decrypt(bytea, bytea, text, text) OWNER TO admin;
65011
65012 --
65013 -- TOC entry 1962 (class 1255 OID 146566761)
65014 -- Dependencies: 8
65015 -- Name: pgp_pub_decrypt_bytea(bytea, bytea); Type: FUNCTION; Schema: public; Owner: admin
65016 --
65017
65018 CREATE FUNCTION pgp_pub_decrypt_bytea(bytea, bytea) RETURNS bytea
65019     LANGUAGE c IMMUTABLE STRICT
65020     AS '$libdir/pgcrypto', 'pgp_pub_decrypt_bytea';
65021
65022
65023 ALTER FUNCTION public.pgp_pub_decrypt_bytea(bytea, bytea) OWNER TO admin;
65024
65025 --
65026 -- TOC entry 1963 (class 1255 OID 146566762)
65027 -- Dependencies: 8
65028 -- Name: pgp_pub_decrypt_bytea(bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
65029 --
65030
65031 CREATE FUNCTION pgp_pub_decrypt_bytea(bytea, bytea, text) RETURNS bytea
65032     LANGUAGE c IMMUTABLE STRICT
65033     AS '$libdir/pgcrypto', 'pgp_pub_decrypt_bytea';
65034
65035
65036 ALTER FUNCTION public.pgp_pub_decrypt_bytea(bytea, bytea, text) OWNER TO admin;
65037
65038 --
65039 -- TOC entry 1964 (class 1255 OID 146566763)
65040 -- Dependencies: 8
65041 -- Name: pgp_pub_decrypt_bytea(bytea, bytea, text, text); Type: FUNCTION; Schema: public; Owner: admin
65042 --
65043
65044 CREATE FUNCTION pgp_pub_decrypt_bytea(bytea, bytea, text, text) RETURNS bytea
65045     LANGUAGE c IMMUTABLE STRICT
65046     AS '$libdir/pgcrypto', 'pgp_pub_decrypt_bytea';
65047
65048
65049 ALTER FUNCTION public.pgp_pub_decrypt_bytea(bytea, bytea, text, text) OWNER TO admin;
65050
65051 --
65052 -- TOC entry 1965 (class 1255 OID 146566764)
65053 -- Dependencies: 8
65054 -- Name: pgp_pub_encrypt(text, bytea); Type: FUNCTION; Schema: public; Owner: admin
65055 --
65056
65057 CREATE FUNCTION pgp_pub_encrypt(text, bytea) RETURNS bytea
65058     LANGUAGE c STRICT
65059     AS '$libdir/pgcrypto', 'pgp_pub_encrypt_text';
65060
65061
65062 ALTER FUNCTION public.pgp_pub_encrypt(text, bytea) OWNER TO admin;
65063
65064 --
65065 -- TOC entry 1966 (class 1255 OID 146566765)
65066 -- Dependencies: 8
65067 -- Name: pgp_pub_encrypt(text, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
65068 --
65069
65070 CREATE FUNCTION pgp_pub_encrypt(text, bytea, text) RETURNS bytea
65071     LANGUAGE c STRICT
65072     AS '$libdir/pgcrypto', 'pgp_pub_encrypt_text';
65073
65074
65075 ALTER FUNCTION public.pgp_pub_encrypt(text, bytea, text) OWNER TO admin;
65076
65077 --
65078 -- TOC entry 1967 (class 1255 OID 146566766)
65079 -- Dependencies: 8
65080 -- Name: pgp_pub_encrypt_bytea(bytea, bytea); Type: FUNCTION; Schema: public; Owner: admin
65081 --
65082
65083 CREATE FUNCTION pgp_pub_encrypt_bytea(bytea, bytea) RETURNS bytea
65084     LANGUAGE c STRICT
65085     AS '$libdir/pgcrypto', 'pgp_pub_encrypt_bytea';
65086
65087
65088 ALTER FUNCTION public.pgp_pub_encrypt_bytea(bytea, bytea) OWNER TO admin;
65089
65090 --
65091 -- TOC entry 1968 (class 1255 OID 146566767)
65092 -- Dependencies: 8
65093 -- Name: pgp_pub_encrypt_bytea(bytea, bytea, text); Type: FUNCTION; Schema: public; Owner: admin
65094 --
65095
65096 CREATE FUNCTION pgp_pub_encrypt_bytea(bytea, bytea, text) RETURNS bytea
65097     LANGUAGE c STRICT
65098     AS '$libdir/pgcrypto', 'pgp_pub_encrypt_bytea';
65099
65100
65101 ALTER FUNCTION public.pgp_pub_encrypt_bytea(bytea, bytea, text) OWNER TO admin;
65102
65103 --
65104 -- TOC entry 1969 (class 1255 OID 146566768)
65105 -- Dependencies: 8
65106 -- Name: pgp_sym_decrypt(bytea, text); Type: FUNCTION; Schema: public; Owner: admin
65107 --
65108
65109 CREATE FUNCTION pgp_sym_decrypt(bytea, text) RETURNS text
65110     LANGUAGE c IMMUTABLE STRICT
65111     AS '$libdir/pgcrypto', 'pgp_sym_decrypt_text';
65112
65113
65114 ALTER FUNCTION public.pgp_sym_decrypt(bytea, text) OWNER TO admin;
65115
65116 --
65117 -- TOC entry 1970 (class 1255 OID 146566769)
65118 -- Dependencies: 8
65119 -- Name: pgp_sym_decrypt(bytea, text, text); Type: FUNCTION; Schema: public; Owner: admin
65120 --
65121
65122 CREATE FUNCTION pgp_sym_decrypt(bytea, text, text) RETURNS text
65123     LANGUAGE c IMMUTABLE STRICT
65124     AS '$libdir/pgcrypto', 'pgp_sym_decrypt_text';
65125
65126
65127 ALTER FUNCTION public.pgp_sym_decrypt(bytea, text, text) OWNER TO admin;
65128
65129 --
65130 -- TOC entry 1971 (class 1255 OID 146566770)
65131 -- Dependencies: 8
65132 -- Name: pgp_sym_decrypt_bytea(bytea, text); Type: FUNCTION; Schema: public; Owner: admin
65133 --
65134
65135 CREATE FUNCTION pgp_sym_decrypt_bytea(bytea, text) RETURNS bytea
65136     LANGUAGE c IMMUTABLE STRICT
65137     AS '$libdir/pgcrypto', 'pgp_sym_decrypt_bytea';
65138
65139
65140 ALTER FUNCTION public.pgp_sym_decrypt_bytea(bytea, text) OWNER TO admin;
65141
65142 --
65143 -- TOC entry 1972 (class 1255 OID 146566771)
65144 -- Dependencies: 8
65145 -- Name: pgp_sym_decrypt_bytea(bytea, text, text); Type: FUNCTION; Schema: public; Owner: admin
65146 --
65147
65148 CREATE FUNCTION pgp_sym_decrypt_bytea(bytea, text, text) RETURNS bytea
65149     LANGUAGE c IMMUTABLE STRICT
65150     AS '$libdir/pgcrypto', 'pgp_sym_decrypt_bytea';
65151
65152
65153 ALTER FUNCTION public.pgp_sym_decrypt_bytea(bytea, text, text) OWNER TO admin;
65154
65155 --
65156 -- TOC entry 1973 (class 1255 OID 146566772)
65157 -- Dependencies: 8
65158 -- Name: pgp_sym_encrypt(text, text); Type: FUNCTION; Schema: public; Owner: admin
65159 --
65160
65161 CREATE FUNCTION pgp_sym_encrypt(text, text) RETURNS bytea
65162     LANGUAGE c STRICT
65163     AS '$libdir/pgcrypto', 'pgp_sym_encrypt_text';
65164
65165
65166 ALTER FUNCTION public.pgp_sym_encrypt(text, text) OWNER TO admin;
65167
65168 --
65169 -- TOC entry 1974 (class 1255 OID 146566773)
65170 -- Dependencies: 8
65171 -- Name: pgp_sym_encrypt(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
65172 --
65173
65174 CREATE FUNCTION pgp_sym_encrypt(text, text, text) RETURNS bytea
65175     LANGUAGE c STRICT
65176     AS '$libdir/pgcrypto', 'pgp_sym_encrypt_text';
65177
65178
65179 ALTER FUNCTION public.pgp_sym_encrypt(text, text, text) OWNER TO admin;
65180
65181 --
65182 -- TOC entry 1975 (class 1255 OID 146566774)
65183 -- Dependencies: 8
65184 -- Name: pgp_sym_encrypt_bytea(bytea, text); Type: FUNCTION; Schema: public; Owner: admin
65185 --
65186
65187 CREATE FUNCTION pgp_sym_encrypt_bytea(bytea, text) RETURNS bytea
65188     LANGUAGE c STRICT
65189     AS '$libdir/pgcrypto', 'pgp_sym_encrypt_bytea';
65190
65191
65192 ALTER FUNCTION public.pgp_sym_encrypt_bytea(bytea, text) OWNER TO admin;
65193
65194 --
65195 -- TOC entry 1976 (class 1255 OID 146566775)
65196 -- Dependencies: 8
65197 -- Name: pgp_sym_encrypt_bytea(bytea, text, text); Type: FUNCTION; Schema: public; Owner: admin
65198 --
65199
65200 CREATE FUNCTION pgp_sym_encrypt_bytea(bytea, text, text) RETURNS bytea
65201     LANGUAGE c STRICT
65202     AS '$libdir/pgcrypto', 'pgp_sym_encrypt_bytea';
65203
65204
65205 ALTER FUNCTION public.pgp_sym_encrypt_bytea(bytea, text, text) OWNER TO admin;
65206
65207 --
65208 -- TOC entry 1977 (class 1255 OID 146566776)
65209 -- Dependencies: 4536 8
65210 -- Name: pkgmaybemodified(name); Type: FUNCTION; Schema: public; Owner: admin
65211 --
65212
65213 CREATE FUNCTION pkgmaybemodified(name) RETURNS boolean
65214     LANGUAGE plpgsql
65215     AS $_$
65216 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65217 -- See www.xtuple.com/CPAL for the full text of the software license.
65218 DECLARE
65219   pschemaname ALIAS FOR $1;
65220   _returnval  BOOLEAN;
65221 BEGIN
65222   SELECT pkghead_indev INTO _returnval
65223   FROM pkghead
65224   WHERE (pkghead_name=pschemaname);
65225   IF (NOT FOUND) THEN
65226     RETURN FALSE;
65227   END IF;
65228   RETURN _returnval;
65229 END;
65230 $_$;
65231
65232
65233 ALTER FUNCTION public.pkgmaybemodified(name) OWNER TO admin;
65234
65235 --
65236 -- TOC entry 1978 (class 1255 OID 146566777)
65237 -- Dependencies: 8
65238 -- Name: plpgsql_call_handler(); Type: FUNCTION; Schema: public; Owner: admin
65239 --
65240
65241 CREATE FUNCTION plpgsql_call_handler() RETURNS language_handler
65242     LANGUAGE c
65243     AS '$libdir/plpgsql', 'plpgsql_call_handler';
65244
65245
65246 ALTER FUNCTION public.plpgsql_call_handler() OWNER TO admin;
65247
65248 --
65249 -- TOC entry 1979 (class 1255 OID 146566778)
65250 -- Dependencies: 8
65251 -- Name: plpgsql_validator(oid); Type: FUNCTION; Schema: public; Owner: admin
65252 --
65253
65254 CREATE FUNCTION plpgsql_validator(oid) RETURNS void
65255     LANGUAGE c
65256     AS '$libdir/plpgsql', 'plpgsql_validator';
65257
65258
65259 ALTER FUNCTION public.plpgsql_validator(oid) OWNER TO admin;
65260
65261 --
65262 -- TOC entry 1935 (class 1255 OID 146566779)
65263 -- Dependencies: 4536 8
65264 -- Name: postapcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
65265 --
65266
65267 CREATE FUNCTION postapcheck(integer) RETURNS integer
65268     LANGUAGE plpgsql
65269     AS $_$
65270 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65271 -- See www.xtuple.com/CPAL for the full text of the software license.
65272 BEGIN
65273   RAISE NOTICE 'postAPCheck() is deprecated - use postCheck() instead';
65274   RETURN postCheck($1, fetchJournalNumber('AP-CK'));
65275 END;
65276 $_$;
65277
65278
65279 ALTER FUNCTION public.postapcheck(integer) OWNER TO admin;
65280
65281 --
65282 -- TOC entry 1951 (class 1255 OID 146566780)
65283 -- Dependencies: 4536 8
65284 -- Name: postapcheck(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
65285 --
65286
65287 CREATE FUNCTION postapcheck(integer, integer) RETURNS integer
65288     LANGUAGE plpgsql
65289     AS $_$
65290 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65291 -- See www.xtuple.com/CPAL for the full text of the software license.
65292 BEGIN
65293   RAISE NOTICE 'postAPCheck() is deprecated - use postCheck() instead';
65294   RETURN postCheck($1, $2);
65295 END;
65296 $_$;
65297
65298
65299 ALTER FUNCTION public.postapcheck(integer, integer) OWNER TO admin;
65300
65301 --
65302 -- TOC entry 1952 (class 1255 OID 146566781)
65303 -- Dependencies: 4536 8
65304 -- Name: postapchecks(integer); Type: FUNCTION; Schema: public; Owner: admin
65305 --
65306
65307 CREATE FUNCTION postapchecks(integer) RETURNS integer
65308     LANGUAGE plpgsql
65309     AS $_$
65310 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65311 -- See www.xtuple.com/CPAL for the full text of the software license.
65312 BEGIN
65313
65314   RAISE NOTICE 'postAPChecks() is deprecated - use postChecks() instead';
65315   RETURN postChecks($1);
65316
65317 END;
65318 $_$;
65319
65320
65321 ALTER FUNCTION public.postapchecks(integer) OWNER TO admin;
65322
65323 --
65324 -- TOC entry 1981 (class 1255 OID 146566782)
65325 -- Dependencies: 4536 8
65326 -- Name: postapcreditmemoapplication(integer); Type: FUNCTION; Schema: public; Owner: admin
65327 --
65328
65329 CREATE FUNCTION postapcreditmemoapplication(integer) RETURNS integer
65330     LANGUAGE plpgsql
65331     AS $_$
65332 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65333 -- See www.xtuple.com/CPAL for the full text of the software license.
65334 DECLARE
65335   pApopenid ALIAS FOR $1;
65336   _src RECORD;
65337   _r RECORD;
65338   _totalAmount NUMERIC := 0.0;
65339   _exchGain NUMERIC := 0.0;
65340   _apaccntid INTEGER;
65341
65342 BEGIN
65343
65344   SELECT apopen_docnumber, (apopen_amount - apopen_paid) AS balance,
65345 --         SUM(currtocurr(apcreditapply_curr_id, apopen_curr_id,
65346 --                               apcreditapply_amount, CURRENT_DATE)) AS toApply,
65347          SUM(apcreditapply_amount) AS toApply,
65348          apopen_curr_rate INTO _src
65349   FROM apopen, apcreditapply
65350   WHERE ( (apcreditapply_source_apopen_id=apopen_id)
65351    AND (apopen_id=pApopenid) )
65352   GROUP BY apopen_docnumber, apopen_amount, apopen_paid,
65353            apopen_curr_rate;
65354   IF (NOT FOUND) THEN
65355     RETURN -1;
65356   ELSIF (_src.toApply = 0) THEN
65357     RETURN -2;
65358   ELSIF (_src.toApply > _src.balance) THEN
65359     RETURN -3;
65360 --  ELSIF (_src.toApply IS NULL AND _src.junk IS NOT NULL) THEN
65361 --    RETURN -4;                -- missing exchange rate
65362   ELSIF (_src.toApply IS NULL) THEN
65363     RETURN -6;          -- amount to apply is NULL for some unknown reason
65364   END IF;
65365
65366   SELECT apopen_id, apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_amount,
65367          apopen_curr_id, apopen_curr_rate, apopen_docdate, apopen_accnt_id INTO _src
65368   FROM apopen
65369   WHERE (apopen_id=pApopenid);
65370   IF (NOT FOUND) THEN
65371     RETURN -5;
65372   END IF;
65373
65374   FOR _r IN SELECT apcreditapply_id, apcreditapply_target_apopen_id,
65375                    apcreditapply_amount AS apply_amountSource,
65376                    currToCurr(apcreditapply_curr_id, apopen_curr_id,
65377                               apcreditapply_amount, CURRENT_DATE) AS apply_amountTarget,
65378                    apopen_id, apopen_doctype, apopen_docnumber, apopen_curr_id, apopen_curr_rate, apopen_docdate
65379             FROM apcreditapply, apopen
65380             WHERE ( (apcreditapply_source_apopen_id=pApopenid)
65381              AND (apcreditapply_target_apopen_id=apopen_id) ) LOOP
65382
65383     IF (_r.apply_amountTarget IS NULL) THEN
65384       RETURN -4;        -- missing exchange rate
65385     END IF;
65386
65387     IF (_r.apply_amountTarget > 0) THEN
65388
65389 --  Update the apopen item to post the paid amount
65390       UPDATE apopen
65391       SET apopen_paid = (apopen_paid + _r.apply_amountTarget)
65392       WHERE (apopen_id=_r.apcreditapply_target_apopen_id);
65393
65394       UPDATE apopen
65395       SET apopen_open = false,
65396         apopen_closedate = current_date
65397       WHERE ( (apopen_id=_r.apcreditapply_target_apopen_id)
65398         AND (apopen_amount <= apopen_paid) );
65399
65400 --  Cache the running amount posted
65401       _totalAmount := (_totalAmount + _r.apply_amountSource);
65402
65403 --  Record the application
65404       INSERT INTO apapply
65405       ( apapply_vend_id, apapply_amount,
65406         apapply_source_apopen_id, apapply_source_doctype, apapply_source_docnumber,
65407         apapply_target_apopen_id, apapply_target_doctype, apapply_target_docnumber,
65408         apapply_postdate, apapply_journalnumber, apapply_username, apapply_curr_id )
65409       VALUES
65410       ( _src.apopen_vend_id, round(_r.apply_amountSource, 2),
65411         pApopenid, 'C', _src.apopen_docnumber,
65412         _r.apopen_id, _r.apopen_doctype, _r.apopen_docnumber,
65413         CURRENT_DATE, 0, getEffectiveXtUser(), _src.apopen_curr_id );
65414
65415     END IF;
65416
65417 --  Delete the posted apcreditapply record
65418     DELETE FROM apcreditapply
65419     WHERE (apcreditapply_id=_r.apcreditapply_id);
65420
65421   END LOOP;
65422
65423 --  Record the amount posted and mark the source apopen as closed if it is completely posted
65424   UPDATE apopen
65425   SET apopen_paid = (apopen_paid + _totalAmount)
65426   WHERE (apopen_id=pApopenid);
65427
65428   UPDATE apopen
65429   SET apopen_open = false,
65430     apopen_closedate = current_date
65431   WHERE ( (apopen_id=pApopenid)
65432     AND (apopen_amount <= apopen_paid) );
65433
65434   IF (_r.apopen_curr_id = _src.apopen_curr_id) THEN
65435     IF (_r.apopen_docdate > _src.apopen_docdate) THEN
65436       _exchGain := (_totalAmount / _r.apopen_curr_rate - _totalAmount / _src.apopen_curr_rate) * -1;
65437     ELSE
65438       _exchGain := _totalAmount / _src.apopen_curr_rate - _totalAmount / _r.apopen_curr_rate;
65439     END IF;
65440   END IF;
65441
65442 -- do not post gain/loss to alternate prepaid
65443 --  IF (_src.apopen_accnt_id > -1) THEN
65444 --    _apaccntid := _src.apopen_accnt_id;
65445 --  ELSE 
65446     _apaccntid := findAPAccount(_src.apopen_vend_id);
65447 --  END IF;
65448
65449   PERFORM insertGLTransaction(fetchJournalNumber('AP-MISC'), 'A/P', 'CM',
65450                             _src.apopen_docnumber, 'CM Application',
65451                             _apaccntid,
65452                             getGainLossAccntId(_apaccntid), -1,
65453                             _exchGain,
65454                             CURRENT_DATE);
65455
65456
65457   RETURN pApopenid;
65458
65459 END;
65460 $_$;
65461
65462
65463 ALTER FUNCTION public.postapcreditmemoapplication(integer) OWNER TO admin;
65464
65465 --
65466 -- TOC entry 1982 (class 1255 OID 146566783)
65467 -- Dependencies: 4536 8
65468 -- Name: postapopenitems(); Type: FUNCTION; Schema: public; Owner: admin
65469 --
65470
65471 CREATE FUNCTION postapopenitems() RETURNS boolean
65472     LANGUAGE plpgsql
65473     AS $$
65474 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65475 -- See www.xtuple.com/CPAL for the full text of the software license.
65476 BEGIN
65477
65478   UPDATE apopen
65479   SET apopen_posted=TRUE
65480   WHERE (NOT apopen_posted);
65481
65482   RETURN TRUE;
65483
65484 END;
65485 $$;
65486
65487
65488 ALTER FUNCTION public.postapopenitems() OWNER TO admin;
65489
65490 --
65491 -- TOC entry 1983 (class 1255 OID 146566784)
65492 -- Dependencies: 4536 8
65493 -- Name: postarcreditmemoapplication(integer); Type: FUNCTION; Schema: public; Owner: admin
65494 --
65495
65496 CREATE FUNCTION postarcreditmemoapplication(integer) RETURNS integer
65497     LANGUAGE plpgsql
65498     AS $_$
65499 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65500 -- See www.xtuple.com/CPAL for the full text of the software license.
65501 DECLARE
65502   pAropenid ALIAS FOR $1;
65503 BEGIN
65504   RETURN postARCreditMemoApplication(pAropenid, CURRENT_DATE);
65505 END;
65506 $_$;
65507
65508
65509 ALTER FUNCTION public.postarcreditmemoapplication(integer) OWNER TO admin;
65510
65511 --
65512 -- TOC entry 1984 (class 1255 OID 146566785)
65513 -- Dependencies: 4536 8
65514 -- Name: postarcreditmemoapplication(integer, date); Type: FUNCTION; Schema: public; Owner: admin
65515 --
65516
65517 CREATE FUNCTION postarcreditmemoapplication(integer, date) RETURNS integer
65518     LANGUAGE plpgsql
65519     AS $_$
65520 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65521 -- See www.xtuple.com/CPAL for the full text of the software license.
65522 DECLARE
65523   pAropenid ALIAS FOR $1;
65524   _applyDate DATE := COALESCE($2, CURRENT_DATE);
65525   _p RECORD;
65526   _r RECORD;
65527   _totalAmount NUMERIC := 0;
65528   _totalTarget NUMERIC := 0;
65529   _exchGain NUMERIC := 0;
65530   _result NUMERIC;
65531   _araccntid INTEGER;
65532
65533 BEGIN
65534
65535   SELECT aropen_docnumber,
65536          ROUND(aropen_amount - aropen_paid, 2) AS balance,
65537          aropen_open, aropen_curr_rate,
65538          ROUND(SUM(currToCurr(arcreditapply_curr_id, aropen_curr_id,
65539               COALESCE(arcreditapply_amount, 0), _applyDate)), 2) AS toApply INTO _p
65540   FROM aropen, arcreditapply
65541   WHERE ( (arcreditapply_source_aropen_id=aropen_id)
65542    AND (aropen_id=pAropenid) )
65543   GROUP BY aropen_docnumber, aropen_amount, aropen_paid, aropen_open, aropen_curr_rate;
65544   IF (NOT FOUND) THEN
65545     RETURN -1;
65546   ELSIF (_p.toApply = 0) THEN
65547     RETURN -2;
65548   ELSIF (_p.toApply > _p.balance) THEN
65549     RETURN -3;
65550   END IF;
65551
65552   SELECT aropen_cust_id, aropen_docnumber, aropen_doctype, aropen_amount,
65553          aropen_curr_id, aropen_docdate, aropen_accnt_id, aropen_cust_id,
65554          aropen_curr_rate INTO _p
65555   FROM aropen
65556   WHERE (aropen_id=pAropenid);
65557   IF (NOT FOUND) THEN
65558     RETURN -5;
65559   END IF;
65560
65561   FOR _r IN SELECT arcreditapply_id, arcreditapply_target_aropen_id,
65562                    arcreditapply_amount AS arcreditapply_amountSource,
65563                    arcreditapply_reftype, arcreditapply_ref_id,
65564                    currToCurr(arcreditapply_curr_id, aropen_curr_id,
65565                               arcreditapply_amount, _applyDate) AS arcreditapply_amountTarget,
65566                    aropen_id, aropen_doctype, aropen_docnumber, aropen_docdate, aropen_curr_rate
65567             FROM arcreditapply, aropen
65568             WHERE ( (arcreditapply_source_aropen_id=pAropenid)
65569              AND (arcreditapply_target_aropen_id=aropen_id) ) LOOP
65570
65571     IF (_r.arcreditapply_amountTarget IS NULL) THEN
65572       RETURN -4;
65573     END IF;
65574
65575     IF (_r.arcreditapply_amountTarget > 0) THEN
65576
65577 --  Update the aropen item to post the paid amount
65578       UPDATE aropen
65579       SET aropen_paid = round(aropen_paid + _r.arcreditapply_amountTarget, 2)
65580       WHERE (aropen_id=_r.arcreditapply_target_aropen_id);
65581
65582       UPDATE aropen
65583       SET aropen_open = (round(aropen_amount, 2) > round(aropen_paid, 2))
65584       WHERE (aropen_id=_r.arcreditapply_target_aropen_id);
65585
65586 --  Cache the running amount posted
65587       _totalAmount := (_totalAmount + _r.arcreditapply_amountSource);
65588       _totalTarget := (_totalTarget + _r.arcreditapply_amountTarget);
65589
65590 --  Record the application
65591       INSERT INTO arapply
65592       ( arapply_cust_id,
65593         arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
65594         arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
65595         arapply_fundstype, arapply_refnumber,
65596         arapply_applied, arapply_closed, arapply_postdate, arapply_distdate,
65597         arapply_journalnumber, arapply_username, arapply_curr_id,
65598         arapply_reftype, arapply_ref_id )
65599       VALUES
65600       ( _p.aropen_cust_id,
65601         pAropenid, _p.aropen_doctype, _p.aropen_docnumber,
65602         _r.aropen_id, _r.aropen_doctype, _r.aropen_docnumber,
65603         '', '',
65604         round(_r.arcreditapply_amountSource, 2), TRUE, _applyDate, _applyDate,
65605         0, getEffectiveXtUser(), _p.aropen_curr_id, 
65606         _r.arcreditapply_reftype, _r.arcreditapply_ref_id );
65607
65608     END IF;
65609
65610 --  Delete the posted arcreditapply record
65611     DELETE FROM arcreditapply
65612     WHERE (arcreditapply_id=_r.arcreditapply_id);
65613
65614     IF (_r.aropen_docdate > _p.aropen_docdate) THEN
65615       _exchGain := (_totalTarget / _r.aropen_curr_rate - _totalAmount / _p.aropen_curr_rate) * -1;
65616     ELSE
65617       _exchGain := _totalAmount / _p.aropen_curr_rate - _totalTarget / _r.aropen_curr_rate;
65618     END IF;
65619
65620     IF (_p.aropen_accnt_id > -1) THEN
65621       _araccntid := _p.aropen_accnt_id;
65622     ELSE 
65623       _araccntid := findARAccount(_p.aropen_cust_id);
65624     END IF;
65625     
65626     IF (_exchGain <> 0) THEN
65627         PERFORM insertGLTransaction(fetchJournalNumber('AR-MISC'), 'A/R',
65628                                     'CR', _p.aropen_docnumber, 'CM Application',
65629                                     _araccntid, getGainLossAccntId(_araccntid),
65630                                     -1, _exchGain * -1, _applyDate);
65631     END IF;
65632
65633   END LOOP;
65634
65635 -- TODO: If this is a Customer Deposit (aropen_doctype='R')
65636 --       the we need to convert the total to a base transaction
65637   IF(_p.aropen_doctype='R') THEN
65638     SELECT insertGLTransaction(fetchJournalNumber('AR-MISC'), 'A/R',
65639                                'CD', _p.aropen_docnumber, 'CM Application',
65640                                cr.accnt_id, db.accnt_id,
65641                                -1, currToBase(_p.aropen_curr_id, _totalAmount, _p.aropen_docdate),
65642                                _applyDate)
65643       INTO _result
65644       FROM accnt AS cr, accnt AS db
65645      WHERE ((db.accnt_id = findDeferredAccount(_p.aropen_cust_id))
65646        AND  (cr.accnt_id = findARAccount(_p.aropen_cust_id)) );
65647     IF(NOT FOUND OR _result < 0) THEN
65648       RAISE EXCEPTION 'There was an error posting the Customer Deposit GL Transactions.';
65649     END IF;
65650   END IF;
65651
65652 --  Record the amount posted and mark the source aropen as closed if it is completely posted
65653   UPDATE aropen
65654   SET aropen_paid = round(aropen_paid + _totalAmount, 2)
65655   WHERE (aropen_id=pAropenid);
65656
65657   UPDATE aropen
65658   SET aropen_open = (round(aropen_amount, 2) > round(aropen_paid, 2))
65659   WHERE (aropen_id=pAropenid);
65660
65661   RETURN pAropenid;
65662
65663 END;
65664 $_$;
65665
65666
65667 ALTER FUNCTION public.postarcreditmemoapplication(integer, date) OWNER TO admin;
65668
65669 --
65670 -- TOC entry 1985 (class 1255 OID 146566787)
65671 -- Dependencies: 4536 8
65672 -- Name: postaropenitems(); Type: FUNCTION; Schema: public; Owner: admin
65673 --
65674
65675 CREATE FUNCTION postaropenitems() RETURNS boolean
65676     LANGUAGE plpgsql
65677     AS $$
65678 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65679 -- See www.xtuple.com/CPAL for the full text of the software license.
65680 BEGIN
65681
65682   UPDATE aropen
65683   SET aropen_posted=TRUE
65684   WHERE (NOT aropen_posted);
65685
65686   RETURN TRUE;
65687
65688 END;
65689 $$;
65690
65691
65692 ALTER FUNCTION public.postaropenitems() OWNER TO admin;
65693
65694 --
65695 -- TOC entry 1986 (class 1255 OID 146566788)
65696 -- Dependencies: 4536 8
65697 -- Name: postbankadjustment(integer); Type: FUNCTION; Schema: public; Owner: admin
65698 --
65699
65700 CREATE FUNCTION postbankadjustment(integer) RETURNS integer
65701     LANGUAGE plpgsql
65702     AS $_$
65703 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65704 -- See www.xtuple.com/CPAL for the full text of the software license.
65705 DECLARE
65706   pBankadjid ALIAS FOR $1;
65707   _sequence INTEGER;
65708   _r RECORD;
65709
65710 BEGIN
65711
65712 --  Post the G/L transaction
65713   SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'), 'G/L', 'AD',
65714                               bankadj_docnumber, (bankadjtype_name || '-' || bankadj_notes),
65715                               bankadjtype_accnt_id, bankaccnt_accnt_id, bankadj_id,
65716                               round(currToBase(bankaccnt_curr_id,
65717                                          CASE WHEN(bankadjtype_iscredit) THEN
65718                                              (bankadj_amount * -1)
65719                                          ELSE bankadj_amount END,
65720                                          bankadj_date), 2),
65721                               bankadj_date, TRUE, TRUE ) INTO _sequence
65722     FROM bankadj, bankaccnt, bankadjtype
65723    WHERE ( (bankadj_bankaccnt_id=bankaccnt_id)
65724      AND   (bankadj_bankadjtype_id=bankadjtype_id)
65725      AND   (NOT bankadj_posted)
65726      AND   (bankadj_id=pBankadjid) );
65727   IF ( NOT FOUND ) THEN
65728     RETURN -1;
65729   END IF;
65730
65731   IF (_sequence >= 0) THEN
65732 --  Update the bankadj record with this sequence and mark it posted
65733     UPDATE bankadj
65734        SET bankadj_sequence = _sequence,
65735            bankadj_posted = TRUE
65736      WHERE bankadj_id=pBankadjid;
65737   END IF;
65738
65739   RETURN _sequence;
65740
65741 END;
65742 $_$;
65743
65744
65745 ALTER FUNCTION public.postbankadjustment(integer) OWNER TO admin;
65746
65747 --
65748 -- TOC entry 1987 (class 1255 OID 146566789)
65749 -- Dependencies: 4536 8
65750 -- Name: postbankreconciliation(integer); Type: FUNCTION; Schema: public; Owner: admin
65751 --
65752
65753 CREATE FUNCTION postbankreconciliation(integer) RETURNS integer
65754     LANGUAGE plpgsql
65755     AS $_$
65756 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65757 -- See www.xtuple.com/CPAL for the full text of the software license.
65758 DECLARE
65759   pBankrecid ALIAS FOR $1;
65760   _accntid INTEGER;
65761   _sequence INTEGER;
65762   _gltransid INTEGER;
65763   _r RECORD;
65764
65765 BEGIN
65766
65767 -- Check the accnt information to make sure it is valid
65768   SELECT accnt_id INTO _accntid
65769     FROM bankrec, bankaccnt, accnt
65770    WHERE ( (bankaccnt_accnt_id=accnt_id)
65771      AND   (bankrec_bankaccnt_id=bankaccnt_id)
65772      AND   (bankrec_id=pBankrecid) );
65773   IF ( NOT FOUND ) THEN
65774     RETURN -1;
65775   END IF;
65776
65777 -- Delete any bankrecitem records that are not marked as cleared for cleanliness
65778   DELETE FROM bankrecitem
65779    WHERE ( (NOT bankrecitem_cleared)
65780      AND   (bankrecitem_bankrec_id=pBankrecid) );
65781
65782 -- Post any bankadj items that were marked as cleared and convert the bankrecitem
65783   FOR _r IN SELECT bankrecitem_id, bankrecitem_source_id
65784               FROM bankrecitem, bankadj
65785              WHERE ( (bankrecitem_source = 'AD')
65786                AND   (bankrecitem_source_id=bankadj_id)
65787                AND   (bankrecitem_cleared)
65788                AND   (NOT bankadj_posted)
65789                AND   (bankrecitem_bankrec_id=pBankrecid) ) LOOP
65790
65791     SELECT postBankAdjustment(_r.bankrecitem_source_id) INTO _sequence;
65792
65793     IF (_sequence < 0) THEN
65794       RETURN -10;
65795     END IF;
65796
65797     SELECT gltrans_id INTO _gltransid
65798       FROM gltrans
65799      WHERE ( (gltrans_sequence=_sequence)
65800        AND   (gltrans_accnt_id=_accntid) );
65801     IF ( NOT FOUND ) THEN
65802       RETURN -11;
65803     END IF;
65804
65805     UPDATE bankrecitem
65806        SET bankrecitem_source = 'GL',
65807            bankrecitem_source_id=_gltransid
65808      WHERE (bankrecitem_id=_r.bankrecitem_id);
65809
65810   END LOOP;
65811
65812 -- Mark all the gltrans items that have been cleared as reconciled.
65813   UPDATE gltrans
65814      SET gltrans_rec = TRUE
65815    WHERE ( (gltrans_id IN (SELECT bankrecitem_source_id
65816                              FROM bankrecitem
65817                             WHERE ((bankrecitem_source = 'GL')
65818                               AND  (bankrecitem_cleared)
65819                               AND  (bankrecitem_bankrec_id=pBankrecid) ) ) )
65820      AND   (gltrans_accnt_id=_accntid) ) ;
65821
65822 -- Mark all the sltrans items that have been cleared as reconciled.
65823   UPDATE sltrans
65824      SET sltrans_rec = TRUE
65825    WHERE ( (sltrans_id IN (SELECT bankrecitem_source_id
65826                              FROM bankrecitem
65827                             WHERE ((bankrecitem_source = 'SL')
65828                               AND  (bankrecitem_cleared)
65829                               AND  (bankrecitem_bankrec_id=pBankrecid) ) ) )
65830      AND   (sltrans_accnt_id=_accntid) ) ;
65831
65832 -- Mark the bankrec record as posted
65833   UPDATE bankrec SET 
65834     bankrec_posted = TRUE,
65835     bankrec_postdate = now()
65836    WHERE (bankrec_id=pBankrecid);
65837
65838   RETURN pBankrecid;
65839 END;
65840 $_$;
65841
65842
65843 ALTER FUNCTION public.postbankreconciliation(integer) OWNER TO admin;
65844
65845 --
65846 -- TOC entry 1988 (class 1255 OID 146566790)
65847 -- Dependencies: 4536 8
65848 -- Name: postbillingselection(integer); Type: FUNCTION; Schema: public; Owner: admin
65849 --
65850
65851 CREATE FUNCTION postbillingselection(integer) RETURNS integer
65852     LANGUAGE plpgsql
65853     AS $_$
65854 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65855 -- See www.xtuple.com/CPAL for the full text of the software license.
65856 DECLARE
65857   pCobmiscid ALIAS FOR $1;
65858
65859 BEGIN
65860
65861   RAISE NOTICE 'postBillingselection(integer) has been deprecated.  Please use createInvoice(integer).';
65862   RETURN createInvoice(pCobmiscid);
65863
65864 END;
65865 $_$;
65866
65867
65868 ALTER FUNCTION public.postbillingselection(integer) OWNER TO admin;
65869
65870 --
65871 -- TOC entry 1989 (class 1255 OID 146566791)
65872 -- Dependencies: 4536 8
65873 -- Name: postbillingselectionconsolidated(integer); Type: FUNCTION; Schema: public; Owner: admin
65874 --
65875
65876 CREATE FUNCTION postbillingselectionconsolidated(integer) RETURNS integer
65877     LANGUAGE plpgsql
65878     AS $_$
65879 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65880 -- See www.xtuple.com/CPAL for the full text of the software license.
65881 DECLARE
65882   pCustid ALIAS FOR $1;
65883
65884 BEGIN
65885
65886   RAISE NOTICE 'postBillingselectionConsolidated(integer) has been deprecated.  Please use createInvoiceConsolidated(integer).';
65887   RETURN createInvoiceConsolidated(pCustid);
65888
65889 END;
65890 $_$;
65891
65892
65893 ALTER FUNCTION public.postbillingselectionconsolidated(integer) OWNER TO admin;
65894
65895 --
65896 -- TOC entry 1990 (class 1255 OID 146566792)
65897 -- Dependencies: 4536 8
65898 -- Name: postbillingselections(); Type: FUNCTION; Schema: public; Owner: admin
65899 --
65900
65901 CREATE FUNCTION postbillingselections() RETURNS integer
65902     LANGUAGE plpgsql
65903     AS $$
65904 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65905 -- See www.xtuple.com/CPAL for the full text of the software license.
65906 BEGIN
65907
65908   RAISE NOTICE 'postBillingselections() has been deprecated.  Please use createInvoices().';
65909   RETURN createInvoices();
65910   
65911 END;
65912 $$;
65913
65914
65915 ALTER FUNCTION public.postbillingselections() OWNER TO admin;
65916
65917 --
65918 -- TOC entry 1991 (class 1255 OID 146566793)
65919 -- Dependencies: 4536 8
65920 -- Name: postbillingselections(integer); Type: FUNCTION; Schema: public; Owner: admin
65921 --
65922
65923 CREATE FUNCTION postbillingselections(integer) RETURNS integer
65924     LANGUAGE plpgsql
65925     AS $_$
65926 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65927 -- See www.xtuple.com/CPAL for the full text of the software license.
65928 BEGIN
65929   RAISE NOTICE 'postBillingselections(int) has been deprecated.  Please use createInvoices(int).';
65930   RETURN createInvoices($1, false);
65931 END;
65932 $_$;
65933
65934
65935 ALTER FUNCTION public.postbillingselections(integer) OWNER TO admin;
65936
65937 --
65938 -- TOC entry 1651 (class 1255 OID 146566794)
65939 -- Dependencies: 4536 8
65940 -- Name: postbillingselections(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
65941 --
65942
65943 CREATE FUNCTION postbillingselections(integer, boolean) RETURNS integer
65944     LANGUAGE plpgsql
65945     AS $_$
65946 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65947 -- See www.xtuple.com/CPAL for the full text of the software license.
65948 DECLARE
65949   pCustTypeId ALIAS FOR $1;
65950   pConsolidate ALIAS FOR $2;
65951
65952 BEGIN
65953
65954   RAISE NOTICE 'postBillingselections(int,bool) has been deprecated.  Please use createInvoices(int,bool).';
65955   RETURN createInvoices(pCustTypeId, pConsolidate);
65956   
65957 END;
65958 $_$;
65959
65960
65961 ALTER FUNCTION public.postbillingselections(integer, boolean) OWNER TO admin;
65962
65963 --
65964 -- TOC entry 1711 (class 1255 OID 146566795)
65965 -- Dependencies: 4536 8
65966 -- Name: postcashreceipt(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
65967 --
65968
65969 CREATE FUNCTION postcashreceipt(pcashrcptid integer, pjournalnumber integer) RETURNS integer
65970     LANGUAGE plpgsql
65971     AS $$
65972 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
65973 -- See www.xtuple.com/CPAL for the full text of the software license.
65974 DECLARE
65975   _ccpayid  INTEGER;
65976   _cctype TEXT;
65977   _p RECORD;
65978   _r RECORD;
65979   _t RECORD;
65980   _v RECORD;
65981   _postToAR NUMERIC;
65982   _postToMisc NUMERIC;
65983   _postToCM NUMERIC;
65984   _posted_base NUMERIC := 0;
65985   _posted NUMERIC := 0;
65986   _sequence INTEGER;
65987   _aropenid INTEGER;
65988   _arMemoNumber TEXT;
65989   _arAccntid INTEGER;
65990   _closed BOOLEAN;
65991   _debitAccntid INTEGER;
65992   _exchGain NUMERIC;
65993   _comment TEXT;
65994   _predist BOOLEAN;
65995   _check INTEGER;
65996
65997 BEGIN
65998   _posted := 0;
65999   _posted_base := 0;
66000
66001   SELECT fetchGLSequence() INTO _sequence;
66002
66003   SELECT accnt_id INTO _arAccntid
66004   FROM cashrcpt, accnt, salescat
66005   WHERE ((cashrcpt_salescat_id=salescat_id)
66006     AND  (salescat_ar_accnt_id=accnt_id)
66007     AND  (cashrcpt_id=pCashrcptid));
66008   IF (NOT FOUND) THEN
66009     SELECT accnt_id INTO _arAccntid
66010     FROM cashrcpt LEFT OUTER JOIN accnt ON (accnt_id=findARAccount(cashrcpt_cust_id))
66011     WHERE ( (findARAccount(cashrcpt_cust_id)=0 OR accnt_id > 0) -- G/L interface might be disabled
66012      AND (cashrcpt_id=pCashrcptid) );
66013     IF (NOT FOUND) THEN
66014       RETURN -5;
66015     END IF;
66016   END IF;
66017
66018   SELECT cashrcpt_cust_id, (cust_number||'-'||cust_name) AS custnote,
66019          cashrcpt_fundstype, cashrcpt_number, cashrcpt_docnumber,
66020          cashrcpt_distdate, cashrcpt_amount, cashrcpt_discount,
66021          (cashrcpt_amount / cashrcpt_curr_rate) AS cashrcpt_amount_base,
66022          (cashrcpt_discount / cashrcpt_curr_rate) AS cashrcpt_discount_base,
66023          cashrcpt_notes,
66024          cashrcpt_bankaccnt_id AS bankaccnt_id,
66025          accnt_id AS prepaid_accnt_id,
66026          cashrcpt_usecustdeposit,
66027          COALESCE(cashrcpt_applydate, cashrcpt_distdate) AS applydate,
66028          cashrcpt_curr_id, cashrcpt_curr_rate, cashrcpt_posted, cashrcpt_void INTO _p
66029   FROM cashrcpt LEFT OUTER JOIN custinfo ON (cashrcpt_cust_id=cust_id)
66030                 LEFT OUTER JOIN accnt ON (accnt_id=findPrepaidAccount(cashrcpt_cust_id))
66031   WHERE ( (findPrepaidAccount(cashrcpt_cust_id)=0 OR accnt_id > 0) -- G/L interface might be disabled
66032      AND (cashrcpt_id=pCashrcptid) );
66033   IF (NOT FOUND) THEN
66034     RETURN -7;
66035   END IF;
66036
66037   IF (COALESCE(_p.cashrcpt_distdate > _p.applydate, false)) THEN
66038     RAISE EXCEPTION 'Cannot post cashrcpt % because application date is before distribution date.', _p.cashrcpt_docnumber;
66039   END IF;
66040
66041   IF (COALESCE(_p.cashrcpt_posted, false)) THEN
66042     RAISE EXCEPTION 'Cannot post cashrcpt % because the document has already been posted.', _p.cashrcpt_docnumber;
66043   END IF;
66044
66045   IF (COALESCE(_p.cashrcpt_void, false)) THEN
66046     RAISE EXCEPTION 'Cannot post cashrcpt % because the document has been voided.', _p.cashrcpt_docnumber;
66047   END IF;
66048
66049   _predist := COALESCE(_p.cashrcpt_distdate < _p.applydate, false);
66050
66051   IF (_p.cashrcpt_fundstype IN ('A', 'D', 'M', 'V')) THEN
66052     SELECT ccpay_id, ccpay_type INTO _ccpayid, _cctype
66053     FROM ccpay
66054     WHERE ((ccpay_r_ordernum IN (CAST(pCashrcptid AS TEXT), _p.cashrcpt_docnumber))
66055        AND (ccpay_status IN ('C', 'A')));
66056
66057     IF NOT FOUND THEN
66058       -- the following select seems to work except for xikar - bug 8848. why?
66059       -- raise warning so there is some visibility if people fall into this path.
66060       SELECT ccpay_id, ccpay_type INTO _ccpayid, _cctype
66061       FROM ccpay
66062       WHERE ((ccpay_order_number IN (CAST(pCashrcptid AS TEXT), _p.cashrcpt_docnumber))
66063          AND (ccpay_status IN ('C', 'A')));
66064       IF (NOT FOUND) THEN
66065         RETURN -8;
66066       ELSE
66067         RAISE NOTICE 'PostCashReceipt() found ccpay_id % for order number %/% (ref 8848).',
66068                       _ccpayid, pCashrcptid, _p.cashrcpt_docnumber;
66069       END IF;
66070     END IF;
66071
66072 -- If there is a ccpay entry and the card was charged directly, use the prepaid account
66073     IF (_cctype = 'C' ) THEN
66074       _debitAccntid := findPrepaidAccount(_p.cashrcpt_cust_id);
66075 -- If there is a ccpay entry and the card was preauthed and then charged, use the Bank account
66076     ELSE
66077       SELECT accnt_id INTO _debitAccntid
66078       FROM cashrcpt, bankaccnt, accnt
66079       WHERE ( (cashrcpt_bankaccnt_id=bankaccnt_id)
66080        AND (bankaccnt_accnt_id=accnt_id)
66081        AND (cashrcpt_id=pCashrcptid) );
66082       IF (NOT FOUND) THEN
66083         RETURN -6;
66084       END IF;
66085     END IF;
66086   ELSE
66087     SELECT accnt_id INTO _debitAccntid
66088     FROM cashrcpt, bankaccnt, accnt
66089     WHERE ( (cashrcpt_bankaccnt_id=bankaccnt_id)
66090      AND (bankaccnt_accnt_id=accnt_id)
66091      AND (cashrcpt_id=pCashrcptid) );
66092     IF (NOT FOUND) THEN
66093       RETURN -6;
66094     END IF;
66095   END IF;
66096
66097 --  Determine the amount to post to A/R Open Items
66098   SELECT COALESCE(SUM(cashrcptitem_amount), 0) INTO _postToAR
66099   FROM cashrcptitem JOIN aropen ON (aropen_id=cashrcptitem_aropen_id)
66100   WHERE (cashrcptitem_cashrcpt_id=pCashrcptid);
66101   IF (NOT FOUND) THEN
66102     _postToAR := 0;
66103   END IF;
66104
66105 --  Determine the amount to post to Misc. Distributions
66106   SELECT COALESCE(SUM(cashrcptmisc_amount), 0) INTO _postToMisc
66107   FROM cashrcptmisc
66108   WHERE (cashrcptmisc_cashrcpt_id=pCashrcptid);
66109   IF (NOT FOUND) THEN
66110     _postToMisc := 0;
66111   END IF;
66112
66113 --  Determine the amount to post to Discount Credit Memo
66114   SELECT COALESCE(SUM(cashrcptitem_discount), 0) INTO _postToCM
66115   FROM cashrcptitem JOIN aropen ON ( (aropen_id=cashrcptitem_aropen_id) AND (aropen_doctype IN ('I', 'D')) )
66116   WHERE (cashrcptitem_cashrcpt_id=pCashrcptid);
66117   IF (NOT FOUND) THEN
66118     _postToCM := 0;
66119   END IF;
66120   
66121 --  Check to see if the C/R is over applied
66122   IF ((_postToAR + _postToMisc) > _p.cashrcpt_amount) THEN
66123     RETURN -1;
66124   END IF;
66125
66126 --  Check to see if the C/R is positive amount
66127   IF (_p.cashrcpt_amount <= 0) THEN
66128     RETURN -2;
66129   END IF;
66130
66131 --  Distribute A/R Applications
66132     FOR _r IN SELECT aropen_id, aropen_doctype, aropen_docnumber, aropen_docdate,
66133                      aropen_duedate, aropen_curr_id, aropen_curr_rate, aropen_amount,
66134                      round(aropen_amount - aropen_paid, 2) <=
66135                         round(currToCurr(_p.cashrcpt_curr_id, aropen_curr_id,abs(cashrcptitem_amount + cashrcptitem_discount),_p.cashrcpt_distdate),2)
66136                                  AS closed,
66137                      cashrcptitem_id, cashrcptitem_amount, cashrcptitem_discount,
66138                      (cashrcptitem_amount / _p.cashrcpt_curr_rate) AS cashrcptitem_amount_base,
66139                      (cashrcptitem_discount / _p.cashrcpt_curr_rate) AS cashrcptitem_discount_base,
66140                      round(aropen_paid + 
66141                        currToCurr(_p.cashrcpt_curr_id, aropen_curr_id,abs(cashrcptitem_amount),_p.cashrcpt_distdate),2) AS new_paid,
66142                      round(currToCurr(_p.cashrcpt_curr_id, aropen_curr_id,cashrcptitem_discount,_p.cashrcpt_distdate),2) AS new_discount
66143               FROM cashrcptitem JOIN aropen ON (aropen_id=cashrcptitem_aropen_id)
66144               WHERE ((cashrcptitem_cashrcpt_id=pCashrcptid)
66145                AND (NOT _predist OR aropen_doctype IN ('C','R'))) LOOP
66146   
66147   --  Handle discount 
66148       IF (_r.cashrcptitem_discount_base > 0) THEN
66149         PERFORM postCashReceiptDisc(_r.cashrcptitem_id, pJournalNumber);
66150       END IF;
66151      
66152   --  Update the aropen item to post the paid amount
66153       UPDATE aropen
66154       SET aropen_paid = _r.new_paid + _r.new_discount,
66155           aropen_open = (NOT _r.closed),
66156           aropen_closedate = CASE WHEN _r.closed THEN _p.cashrcpt_distdate END
66157       WHERE (aropen_id=_r.aropen_id);
66158   
66159   --  Cache the running amount posted
66160       _posted_base := _posted_base + _r.cashrcptitem_amount_base;
66161       _posted := _posted + _r.cashrcptitem_amount;
66162  
66163   --  Record the cashrcpt application
66164     IF (_r.aropen_doctype IN ('I','D')) THEN
66165       INSERT INTO arapply
66166       ( arapply_cust_id,
66167         arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
66168         arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
66169         arapply_fundstype, arapply_refnumber, arapply_reftype, arapply_ref_id,
66170         arapply_applied, arapply_closed,
66171         arapply_postdate, arapply_distdate, arapply_journalnumber, arapply_username,
66172         arapply_curr_id )
66173       VALUES
66174       ( _p.cashrcpt_cust_id,
66175         -1, 'K', _p.cashrcpt_number,
66176         _r.aropen_id, _r.aropen_doctype, _r.aropen_docnumber,
66177         _p.cashrcpt_fundstype, _p.cashrcpt_docnumber, 'CRA', _r.cashrcptitem_id,
66178         round(_r.cashrcptitem_amount, 2), _r.closed,
66179         _p.applydate, _p.cashrcpt_distdate, pJournalNumber, getEffectiveXtUser(), _p.cashrcpt_curr_id);
66180     ELSE
66181       INSERT INTO arapply
66182       ( arapply_cust_id,
66183         arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
66184         arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
66185         arapply_fundstype, arapply_refnumber, arapply_reftype, arapply_ref_id,
66186         arapply_applied, arapply_closed, arapply_postdate, arapply_distdate,
66187         arapply_journalnumber, arapply_username, arapply_curr_id )
66188       VALUES
66189       ( _p.cashrcpt_cust_id,
66190         _r.aropen_id, _r.aropen_doctype, _r.aropen_docnumber,
66191         -1, 'R', _p.cashrcpt_number,
66192         '', '', 'CRA', _r.cashrcptitem_id,
66193         round(abs(_r.cashrcptitem_amount), 2), _r.closed,
66194         _p.applydate, _p.cashrcpt_distdate, pJournalNumber, getEffectiveXtUser(), _p.cashrcpt_curr_id );
66195     END IF;
66196   
66197       _exchGain := arCurrGain(_r.aropen_id,_p.cashrcpt_curr_id, abs(_r.cashrcptitem_amount),
66198                              _p.cashrcpt_distdate);
66199
66200        PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR',
66201                           (_r.aropen_doctype || '-' || _r.aropen_docnumber),
66202                           CASE WHEN _r.aropen_doctype != 'R' THEN _arAccntid
66203                           ELSE findDeferredAccount(_p.cashrcpt_cust_id) END, 
66204                           round(_r.cashrcptitem_amount_base + _exchGain, 2),
66205                           _p.cashrcpt_distdate, _p.custnote, pCashrcptid );      
66206                           
66207       IF (_exchGain <> 0) THEN
66208           PERFORM insertIntoGLSeries(_sequence, 'A/R', 'CR',
66209                  _r.aropen_doctype || '-' || _r.aropen_docnumber,
66210                  getGainLossAccntId(
66211                    CASE WHEN _r.aropen_doctype != 'R' THEN _arAccntid
66212                    ELSE findDeferredAccount(_p.cashrcpt_cust_id) END
66213                  ), round(_exchGain, 2) * -1,
66214                  _p.cashrcpt_distdate, _p.custnote, pCashrcptid);
66215       END IF;
66216
66217     END LOOP;
66218
66219 --  Distribute Misc. Applications
66220   FOR _r IN SELECT cashrcptmisc_id, cashrcptmisc_accnt_id, cashrcptmisc_amount,
66221                    (cashrcptmisc_amount / cashrcpt_curr_rate) AS cashrcptmisc_amount_base,
66222                    cashrcptmisc_notes, cashrcpt_curr_id
66223             FROM cashrcptmisc JOIN
66224                  cashrcpt ON (cashrcptmisc_cashrcpt_id = cashrcpt_id)
66225             WHERE (cashrcptmisc_cashrcpt_id=pCashrcptid)  LOOP
66226
66227 --  Cache the running amount posted
66228     _posted_base := (_posted_base + _r.cashrcptmisc_amount_base);
66229     _posted := (_posted + _r.cashrcptmisc_amount);
66230
66231 --  Record the cashrcpt application
66232     INSERT INTO arapply
66233     ( arapply_cust_id,
66234       arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
66235       arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
66236       arapply_fundstype, arapply_refnumber,
66237       arapply_applied, arapply_closed,
66238       arapply_postdate, arapply_distdate, arapply_journalnumber, arapply_username,
66239       arapply_curr_id, arapply_reftype, arapply_ref_id )
66240     VALUES
66241     ( _p.cashrcpt_cust_id,
66242       -1, 'K', '',
66243       -1, 'Misc.', '',
66244       _p.cashrcpt_fundstype, _p.cashrcpt_docnumber,
66245       round(_r.cashrcptmisc_amount, 2), TRUE,
66246       _p.applydate, _p.cashrcpt_distdate, pJournalNumber, getEffectiveXtUser(), 
66247       _r.cashrcpt_curr_id, 'CRD', _r.cashrcptmisc_id );
66248     PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR', _r.cashrcptmisc_notes,
66249                                 _r.cashrcptmisc_accnt_id,
66250                                 round(_r.cashrcptmisc_amount_base, 2),
66251                                 _p.cashrcpt_distdate, _p.custnote, pCashrcptid );
66252
66253   END LOOP;
66254
66255 --  Post any remaining Cash to an A/R Cash Despoit (Credit Memo)
66256 --  this credit memo may absorb an occasional currency exchange rounding error
66257   IF (round(_posted_base, 2) < round(_p.cashrcpt_amount_base, 2)) THEN
66258     _comment := ('Unapplied from ' || _p.cashrcpt_fundstype || '-' || _p.cashrcpt_docnumber);
66259     PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR',
66260                                 _comment,
66261                                 _p.prepaid_accnt_id,
66262                                 round(_p.cashrcpt_amount_base, 2) -
66263                                                         round(_posted_base, 2),
66264                                 _p.cashrcpt_distdate, _p.custnote, pCashrcptid );
66265     SELECT fetchArMemoNumber() INTO _arMemoNumber;
66266     IF(_p.cashrcpt_usecustdeposit) THEN
66267       -- Post Customer Deposit
66268       SELECT createARCashDeposit(_p.cashrcpt_cust_id, _arMemoNumber, '',
66269                                  _p.cashrcpt_distdate, (_p.cashrcpt_amount - _posted),
66270                                  _comment, pJournalNumber, _p.cashrcpt_curr_id) INTO _aropenid;
66271     ELSE
66272       -- Post A/R Credit Memo
66273       _aropenid := createARCreditMemo(NULL, _p.cashrcpt_cust_id, _arMemoNumber, '',
66274                                 _p.cashrcpt_distdate, (_p.cashrcpt_amount - _posted),
66275                                 _comment, -1, -1, -1, _p.cashrcpt_distdate, -1, NULL, 0,
66276                                 pJournalNumber, _p.cashrcpt_curr_id, _arAccntid);
66277     END IF;
66278
66279     IF (_ccpayid IS NOT NULL) THEN
66280       INSERT INTO payaropen (payaropen_ccpay_id, payaropen_aropen_id,
66281                              payaropen_amount,   payaropen_curr_id
66282                    ) VALUES (_ccpayid,           _aropenid,
66283                              _p.cashrcpt_amount, _p.cashrcpt_curr_id);
66284     END IF;
66285
66286     -- Create Cash Receipt Item to capture posting
66287     IF (_predist=false) THEN
66288       INSERT INTO cashrcptitem
66289         ( cashrcptitem_cashrcpt_id, cashrcptitem_aropen_id, cashrcptitem_amount, cashrcptitem_applied )
66290       VALUES
66291         ( pCashrcptid, _aropenid, (_p.cashrcpt_amount - _posted), false );
66292     END IF;
66293
66294   ELSIF (round(_posted_base, 2) > round((_p.cashrcpt_amount_base), 2)) THEN
66295     PERFORM insertIntoGLSeries(_sequence, 'A/R', 'CR',
66296                    'Currency Exchange Rounding - ' || _p.cashrcpt_docnumber,
66297                    getGainLossAccntId(_debitAccntid),
66298                    round(_posted_base, 2) - round((_p.cashrcpt_amount_base + _p.cashrcpt_discount_base), 2),
66299                    _p.cashrcpt_distdate, _p.custnote, pCashrcptid);
66300   END IF;
66301
66302 --  Debit Cash
66303   PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR',
66304                     (_p.cashrcpt_fundstype || '-' || _p.cashrcpt_docnumber),
66305                      _debitAccntid, round(_p.cashrcpt_amount_base, 2) * -1, 
66306                      _p.cashrcpt_distdate,
66307                      _p.custnote, pCashrcptid );
66308
66309   PERFORM postGLSeries(_sequence, pJournalNumber);
66310
66311   -- convert the cashrcptitem records to applications against the cm/cd if we are _predist
66312   IF(_predist=true) THEN
66313     FOR _r IN SELECT *
66314               FROM cashrcptitem
66315               WHERE ((cashrcptitem_cashrcpt_id=pCashrcptid)
66316                 AND (cashrcptitem_amount > 0)) LOOP
66317
66318       -- Handle discount if applicable
66319       IF (_r.cashrcptitem_discount > 0) THEN
66320         PERFORM postCashReceiptDisc(_r.cashrcptitem_id, pJournalNumber);
66321       END IF;
66322       
66323       INSERT INTO arcreditapply (arcreditapply_source_aropen_id, arcreditapply_target_aropen_id,
66324                                  arcreditapply_amount, arcreditapply_curr_id)
66325                           VALUES(_aropenid, _r.cashrcptitem_aropen_id,
66326                                  _r.cashrcptitem_amount, _p.cashrcpt_curr_id);
66327       _posted := (_posted + _r.cashrcptitem_amount);
66328       
66329     END LOOP;
66330
66331     PERFORM postArCreditMemoApplication(_aropenid, _p.applydate);
66332     
66333     -- If there is any left over go ahead and create an additional cashrcptitem record for it with the amount
66334     IF (round(_posted, 2) < round(_p.cashrcpt_amount, 2)) THEN
66335       INSERT INTO cashrcptitem
66336         ( cashrcptitem_cashrcpt_id, cashrcptitem_aropen_id, cashrcptitem_amount, cashrcptitem_applied )
66337       VALUES
66338         ( pCashrcptid, _aropenid, (_p.cashrcpt_amount - _posted), false );
66339     END IF;
66340   END IF;
66341
66342 --  Update the posted cashrcpt
66343   UPDATE cashrcpt SET cashrcpt_posted=TRUE,
66344                       cashrcpt_posteddate=CURRENT_DATE,
66345                       cashrcpt_postedby=getEffectiveXtUser()
66346   WHERE (cashrcpt_id=pCashrcptid);
66347
66348   RETURN 1;
66349
66350 END;
66351 $$;
66352
66353
66354 ALTER FUNCTION public.postcashreceipt(pcashrcptid integer, pjournalnumber integer) OWNER TO admin;
66355
66356 --
66357 -- TOC entry 1728 (class 1255 OID 146566797)
66358 -- Dependencies: 4536 8
66359 -- Name: postcashreceiptdisc(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
66360 --
66361
66362 CREATE FUNCTION postcashreceiptdisc(integer, integer) RETURNS integer
66363     LANGUAGE plpgsql
66364     AS $_$
66365 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
66366 -- See www.xtuple.com/CPAL for the full text of the software license.
66367 DECLARE
66368   pCashrcptItemId ALIAS FOR $1;
66369   pJournalNumber ALIAS FOR $2;
66370   _r RECORD;
66371   _t RECORD;
66372   _v RECORD;
66373   _ardiscountid INTEGER;
66374   _arMemoNumber TEXT;
66375   _arAccntid INTEGER;
66376   _discountAccntid INTEGER;
66377   _comment      TEXT;
66378   _discprcnt NUMERIC;
66379   _check INTEGER;
66380
66381 BEGIN
66382
66383     -- Fetch base records for processing
66384     SELECT aropen_id, aropen_doctype, aropen_amount,
66385            cashrcptitem_discount,
66386            cashrcpt_cust_id, cashrcpt_distdate, cashrcpt_applydate,
66387            cashrcpt_curr_id, cashrcpt_fundstype, cashrcpt_docnumber,
66388            round(currToCurr(cashrcpt_curr_id, aropen_curr_id, cashrcptitem_discount, cashrcpt_distdate),2) AS aropen_discount
66389       INTO _r
66390     FROM cashrcptitem 
66391       JOIN cashrcpt ON (cashrcptitem_cashrcpt_id=cashrcpt_id)
66392       JOIN aropen ON ( (aropen_id=cashrcptitem_aropen_id) AND (aropen_doctype IN ('I', 'D')) )
66393     WHERE (cashrcptitem_id=pCashrcptItemId);
66394
66395     -- Get discount account
66396     _discountAccntid := findardiscountaccount(_r.cashrcpt_cust_id);
66397   
66398     IF (_r.cashrcptitem_discount > 0) THEN
66399       --  Determine discount percentage
66400       _discprcnt := _r.aropen_discount / _r.aropen_amount;
66401
66402       SELECT fetchArMemoNumber() INTO _arMemoNumber;
66403       _comment := 'Discount Credit from ' || _r.cashrcpt_fundstype || '-' || _r.cashrcpt_docnumber;
66404
66405       -- Create misc credit memo record
66406       _ardiscountid := nextval('aropen_aropen_id_seq');
66407       INSERT INTO aropen (
66408         aropen_id, aropen_docdate, aropen_duedate, aropen_doctype, 
66409         aropen_docnumber, aropen_curr_id, aropen_posted, aropen_amount) 
66410       VALUES (
66411         _ardiscountid, _r.cashrcpt_distdate, _r.cashrcpt_distdate, 'C', 
66412         _arMemoNumber, _r.cashrcpt_curr_id, false,_r.cashrcptitem_discount);
66413         
66414       IF (fetchMetricBool('CreditTaxDiscount')) THEN
66415         --  proportional tax credits calculated and implemented for the credit memo generated by the discount
66416         IF (_r.aropen_doctype  = 'I') THEN
66417           -- Tax for invoices
66418           SELECT aropen_cobmisc_id AS invcheadid, 
66419                  invchead_curr_id, 
66420                  invchead_invcdate INTO _t
66421           FROM aropen
66422             LEFT OUTER JOIN invchead ON (aropen_cobmisc_id = invchead_id) 
66423             LEFT OUTER JOIN invcitem ON (invchead_id = invcitem_invchead_id)
66424           WHERE aropen_id = _r.aropen_id;
66425
66426           FOR _v IN SELECT tax_sales_accnt_id,
66427                            tax_id, 
66428                            round(sum(taxdetail_tax), 2) AS tax,
66429                            currToBase(_t.invchead_curr_id, round(sum(taxdetail_tax), 2), _t.invchead_invcdate) AS taxbasevalue
66430           FROM tax 
66431             JOIN calculateTaxDetailSummary('I', _t.invcheadid, 'T') ON (taxdetail_tax_id=tax_id)
66432             GROUP BY tax_id, tax_sales_accnt_id 
66433           LOOP
66434             INSERT INTO aropentax(
66435               taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
66436               taxhist_percent, taxhist_amount, taxhist_tax, 
66437               taxhist_docdate, taxhist_basis)
66438             VALUES (
66439               _ardiscountid, getadjustmenttaxtypeid(), _v.tax_id, 
66440               0.00, 0.00, (round((_v.tax * _discprcnt), 2) * -1), 
66441               _r.cashrcpt_distdate, 0.00);
66442           END LOOP;
66443
66444         ELSIF (_r.aropen_doctype  = 'D') THEN
66445           -- Tax for debit memos
66446           INSERT INTO aropentax(
66447             taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
66448             taxhist_percent, taxhist_amount, taxhist_tax, 
66449             taxhist_docdate, taxhist_basis)
66450           SELECT
66451             _ardiscountid, taxhist_taxtype_id, taxhist_tax_id, 
66452             0.00, 0.00, (round((taxhist_tax * _discprcnt), 2) * -1),  
66453             _r.cashrcpt_distdate, 0.00
66454           FROM aropentax
66455           WHERE (taxhist_parent_id=_r.aropen_id);
66456               
66457         END IF;
66458       END IF; -- End taxes
66459
66460       -- Create credit memo for discount
66461       SELECT createARCreditMemo(_ardiscountid, _r.cashrcpt_cust_id, _arMemoNumber, '',
66462                                 _r.cashrcpt_distdate, _r.cashrcptitem_discount,
66463                                 _comment, -1, -1, _discountAccntid, _r.cashrcpt_distdate,
66464                                 -1, NULL, 0,
66465                                 pJournalNumber, _r.cashrcpt_curr_id) INTO _ardiscountid;
66466
66467       -- Apply discount credit memo
66468       INSERT INTO arcreditapply ( 
66469         arcreditapply_source_aropen_id, arcreditapply_target_aropen_id,
66470         arcreditapply_amount, arcreditapply_curr_id )
66471       VALUES ( 
66472         _ardiscountid, _r.aropen_id, _r.cashrcptitem_discount, _r.cashrcpt_curr_id );
66473  
66474       SELECT postARCreditMemoApplication(_ardiscountid, _r.cashrcpt_applydate) INTO _check;
66475       IF (_check < 0) THEN
66476         RAISE EXCEPTION 'Error posting discount credit memo application. Code %', _check;
66477       END IF;
66478         
66479    END IF; -- End handle Discount
66480
66481    RETURN 1;
66482
66483 END;
66484 $_$;
66485
66486
66487 ALTER FUNCTION public.postcashreceiptdisc(integer, integer) OWNER TO admin;
66488
66489 --
66490 -- TOC entry 1750 (class 1255 OID 146566799)
66491 -- Dependencies: 4536 8
66492 -- Name: postcccashreceipt(integer, integer, text, numeric); Type: FUNCTION; Schema: public; Owner: admin
66493 --
66494
66495 CREATE FUNCTION postcccashreceipt(pccpay integer, pdocid integer, pdoctype text DEFAULT NULL::text, pamount numeric DEFAULT NULL::numeric) RETURNS integer
66496     LANGUAGE plpgsql
66497     AS $$
66498 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
66499 -- See www.xtuple.com/CPAL for the full text of the software license.
66500 DECLARE
66501   _aropenid     INTEGER;
66502   _bankaccnt_id INTEGER;
66503   _c            RECORD;
66504   _ccOrderDesc  TEXT;
66505   _journal      INTEGER;
66506   _realaccnt    INTEGER;
66507   _return       INTEGER := 0;
66508
66509 BEGIN
66510   SELECT * INTO _c
66511      FROM ccpay, ccard, custinfo
66512      WHERE ( (ccpay_id = pCCpay)
66513        AND   (ccpay_ccard_id = ccard_id)
66514        AND   (ccpay_cust_id = cust_id) );
66515
66516   IF (NOT FOUND) THEN
66517     RAISE EXCEPTION 'Cannot find the Credit Card transaction information [xtuple: postCCcashReceipt, -11, %]',
66518                     pCCpay;
66519   END IF;
66520
66521   IF (pamount IS NOT NULL) THEN
66522     _c.ccpay_amount = pamount;
66523   END IF;
66524
66525   SELECT bankaccnt_id, bankaccnt_accnt_id INTO _bankaccnt_id, _realaccnt
66526   FROM ccbank JOIN bankaccnt ON (ccbank_bankaccnt_id=bankaccnt_id)
66527   WHERE (ccbank_ccard_type=_c.ccard_type);
66528
66529   IF (_bankaccnt_id IS NULL) THEN
66530     RAISE EXCEPTION 'Cannot find the default Bank Account for this Credit Card [xtuple: postCCcredit, -1, %]',
66531                     _c.ccard_type;
66532   END IF;
66533
66534   _ccOrderDesc := (_c.ccard_type || '-' || _c.ccpay_order_number::TEXT ||
66535                    '-' || _c.ccpay_order_number_seq::TEXT);
66536
66537   _journal := fetchJournalNumber('C/R');
66538
66539   IF (pdoctype = 'cashrcpt') THEN
66540     IF (COALESCE(pdocid, -1) < 0) THEN
66541       INSERT INTO cashrcpt (
66542         cashrcpt_cust_id,   cashrcpt_amount,     cashrcpt_curr_id,
66543         cashrcpt_fundstype, cashrcpt_docnumber,  cashrcpt_notes,
66544         cashrcpt_distdate,  cashrcpt_bankaccnt_id,
66545         cashrcpt_usecustdeposit
66546       ) VALUES (
66547         _c.ccpay_cust_id,   _c.ccpay_amount,     _c.ccpay_curr_id,
66548         _c.ccard_type,      _c.ccpay_r_ordernum, _ccOrderDesc,
66549         CURRENT_DATE,       _bankaccnt_id,
66550         fetchMetricBool('EnableCustomerDeposits'))
66551       RETURNING cashrcpt_id INTO _return;
66552     ELSE
66553       UPDATE cashrcpt
66554       SET cashrcpt_cust_id=_c.ccpay_cust_id,
66555           cashrcpt_amount=_c.ccpay_amount,
66556           cashrcpt_curr_id=_c.ccpay_curr_id,
66557           cashrcpt_fundstype=_c.ccard_type,
66558           cashrcpt_docnumber=_c.ccpay_r_ordernum,
66559           cashrcpt_notes=_ccOrderDesc,
66560           cashrcpt_distdate=CURRENT_DATE,
66561           cashrcpt_bankaccnt_id=_bankaccnt_id
66562       WHERE (cashrcpt_id=pdocid);
66563       _return := pdocid;
66564     END IF;
66565
66566   ELSIF (pdoctype = 'cohead') THEN
66567     SELECT createARCreditMemo(NULL,               _c.ccpay_cust_id,
66568                              fetchArMemoNumber(), cohead_number,
66569                              CURRENT_DATE,        _c.ccpay_amount,
66570                              'Unapplied from ' || _ccOrderDesc,
66571                              NULL,                NULL, NULL,
66572                              CURRENT_DATE,        NULL,
66573                              cohead_salesrep_id,  NULL,
66574                              _journal,            _c.ccpay_curr_id,
66575                              NULL,                pCCpay) INTO _aropenid
66576       FROM cohead
66577      WHERE cohead_id = pdocid;
66578     IF (COALESCE(_aropenid, -1) < 0) THEN       -- coalesce handles not-found case
66579       RAISE EXCEPTION '[xtuple: createARCreditMemo, %]', _aropenid;
66580     END IF;
66581
66582     INSERT INTO payaropen (payaropen_ccpay_id, payaropen_aropen_id,
66583                            payaropen_amount,   payaropen_curr_id)
66584                   VALUES  (pccpay,             _aropenid,
66585                            _c.ccpay_amount,    _c.ccpay_curr_id);
66586     INSERT INTO aropenalloc (aropenalloc_aropen_id, aropenalloc_doctype, aropenalloc_doc_id,
66587                              aropenalloc_amount,    aropenalloc_curr_id)
66588                      VALUES (_aropenid, 'S',          pdocid,
66589                              _c.ccpay_amount,    _c.ccpay_curr_id);
66590     _return := _aropenid;
66591   END IF;
66592
66593   PERFORM insertGLTransaction(_journal, 'A/R', 'CR', _ccOrderDesc, 
66594                               ('Cash Receipt from Credit Card ' || _c.cust_name),
66595                               findPrepaidAccount(_c.ccpay_cust_id),
66596                               _realaccnt,
66597                               NULL,
66598                               ROUND(currToBase(_c.ccpay_curr_id,
66599                                                _c.ccpay_amount,
66600                                                _c.ccpay_transaction_datetime::DATE),2),
66601                               CURRENT_DATE);
66602
66603   RETURN _return;
66604 END;
66605 $$;
66606
66607
66608 ALTER FUNCTION public.postcccashreceipt(pccpay integer, pdocid integer, pdoctype text, pamount numeric) OWNER TO admin;
66609
66610 --
66611 -- TOC entry 1992 (class 1255 OID 146566801)
66612 -- Dependencies: 4536 8
66613 -- Name: postcccredit(integer, text, integer); Type: FUNCTION; Schema: public; Owner: admin
66614 --
66615
66616 CREATE FUNCTION postcccredit(integer, text, integer) RETURNS integer
66617     LANGUAGE plpgsql
66618     AS $_$
66619 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
66620 -- See www.xtuple.com/CPAL for the full text of the software license.
66621 DECLARE
66622   pCCpay        ALIAS FOR $1;
66623   preftype      ALIAS FOR $2;
66624   prefid        ALIAS FOR $3;
66625   _c            RECORD;
66626   _ccOrderDesc  TEXT;
66627   _cglaccnt     INTEGER;
66628   _dglaccnt     INTEGER;
66629   _glseriesres  INTEGER;
66630   _notes        TEXT := 'Credit via Credit Card';
66631   _r            RECORD;
66632   _sequence     INTEGER;
66633   _dmaropenid   INTEGER;
66634
66635 BEGIN
66636   IF ((preftype = 'cohead') AND NOT EXISTS(SELECT cohead_id
66637                                              FROM cohead
66638                                              WHERE (cohead_id=prefid))) THEN
66639     RAISE EXCEPTION 'Cannot find original Sales Order for this Credit Card credit [xtuple: postCCcredit, -2, %, %, %]',
66640                     pCCpay, preftype, prefid;
66641   ELSIF ((preftype = 'aropen') AND NOT EXISTS(SELECT aropen_id
66642                                                 FROM aropen
66643                                                 WHERE (aropen_id=prefid))) THEN
66644     RAISE EXCEPTION 'Cannot find original A/R Open record for this Credit Card credit [xtuple: postCCcredit, -2, %, %, %]',
66645                     pCCpay, preftype, prefid;
66646   ELSIF ((preftype = 'cmhead') AND NOT EXISTS(SELECT cmhead_id
66647                                                 FROM cmhead
66648                                                WHERE cmhead_id=prefid)) THEN
66649     RAISE EXCEPTION 'Cannot find original Credit Memo record for this Credit Card credit [xtuple: postCCcredit, -2, %, %, %]',
66650                     pCCpay, preftype, prefid;
66651   END IF;
66652
66653   SELECT * INTO _c
66654      FROM ccpay
66655      JOIN ccard  ON (ccpay_ccard_id = ccard_id)
66656      JOIN ccbank ON (ccard_type=ccbank_ccard_type)
66657     WHERE (ccpay_id = pCCpay);
66658
66659   IF (NOT FOUND) THEN
66660     RAISE EXCEPTION 'Cannot find the record for this Credit Card credit [xtuple: postCCcredit, -3, %, %, %]',
66661                     pCCpay, preftype, prefid;
66662   END IF;
66663
66664   IF (preftype = 'cohead') THEN
66665     _dglaccnt := findPrepaidAccount(_c.ccpay_cust_id);
66666   ELSE
66667     _dglaccnt := findARAccount(_c.ccpay_cust_id);
66668   END IF;
66669
66670   SELECT bankaccnt_accnt_id INTO _cglaccnt
66671   FROM bankaccnt
66672   WHERE (bankaccnt_id=_c.ccbank_bankaccnt_id);
66673
66674   IF (NOT FOUND) THEN
66675     RAISE EXCEPTION 'Cannot find the default Bank Account for this Credit Card [xtuple: postCCcredit, -1, %]',
66676                     pCCpay;
66677   END IF;
66678
66679   IF (_c.ccpay_type != 'R') THEN
66680     RAISE EXCEPTION 'This Credit Card transaction is not a credit/refund [xtuple: postCCcredit, -4, %]',
66681                     pCCpay;
66682   END IF;
66683
66684   _sequence := fetchGLSequence();
66685
66686   IF (_c.ccpay_r_ref IS NOT NULL) THEN
66687     _ccOrderDesc := (_c.ccard_type || '-' || _c.ccpay_r_ref);
66688   ELSE
66689     _ccOrderDesc := (_c.ccard_type || '-' || _c.ccpay_order_number::TEXT ||
66690                      '-' || COALESCE(_c.ccpay_order_number_seq::TEXT, ''));
66691   END IF;
66692
66693   _glseriesres := insertIntoGLSeries(_sequence, 'A/R', 'CC', _ccOrderDesc,
66694                                      _dglaccnt,
66695                                      ROUND(currToBase(_c.ccpay_curr_id,
66696                                                       _c.ccpay_amount,
66697                                                       _c.ccpay_transaction_datetime::DATE), 2) * -1,
66698                                      CURRENT_DATE, _notes);
66699   IF (_glseriesres < 0) THEN
66700     RAISE EXCEPTION 'Could not write debit side of Credit Card credit to the G/L [xtuple: insertIntoGLSeries, %]',
66701                     _glseriesres;
66702   END IF;
66703
66704   _glseriesres := insertIntoGLSeries(_sequence, 'A/R', 'CC', _ccOrderDesc,
66705                                      _cglaccnt,
66706                                      ROUND(currToBase(_c.ccpay_curr_id,
66707                                                       _c.ccpay_amount,
66708                                                       _c.ccpay_transaction_datetime::DATE),2),
66709                                      CURRENT_DATE, _notes);
66710   IF (_glseriesres < 0) THEN
66711     RAISE EXCEPTION 'Could not write credit side of Credit Card credit to the G/L [xtuple: insertIntoGLSeries, %]',
66712                     _glseriesres;
66713   END IF;
66714
66715   _glseriesres := postGLSeries(_sequence, fetchJournalNumber('C/R') );
66716   IF (_glseriesres < 0) THEN
66717     RAISE EXCEPTION 'Could not post Credit Card credit to the G/L [xtuple: postglseries, %]',
66718                     _glseriesres;
66719   END IF;
66720
66721   IF (preftype = 'aropen') THEN
66722     SELECT * INTO _r
66723     FROM aropen
66724     WHERE (aropen_id=prefid);
66725
66726   ELSE
66727     SELECT aropen.* INTO _r
66728     FROM ccpay n
66729       JOIN ccpay o  ON (o.ccpay_id=n.ccpay_ccpay_id)
66730       JOIN payaropen ON (payaropen_ccpay_id=o.ccpay_id)
66731       JOIN aropen ON (payaropen_aropen_id=aropen_id)
66732     WHERE (n.ccpay_id=pCCpay);
66733   END IF;
66734
66735   IF (FOUND) THEN
66736     SELECT createardebitmemo(
66737             NULL, 
66738             _r.aropen_cust_id, NULL, fetchARMemoNumber(),
66739             _r.aropen_ordernumber, current_date, _c.ccpay_amount,
66740             _notes,
66741             -1, -1, -1, CURRENT_DATE, -1, NULL, 0, 
66742             _r.aropen_curr_id) INTO _dmaropenid;
66743
66744     IF (_r.aropen_open) THEN
66745       PERFORM applyARCreditMemoToBalance(_r.aropen_id, _dmaropenid);
66746       PERFORM postARCreditMemoApplication(_r.aropen_id);
66747     END IF;
66748     
66749   END IF;
66750
66751   IF (preftype = 'cohead') THEN
66752     INSERT INTO payco (
66753       payco_ccpay_id, payco_cohead_id, payco_amount, payco_curr_id 
66754     ) VALUES (
66755       pCCpay, prefid, 0 - _c.ccpay_amount, _c.ccpay_curr_id
66756     );
66757   END IF;
66758
66759   RETURN 0;
66760
66761 END;
66762 $_$;
66763
66764
66765 ALTER FUNCTION public.postcccredit(integer, text, integer) OWNER TO admin;
66766
66767 --
66768 -- TOC entry 1993 (class 1255 OID 146566802)
66769 -- Dependencies: 4536 8
66770 -- Name: postccvoid(integer); Type: FUNCTION; Schema: public; Owner: admin
66771 --
66772
66773 CREATE FUNCTION postccvoid(integer) RETURNS integer
66774     LANGUAGE plpgsql
66775     AS $_$
66776 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
66777 -- See www.xtuple.com/CPAL for the full text of the software license.
66778 DECLARE
66779   pccpayid ALIAS FOR $1;
66780
66781 BEGIN
66782   -- for now this is very simple: mark the ccpay record voided.
66783   -- in the future this might be expanded to back out changes to other tables
66784   -- but for now the VOID request is sent to the credit card processing company
66785   -- before those other tables are modified.
66786
66787   UPDATE ccpay SET ccpay_status = 'V' WHERE (ccpay_id=pccpayid);
66788
66789   IF (NOT FOUND) THEN
66790     RETURN -1;
66791   END IF;
66792
66793   RETURN 0;
66794
66795 END;
66796 $_$;
66797
66798
66799 ALTER FUNCTION public.postccvoid(integer) OWNER TO admin;
66800
66801 --
66802 -- TOC entry 1994 (class 1255 OID 146566803)
66803 -- Dependencies: 4536 8
66804 -- Name: postcheck(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
66805 --
66806
66807 CREATE FUNCTION postcheck(integer, integer) RETURNS integer
66808     LANGUAGE plpgsql
66809     AS $_$
66810 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
66811 -- See www.xtuple.com/CPAL for the full text of the software license.
66812 DECLARE
66813   pcheckid              ALIAS FOR $1;
66814   _journalNumber        INTEGER := $2;
66815   _amount_base          NUMERIC := 0;
66816   _credit_glaccnt       INTEGER;
66817   _exchGain             NUMERIC := 0;
66818   _exchGainTmp          NUMERIC := 0;
66819   _gltransNote          TEXT;
66820   _p                    RECORD;
66821   _r                    RECORD;
66822   _t                    RECORD;
66823   _sequence             INTEGER;
66824   _test                 INTEGER;
66825   _cm                   BOOLEAN;
66826   _amount_check         NUMERIC := 0;
66827
66828 BEGIN
66829
66830   _cm := FALSE;
66831
66832   SELECT fetchGLSequence() INTO _sequence;
66833   IF (_journalNumber IS NULL) THEN
66834     _journalNumber := fetchJournalNumber('AP-CK');
66835   END IF;
66836
66837   SELECT checkhead.*,
66838          checkhead_amount / checkhead_curr_rate AS checkhead_amount_base,
66839          bankaccnt_accnt_id AS bankaccntid INTO _p
66840   FROM checkhead
66841    JOIN bankaccnt ON (checkhead_bankaccnt_id=bankaccnt_id)
66842   WHERE (checkhead_id=pcheckid);
66843
66844   IF (FOUND) THEN
66845     IF (_p.checkhead_recip_type = 'V') THEN
66846       SELECT
66847         vend_number AS checkrecip_number,
66848         vend_name AS checkrecip_name,
66849         findAPAccount(vend_id) AS checkrecip_accnt_id,
66850         'A/P'::text AS checkrecip_gltrans_source
66851         INTO _t
66852       FROM vendinfo
66853       WHERE (vend_id=_p.checkhead_recip_id);
66854     ELSIF (_p.checkhead_recip_type = 'C') THEN
66855       SELECT
66856         cust_number AS checkrecip_number,
66857         cust_name AS checkrecip_name,
66858         findARAccount(cust_id) AS checkrecip_accnt_id,
66859         'A/R'::text AS checkrecip_gltrans_source
66860         INTO _t
66861       FROM custinfo
66862       WHERE (cust_id=_p.checkhead_recip_id); 
66863     ELSIF (_p.checkhead_recip_type = 'T') THEN
66864       SELECT
66865         taxauth_code AS checkrecip_number,
66866         taxauth_name AS checkrecip_name,
66867         taxauth_accnt_id AS checkrecip_accnt_id,
66868         'G/L'::text AS checkrecip_gltrans_source
66869         INTO _t
66870       FROM taxauth
66871       WHERE (taxauth_id=_p.checkhead_recip_id);
66872     ELSE
66873       RETURN -11;
66874     END IF;
66875   ELSE
66876     RETURN -11;
66877   END IF;
66878
66879   IF (_p.checkhead_posted) THEN
66880     RETURN -10;
66881   END IF;
66882
66883   IF (_p.checkhead_recip_type = 'C') THEN
66884     SELECT checkitem_id FROM checkitem INTO _test
66885     WHERE (checkitem_checkhead_id=pcheckid)
66886     LIMIT 1;
66887     IF (FOUND) THEN
66888       _cm := TRUE;
66889     END IF;
66890   END IF;
66891
66892   _gltransNote := _t.checkrecip_number || '-' || _t.checkrecip_name;
66893
66894   IF (_p.checkhead_misc AND NOT _cm) THEN
66895     IF (COALESCE(_p.checkhead_expcat_id, -1) < 0) THEN
66896       IF (_p.checkhead_recip_type = 'V') THEN
66897         PERFORM createAPCreditMemo( _p.checkhead_recip_id, _journalNumber,
66898                                     CAST(fetchAPMemoNumber() AS text), '',
66899                                     _p.checkhead_checkdate, _p.checkhead_amount,
66900                                     _gltransNote || ' ' || _p.checkhead_notes,
66901                                     -1, _p.checkhead_checkdate,
66902                                     -1, _p.checkhead_curr_id );
66903         _credit_glaccnt := findAPPrepaidAccount(_p.checkhead_recip_id);
66904
66905       ELSIF (_p.checkhead_recip_type = 'C') THEN
66906         PERFORM createARDebitMemo(NULL, _p.checkhead_recip_id, NULL,
66907                                      fetchARMemoNumber(), '',
66908                                      _p.checkhead_checkdate, _p.checkhead_amount,
66909                                      _gltransNote || ' ' || _p.checkhead_notes,
66910                                      -1, -1, -1, _p.checkhead_checkdate, -1, NULL, 0,
66911                                      _p.checkhead_curr_id );
66912         _credit_glaccnt := findPrepaidAccount(_p.checkhead_recip_id);
66913       ELSIF (_p.checkhead_recip_type = 'T') THEN
66914         -- TODO: should we create a credit memo for the tax authority? how?
66915         _credit_glaccnt := _t.checkrecip_accnt_id;
66916
66917       END IF; -- recip type
66918
66919     ELSE
66920       IF (_cm) THEN
66921         _credit_glaccnt := findARAccount(_p.checkhead_recip_id);
66922       ELSE
66923         SELECT expcat_exp_accnt_id INTO _credit_glaccnt
66924         FROM expcat
66925         WHERE (expcat_id=_p.checkhead_expcat_id);
66926         IF (NOT FOUND) THEN
66927           RETURN -12;
66928         END IF;
66929       END IF;
66930     END IF;
66931
66932     IF (COALESCE(_credit_glaccnt, -1) < 0) THEN
66933       RETURN -13;
66934     END IF;
66935
66936     PERFORM insertIntoGLSeries( _sequence, _t.checkrecip_gltrans_source, 'CK',
66937                                 CAST(_p.checkhead_number AS TEXT),
66938                                 _credit_glaccnt,
66939                                 round(_p.checkhead_amount_base, 2) * -1,
66940                                 _p.checkhead_checkdate, _gltransNote, pcheckid );
66941
66942     _amount_base := _p.checkhead_amount_base;
66943
66944   ELSE
66945     FOR _r IN SELECT checkitem_amount, checkitem_discount,
66946                      CASE WHEN (checkitem_apopen_id IS NOT NULL AND apopen_doctype='C') THEN
66947                             checkitem_amount / apopen_curr_rate * -1.0
66948                           WHEN (checkitem_apopen_id IS NOT NULL) THEN
66949                             checkitem_amount / apopen_curr_rate
66950                           ELSE
66951                             currToBase(checkitem_curr_id,
66952                                        checkitem_amount,
66953                                        COALESCE(checkitem_docdate, _p.checkhead_checkdate)) 
66954                      END AS checkitem_amount_base,
66955                      currTocurr(checkitem_curr_id, _p.checkhead_curr_id,
66956                                 CASE WHEN (checkitem_apopen_id IS NOT NULL AND apopen_doctype='C') THEN
66957                                           checkitem_amount * -1.0
66958                                      ELSE checkitem_amount END,
66959                                   _p.checkhead_checkdate) AS amount_check,
66960                      apopen_id, apopen_doctype, apopen_docnumber,
66961                      aropen_id, aropen_doctype, aropen_docnumber,
66962                      checkitem_curr_id, checkitem_curr_rate, apopen_curr_rate,
66963                      COALESCE(checkitem_docdate, _p.checkhead_checkdate) AS docdate
66964               FROM (checkitem LEFT OUTER JOIN
66965                     apopen ON (checkitem_apopen_id=apopen_id)) LEFT OUTER JOIN
66966                     aropen ON (checkitem_aropen_id=aropen_id)
66967               WHERE (checkitem_checkhead_id=pcheckid) LOOP
66968
66969       _exchGainTmp := 0;
66970       IF (_r.apopen_id IS NOT NULL) THEN
66971         --  take the discount if specified before we do anything else
66972         IF(_r.checkitem_discount > 0.0) THEN
66973           PERFORM createAPDiscount(_r.apopen_id, _r.checkitem_discount);
66974         END IF;
66975
66976         UPDATE apopen
66977
66978         SET apopen_paid = round(apopen_paid + _r.checkitem_amount, 2),
66979             apopen_open = round(apopen_amount, 2) >
66980                           round(apopen_paid + _r.checkitem_amount, 2),
66981             apopen_closedate = CASE WHEN (round(apopen_amount, 2) <=
66982                                           round(apopen_paid + _r.checkitem_amount, 2)) THEN _p.checkhead_checkdate END
66983         WHERE (apopen_id=_r.apopen_id);
66984
66985         --  Post the application
66986         INSERT INTO apapply
66987         ( apapply_vend_id, apapply_postdate, apapply_username,
66988           apapply_source_apopen_id, apapply_source_doctype, apapply_source_docnumber,
66989           apapply_target_apopen_id, apapply_target_doctype, apapply_target_docnumber,
66990           apapply_journalnumber, apapply_amount, apapply_curr_id, apapply_checkhead_id )
66991         VALUES
66992         ( _p.checkhead_recip_id, _p.checkhead_checkdate, getEffectiveXtUser(),
66993           -1, 'K', _p.checkhead_number,
66994           _r.apopen_id, _r.apopen_doctype, _r.apopen_docnumber,
66995           _journalNumber, _r.checkitem_amount, _r.checkitem_curr_id, _p.checkhead_id );
66996       END IF; -- if check item's apopen_id is not null
66997
66998       IF (_r.aropen_id IS NOT NULL) THEN
66999
67000         UPDATE aropen
67001         SET aropen_paid = round(aropen_paid + _r.checkitem_amount, 2),
67002             aropen_open = round(aropen_amount, 2) >
67003                           round(aropen_paid + _r.checkitem_amount, 2),
67004             aropen_closedate = CASE WHEN (round(aropen_amount, 2) <=
67005                                           round(aropen_paid + _r.checkitem_amount, 2)) THEN _p.checkhead_checkdate END
67006         WHERE (aropen_id=_r.aropen_id);
67007
67008         --  Post the application
67009         INSERT INTO arapply
67010         ( arapply_cust_id, arapply_postdate, arapply_distdate, arapply_username,
67011           arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
67012           arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
67013           arapply_journalnumber, arapply_applied, arapply_curr_id )
67014         VALUES
67015         ( _p.checkhead_recip_id, _p.checkhead_checkdate, _p.checkhead_checkdate, getEffectiveXtUser(),
67016           _r.aropen_id,_r.aropen_doctype, _r.aropen_docnumber,
67017           -1, 'K',_p.checkhead_number ,
67018           _journalNumber, _r.checkitem_amount, _r.checkitem_curr_id );
67019
67020       END IF; -- if check item's aropen_id is not null
67021
67022       IF (_r.apopen_id IS NOT NULL) THEN
67023         SELECT apCurrGain(_r.apopen_id,_r.checkitem_curr_id, _r.checkitem_amount,
67024                         _p.checkhead_checkdate)
67025               INTO _exchGainTmp;
67026       ELSIF (_r.aropen_id IS NOT NULL) THEN
67027         SELECT arCurrGain(_r.aropen_id,_r.checkitem_curr_id, _r.checkitem_amount,
67028                         _p.checkhead_checkdate)
67029               INTO _exchGainTmp;
67030       END IF;
67031       _exchGain := _exchGain + _exchGainTmp;
67032
67033       PERFORM insertIntoGLSeries( _sequence, _t.checkrecip_gltrans_source,
67034                                   'CK', CAST(_p.checkhead_number AS TEXT),
67035                                   _t.checkrecip_accnt_id,
67036                                   round(_r.checkitem_amount_base, 2) * -1.0,
67037                                   _p.checkhead_checkdate, _gltransNote, pcheckid );
67038       IF (_exchGainTmp <> 0) THEN
67039         PERFORM insertIntoGLSeries( _sequence, _t.checkrecip_gltrans_source,
67040                                    'CK', CAST(_p.checkhead_number AS TEXT),
67041                                    getGainLossAccntId(_t.checkrecip_accnt_id),
67042                                    round(_exchGainTmp,2),
67043                                    _p.checkhead_checkdate, _gltransNote, pcheckid );
67044       END IF;
67045
67046       _amount_check := (_amount_check + _r.amount_check);
67047       _amount_base := (_amount_base + _r.checkitem_amount_base);
67048
67049     END LOOP;
67050
67051     IF( (_amount_check - _p.checkhead_amount) <> 0.0 ) THEN 
67052       _exchGainTmp := currToBase(_p.checkhead_curr_id,
67053                                  _amount_check - _p.checkhead_amount,
67054                                  _p.checkhead_checkdate);
67055       _exchGain := _exchGain + _exchGainTmp;
67056     END IF;
67057     --  ensure that the check balances, attribute rounding errors to gain/loss
67058     IF round(_amount_base, 2) - round(_exchGain, 2) <> round(_p.checkhead_amount_base, 2) THEN
67059       IF round(_amount_base - _exchGain, 2) = round(_p.checkhead_amount_base, 2) THEN
67060         PERFORM insertIntoGLSeries( _sequence, _t.checkrecip_gltrans_source,
67061                                     'CK',
67062                                     CAST(_p.checkhead_number AS TEXT),
67063                                     getGainLossAccntId(_p.bankaccntid),
67064                                     round(_amount_base, 2) -
67065                                       round(_exchGain, 2) -
67066                                       round(_p.checkhead_amount_base, 2),
67067                                     _p.checkhead_checkdate, _gltransNote, pcheckid );
67068       ELSE
67069         RAISE EXCEPTION 'checkhead_id % does not balance (% - % <> %)', pcheckid,
67070               _amount_base, _exchGain, _p.checkhead_amount_base;
67071       END IF;
67072     END IF;
67073   END IF;
67074
67075   PERFORM insertIntoGLSeries( _sequence, _t.checkrecip_gltrans_source, 'CK',
67076                               CAST(_p.checkhead_number AS TEXT),
67077                               _p.bankaccntid,
67078                               round(_p.checkhead_amount_base, 2),
67079                               _p.checkhead_checkdate, _gltransNote, pcheckid );
67080
67081   PERFORM postGLSeries(_sequence, _journalNumber);
67082
67083   UPDATE checkhead
67084   SET checkhead_posted=TRUE,
67085       checkhead_journalnumber=_journalNumber
67086   WHERE (checkhead_id=pcheckid);
67087
67088   RETURN _journalNumber;
67089
67090 END;
67091 $_$;
67092
67093
67094 ALTER FUNCTION public.postcheck(integer, integer) OWNER TO admin;
67095
67096 --
67097 -- TOC entry 1995 (class 1255 OID 146566805)
67098 -- Dependencies: 4536 8
67099 -- Name: postchecks(integer); Type: FUNCTION; Schema: public; Owner: admin
67100 --
67101
67102 CREATE FUNCTION postchecks(integer) RETURNS integer
67103     LANGUAGE plpgsql
67104     AS $_$
67105 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67106 -- See www.xtuple.com/CPAL for the full text of the software license.
67107 DECLARE
67108   pBankaccntid ALIAS FOR $1;
67109   _journalNumber INTEGER;
67110
67111 BEGIN
67112
67113   SELECT fetchJournalNumber('AP-CK') INTO _journalNumber;
67114
67115   PERFORM postCheck(checkhead_id, _journalNumber)
67116   FROM checkhead
67117   WHERE ( (NOT checkhead_void)
67118     AND   (NOT checkhead_posted)
67119     AND   (checkhead_printed)
67120     AND   (checkhead_bankaccnt_id=pBankaccntid) );
67121
67122   RETURN _journalNumber;
67123
67124 END;
67125 $_$;
67126
67127
67128 ALTER FUNCTION public.postchecks(integer) OWNER TO admin;
67129
67130 --
67131 -- TOC entry 1996 (class 1255 OID 146566806)
67132 -- Dependencies: 4536 8
67133 -- Name: postcomment(integer, text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
67134 --
67135
67136 CREATE FUNCTION postcomment(pcmnttypeid integer, psource text, psourceid integer, ptext text) RETURNS integer
67137     LANGUAGE plpgsql
67138     AS $$
67139 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67140 -- See www.xtuple.com/CPAL for the full text of the software license.
67141 DECLARE
67142
67143 BEGIN
67144   RETURN postComment(pCmnttypeid, pSource, pSourceid, pText, NULL);
67145 END
67146 $$;
67147
67148
67149 ALTER FUNCTION public.postcomment(pcmnttypeid integer, psource text, psourceid integer, ptext text) OWNER TO admin;
67150
67151 --
67152 -- TOC entry 1998 (class 1255 OID 146566808)
67153 -- Dependencies: 4536 8
67154 -- Name: postcomment(text, text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
67155 --
67156
67157 CREATE FUNCTION postcomment(pcmnttypename text, psource text, psourceid integer, ptext text) RETURNS integer
67158     LANGUAGE plpgsql
67159     AS $$
67160 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67161 -- See www.xtuple.com/CPAL for the full text of the software license.
67162 DECLARE
67163   _cmnttypeid INTEGER;
67164
67165 BEGIN
67166   SELECT cmnttype_id INTO _cmnttypeid
67167   FROM cmnttype
67168   WHERE (cmnttype_name=pCmnttypename);
67169   IF (NOT FOUND) THEN
67170     RAISE EXCEPTION 'Comment type % not found.', pCmnttypename;
67171   END IF;
67172
67173   RETURN postComment(_cmnttypeid, pSource, pSourceid, pText, NULL);
67174 END
67175 $$;
67176
67177
67178 ALTER FUNCTION public.postcomment(pcmnttypename text, psource text, psourceid integer, ptext text) OWNER TO admin;
67179
67180 --
67181 -- TOC entry 1997 (class 1255 OID 146566807)
67182 -- Dependencies: 4536 8
67183 -- Name: postcomment(integer, text, integer, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
67184 --
67185
67186 CREATE FUNCTION postcomment(pcmnttypeid integer, psource text, psourceid integer, ptext text, ppublic boolean) RETURNS integer
67187     LANGUAGE plpgsql
67188     AS $$
67189 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67190 -- See www.xtuple.com/CPAL for the full text of the software license.
67191 DECLARE
67192   _commentid INTEGER;
67193   _public BOOLEAN;
67194
67195 BEGIN
67196   _public := COALESCE(pPublic, fetchmetricbool('CommentPublicDefault'));
67197
67198   INSERT INTO comment
67199   ( comment_cmnttype_id, comment_source, comment_source_id,
67200     comment_date, comment_user, comment_text, comment_public )
67201   VALUES
67202   ( pCmnttypeid, pSource, pSourceid,
67203     CURRENT_TIMESTAMP, getEffectiveXtUser(), pText, _public )
67204   RETURNING comment_id INTO _commentid;
67205
67206   RETURN _commentid;
67207
67208 END;
67209 $$;
67210
67211
67212 ALTER FUNCTION public.postcomment(pcmnttypeid integer, psource text, psourceid integer, ptext text, ppublic boolean) OWNER TO admin;
67213
67214 --
67215 -- TOC entry 1999 (class 1255 OID 146566809)
67216 -- Dependencies: 4536 8
67217 -- Name: postcost(integer); Type: FUNCTION; Schema: public; Owner: admin
67218 --
67219
67220 CREATE FUNCTION postcost(integer) RETURNS boolean
67221     LANGUAGE plpgsql
67222     AS $_$
67223 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67224 -- See www.xtuple.com/CPAL for the full text of the software license.
67225 DECLARE
67226   pItemcostid ALIAS FOR $1;
67227   _p RECORD;
67228
67229 BEGIN
67230
67231   SELECT round(currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE),6) AS newcost,
67232          itemcost_curr_id, CURRENT_DATE AS effective,
67233          item_number,
67234          itemcost_stdcost AS oldcost INTO _p
67235   FROM itemcost, item
67236   WHERE ((itemcost_item_id=item_id)
67237     AND  (itemcost_id=pItemcostid));
67238
67239   IF (_p.newcost IS NULL) THEN
67240       RAISE EXCEPTION 'There is no valid Exchange Rate for this currency. (%, %)',
67241                   _p.itemcost_curr_id, _p.effective;
67242       RETURN FALSE;
67243   END IF;
67244
67245   RETURN updateStdCost(pItemcostid, _p.newcost, _p.oldcost, 'Post Cost',
67246                ('Post Actual Cost to Standard for item ' || _p.item_number));
67247
67248 END;
67249 $_$;
67250
67251
67252 ALTER FUNCTION public.postcost(integer) OWNER TO admin;
67253
67254 --
67255 -- TOC entry 2001 (class 1255 OID 146566810)
67256 -- Dependencies: 4536 8
67257 -- Name: postcountslip(integer); Type: FUNCTION; Schema: public; Owner: admin
67258 --
67259
67260 CREATE FUNCTION postcountslip(integer) RETURNS integer
67261     LANGUAGE plpgsql
67262     AS $_$
67263 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67264 -- See www.xtuple.com/CPAL for the full text of the software license.
67265 DECLARE
67266   pCntslipid ALIAS FOR $1;
67267   _p RECORD;
67268   _comments TEXT;
67269   _temp TEXT;
67270
67271 BEGIN
67272
67273   SELECT itemsite_loccntrl, itemsite_controlmethod,
67274          cntslip_posted, cntslip_lotserial, cntslip_comments,
67275          cntslip_number, cntslip_qty INTO _p
67276   FROM cntslip, invcnt, itemsite
67277   WHERE ( (cntslip_cnttag_id=invcnt_id)
67278    AND (invcnt_itemsite_id=itemsite_id)
67279    AND (cntslip_id=pCntslipid) );
67280
67281   IF (NOT _p.cntslip_posted) THEN
67282     SELECT ( E'\nCount Slip #' || _p.cntslip_number ||
67283              ' counted ' || formatQty(_p.cntslip_qty) ) INTO _comments;
67284
67285 --  Add the Location name if the itemsite is MLC
67286     IF (_p.itemsite_loccntrl) THEN
67287       SELECT ( ', Location:' || location_name ) INTO _temp
67288       FROM location, cntslip
67289       WHERE ( (cntslip_location_id=location_id)
67290        AND (cntslip_id=pCntslipid) );
67291
67292       _comments := (_comments || _temp);
67293     END IF;
67294
67295 --  Add the Lot/Serial if the itemsite is Lot or Serial controlled
67296     IF (_p.itemsite_controlmethod = 'L') THEN
67297       _comments := (_comments || ( ', Lot #:' || _p.cntslip_lotserial));
67298     ELSIF (_p.itemsite_controlmethod = 'S') THEN
67299       _comments := (_comments || ( ', Serial #:' || _p.cntslip_lotserial));
67300     END IF;
67301
67302     _comments := (_comments || ' ' || _p.cntslip_comments);
67303
67304     UPDATE cntslip
67305     SET cntslip_posted=TRUE
67306     WHERE (cntslip_id=pCntslipid);
67307
67308     UPDATE invcnt
67309     SET invcnt_qoh_after = ( COALESCE(invcnt_qoh_after, 0) + cntslip_qty),
67310         invcnt_comments = (invcnt_comments || _comments)
67311     FROM cntslip
67312     WHERE ( (cntslip_cnttag_id=invcnt_id)
67313      AND (cntslip_id=pCntslipid) );
67314
67315     RETURN 1;
67316
67317   ELSE
67318     RETURN -1;
67319   END IF;
67320
67321 END;
67322 $_$;
67323
67324
67325 ALTER FUNCTION public.postcountslip(integer) OWNER TO admin;
67326
67327 --
67328 -- TOC entry 2002 (class 1255 OID 146566811)
67329 -- Dependencies: 4536 8
67330 -- Name: postcounttag(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
67331 --
67332
67333 CREATE FUNCTION postcounttag(integer, boolean) RETURNS integer
67334     LANGUAGE plpgsql
67335     AS $_$
67336 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67337 -- See www.xtuple.com/CPAL for the full text of the software license.
67338 DECLARE
67339   pInvcntid ALIAS FOR $1;
67340   pThaw ALIAS FOR $2;
67341   _avgCostingMethod TEXT;
67342   _invhistid INTEGER;
67343   _postDate TIMESTAMP;
67344   _runningQty NUMERIC;
67345   _errorCode INTEGER;
67346   _itemlocSeries INTEGER := 0;
67347   _hasDetail BOOLEAN;
67348   _p RECORD;
67349   _itemloc RECORD;
67350   _cntslip RECORD;
67351   _lsid INTEGER;
67352
67353 BEGIN
67354
67355   SELECT COALESCE(fetchMetricText('CountAvgCostMethod'), 'STD') INTO _avgCostingMethod;
67356
67357   SELECT invcnt_id, invcnt_tagnumber, invcnt_qoh_after,
67358          invcnt_location_id,
67359          item_number,
67360          itemsite_id, itemsite_freeze,
67361          itemsite_qtyonhand,
67362          itemsite_loccntrl, itemsite_location_id,
67363          CASE WHEN (itemsite_costmethod = 'N') THEN 0
67364               WHEN ( (itemsite_costmethod = 'A') AND
67365                      (itemsite_qtyonhand = 0) AND
67366                      (_avgCostingMethod = 'ACT') ) THEN actcost(itemsite_item_id)
67367               WHEN ( (itemsite_costmethod = 'A') AND
67368                      (_avgCostingMethod IN ('ACT', 'AVG')) ) THEN avgcost(itemsite_id)
67369               ELSE stdcost(itemsite_item_id)
67370          END AS cost, itemsite_costmethod,
67371          itemsite_controlmethod,
67372          itemsite_value INTO _p
67373   FROM invcnt, itemsite, item
67374   WHERE ( (invcnt_itemsite_id=itemsite_id)
67375    AND (itemsite_item_id=item_id)
67376    AND (invcnt_qoh_after IS NOT NULL)
67377    AND (NOT invcnt_posted)
67378    AND (invcnt_id=pInvcntid) );
67379   IF (FOUND) THEN
67380 -- If the invcnt_location_id is not null then
67381 -- call a separate function so as not to affect
67382 -- the existing functionality.
67383     IF (_p.invcnt_location_id IS NOT NULL) THEN
67384       RETURN postCountTagLocation(pInvcntid, pThaw);
67385     END IF;
67386
67387     SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
67388
67389     IF (_p.itemsite_freeze) THEN
67390       SELECT invcnt_tagdate INTO _postDate
67391       FROM invcnt
67392       WHERE (invcnt_id=pInvcntid) ;
67393     ELSE
67394       _postDate = CURRENT_TIMESTAMP;
67395     END IF;
67396
67397     _hasDetail = FALSE;
67398
67399 --  Post the detail indicated by cntslips
67400     IF ( (_p.itemsite_loccntrl) OR
67401          (_p.itemsite_controlmethod IN ('L', 'S')) ) THEN
67402
67403       SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
67404
67405 --  Adjust any existing detail to 0
67406       FOR _itemloc IN SELECT itemloc_id, itemloc_location_id,
67407                              itemloc_ls_id, itemloc_qty
67408                       FROM itemloc
67409                       WHERE (itemloc_itemsite_id=_p.itemsite_id) LOOP
67410
67411         _hasDetail = TRUE;
67412
67413 --  Create the itemlocdist flushing records
67414         INSERT INTO itemlocdist
67415         ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67416           itemlocdist_expiration,
67417           itemlocdist_itemsite_id, itemlocdist_invhist_id, itemlocdist_flush )
67418         VALUES
67419         ( _itemlocSeries, 'I', _itemloc.itemloc_id,
67420           endOfTime(),
67421           _p.itemsite_id, _invhistid, TRUE );
67422
67423       END LOOP;
67424
67425 --  Clear the running detail Qty
67426       _runningQty := 0;
67427
67428 --  Adjust the detail to the cntslip indicated value
67429       FOR _cntslip IN SELECT cntslip_location_id, cntslip_lotserial,
67430                              cntslip_lotserial_expiration,
67431                              cntslip_lotserial_warrpurc,
67432                              SUM(cntslip_qty) AS qty,
67433                              itemsite_item_id
67434                       FROM cntslip, invcnt, itemsite
67435                       WHERE ((cntslip_cnttag_id=pInvcntid)
67436                       AND (cntslip_cnttag_id=invcnt_id)
67437                       AND (invcnt_itemsite_id=itemsite_id))
67438                       GROUP BY cntslip_location_id, cntslip_lotserial, 
67439                       cntslip_lotserial_expiration, cntslip_lotserial_warrpurc,itemsite_item_id LOOP
67440
67441 --  Handle the LotSerial
67442         IF (LENGTH(_cntslip.cntslip_lotserial)>0) THEN
67443           SELECT ls_id INTO _lsid
67444           FROM ls
67445           WHERE ((ls_item_id=_cntslip.itemsite_item_id)
67446           AND (UPPER(ls_number)=UPPER(_cntslip.cntslip_lotserial)));
67447
67448           IF (NOT FOUND) THEN
67449             _lsid := NEXTVAL('ls_ls_id_seq');
67450             INSERT INTO ls
67451             VALUES (_lsid,_cntslip.itemsite_item_id,UPPER(_cntslip.cntslip_lotserial));
67452           END IF;
67453         END IF;
67454
67455 --  Track the running Qty
67456         _runningQty := (_runningQty + _cntslip.qty);
67457         _hasDetail = TRUE;
67458
67459 --  Create the itemlocdist populating record
67460         INSERT INTO itemlocdist
67461         ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67462           itemlocdist_itemsite_id,
67463           itemlocdist_ls_id, itemlocdist_expiration, itemlocdist_warranty,
67464           itemlocdist_qty, itemlocdist_invhist_id )
67465         VALUES
67466         ( _itemlocSeries, 'L', _cntslip.cntslip_location_id,
67467           _p.itemsite_id,
67468           _lsid, COALESCE(_cntslip.cntslip_lotserial_expiration, endOfTime()),
67469           _cntslip.cntslip_lotserial_warrpurc,_cntslip.qty, _invhistid );
67470
67471       END LOOP;
67472
67473       IF (_runningQty > _p.invcnt_qoh_after) THEN
67474 --  The total Count Slip Qty is greater than the Count Tag Qty,
67475 --  Don't post the Count.
67476         _errorCode = -1;
67477
67478       ELSIF ( (_runningQty < _p.invcnt_qoh_after) AND
67479               (_p.itemsite_controlmethod IN ('L', 'S')) ) THEN
67480 --  The total Count Slip Qty is less than the Count Tag Qty,
67481 --  and the Item Site is Lot/Serial controlled.
67482 --  Don't post the Count.
67483         _errorCode = -2;
67484
67485       ELSIF (_runningQty < _p.invcnt_qoh_after) THEN
67486         IF ( (NOT _p.itemsite_loccntrl) OR
67487              (_p.itemsite_location_id = -1) ) THEN
67488 --  The total Count Slip Qty is less than the Count Tag Qty,
67489 --  and there isn't a default location to post into.
67490 --  Don't post the Count.
67491           _errorCode = -3;
67492
67493         ELSIF ( SELECT (metric_value='f')
67494                 FROM metric
67495                 WHERE (metric_name='PostCountTagToDefault') ) THEN
67496 --  The total Count Slip Qty is less than the Count Tag Qty,
67497 --  and we don't post Count Tags to default Locations
67498 --  Don't post the Count.
67499           _errorCode = -4;
67500
67501         ELSE
67502 --  Distribute the remaining qty into the default location.
67503           INSERT INTO itemlocdist
67504           ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67505             itemlocdist_itemsite_id,
67506             itemlocdist_expiration,
67507             itemlocdist_qty, itemlocdist_invhist_id )
67508           SELECT _itemlocSeries, 'L', _p.itemsite_location_id,
67509                  _p.itemsite_id,
67510                  endOfTime(),
67511                  (_p.invcnt_qoh_after - _runningQty), _invhistid;
67512
67513           _hasDetail = TRUE;
67514           _errorCode = 0;
67515         END IF;
67516       ELSE
67517 --  The Count Slip Qty. must equal the Count Tag Qty.
67518         _errorCode = 0;
67519       END IF;
67520
67521 --  If we shouldn't post the count then delete the itemlocdist records,
67522 --  and return with the error.
67523       IF (_errorCode <> 0) THEN
67524         DELETE FROM itemlocdist
67525         WHERE (itemlocdist_series=_itemlocSeries);
67526   
67527         RETURN _errorCode;
67528       END IF;
67529
67530     END IF;
67531
67532 --  Mod. the Count Tag.
67533     UPDATE invcnt
67534     SET invcnt_qoh_before=_p.itemsite_qtyonhand,
67535         invcnt_postdate=_postDate,
67536         invcnt_posted=TRUE,
67537         invcnt_invhist_id=_invhistid,
67538         invcnt_post_username=getEffectiveXtUser()
67539     WHERE (invcnt_id=pInvcntid);
67540
67541 --  Create the CC transaction
67542     INSERT INTO invhist
67543      ( invhist_id, invhist_itemsite_id,
67544        invhist_transdate, invhist_transtype, invhist_invqty,
67545        invhist_qoh_before, invhist_qoh_after,
67546        invhist_docnumber, invhist_comments,
67547        invhist_invuom, invhist_unitcost, invhist_hasdetail,
67548        invhist_costmethod, invhist_value_before, invhist_value_after,
67549        invhist_series )
67550     SELECT _invhistid, itemsite_id,
67551            _postDate, 'CC', (invcnt_qoh_after - invcnt_qoh_before),
67552            invcnt_qoh_before, invcnt_qoh_after,
67553            invcnt_tagnumber, invcnt_comments,
67554            uom_name, _p.cost, _hasDetail,
67555            _p.itemsite_costmethod, _p.itemsite_value, 
67556            _p.itemsite_value + (_p.cost * (invcnt_qoh_after - invcnt_qoh_before)),
67557            _itemlocSeries
67558     FROM itemsite, invcnt, item, uom
67559     WHERE ( (invcnt_itemsite_id=itemsite_id)
67560      AND (itemsite_item_id=item_id)
67561      AND (item_inv_uom_id=uom_id)
67562      AND (itemsite_controlmethod <> 'N')
67563      AND (invcnt_id=pInvcntid) );
67564
67565     IF ( SELECT metric_value
67566         FROM metric
67567         WHERE ((metric_name = 'EnableAsOfQOH')
67568         AND (metric_value = 't'))) THEN
67569       IF (NOT postIntoInvBalance(_invhistid)) THEN
67570         RAISE EXCEPTION 'Post into Inventory Balance for invhist_id=% was unsuccessful',_invhistid;
67571       END IF;
67572     END IF;
67573
67574 --  Update the QOH
67575 --  Avoid negative value when average cost item
67576     UPDATE itemsite
67577     SET itemsite_qtyonhand=_p.invcnt_qoh_after,
67578         itemsite_nnqoh = 0,
67579         itemsite_value = CASE WHEN ((itemsite_costmethod='A') AND (_p.itemsite_value + (_p.cost * (_p.invcnt_qoh_after - itemsite_qtyonhand))) < 0.0) THEN 0.0
67580                               ELSE (_p.itemsite_value + (_p.cost * (_p.invcnt_qoh_after - itemsite_qtyonhand)))
67581                          END,
67582         itemsite_datelastcount=_postDate
67583     WHERE (itemsite_id=_p.itemsite_id);
67584  
67585 --  Post the detail, if any
67586     IF (_hasDetail) THEN
67587       PERFORM distributeItemlocSeries(_itemlocSeries);
67588     END IF;
67589
67590 --  Thaw the itemsite if it's frozen
67591     IF (pThaw) THEN
67592       PERFORM thawItemSite(invcnt_itemsite_id) 
67593       FROM invcnt
67594       WHERE (invcnt_id=pInvcntid);
67595     END IF;
67596
67597 --  Distribute to G/L
67598     PERFORM insertGLTransaction( 'I/M', 'CT', _p.invcnt_tagnumber, ('Post Count Tag #' || _p.invcnt_tagnumber || ' for Item ' || _p.item_number),
67599                                  costcat_adjustment_accnt_id, costcat_asset_accnt_id, _invhistid,
67600                                  ( (_p.invcnt_qoh_after - _p.itemsite_qtyonhand) * _p.cost), _postDate::DATE )
67601     FROM invcnt, itemsite, costcat
67602     WHERE ( (invcnt_itemsite_id=itemsite_id)
67603      AND (itemsite_costcat_id=costcat_id)
67604      AND (invcnt_id=pInvcntid) );
67605
67606     RETURN 0;
67607
67608   ELSE
67609     RETURN -9;
67610   END IF;
67611
67612 END;
67613 $_$;
67614
67615
67616 ALTER FUNCTION public.postcounttag(integer, boolean) OWNER TO admin;
67617
67618 --
67619 -- TOC entry 2003 (class 1255 OID 146566813)
67620 -- Dependencies: 4536 8
67621 -- Name: postcounttaglocation(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
67622 --
67623
67624 CREATE FUNCTION postcounttaglocation(integer, boolean) RETURNS integer
67625     LANGUAGE plpgsql
67626     AS $_$
67627 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
67628 -- See www.xtuple.com/CPAL for the full text of the software license.
67629 DECLARE
67630   pInvcntid ALIAS FOR $1;
67631   pThaw ALIAS FOR $2;
67632   _avgCostingMethod TEXT;
67633   _invhistid INTEGER;
67634   _postDate TIMESTAMP;
67635   _runningQty NUMERIC;
67636   _errorCode INTEGER;
67637   _itemlocSeries INTEGER := 0;
67638   _hasDetail BOOLEAN;
67639   _p RECORD;
67640   _itemloc RECORD;
67641   _cntslip RECORD;
67642   _origLocQty NUMERIC;
67643   _netable BOOLEAN;
67644   _lsid INTEGER;
67645 BEGIN
67646
67647   SELECT COALESCE(fetchMetricText('CountAvgCostMethod'), 'STD') INTO _avgCostingMethod;
67648
67649   SELECT invcnt_id, invcnt_tagnumber, invcnt_qoh_after,
67650          invcnt_location_id, invcnt_tagdate,
67651          item_number,
67652          itemsite_id, itemsite_freeze,
67653          itemsite_qtyonhand,
67654          itemsite_loccntrl, COALESCE(invcnt_location_id, -1) AS itemsite_location_id,
67655          CASE WHEN (itemsite_costmethod = 'N') THEN 0
67656               WHEN ( (itemsite_costmethod = 'A') AND
67657                      (itemsite_qtyonhand = 0) AND
67658                      (_avgCostingMethod = 'ACT') ) THEN actcost(itemsite_item_id)
67659               WHEN ( (itemsite_costmethod = 'A') AND
67660                      (_avgCostingMethod IN ('ACT', 'AVG')) ) THEN avgcost(itemsite_id)
67661               ELSE stdcost(itemsite_item_id)
67662          END AS cost, itemsite_costmethod,
67663          itemsite_controlmethod, itemsite_value INTO _p
67664   FROM invcnt, itemsite, item
67665   WHERE ( (invcnt_itemsite_id=itemsite_id)
67666    AND (itemsite_item_id=item_id)
67667    AND (invcnt_qoh_after IS NOT NULL)
67668    AND (NOT invcnt_posted)
67669    AND (invcnt_id=pInvcntid) );
67670   IF (NOT FOUND) THEN
67671     RETURN -9;
67672   END IF;
67673
67674   SELECT COALESCE(SUM(itemloc_qty),0.0), location_netable INTO _origLocQty,_netable
67675     FROM itemloc,location
67676    WHERE ((itemloc_itemsite_id=_p.itemsite_id)
67677      AND  (location_id=itemloc_location_id)
67678      AND  (itemloc_location_id=_p.invcnt_location_id))
67679    GROUP BY location_netable;
67680   IF (NOT FOUND) THEN
67681     _origLocQty := 0.0;
67682     _netable := TRUE;
67683   END IF;
67684
67685   SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
67686
67687   IF (_p.itemsite_freeze) THEN
67688     _postDate := _p.invcnt_tagdate;
67689   ELSE
67690     _postDate := CURRENT_TIMESTAMP;
67691   END IF;
67692
67693   _hasDetail = FALSE;
67694
67695 --  Post the detail indicated by cntslips
67696   IF ( (_p.itemsite_loccntrl) OR
67697        (_p.itemsite_controlmethod IN ('L', 'S')) ) THEN
67698
67699     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
67700
67701 --  Adjust any existing detail to 0
67702     FOR _itemloc IN SELECT itemloc_id, itemloc_location_id,
67703                            itemloc_ls_id, itemloc_qty
67704                     FROM itemloc
67705                     WHERE ((itemloc_itemsite_id=_p.itemsite_id)
67706                       AND  (itemloc_location_id=_p.invcnt_location_id)) LOOP
67707
67708       _hasDetail = TRUE;
67709
67710 --  Create the itemlocdist flushing records
67711       INSERT INTO itemlocdist
67712       ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67713         itemlocdist_expiration,
67714         itemlocdist_itemsite_id, itemlocdist_invhist_id, itemlocdist_flush )
67715       VALUES
67716       ( _itemlocSeries, 'I', _itemloc.itemloc_id,
67717         endOfTime(),
67718         _p.itemsite_id, _invhistid, TRUE );
67719
67720     END LOOP;
67721
67722 --  Clear the running detail Qty
67723     _runningQty := 0;
67724
67725 --  Adjust the detail to the cntslip indicated value
67726     FOR _cntslip IN SELECT cntslip_location_id, cntslip_lotserial,
67727                            cntslip_lotserial_expiration,
67728                            cntslip_lotserial_warrpurc,
67729                            SUM(cntslip_qty) AS qty,
67730                            itemsite_item_id
67731                     FROM cntslip,invcnt,itemsite
67732                     WHERE ((cntslip_cnttag_id=pInvcntid)
67733                     AND (cntslip_cnttag_id=invcnt_id)
67734                     AND (invcnt_itemsite_id=itemsite_id))
67735                     GROUP BY cntslip_location_id, cntslip_lotserial, cntslip_lotserial_expiration,
67736                     cntslip_lotserial_warrpurc, itemsite_item_id LOOP
67737
67738 --  Handle the LotSerial
67739       IF (LENGTH(_cntslip.cntslip_lotserial)>0) THEN
67740         SELECT ls_id INTO _lsid
67741         FROM ls
67742         WHERE ((ls_item_id=_cntslip.itemsite_item_id)
67743         AND (UPPER(ls_number)=UPPER(_cntslip.cntslip_lotserial)));
67744
67745         IF (NOT FOUND) THEN
67746           _lsid := NEXTVAL('ls_ls_id_seq');
67747           INSERT INTO ls
67748           VALUES (_lsid,_cntslip.itemsite_item_id,UPPER(_cntslip.cntslip_lotserial));
67749         END IF;
67750       END IF;
67751        
67752 --  Track the running Qty
67753       _runningQty := (_runningQty + _cntslip.qty);
67754       _hasDetail = TRUE;
67755
67756 --  Create the itemlocdist populating record
67757       INSERT INTO itemlocdist
67758       ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67759         itemlocdist_itemsite_id,
67760         itemlocdist_ls_id, itemlocdist_expiration, itemlocdist_warranty,
67761         itemlocdist_qty, itemlocdist_invhist_id )
67762       VALUES
67763       ( _itemlocSeries, 'L', _cntslip.cntslip_location_id,
67764         _p.itemsite_id,
67765         _lsid, COALESCE(_cntslip.cntslip_lotserial_expiration, endOfTime()),
67766         _cntslip.cntslip_lotserial_warrpurc,
67767         _cntslip.qty, _invhistid );
67768
67769     END LOOP;
67770
67771     IF (_runningQty > _p.invcnt_qoh_after) THEN
67772 --  The total Count Slip Qty is greater than the Count Tag Qty,
67773 --  Don't post the Count.
67774       _errorCode = -1;
67775
67776     ELSIF ( (_runningQty < _p.invcnt_qoh_after) AND
67777             (_p.itemsite_controlmethod IN ('L', 'S')) ) THEN
67778 --  The total Count Slip Qty is less than the Count Tag Qty,
67779 --  and the Item Site is Lot/Serial controlled.
67780 --  Don't post the Count.
67781       _errorCode = -2;
67782
67783     ELSIF (_runningQty < _p.invcnt_qoh_after) THEN
67784       IF ( (NOT _p.itemsite_loccntrl) OR
67785            (_p.itemsite_location_id = -1) ) THEN
67786 --  The total Count Slip Qty is less than the Count Tag Qty,
67787 --  and there isn't a default location to post into.
67788 --  Don't post the Count.
67789         _errorCode = -3;
67790
67791       ELSIF ( SELECT (metric_value='f')
67792               FROM metric
67793               WHERE (metric_name='PostCountTagToDefault') ) THEN
67794 --  The total Count Slip Qty is less than the Count Tag Qty,
67795 --  and we don't post Count Tags to default Locations
67796 --  Don't post the Count.
67797         _errorCode = -4;
67798
67799       ELSE
67800 --  Distribute the remaining qty into the default location.
67801         INSERT INTO itemlocdist
67802         ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67803           itemlocdist_itemsite_id,
67804           itemlocdist_ls_id, itemlocdist_expiration,
67805           itemlocdist_qty, itemlocdist_invhist_id )
67806         SELECT _itemlocSeries, 'L', _p.itemsite_location_id,
67807                _p.itemsite_id,
67808                _lsid, endOfTime(),
67809                (_p.invcnt_qoh_after - _runningQty), _invhistid;
67810
67811         _hasDetail = TRUE;
67812         _errorCode = 0;
67813       END IF;
67814     ELSE
67815 --  The Count Slip Qty. must equal the Count Tag Qty.
67816       _errorCode = 0;
67817     END IF;
67818
67819 --  If we shouldn't post the count then delete the itemlocdist records,
67820 --  and return with the error.
67821     IF (_errorCode <> 0) THEN
67822       DELETE FROM itemlocdist
67823       WHERE (itemlocdist_series=_itemlocSeries);
67824   
67825       RETURN _errorCode;
67826     END IF;
67827
67828   END IF;
67829
67830 --  Mod. the Count Tag.
67831   UPDATE invcnt
67832   SET invcnt_qoh_before=_origLocQty,
67833       invcnt_postdate=_postDate,
67834       invcnt_posted=TRUE,
67835       invcnt_invhist_id=_invhistid,
67836       invcnt_post_username=getEffectiveXtUser()
67837   WHERE (invcnt_id=pInvcntid);
67838
67839 --  Create the CC transaction
67840   INSERT INTO invhist
67841    ( invhist_id, invhist_itemsite_id,
67842      invhist_transdate, invhist_transtype, invhist_invqty,
67843      invhist_qoh_before, invhist_qoh_after,
67844      invhist_docnumber, invhist_comments,
67845      invhist_invuom, invhist_unitcost, invhist_hasdetail,
67846      invhist_costmethod, invhist_value_before, invhist_value_after,
67847      invhist_series )
67848   SELECT _invhistid, itemsite_id,
67849          _postDate, 'CC', (invcnt_qoh_after - invcnt_qoh_before),
67850          invcnt_qoh_before, invcnt_qoh_after,
67851          invcnt_tagnumber, invcnt_comments,
67852          uom_name, _p.cost, _hasDetail,
67853          _p.itemsite_costmethod, _p.itemsite_value,
67854          _p.itemsite_value + (_p.cost * (invcnt_qoh_after - invcnt_qoh_before)),
67855          _itemlocSeries
67856   FROM itemsite, invcnt, item, uom
67857   WHERE ( (invcnt_itemsite_id=itemsite_id)
67858    AND (itemsite_item_id=item_id)
67859    AND (item_inv_uom_id=uom_id)
67860    AND (itemsite_controlmethod <> 'N')
67861    AND (invcnt_id=pInvcntid) );
67862
67863 --  Update the QOH
67864   IF (_netable) THEN
67865     UPDATE itemsite
67866     SET itemsite_qtyonhand= itemsite_qtyonhand + (_p.invcnt_qoh_after - _origLocQty),
67867         itemsite_datelastcount=_postDate
67868     WHERE (itemsite_id=_p.itemsite_id);
67869   ELSE
67870     UPDATE itemsite
67871     SET itemsite_nnqoh =  itemsite_nnqoh - _origLocQty,
67872         itemsite_qtyonhand = itemsite_qtyonhand + _p.invcnt_qoh_after,
67873         itemsite_datelastcount=_postDate
67874     WHERE (itemsite_id=_p.itemsite_id);
67875   END IF;
67876  
67877 --  Post the detail, if any
67878   IF (_hasDetail) THEN
67879     PERFORM distributeItemlocSeries(_itemlocSeries);
67880   END IF;
67881
67882 --  Thaw the itemsite if it's frozen
67883   IF (pThaw) THEN
67884     PERFORM thawItemSite(invcnt_itemsite_id) 
67885     FROM invcnt
67886     WHERE (invcnt_id=pInvcntid);
67887   END IF;
67888
67889 --  Distribute to G/L
67890   PERFORM insertGLTransaction( 'I/M', 'CT', _p.invcnt_tagnumber, ('Post Count Tag #' || _p.invcnt_tagnumber || ' for Item ' || _p.item_number),
67891                                costcat_adjustment_accnt_id, costcat_asset_accnt_id, _invhistid,
67892                                ( (_p.invcnt_qoh_after - _origLocQty) * _p.cost), CURRENT_DATE )
67893   FROM invcnt, itemsite, costcat
67894   WHERE ( (invcnt_itemsite_id=itemsite_id)
67895    AND (itemsite_costcat_id=costcat_id)
67896    AND (invcnt_id=pInvcntid) );
67897
67898   RETURN 0;
67899 END;
67900 $_$;
67901
67902
67903 ALTER FUNCTION public.postcounttaglocation(integer, boolean) OWNER TO admin;
67904
67905 --
67906 -- TOC entry 2004 (class 1255 OID 146566815)
67907 -- Dependencies: 4536 8
67908 -- Name: postcounttaglocation(integer, boolean, text); Type: FUNCTION; Schema: public; Owner: admin
67909 --
67910
67911 CREATE FUNCTION postcounttaglocation(integer, boolean, text) RETURNS integer
67912     LANGUAGE plpgsql
67913     AS $_$
67914 DECLARE
67915   pInvcntid ALIAS FOR $1;
67916   pThaw ALIAS FOR $2;
67917   pAvgCostingMethod ALIAS FOR $3;
67918   _invhistid INTEGER;
67919   _postDate TIMESTAMP;
67920   _runningQty NUMERIC;
67921   _errorCode INTEGER;
67922   _itemlocSeries INTEGER := 0;
67923   _hasDetail BOOLEAN;
67924   _p RECORD;
67925   _itemloc RECORD;
67926   _cntslip RECORD;
67927   _origLocQty NUMERIC;
67928   _netable BOOLEAN;
67929   _lsid INTEGER;
67930 BEGIN
67931
67932   SELECT invcnt_id, invcnt_tagnumber, invcnt_qoh_after,
67933          invcnt_location_id, invcnt_tagdate,
67934          item_number,
67935          itemsite_id, itemsite_freeze,
67936          itemsite_qtyonhand,
67937          itemsite_loccntrl, COALESCE(invcnt_location_id, -1) AS itemsite_location_id,
67938          CASE WHEN (itemsite_costmethod = 'N') THEN 0
67939               WHEN ( (itemsite_costmethod = 'A') AND
67940                      (itemsite_qtyonhand = 0) AND
67941                      (pAvgCostingMethod = 'ACT') ) THEN actcost(itemsite_item_id)
67942               WHEN ( (itemsite_costmethod = 'A') AND
67943                      (pAvgCostingMethod IN ('ACT', 'AVG')) ) THEN avgcost(itemsite_id)
67944               ELSE stdcost(itemsite_item_id)
67945          END AS cost, itemsite_costmethod,
67946          itemsite_controlmethod, itemsite_value INTO _p
67947   FROM invcnt, itemsite, item
67948   WHERE ( (invcnt_itemsite_id=itemsite_id)
67949    AND (itemsite_item_id=item_id)
67950    AND (invcnt_qoh_after IS NOT NULL)
67951    AND (NOT invcnt_posted)
67952    AND (invcnt_id=pInvcntid) );
67953   IF (NOT FOUND) THEN
67954     RETURN -9;
67955   END IF;
67956
67957   SELECT COALESCE(SUM(itemloc_qty),0.0), location_netable INTO _origLocQty,_netable
67958     FROM itemloc,location
67959    WHERE ((itemloc_itemsite_id=_p.itemsite_id)
67960      AND  (location_id=itemloc_location_id)
67961      AND  (itemloc_location_id=_p.invcnt_location_id))
67962    GROUP BY location_netable;
67963   IF (NOT FOUND) THEN
67964     _origLocQty := 0.0;
67965     _netable := TRUE;
67966   END IF;
67967
67968   SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
67969
67970   IF (_p.itemsite_freeze) THEN
67971     _postDate := _p.invcnt_tagdate;
67972   ELSE
67973     _postDate := CURRENT_TIMESTAMP;
67974   END IF;
67975
67976   _hasDetail = FALSE;
67977
67978 --  Post the detail indicated by cntslips
67979   IF ( (_p.itemsite_loccntrl) OR
67980        (_p.itemsite_controlmethod IN ('L', 'S')) ) THEN
67981
67982     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
67983
67984 --  Adjust any existing detail to 0
67985     FOR _itemloc IN SELECT itemloc_id, itemloc_location_id,
67986                            itemloc_ls_id, itemloc_qty
67987                     FROM itemloc
67988                     WHERE ((itemloc_itemsite_id=_p.itemsite_id)
67989                       AND  (itemloc_location_id=_p.invcnt_location_id)) LOOP
67990
67991       _hasDetail = TRUE;
67992
67993 --  Create the itemlocdist flushing records
67994       INSERT INTO itemlocdist
67995       ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
67996         itemlocdist_expiration,
67997         itemlocdist_itemsite_id, itemlocdist_invhist_id, itemlocdist_flush )
67998       VALUES
67999       ( _itemlocSeries, 'I', _itemloc.itemloc_id,
68000         endOfTime(),
68001         _p.itemsite_id, _invhistid, TRUE );
68002
68003     END LOOP;
68004
68005 --  Clear the running detail Qty
68006     _runningQty := 0;
68007
68008 --  Adjust the detail to the cntslip indicated value
68009     FOR _cntslip IN SELECT cntslip_location_id, cntslip_lotserial,
68010                            cntslip_lotserial_expiration,
68011                            cntslip_lotserial_warrpurc,
68012                            SUM(cntslip_qty) AS qty,
68013                            itemsite_item_id
68014                     FROM cntslip,invcnt,itemsite
68015                     WHERE ((cntslip_cnttag_id=pInvcntid)
68016                     AND (cntslip_cnttag_id=invcnt_id)
68017                     AND (invcnt_itemsite_id=itemsite_id))
68018                     GROUP BY cntslip_location_id, cntslip_lotserial, cntslip_lotserial_expiration,
68019                     cntslip_lotserial_warrpurc, itemsite_item_id LOOP
68020
68021 --  Handle the LotSerial
68022       IF (LENGTH(_cntslip.cntslip_lotserial)>0) THEN
68023         SELECT ls_id INTO _lsid
68024         FROM ls
68025         WHERE ((ls_item_id=_cntslip.itemsite_item_id)
68026         AND (UPPER(ls_number)=UPPER(_cntslip.cntslip_lotserial)));
68027
68028         IF (NOT FOUND) THEN
68029           _lsid := NEXTVAL('ls_ls_id_seq');
68030           INSERT INTO ls
68031           VALUES (_lsid,_cntslip.itemsite_item_id,UPPER(_cntslip.cntslip_lotserial));
68032         END IF;
68033       END IF;
68034        
68035 --  Track the running Qty
68036       _runningQty := (_runningQty + _cntslip.qty);
68037       _hasDetail = TRUE;
68038
68039 --  Create the itemlocdist populating record
68040       INSERT INTO itemlocdist
68041       ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
68042         itemlocdist_itemsite_id,
68043         itemlocdist_ls_id, itemlocdist_expiration, itemlocdist_warranty,
68044         itemlocdist_qty, itemlocdist_invhist_id )
68045       VALUES
68046       ( _itemlocSeries, 'L', _cntslip.cntslip_location_id,
68047         _p.itemsite_id,
68048         _lsid, COALESCE(_cntslip.cntslip_lotserial_expiration, endOfTime()),
68049         _cntslip.cntslip_lotserial_warrpurc,
68050         _cntslip.qty, _invhistid );
68051
68052     END LOOP;
68053
68054     IF (_runningQty > _p.invcnt_qoh_after) THEN
68055 --  The total Count Slip Qty is greater than the Count Tag Qty,
68056 --  Don't post the Count.
68057       _errorCode = -1;
68058
68059     ELSIF ( (_runningQty < _p.invcnt_qoh_after) AND
68060             (_p.itemsite_controlmethod IN ('L', 'S')) ) THEN
68061 --  The total Count Slip Qty is less than the Count Tag Qty,
68062 --  and the Item Site is Lot/Serial controlled.
68063 --  Don't post the Count.
68064       _errorCode = -2;
68065
68066     ELSIF (_runningQty < _p.invcnt_qoh_after) THEN
68067       IF ( (NOT _p.itemsite_loccntrl) OR
68068            (_p.itemsite_location_id = -1) ) THEN
68069 --  The total Count Slip Qty is less than the Count Tag Qty,
68070 --  and there isn't a default location to post into.
68071 --  Don't post the Count.
68072         _errorCode = -3;
68073
68074       ELSIF ( SELECT (metric_value='f')
68075               FROM metric
68076               WHERE (metric_name='PostCountTagToDefault') ) THEN
68077 --  The total Count Slip Qty is less than the Count Tag Qty,
68078 --  and we don't post Count Tags to default Locations
68079 --  Don't post the Count.
68080         _errorCode = -4;
68081
68082       ELSE
68083 --  Distribute the remaining qty into the default location.
68084         INSERT INTO itemlocdist
68085         ( itemlocdist_series, itemlocdist_source_type, itemlocdist_source_id,
68086           itemlocdist_itemsite_id,
68087           itemlocdist_ls_id, itemlocdist_expiration,
68088           itemlocdist_qty, itemlocdist_invhist_id )
68089         SELECT _itemlocSeries, 'L', _p.itemsite_location_id,
68090                _p.itemsite_id,
68091                _lsid, endOfTime(),
68092                (_p.invcnt_qoh_after - _runningQty), _invhistid;
68093
68094         _hasDetail = TRUE;
68095         _errorCode = 0;
68096       END IF;
68097     ELSE
68098 --  The Count Slip Qty. must equal the Count Tag Qty.
68099       _errorCode = 0;
68100     END IF;
68101
68102 --  If we shouldn't post the count then delete the itemlocdist records,
68103 --  and return with the error.
68104     IF (_errorCode <> 0) THEN
68105       DELETE FROM itemlocdist
68106       WHERE (itemlocdist_series=_itemlocSeries);
68107   
68108       RETURN _errorCode;
68109     END IF;
68110
68111   END IF;
68112
68113 --  Mod. the Count Tag.
68114   UPDATE invcnt
68115   SET invcnt_qoh_before=_origLocQty,
68116       invcnt_postdate=_postDate,
68117       invcnt_posted=TRUE,
68118       invcnt_invhist_id=_invhistid,
68119       invcnt_post_username=CURRENT_USER
68120   WHERE (invcnt_id=pInvcntid);
68121
68122 --  Create the CC transaction
68123   INSERT INTO invhist
68124    ( invhist_id, invhist_itemsite_id,
68125      invhist_transdate, invhist_transtype, invhist_invqty,
68126      invhist_qoh_before, invhist_qoh_after,
68127      invhist_docnumber, invhist_comments,
68128      invhist_invuom, invhist_unitcost, invhist_hasdetail,
68129      invhist_costmethod, invhist_value_before, invhist_value_after,
68130      invhist_series )
68131   SELECT _invhistid, itemsite_id,
68132          _postDate, 'CC', (invcnt_qoh_after - invcnt_qoh_before),
68133          invcnt_qoh_before, invcnt_qoh_after,
68134          invcnt_tagnumber, invcnt_comments,
68135          uom_name, _p.cost, _hasDetail,
68136          _p.itemsite_costmethod, _p.itemsite_value,
68137          _p.itemsite_value + (_p.cost * (invcnt_qoh_after - invcnt_qoh_before)),
68138          _itemlocSeries
68139   FROM itemsite, invcnt, item, uom
68140   WHERE ( (invcnt_itemsite_id=itemsite_id)
68141    AND (itemsite_item_id=item_id)
68142    AND (item_inv_uom_id=uom_id)
68143    AND (itemsite_controlmethod <> 'N')
68144    AND (invcnt_id=pInvcntid) );
68145
68146 --  Update the QOH
68147   IF (_netable) THEN
68148     UPDATE itemsite
68149     SET itemsite_qtyonhand= itemsite_qtyonhand + (_p.invcnt_qoh_after - _origLocQty),
68150         itemsite_datelastcount=_postDate
68151     WHERE (itemsite_id=_p.itemsite_id);
68152   ELSE
68153     UPDATE itemsite
68154     SET itemsite_nnqoh =  itemsite_nnqoh - _origLocQty,
68155         itemsite_qtyonhand = itemsite_qtyonhand + _p.invcnt_qoh_after,
68156         itemsite_datelastcount=_postDate
68157     WHERE (itemsite_id=_p.itemsite_id);
68158   END IF;
68159  
68160 --  Post the detail, if any
68161   IF (_hasDetail) THEN
68162     PERFORM distributeItemlocSeries(_itemlocSeries);
68163   END IF;
68164
68165 --  Thaw the itemsite if it's frozen
68166   IF (pThaw) THEN
68167     PERFORM thawItemSite(invcnt_itemsite_id) 
68168     FROM invcnt
68169     WHERE (invcnt_id=pInvcntid);
68170   END IF;
68171
68172 --  Distribute to G/L
68173   PERFORM insertGLTransaction( 'I/M', 'CT', _p.invcnt_tagnumber, ('Post Count Tag #' || _p.invcnt_tagnumber || ' for Item ' || _p.item_number),
68174                                costcat_adjustment_accnt_id, costcat_asset_accnt_id, _invhistid,
68175                                ( (_p.invcnt_qoh_after - _origLocQty) * _p.cost), CURRENT_DATE )
68176   FROM invcnt, itemsite, costcat
68177   WHERE ( (invcnt_itemsite_id=itemsite_id)
68178    AND (itemsite_costcat_id=costcat_id)
68179    AND (invcnt_id=pInvcntid) );
68180
68181   RETURN 0;
68182 END;
68183 $_$;
68184
68185
68186 ALTER FUNCTION public.postcounttaglocation(integer, boolean, text) OWNER TO admin;
68187
68188 --
68189 -- TOC entry 2005 (class 1255 OID 146566817)
68190 -- Dependencies: 4536 8
68191 -- Name: postcounttags(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
68192 --
68193
68194 CREATE FUNCTION postcounttags(integer, boolean) RETURNS integer
68195     LANGUAGE plpgsql
68196     AS $_$
68197 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68198 -- See www.xtuple.com/CPAL for the full text of the software license.
68199 DECLARE
68200   pWarehousid ALIAS FOR $1;
68201   pThaw ALIAS FOR $2;
68202   _invcnt RECORD;
68203   _result INTEGER := 0;
68204   _return INTEGER := 0;
68205
68206 BEGIN
68207
68208   FOR _invcnt IN SELECT invcnt_id
68209                  FROM invcnt, itemsite
68210                  WHERE ( (invcnt_itemsite_id=itemsite_id)
68211                   AND ( (pWarehousid=-1) OR (itemsite_warehous_id=pWarehousid) )
68212                   AND (invcnt_qoh_after IS NOT NULL)
68213                   AND (NOT invcnt_posted) ) LOOP
68214     SELECT postCountTag(_invcnt.invcnt_id, pThaw) INTO _result;
68215     IF (_result < _return) THEN
68216       _return := _result;
68217     END IF;
68218   END LOOP;
68219
68220   RETURN _return;
68221
68222 END;
68223 $_$;
68224
68225
68226 ALTER FUNCTION public.postcounttags(integer, boolean) OWNER TO admin;
68227
68228 --
68229 -- TOC entry 2006 (class 1255 OID 146566818)
68230 -- Dependencies: 4536 8
68231 -- Name: postcreditmemo(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
68232 --
68233
68234 CREATE FUNCTION postcreditmemo(integer, integer) RETURNS integer
68235     LANGUAGE plpgsql
68236     AS $_$
68237 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68238 -- See www.xtuple.com/CPAL for the full text of the software license.
68239 DECLARE
68240   pCmheadid ALIAS FOR $1;
68241   pItemlocSeries ALIAS FOR $2;
68242   _return INTEGER;
68243
68244 BEGIN
68245
68246   SELECT postCreditMemo(pCmheadid, fetchJournalNumber('AR-CM'), pItemlocSeries) INTO _return;
68247
68248   RETURN _return;
68249
68250 END;
68251 $_$;
68252
68253
68254 ALTER FUNCTION public.postcreditmemo(integer, integer) OWNER TO admin;
68255
68256 --
68257 -- TOC entry 2007 (class 1255 OID 146566819)
68258 -- Dependencies: 4536 8
68259 -- Name: postcreditmemo(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
68260 --
68261
68262 CREATE FUNCTION postcreditmemo(integer, integer, integer) RETURNS integer
68263     LANGUAGE plpgsql
68264     AS $_$
68265 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68266 -- See www.xtuple.com/CPAL for the full text of the software license.
68267 DECLARE
68268   pCmheadid ALIAS FOR $1;
68269   pJournalNumber ALIAS FOR $2;
68270   pItemlocSeries ALIAS FOR $3;
68271   _r RECORD;
68272   _p RECORD;
68273   _aropenid INTEGER;
68274   _cohistid INTEGER;
68275   _sequence INTEGER;
68276   _itemlocSeries INTEGER;
68277   _invhistid INTEGER;
68278   _test INTEGER;
68279   _totalAmount NUMERIC   := 0;
68280   _commissionDue NUMERIC := 0;
68281   _toApply NUMERIC;
68282   _toClose BOOLEAN;
68283   _glDate       DATE;
68284   _taxBaseValue NUMERIC := 0;
68285
68286 BEGIN
68287
68288 --  Cache some parameters
68289   SELECT cmhead.*,
68290          findARAccount(cmhead_cust_id) AS ar_accnt_id,
68291          ( SELECT COALESCE(SUM(taxhist_tax), 0)
68292            FROM cmheadtax
68293            WHERE ( (taxhist_parent_id = cmhead_id)
68294              AND   (taxhist_taxtype_id = getAdjustmentTaxtypeId()) ) ) AS adjtax
68295          INTO _p
68296   FROM cmhead
68297   WHERE (cmhead_id=pCmheadid);
68298
68299   IF (_p.cmhead_posted) THEN
68300     RETURN -10;
68301   END IF;
68302
68303   IF (_p.cmhead_hold) THEN
68304     RETURN -11;
68305   END IF;
68306
68307   _glDate := COALESCE(_p.cmhead_gldistdate, _p.cmhead_docdate);
68308
68309   _itemlocSeries = pItemlocSeries;
68310
68311   SELECT fetchGLSequence() INTO _sequence;
68312
68313 --  Start by handling taxes
68314   FOR _r IN SELECT tax_sales_accnt_id, 
68315               round(sum(taxdetail_tax),2) AS tax,
68316               currToBase(_p.cmhead_curr_id, round(sum(taxdetail_tax),2), _p.cmhead_docdate) AS taxbasevalue
68317             FROM tax 
68318              JOIN calculateTaxDetailSummary('CM', pCmheadid, 'T') ON (taxdetail_tax_id=tax_id)
68319             GROUP BY tax_id, tax_sales_accnt_id LOOP
68320
68321     PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CM', _p.cmhead_number,
68322                                 _r.tax_sales_accnt_id, 
68323                                 _r.taxbasevalue,
68324                                 _glDate, _p.cmhead_billtoname );
68325
68326     _totalAmount := _totalAmount + _r.tax * -1;
68327   END LOOP;
68328
68329 -- Update item tax records with posting data
68330   UPDATE cmitemtax SET 
68331     taxhist_docdate=_p.cmhead_docdate,
68332     taxhist_distdate=_glDate,
68333     taxhist_curr_id=_p.cmhead_curr_id,
68334     taxhist_curr_rate=curr_rate,
68335     taxhist_journalnumber=pJournalNumber
68336   FROM cmhead
68337    JOIN cmitem ON (cmhead_id=cmitem_cmhead_id),
68338    curr_rate
68339   WHERE ((cmhead_id=pCmheadId)
68340     AND (taxhist_parent_id=cmitem_id)
68341     AND (_p.cmhead_curr_id=curr_id)
68342     AND (_p.cmhead_docdate BETWEEN curr_effective 
68343                            AND curr_expires) );
68344
68345 -- Update Header taxes (Freight and Adjustments) with posting data
68346   UPDATE cmheadtax SET 
68347     taxhist_docdate=_p.cmhead_docdate,
68348     taxhist_distdate=_glDate,
68349     taxhist_curr_id=_p.cmhead_curr_id,
68350     taxhist_curr_rate=curr_rate,
68351     taxhist_journalnumber=pJournalNumber
68352   FROM curr_rate
68353   WHERE ((taxhist_parent_id=pCmheadId)
68354     AND (_p.cmhead_curr_id=curr_id)
68355     AND (_p.cmhead_docdate BETWEEN curr_effective 
68356                            AND curr_expires) );
68357
68358 -- Process line items
68359 -- Always use std cost
68360   FOR _r IN SELECT *, stdCost(item_id) AS std_cost
68361             FROM creditmemoitem
68362             WHERE ( (cmitem_cmhead_id=pCmheadid)
68363               AND   (cmitem_qtycredit <> 0 ) ) LOOP
68364
68365 --  Calcuate the Commission to be debited
68366     _commissionDue := (_commissionDue + (_r.extprice * _p.cmhead_commission));
68367
68368     IF (_r.extprice <> 0) THEN
68369 --  Debit the Sales Account for the current cmitem
68370       SELECT insertIntoGLSeries( _sequence, 'A/R', 'CM', _p.cmhead_number,
68371                                  CASE WHEN _p.cmhead_rahead_id IS NULL THEN
68372                                    getPrjAccntId(_p.cmhead_prj_id, salesaccnt_credit_accnt_id)
68373                                  ELSE
68374                                    getPrjAccntId(_p.cmhead_prj_id, salesaccnt_returns_accnt_id)
68375                                  END,
68376                                round(currToBase(_p.cmhead_curr_id,
68377                                                 _r.extprice * -1,
68378                                                 _p.cmhead_docdate), 2),
68379                                  _glDate, _p.cmhead_billtoname) INTO _test
68380       FROM salesaccnt
68381       WHERE (salesaccnt_id=findSalesAccnt(_r.cmitem_itemsite_id, 'IS', _p.cmhead_cust_id,
68382                                           _p.cmhead_saletype_id, _p.cmhead_shipzone_id));
68383       IF (NOT FOUND) THEN
68384         PERFORM deleteGLSeries(_sequence);
68385         RETURN -12;
68386       END IF;
68387     END IF;
68388
68389 --  Record Sales History for this C/M Item
68390     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
68391     INSERT INTO cohist
68392     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
68393       cohist_shipdate, cohist_shipvia,
68394       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
68395       cohist_doctype, cohist_invcnumber, cohist_invcdate,
68396       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
68397       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
68398       cohist_billtoname, cohist_billtoaddress1,
68399       cohist_billtoaddress2, cohist_billtoaddress3,
68400       cohist_billtocity, cohist_billtostate, cohist_billtozip,
68401       cohist_shiptoname, cohist_shiptoaddress1,
68402       cohist_shiptoaddress2, cohist_shiptoaddress3,
68403       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
68404       cohist_curr_id, cohist_taxtype_id, cohist_taxzone_id,
68405       cohist_shipzone_id, cohist_saletype_id )
68406     VALUES
68407     ( _cohistid, _p.cmhead_cust_id, _r.cmitem_itemsite_id, _p.cmhead_shipto_id,
68408       _p.cmhead_docdate, '',
68409       _p.cmhead_number, _p.cmhead_custponumber, _p.cmhead_docdate,
68410       'C', _p.cmhead_invcnumber, _p.cmhead_docdate,
68411       (_r.qty * -1), _r.unitprice, _r.std_cost,
68412       _p.cmhead_salesrep_id, (_p.cmhead_commission * _r.extprice * -1), FALSE,
68413       _p.cmhead_billtoname, _p.cmhead_billtoaddress1,
68414       _p.cmhead_billtoaddress2, _p.cmhead_billtoaddress3,
68415       _p.cmhead_billtocity, _p.cmhead_billtostate, _p.cmhead_billtozip,
68416       _p.cmhead_shipto_name, _p.cmhead_shipto_address1,
68417       _p.cmhead_shipto_address2, _p.cmhead_shipto_address3,
68418       _p.cmhead_shipto_city, _p.cmhead_shipto_state, _p.cmhead_shipto_zipcode,
68419       _p.cmhead_curr_id, _r.cmitem_taxtype_id, _p.cmhead_taxzone_id,
68420       _p.cmhead_shipzone_id, _p.cmhead_saletype_id );
68421     INSERT INTO cohisttax
68422     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
68423       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
68424       taxhist_percent, taxhist_amount, taxhist_tax,
68425       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
68426       taxhist_journalnumber )
68427     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
68428            taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
68429            taxhist_percent, taxhist_amount, taxhist_tax,
68430            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
68431            taxhist_journalnumber 
68432     FROM cmitemtax
68433     WHERE (taxhist_parent_id=_r.cmitem_id);
68434
68435     _totalAmount := _totalAmount + round(_r.extprice, 2);
68436
68437   END LOOP;
68438
68439 --  Credit the Misc. Account for Miscellaneous Charges
68440   IF (_p.cmhead_misc <> 0) THEN
68441     SELECT insertIntoGLSeries( _sequence, 'A/R', 'CM', _p.cmhead_number,
68442                                getPrjAccntId(_p.cmhead_prj_id, accnt_id), round(currToBase(_p.cmhead_curr_id,
68443                                                           _p.cmhead_misc * -1,
68444                                                           _p.cmhead_docdate), 2),
68445                                _glDate, _p.cmhead_billtoname) INTO _test
68446     FROM accnt
68447     WHERE (accnt_id=_p.cmhead_misc_accnt_id);
68448
68449 --  If the Misc. Charges Account was not found then punt
68450     IF (NOT FOUND) THEN
68451       PERFORM deleteGLSeries(_sequence);
68452       RETURN -14;
68453     END IF;
68454
68455 --  Record the Sales History for any Misc. Charge
68456     INSERT INTO cohist
68457     ( cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
68458       cohist_misc_type, cohist_misc_descrip, cohist_misc_id,
68459       cohist_shipdate, cohist_shipvia,
68460       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
68461       cohist_doctype, cohist_invcnumber, cohist_invcdate,
68462       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
68463       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
68464       cohist_billtoname, cohist_billtoaddress1,
68465       cohist_billtoaddress2, cohist_billtoaddress3,
68466       cohist_billtocity, cohist_billtostate, cohist_billtozip,
68467       cohist_shiptoname, cohist_shiptoaddress1,
68468       cohist_shiptoaddress2, cohist_shiptoaddress3,
68469       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
68470       cohist_curr_id,
68471       cohist_shipzone_id, cohist_saletype_id )
68472     VALUES
68473     ( _p.cmhead_cust_id, -1, _p.cmhead_shipto_id,
68474       'M', _p.cmhead_misc_descrip, _p.cmhead_misc_accnt_id,
68475       _p.cmhead_docdate, '',
68476       _p.cmhead_number, _p.cmhead_custponumber, _p.cmhead_docdate,
68477       'C', _p.cmhead_invcnumber, _p.cmhead_docdate,
68478       1, (_p.cmhead_misc * -1), (_p.cmhead_misc * -1),
68479       _p.cmhead_salesrep_id, 0, FALSE,
68480       _p.cmhead_billtoname, _p.cmhead_billtoaddress1,
68481       _p.cmhead_billtoaddress2, _p.cmhead_billtoaddress3,
68482       _p.cmhead_billtocity, _p.cmhead_billtostate, _p.cmhead_billtozip,
68483       _p.cmhead_shipto_name, _p.cmhead_shipto_address1,
68484       _p.cmhead_shipto_address2, _p.cmhead_shipto_address3,
68485       _p.cmhead_shipto_city, _p.cmhead_shipto_state, _p.cmhead_shipto_zipcode,
68486       _p.cmhead_curr_id,
68487       _p.cmhead_shipzone_id, _p.cmhead_saletype_id );
68488
68489 --  Cache the Misc. Amount distributed
68490     _totalAmount := _totalAmount + _p.cmhead_misc;
68491   END IF;
68492
68493   -- Credit Tax Adjustments
68494   IF (_p.adjtax <> 0) THEN
68495   --  Record the Sales History for Tax Adjustment
68496     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
68497     INSERT INTO cohist
68498     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
68499       cohist_misc_type, cohist_misc_descrip,
68500       cohist_shipdate, cohist_shipvia,
68501       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
68502       cohist_doctype, cohist_invcnumber, cohist_invcdate,
68503       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
68504       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
68505       cohist_billtoname, cohist_billtoaddress1,
68506       cohist_billtoaddress2, cohist_billtoaddress3,
68507       cohist_billtocity, cohist_billtostate, cohist_billtozip,
68508       cohist_shiptoname, cohist_shiptoaddress1,
68509       cohist_shiptoaddress2, cohist_shiptoaddress3,
68510       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
68511       cohist_curr_id, cohist_taxtype_id, cohist_taxzone_id,
68512       cohist_shipzone_id, cohist_saletype_id )
68513     VALUES
68514     ( _cohistid, _p.cmhead_cust_id, -1, _p.cmhead_shipto_id,
68515       'T', 'Misc Tax Adjustment',
68516       _p.cmhead_docdate, '',
68517       _p.cmhead_number, _p.cmhead_custponumber, _p.cmhead_docdate,
68518       'C', _p.cmhead_invcnumber, _p.cmhead_docdate,
68519       0, 0, 0,
68520       _p.cmhead_salesrep_id, 0, FALSE,
68521       _p.cmhead_billtoname, _p.cmhead_billtoaddress1,
68522       _p.cmhead_billtoaddress2, _p.cmhead_billtoaddress3,
68523       _p.cmhead_billtocity, _p.cmhead_billtostate, _p.cmhead_billtozip,
68524       _p.cmhead_shipto_name, _p.cmhead_shipto_address1,
68525       _p.cmhead_shipto_address2, _p.cmhead_shipto_address3,
68526       _p.cmhead_shipto_city, _p.cmhead_shipto_state, _p.cmhead_shipto_zipcode,
68527       _p.cmhead_curr_id, getAdjustmentTaxtypeId(), _p.cmhead_taxzone_id,
68528       _p.cmhead_shipzone_id, _p.cmhead_saletype_id );
68529     INSERT INTO cohisttax
68530     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
68531       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
68532       taxhist_percent, taxhist_amount, taxhist_tax,
68533       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
68534       taxhist_journalnumber  )
68535     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
68536            (taxhist_basis * -1), taxhist_basis_tax_id, taxhist_sequence,
68537            taxhist_percent, taxhist_amount, taxhist_tax,
68538            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
68539            taxhist_journalnumber 
68540     FROM cmheadtax
68541     WHERE ( (taxhist_parent_id=_p.cmhead_id)
68542       AND   (taxhist_taxtype_id=getAdjustmentTaxtypeId()) );
68543
68544   END IF;
68545
68546 --  Debit the Freight Account
68547   IF (_p.cmhead_freight <> 0) THEN
68548     SELECT insertIntoGLSeries( _sequence, 'A/R', 'CM', _p.cmhead_number,
68549                                getPrjAccntId(_p.cmhead_prj_id, accnt_id),
68550                                round(currToBase(_p.cmhead_curr_id,
68551                                                 _p.cmhead_freight * -1,
68552                                                 _p.cmhead_docdate), 2),
68553                                _glDate, _p.cmhead_billtoname) INTO _test
68554     FROM accnt
68555     WHERE (accnt_id=findFreightAccount(_p.cmhead_cust_id));
68556
68557 --  If the Freight Charges Account was not found then punt
68558     IF (NOT FOUND) THEN
68559       PERFORM deleteGLSeries(_sequence);
68560       RETURN -16;
68561     END IF;
68562
68563 --  Cache the Amount Distributed to Freight
68564     _totalAmount := _totalAmount + _p.cmhead_freight;
68565
68566 --  Record the Sales History for any Freight
68567     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
68568     INSERT INTO cohist
68569     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
68570       cohist_misc_type, cohist_misc_descrip,
68571       cohist_shipdate, cohist_shipvia,
68572       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
68573       cohist_doctype, cohist_invcnumber, cohist_invcdate,
68574       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
68575       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
68576       cohist_billtoname, cohist_billtoaddress1,
68577       cohist_billtoaddress2, cohist_billtoaddress3,
68578       cohist_billtocity, cohist_billtostate, cohist_billtozip,
68579       cohist_shiptoname, cohist_shiptoaddress1,
68580       cohist_shiptoaddress2, cohist_shiptoaddress3,
68581       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
68582       cohist_curr_id, cohist_taxtype_id, cohist_taxzone_id,
68583       cohist_shipzone_id, cohist_saletype_id )
68584     VALUES
68585     ( _cohistid, _p.cmhead_cust_id, -1, _p.cmhead_shipto_id,
68586       'F', 'Freight Charge',
68587       _p.cmhead_docdate, '',
68588       _p.cmhead_number, _p.cmhead_custponumber, _p.cmhead_docdate,
68589       'C', _p.cmhead_invcnumber, _p.cmhead_docdate,
68590       1, (_p.cmhead_freight * -1), (_p.cmhead_freight * -1),
68591       _p.cmhead_salesrep_id, 0, FALSE,
68592       _p.cmhead_billtoname, _p.cmhead_billtoaddress1,
68593       _p.cmhead_billtoaddress2, _p.cmhead_billtoaddress3,
68594       _p.cmhead_billtocity, _p.cmhead_billtostate, _p.cmhead_billtozip,
68595       _p.cmhead_shipto_name, _p.cmhead_shipto_address1,
68596       _p.cmhead_shipto_address2, _p.cmhead_shipto_address3,
68597       _p.cmhead_shipto_city, _p.cmhead_shipto_state, _p.cmhead_shipto_zipcode,
68598       _p.cmhead_curr_id, getFreightTaxtypeId(), _p.cmhead_taxzone_id,
68599       _p.cmhead_shipzone_id, _p.cmhead_saletype_id );
68600     INSERT INTO cohisttax
68601     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
68602       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
68603       taxhist_percent, taxhist_amount, taxhist_tax,
68604       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
68605       taxhist_journalnumber  )
68606     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
68607            (taxhist_basis * -1), taxhist_basis_tax_id, taxhist_sequence,
68608            taxhist_percent, taxhist_amount, taxhist_tax,
68609            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
68610            taxhist_journalnumber 
68611     FROM cmheadtax
68612     WHERE ( (taxhist_parent_id=_p.cmhead_id)
68613       AND   (taxhist_taxtype_id=getFreightTaxtypeId()) );
68614
68615   END IF;
68616
68617   _totalAmount := _totalAmount;
68618
68619 --  Credit the A/R for the total Amount
68620   IF (_totalAmount <> 0) THEN
68621     IF (_p.ar_accnt_id != -1) THEN
68622       PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CM', _p.cmhead_number,
68623                                   _p.ar_accnt_id,
68624                                   round(currToBase(_p.cmhead_curr_id,
68625                                                    _totalAmount,
68626                                                    _p.cmhead_docdate), 2),
68627                                   _glDate, _p.cmhead_billtoname);
68628     ELSE
68629       PERFORM deleteGLSeries(_sequence);
68630       RETURN -18;
68631     END IF;
68632   END IF;
68633
68634 --  Commit the GLSeries;
68635   PERFORM postGLSeries(_sequence, pJournalNumber);
68636
68637 --  Create the Invoice aropen item
68638   SELECT NEXTVAL('aropen_aropen_id_seq') INTO _aropenid;
68639   INSERT INTO aropen
68640   ( aropen_id, aropen_username, aropen_journalnumber,
68641     aropen_open, aropen_posted,
68642     aropen_cust_id, aropen_ponumber,
68643     aropen_docnumber,
68644     aropen_applyto, aropen_doctype,
68645     aropen_docdate, aropen_duedate, aropen_distdate, aropen_terms_id,
68646     aropen_amount, aropen_paid,
68647     aropen_salesrep_id, aropen_commission_due, aropen_commission_paid,
68648     aropen_ordernumber, aropen_notes,
68649     aropen_rsncode_id, aropen_curr_id )
68650   SELECT _aropenid, getEffectiveXtUser(), pJournalNumber,
68651          TRUE, FALSE,
68652          cmhead_cust_id, cmhead_custponumber,
68653          cmhead_number,
68654          CASE WHEN (cmhead_invcnumber='-1') THEN 'OPEN'
68655               ELSE (cmhead_invcnumber::TEXT)
68656          END,
68657          'C',
68658          cmhead_docdate, cmhead_docdate, _glDate, -1,
68659          _totalAmount, 0,
68660          cmhead_salesrep_id, (_commissionDue * -1), FALSE,
68661          cmhead_number::TEXT, cmhead_comments,
68662          cmhead_rsncode_id, cmhead_curr_id
68663   FROM cmhead
68664   WHERE (cmhead_id=pCmheadid);
68665
68666 -- Handle the Inventory and G/L Transactions for any returned Inventory where cmitem_updateinv is true
68667   FOR _r IN SELECT cmitem_itemsite_id AS itemsite_id, cmitem_id,
68668                    (cmitem_qtyreturned * cmitem_qty_invuomratio) AS qty,
68669                    cmhead_number, cmhead_cust_id AS cust_id, item_number,
68670                    cmhead_saletype_id AS saletype_id, cmhead_shipzone_id AS shipzone_id,
68671                    stdCost(item_id) AS std_cost, cmhead_prj_id,
68672                    itemsite_costmethod
68673             FROM cmhead, cmitem, itemsite, item
68674             WHERE ( (cmitem_cmhead_id=cmhead_id)
68675              AND (cmitem_itemsite_id=itemsite_id)
68676              AND (itemsite_item_id=item_id)
68677              AND (cmitem_qtyreturned <> 0)
68678              AND (cmitem_updateinv)
68679              AND (cmhead_id=pCmheadid) ) LOOP
68680
68681 --  Return credited stock to inventory
68682     IF (_itemlocSeries = 0) THEN
68683       _itemlocSeries := NEXTVAL('itemloc_series_seq');
68684     END IF;
68685     IF (_r.itemsite_costmethod != 'J') THEN
68686       SELECT postInvTrans(itemsite_id, 'RS', _r.qty,
68687                          'S/O', 'CM', _r.cmhead_number, '',
68688                          ('Credit Return ' || _r.item_number),
68689                          costcat_asset_accnt_id,
68690                          getPrjAccntId(_r.cmhead_prj_id, resolveCOSAccount(itemsite_id, _r.cust_id, _r.saletype_id, _r.shipzone_id)), 
68691                          _itemlocSeries, _glDate, _r.std_cost) INTO _invhistid
68692         FROM itemsite, costcat
68693        WHERE ((itemsite_costcat_id=costcat_id)
68694           AND (itemsite_id=_r.itemsite_id));
68695     ELSE
68696       RAISE DEBUG 'postCreditMemo(%, %, %) tried to postInvTrans a %-costed item',
68697                   pCmheadid, pJournalNumber, pItemlocSeries,
68698                   _r.itemsite_costmethod;
68699     END IF;
68700
68701   END LOOP;
68702
68703 --  Update coitem to reflect the returned qty where cmitem_updateinv is true
68704   FOR _r IN SELECT cmitem_qtyreturned, cmitem_itemsite_id, cohead_id
68705             FROM cmitem, cmhead, invchead, cohead
68706             WHERE ( (cmitem_cmhead_id=cmhead_id)
68707              AND (cmhead_invcnumber=invchead_invcnumber)
68708              AND (invchead_ordernumber=cohead_number)
68709              AND (cmitem_qtyreturned <> 0)
68710              AND (cmitem_updateinv)
68711              AND (cmhead_id=pCmheadid) ) LOOP
68712     UPDATE coitem
68713     SET coitem_qtyreturned = (coitem_qtyreturned + _r.cmitem_qtyreturned)
68714     WHERE coitem_id IN ( SELECT coitem_id
68715                          FROM coitem
68716                          WHERE ( (coitem_cohead_id=_r.cohead_id)
68717                           AND (coitem_itemsite_id = _r.cmitem_itemsite_id) )
68718                          LIMIT 1 );
68719   END LOOP;
68720
68721 --  Mark the cmhead as posted
68722   UPDATE cmhead
68723   SET cmhead_posted=TRUE, cmhead_gldistdate=_glDate
68724   WHERE (cmhead_id=pCmheadid);
68725
68726 --  Find the apply-to document and make the application
68727   SELECT cmhead_number, cmhead_curr_id, cmhead_docdate,
68728          aropen_id, aropen_cust_id, aropen_docnumber,
68729          currToCurr(aropen_curr_id, cmhead_curr_id, aropen_amount - aropen_paid,
68730                     cmhead_docdate) AS balance INTO _p
68731   FROM aropen, cmhead
68732   WHERE ( (aropen_doctype='I')
68733    AND (aropen_docnumber=cmhead_invcnumber)
68734    AND (cmhead_id=pCmheadid) );
68735   IF (FOUND) THEN
68736
68737     IF round(_totalAmount, 2) <= round(_p.balance, 2) THEN
68738       _toApply = _totalAmount;
68739     ELSE
68740       _toApply = _p.balance;
68741     END IF;
68742
68743     UPDATE aropen
68744     SET aropen_paid = round(aropen_paid + currToCurr(_p.cmhead_curr_id,
68745                                                      aropen_curr_id, _toApply,
68746                                                      _p.cmhead_docdate), 2)
68747     WHERE (aropen_id=_p.aropen_id);
68748
68749 --  Alter the new A/R Open Item to reflect the application
68750     UPDATE aropen
68751     SET aropen_paid = round(currToCurr(_p.cmhead_curr_id, aropen_curr_id,
68752                                        _toApply, _p.cmhead_docdate), 2)
68753     WHERE (aropen_id=_aropenid);
68754
68755 --  Record the application
68756     INSERT INTO arapply
68757     ( arapply_cust_id,
68758       arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
68759       arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
68760       arapply_fundstype, arapply_refnumber,
68761       arapply_applied, arapply_closed,
68762       arapply_postdate, arapply_distdate, arapply_journalnumber, arapply_curr_id )
68763     VALUES
68764     ( _p.aropen_cust_id,
68765       _aropenid, 'C', _p.cmhead_number,
68766       _p.aropen_id, 'I', _p.aropen_docnumber,
68767       '', '',
68768       round(_toApply, 2), _toClose,
68769       CURRENT_DATE, _p.cmhead_docdate, 0, _p.cmhead_curr_id );
68770
68771   END IF;
68772     
68773   RETURN _itemlocSeries;
68774
68775 END;
68776 $_$;
68777
68778
68779 ALTER FUNCTION public.postcreditmemo(integer, integer, integer) OWNER TO admin;
68780
68781 --
68782 -- TOC entry 2008 (class 1255 OID 146566821)
68783 -- Dependencies: 4536 8
68784 -- Name: postcreditmemos(boolean); Type: FUNCTION; Schema: public; Owner: admin
68785 --
68786
68787 CREATE FUNCTION postcreditmemos(boolean) RETURNS integer
68788     LANGUAGE plpgsql
68789     AS $_$
68790 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68791 -- See www.xtuple.com/CPAL for the full text of the software license.
68792 DECLARE
68793   pPostUnprinted ALIAS FOR $1;
68794   _cmhead RECORD;
68795   _result INTEGER;
68796   _return INTEGER        := 0;
68797   _itemlocSeries INTEGER := 0;
68798
68799 BEGIN
68800
68801   _itemlocSeries := 0;
68802
68803   FOR _cmhead IN SELECT cmhead_id
68804                  FROM cmhead
68805                  WHERE ( (NOT cmhead_posted)
68806                    AND   (NOT cmhead_hold)
68807                    AND   (checkCreditMemoSitePrivs(cmhead_id))
68808                    AND   ((pPostUnprinted) OR (cmhead_printed)) ) LOOP
68809
68810     SELECT postCreditMemo(_cmhead.cmhead_id, _itemlocSeries) INTO _result;
68811     IF (_result < _return) THEN
68812       _return := _result;
68813     END IF;
68814
68815   END LOOP;
68816
68817   RETURN _return;
68818
68819 END;
68820 $_$;
68821
68822
68823 ALTER FUNCTION public.postcreditmemos(boolean) OWNER TO admin;
68824
68825 --
68826 -- TOC entry 2009 (class 1255 OID 146566822)
68827 -- Dependencies: 4536 8
68828 -- Name: postcreditmemos(boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
68829 --
68830
68831 CREATE FUNCTION postcreditmemos(boolean, integer) RETURNS integer
68832     LANGUAGE plpgsql
68833     AS $_$
68834 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68835 -- See www.xtuple.com/CPAL for the full text of the software license.
68836 DECLARE
68837   pPostUnprinted ALIAS FOR $1;
68838   pJournalNumber ALIAS FOR $2;
68839   _r RECORD;
68840   _itemlocSeries INTEGER := 0;
68841
68842 BEGIN
68843
68844   _itemlocSeries := 0;
68845
68846   FOR _r IN SELECT cmhead_id
68847             FROM cmhead
68848             WHERE ( (NOT cmhead_posted)
68849               AND   (NOT cmhead_hold)
68850               AND   (checkCreditMemoSitePrivs(cmhead_id))
68851               AND   ((pPostUnprinted) OR (cmhead_printed)) ) LOOP
68852
68853     SELECT postCreditMemo(_r.cmhead_id, pJournalNumber, _itemlocSeries) INTO _itemlocSeries;
68854
68855   END LOOP;
68856
68857   RETURN _itemlocSeries;
68858
68859 END;
68860 $_$;
68861
68862
68863 ALTER FUNCTION public.postcreditmemos(boolean, integer) OWNER TO admin;
68864
68865 --
68866 -- TOC entry 2010 (class 1255 OID 146566823)
68867 -- Dependencies: 4536 8
68868 -- Name: postevent(text, text, integer, integer, text, numeric, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
68869 --
68870
68871 CREATE FUNCTION postevent(pevnttypename text, pordtype text, pordid integer, pwhsid integer, pnumber text, pnewvalue numeric, poldvalue numeric, pnewdate date, polddate date) RETURNS integer
68872     LANGUAGE plpgsql
68873     AS $$
68874 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68875 -- See www.xtuple.com/CPAL for the full text of the software license.
68876 DECLARE
68877   _evnttypeid INTEGER;
68878   _whsid INTEGER;
68879
68880 BEGIN
68881   -- Find event type
68882   SELECT evnttype_id INTO _evnttypeid
68883   FROM evnttype
68884   WHERE (evnttype_name=pEvnttypename);
68885   IF (NOT FOUND) THEN
68886     RAISE EXCEPTION 'Event type % not found.', pEvnttypename;
68887   END IF;
68888
68889   IF (pWhsid IS NULL) THEN
68890     -- Find user preferred warehouse
68891     SELECT usrpref_value  INTO _whsid
68892     FROM usrpref
68893     WHERE usrpref_username = getEffectiveXtUser()
68894       AND usrpref_name = 'PreferredWarehouse';
68895   ELSE
68896     _whsid := pWhsid;
68897   END IF;
68898
68899   INSERT INTO evntlog ( evntlog_evnttime, evntlog_evnttype_id,
68900                         evntlog_ordtype, evntlog_ord_id,
68901                         evntlog_warehous_id, evntlog_number,
68902                         evntlog_newvalue, evntlog_oldvalue,
68903                         evntlog_newdate, evntlog_olddate,
68904                         evntlog_username )
68905   SELECT CURRENT_TIMESTAMP, evnttype_id,
68906          pOrdtype, pOrdid,
68907          _whsid, pNumber,
68908          pNewValue, pOldValue,
68909          pNewDate, pOldDate,
68910          evntnot_username
68911   FROM evnttype JOIN evntnot ON ( (evntnot_evnttype_id=evnttype_id) AND
68912                                   (evntnot_warehous_id=_whsid) )
68913   WHERE (evnttype_id=_evnttypeid);
68914
68915   RETURN 0;
68916
68917 END
68918 $$;
68919
68920
68921 ALTER FUNCTION public.postevent(pevnttypename text, pordtype text, pordid integer, pwhsid integer, pnumber text, pnewvalue numeric, poldvalue numeric, pnewdate date, polddate date) OWNER TO admin;
68922
68923 --
68924 -- TOC entry 1772 (class 1255 OID 146566824)
68925 -- Dependencies: 4536 8
68926 -- Name: postglseries(integer); Type: FUNCTION; Schema: public; Owner: admin
68927 --
68928
68929 CREATE FUNCTION postglseries(integer) RETURNS integer
68930     LANGUAGE plpgsql
68931     AS $_$
68932 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68933 -- See www.xtuple.com/CPAL for the full text of the software license.
68934 DECLARE
68935   pSequence ALIAS FOR $1;
68936   _journalNumber INTEGER;
68937   _returnValue INTEGER;
68938
68939 BEGIN
68940
68941   SELECT postGLSeries(pSequence, fetchJournalNumber('G/L')) INTO _returnValue;
68942   RETURN _returnValue;
68943
68944 END;
68945 $_$;
68946
68947
68948 ALTER FUNCTION public.postglseries(integer) OWNER TO admin;
68949
68950 --
68951 -- TOC entry 1793 (class 1255 OID 146566825)
68952 -- Dependencies: 4536 8
68953 -- Name: postglseries(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
68954 --
68955
68956 CREATE FUNCTION postglseries(integer, integer) RETURNS integer
68957     LANGUAGE plpgsql
68958     AS $_$
68959 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68960 -- See www.xtuple.com/CPAL for the full text of the software license.
68961 DECLARE
68962   pSequence ALIAS FOR $1;
68963   pJournalNumber ALIAS FOR $2;
68964   _returnValue INTEGER;
68965
68966 BEGIN
68967
68968   SELECT postGLSeries(pSequence, pJournalNumber, true) INTO _returnValue;
68969   RETURN _returnValue;
68970
68971 END;
68972 $_$;
68973
68974
68975 ALTER FUNCTION public.postglseries(integer, integer) OWNER TO admin;
68976
68977 --
68978 -- TOC entry 1804 (class 1255 OID 146566826)
68979 -- Dependencies: 4536 8
68980 -- Name: postglseries(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
68981 --
68982
68983 CREATE FUNCTION postglseries(integer, integer, boolean) RETURNS integer
68984     LANGUAGE plpgsql
68985     AS $_$
68986 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
68987 -- See www.xtuple.com/CPAL for the full text of the software license.
68988 DECLARE
68989   pSequence             ALIAS FOR $1;
68990   pJournalNumber        ALIAS FOR $2;
68991   pPostZero             ALIAS FOR $3;
68992   _glseries RECORD;
68993   _transCount INTEGER := 0;
68994   _delta NUMERIC;
68995   _discrepDate DATE;
68996   _discrepAccntid INTEGER;
68997   _rows INTEGER;
68998 BEGIN
68999
69000 /*  Make sure we don't create an imbalance across companies.
69001     The 'IgnoreCompanyBalance' metric is a back door mechanism to
69002     allow legacy users to create transactions accross companies if
69003     they have been using the company segment for something else
69004     and they MUST continue to be able to do so.  It can only be 
69005     implemented by direct sql update to the metric table and should 
69006     otherwise be discouraged.
69007 */ 
69008   IF (COALESCE(fetchMetricValue('GLCompanySize'),0) > 0 
69009     AND fetchMetricBool('IgnoreCompany') = false)  THEN
69010
69011     SELECT count(accnt_company) INTO _rows
69012     FROM (
69013       SELECT DISTINCT accnt_company
69014       FROM accnt 
69015         JOIN glseries ON (glseries_accnt_id=accnt_id)
69016       WHERE (glseries_sequence=pSequence)) _data;
69017     
69018     IF (_rows > 1) THEN
69019       RAISE EXCEPTION 'G/L Series can not be posted because multiple companies are referenced in the same series.';
69020     END IF;
69021   END IF;
69022   
69023 --  Make sure that we balance
69024   SELECT SUM(glseries_amount), MAX(glseries_distdate) INTO _delta, _discrepDate
69025     FROM glseries
69026    WHERE (glseries_sequence=pSequence);
69027   IF ( _delta <> 0 ) THEN
69028     IF (COALESCE(fetchMetricValue('GLCompanySize'),0) = 0) THEN
69029       SELECT accnt_id INTO _discrepAccntid
69030         FROM accnt, metric
69031        WHERE ((metric_name='GLSeriesDiscrepancyAccount')
69032          AND  (accnt_id=CAST(metric_value AS INTEGER)));
69033     ELSE
69034        SELECT company_dscrp_accnt_id INTO _discrepAccntid
69035         FROM company
69036           JOIN accnt ON (accnt_company=company_number) 
69037           JOIN glseries ON (glseries_accnt_id=accnt_id)
69038        WHERE (glseries_sequence=pSequence)
69039        LIMIT 1;
69040     END IF;
69041
69042     IF (NOT FOUND) THEN
69043       RETURN -5;
69044     END IF;
69045     
69046     INSERT INTO glseries
69047            ( glseries_sequence, glseries_source, glseries_doctype, glseries_docnumber,
69048              glseries_accnt_id, glseries_amount, glseries_distdate, glseries_notes )
69049     SELECT glseries_sequence, glseries_source, glseries_doctype, glseries_docnumber,
69050              _discrepAccntid, (_delta * -1), _discrepDate, 'G/L Series Discrepancy'
69051       FROM glseries
69052      WHERE (glseries_sequence=pSequence)
69053      LIMIT 1;
69054   END IF;
69055
69056 --  March through the glseries members, posting them one at a time
69057   FOR _glseries IN SELECT glseries_source, glseries_doctype, glseries_docnumber,
69058                           glseries_accnt_id, glseries_distdate, glseries_notes,
69059                           glseries_misc_id,
69060                           SUM(glseries_amount) as amount
69061                      FROM glseries
69062                     WHERE ((glseries_amount<>0.0)
69063                       AND  (glseries_sequence=pSequence))
69064                     GROUP BY glseries_source, glseries_doctype, glseries_docnumber,
69065                              glseries_accnt_id, glseries_distdate, glseries_notes,
69066                              glseries_misc_id LOOP
69067
69068 -- refuse to accept postings into closed periods
69069     IF (SELECT BOOL_AND(COALESCE(period_closed, FALSE))
69070         FROM accnt LEFT OUTER JOIN
69071              period ON (_glseries.glseries_distdate BETWEEN period_start AND period_end)
69072         WHERE (accnt_id = _glseries.glseries_accnt_id)) THEN
69073       RAISE EXCEPTION 'Cannot post to closed period (%).', _glseries.glseries_distdate;
69074       RETURN -4;        -- remove raise exception when all callers check return code
69075     END IF;
69076
69077 -- refuse to accept postings into frozen periods without proper priv
69078     IF (SELECT NOT BOOL_AND(checkPrivilege('PostFrozenPeriod')) AND
69079                BOOL_AND(COALESCE(period_freeze, FALSE))
69080         FROM accnt LEFT OUTER JOIN
69081              period ON (_glseries.glseries_distdate BETWEEN period_start AND period_end)
69082         WHERE (accnt_id = _glseries.glseries_accnt_id)) THEN
69083       RAISE EXCEPTION 'Cannot post to frozen period (%).', _glseries.glseries_distdate;
69084       RETURN -4;        -- remove raise exception when all callers check return code
69085     END IF;
69086
69087 -- refuse to accept postings into nonexistent periods
69088     IF NOT EXISTS(SELECT period_id
69089                   FROM period
69090                   WHERE (_glseries.glseries_distdate BETWEEN period_start AND period_end)) THEN
69091       RAISE EXCEPTION 'Cannot post to nonexistent period (%).', pDistDate;
69092     END IF;
69093
69094     IF (_glseries.amount != 0 OR pPostZero) THEN
69095       IF (fetchMetricBool('UseJournals')) THEN
69096        INSERT INTO sltrans
69097         ( sltrans_posted, sltrans_created, sltrans_date, sltrans_misc_id,
69098           sltrans_sequence, sltrans_accnt_id, sltrans_source, sltrans_notes,
69099           sltrans_doctype, sltrans_docnumber, sltrans_amount, sltrans_journalnumber )
69100         VALUES
69101         ( FALSE, CURRENT_TIMESTAMP, _glseries.glseries_distdate, _glseries.glseries_misc_id,
69102           pSequence, _glseries.glseries_accnt_id, _glseries.glseries_source, _glseries.glseries_notes,
69103           _glseries.glseries_doctype, _glseries.glseries_docnumber, _glseries.amount, pJournalNumber );      
69104       ELSE
69105        INSERT INTO gltrans
69106         ( gltrans_posted, gltrans_exported, gltrans_created, gltrans_date, gltrans_misc_id,
69107           gltrans_sequence, gltrans_accnt_id, gltrans_source, gltrans_notes,
69108           gltrans_doctype, gltrans_docnumber, gltrans_amount, gltrans_journalnumber )
69109         VALUES
69110         ( FALSE, FALSE, CURRENT_TIMESTAMP, _glseries.glseries_distdate, _glseries.glseries_misc_id,
69111           pSequence, _glseries.glseries_accnt_id, _glseries.glseries_source, _glseries.glseries_notes,
69112           _glseries.glseries_doctype, _glseries.glseries_docnumber, _glseries.amount, pJournalNumber );
69113       END IF;
69114       
69115       _transCount := _transCount + 1;
69116     END IF;
69117   END LOOP;
69118
69119 --  Delete all of the posted glseries members
69120   DELETE FROM glseries
69121   WHERE (glseries_sequence=pSequence);
69122
69123   PERFORM postIntoTrialBalance(pSequence);
69124
69125   RETURN _transCount;
69126
69127 END;
69128 $_$;
69129
69130
69131 ALTER FUNCTION public.postglseries(integer, integer, boolean) OWNER TO admin;
69132
69133 --
69134 -- TOC entry 1853 (class 1255 OID 146566828)
69135 -- Dependencies: 4536 8
69136 -- Name: postglseriesnosumm(integer); Type: FUNCTION; Schema: public; Owner: admin
69137 --
69138
69139 CREATE FUNCTION postglseriesnosumm(integer) RETURNS integer
69140     LANGUAGE plpgsql
69141     AS $_$
69142 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69143 -- See www.xtuple.com/CPAL for the full text of the software license.
69144 DECLARE
69145   pSequence ALIAS FOR $1;
69146   _journalNumber INTEGER;
69147   _returnValue INTEGER;
69148
69149 BEGIN
69150
69151   SELECT postGLSeriesNoSumm(pSequence, fetchJournalNumber('G/L')) INTO _returnValue;
69152   RETURN _returnValue;
69153
69154 END;
69155 $_$;
69156
69157
69158 ALTER FUNCTION public.postglseriesnosumm(integer) OWNER TO admin;
69159
69160 --
69161 -- TOC entry 1854 (class 1255 OID 146566829)
69162 -- Dependencies: 4536 8
69163 -- Name: postglseriesnosumm(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
69164 --
69165
69166 CREATE FUNCTION postglseriesnosumm(integer, integer) RETURNS integer
69167     LANGUAGE plpgsql
69168     AS $_$
69169 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69170 -- See www.xtuple.com/CPAL for the full text of the software license.
69171 DECLARE
69172   pSequence ALIAS FOR $1;
69173   pJournalNumber ALIAS FOR $2;
69174   _glseries RECORD;
69175   _transCount INTEGER := 0;
69176   _rows INTEGER;
69177
69178 BEGIN
69179
69180 /*  Make sure we don't create an imbalance across companies.
69181     The 'IgnoreCompanyBalance' metric is a back door mechanism to
69182     allow legacy users to create transactions accross companies if
69183     they have been using the company segment for something else
69184     and they MUST continue to be able to do so.  It can only be 
69185     implemented by direct sql update to the metric table and should 
69186     otherwise be discouraged.
69187 */  
69188   IF (COALESCE(fetchMetricValue('GLCompanySize'),0) > 0 
69189     AND fetchMetricBool('IgnoreCompany') = false)  THEN
69190
69191     SELECT count(accnt_company) INTO _rows
69192     FROM (
69193       SELECT DISTINCT accnt_company
69194       FROM accnt 
69195         JOIN glseries ON (glseries_accnt_id=accnt_id)
69196       WHERE (glseries_sequence=pSequence)) _data;
69197     
69198     IF (_rows > 1) THEN
69199       RAISE EXCEPTION 'G/L Series can not be posted because multiple companies are referenced in the same series.';
69200     END IF;
69201   END IF;
69202   
69203 --  Make sure that we balance
69204   IF ( ( SELECT SUM(glseries_amount)
69205          FROM glseries
69206          WHERE (glseries_sequence=pSequence) ) <> 0 ) THEN
69207     RETURN -1;
69208   END IF;
69209
69210 --  March through the glseries members, posting them one at a time
69211   FOR _glseries IN SELECT glseries_source, glseries_doctype, glseries_docnumber,
69212                           glseries_accnt_id, glseries_distdate, glseries_notes,
69213                           glseries_misc_id, glseries_amount as amount
69214                      FROM glseries
69215                     WHERE ((glseries_amount<>0.0)
69216                       AND  (glseries_sequence=pSequence)) LOOP
69217
69218 -- refuse to accept postings into closed periods
69219     IF (SELECT BOOL_AND(COALESCE(period_closed, FALSE))
69220         FROM accnt LEFT OUTER JOIN
69221              period ON (_glseries.glseries_distdate BETWEEN period_start AND period_end)
69222         WHERE (accnt_id = _glseries.glseries_accnt_id)) THEN
69223       RAISE EXCEPTION 'Cannot post to closed period (%).', _glseries.glseries_distdate;
69224       RETURN -4;        -- remove raise exception when all callers check return code
69225     END IF;
69226
69227 -- refuse to accept postings into frozen periods without proper priv
69228     IF (SELECT NOT BOOL_AND(checkPrivilege('PostFrozenPeriod')) AND
69229                BOOL_AND(COALESCE(period_freeze, FALSE))
69230         FROM accnt LEFT OUTER JOIN
69231              period ON (_glseries.glseries_distdate BETWEEN period_start AND period_end)
69232         WHERE (accnt_id = _glseries.glseries_accnt_id)) THEN
69233       RAISE EXCEPTION 'Cannot post to frozen period (%).', _glseries.glseries_distdate;
69234       RETURN -4;        -- remove raise exception when all callers check return code
69235     END IF;
69236
69237 -- refuse to accept postings into nonexistent periods
69238     IF NOT EXISTS(SELECT period_id
69239                   FROM period
69240                   WHERE (_glseries.glseries_distdate BETWEEN period_start AND period_end)) THEN
69241       RAISE EXCEPTION 'Cannot post to nonexistent period (%).', pDistDate;
69242     END IF;
69243
69244     IF (fetchMetricBool('UseJournals')) THEN
69245       INSERT INTO sltrans
69246       ( sltrans_posted, sltrans_created, sltrans_date, sltrans_misc_id,
69247         sltrans_sequence, sltrans_accnt_id, sltrans_source, sltrans_notes,
69248         sltrans_doctype, sltrans_docnumber, sltrans_amount, sltrans_journalnumber )
69249       VALUES
69250       ( FALSE, CURRENT_TIMESTAMP, _glseries.glseries_distdate, _glseries.glseries_misc_id,
69251         pSequence, _glseries.glseries_accnt_id, _glseries.glseries_source, _glseries.glseries_notes,
69252         _glseries.glseries_doctype, _glseries.glseries_docnumber, _glseries.amount, pJournalNumber );
69253     ELSE
69254       INSERT INTO gltrans
69255       ( gltrans_posted, gltrans_exported, gltrans_created, gltrans_date, gltrans_misc_id,
69256         gltrans_sequence, gltrans_accnt_id, gltrans_source, gltrans_notes,
69257         gltrans_doctype, gltrans_docnumber, gltrans_amount, gltrans_journalnumber )
69258       VALUES
69259       ( FALSE, FALSE, CURRENT_TIMESTAMP, _glseries.glseries_distdate, _glseries.glseries_misc_id,
69260         pSequence, _glseries.glseries_accnt_id, _glseries.glseries_source, _glseries.glseries_notes,
69261         _glseries.glseries_doctype, _glseries.glseries_docnumber, _glseries.amount, pJournalNumber );
69262     END IF;
69263
69264     _transCount := _transCount + 1;
69265
69266   END LOOP;
69267
69268 --  Delete all of the posted glseries members
69269   DELETE FROM glseries
69270   WHERE (glseries_sequence=pSequence);
69271
69272   PERFORM postIntoTrialBalance(pSequence);
69273
69274   RETURN _transCount;
69275
69276 END;
69277 $_$;
69278
69279
69280 ALTER FUNCTION public.postglseriesnosumm(integer, integer) OWNER TO admin;
69281
69282 --
69283 -- TOC entry 1868 (class 1255 OID 146566831)
69284 -- Dependencies: 4536 8
69285 -- Name: postintoinvbalance(integer); Type: FUNCTION; Schema: public; Owner: admin
69286 --
69287
69288 CREATE FUNCTION postintoinvbalance(integer) RETURNS boolean
69289     LANGUAGE plpgsql
69290     AS $_$
69291 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69292 -- See www.xtuple.com/CPAL for the full text of the software license.
69293 DECLARE
69294   pInvhistId ALIAS FOR $1;
69295   _invbalid INTEGER;
69296   _r RECORD;
69297   _count INTEGER;
69298   _qty NUMERIC;
69299
69300 BEGIN
69301
69302 --  Grab the invhist record to post
69303 --  Special fix for transit sites when transtype=TS and invqty<0
69304 --  Set the sense to 1 to correct invhist populated incorrectly.
69305   SELECT invhist.*,
69306          CASE WHEN (invhist_transtype='TS' AND invhist_invqty < 0.0 AND warehous_transit) THEN 1
69307               ELSE invhistSense(invhist_id)
69308          END AS sense,
69309          period_id INTO _r
69310   FROM invhist
69311     JOIN itemsite ON (itemsite_id=invhist_itemsite_id)
69312     JOIN whsinfo ON (warehous_id=itemsite_warehous_id)
69313     LEFT OUTER JOIN period ON (invhist_transdate::date BETWEEN period_start AND period_end)
69314   WHERE ( invhist_id=pInvhistId );
69315
69316   GET DIAGNOSTICS _count = ROW_COUNT;
69317
69318 --  If we can post into a Inv Balance, do so
69319   IF ( _count > 0 ) THEN
69320
69321 --  Validate
69322     IF (_r.period_id IS NULL) THEN
69323       RAISE EXCEPTION 'No accounting period exists for invhist_id %, transaction date %.  Transaction can not be posted.', _r.invhist_id, formatDate(_r.invhist_transdate);
69324     END IF;
69325
69326 --  If cycle count, then we need to reference balance which needs to be accurate
69327 --    IF (_r.invhist_transtype = 'CC') THEN
69328 --      PERFORM forwardupdateitemsite(_r.invhist_itemsite_id);
69329 --    END IF;
69330
69331 --  Try to find an existing invbal
69332     SELECT 
69333       invbal_id, 
69334 --      CASE WHEN (_r.invhist_transtype != 'CC') THEN _r.invhist_invqty ELSE _r.invhist_invqty - invbal_qoh_ending END 
69335       _r.invhist_invqty
69336       INTO _invbalid, _qty
69337     FROM invbal
69338     WHERE ( (invbal_period_id=_r.period_id)
69339       AND (invbal_itemsite_id=_r.invhist_itemsite_id) );
69340
69341     GET DIAGNOSTICS _count = ROW_COUNT;
69342     IF (_count > 0) THEN
69343
69344 --  We found a invbal, update it with the Inventory Transaction
69345 --  Note - two stage update to avoid any funny value caching logic
69346     IF (_r.sense * _qty > 0) THEN
69347       UPDATE invbal SET 
69348         invbal_qty_in = (invbal_qty_in + abs(_qty)),
69349         invbal_value_in = (invbal_value_in + abs(_qty) * _r.invhist_unitcost)
69350       WHERE (invbal_id=_invbalid);
69351     ELSIF (_r.sense * _qty < 0) THEN
69352       UPDATE invbal SET 
69353         invbal_qty_out = (invbal_qty_out + abs(_qty)),
69354         invbal_value_out = (invbal_value_out + abs(_qty) *  _r.invhist_unitcost)
69355       WHERE (invbal_id=_invbalid);
69356     END IF;
69357
69358     -- Non-netable transactions have their own balances
69359     IF (_r.invhist_transtype = 'NN') THEN
69360       UPDATE invbal SET 
69361         invbal_nn_in = (invbal_nn_in + _qty * -1),
69362         invbal_nnval_in = (invbal_nnval_in + _qty * -1 * _r.invhist_unitcost)
69363       WHERE (invbal_id=_invbalid);
69364     END IF;
69365
69366     UPDATE invbal SET 
69367       invbal_qoh_ending = (invbal_qoh_beginning + invbal_qty_in - invbal_qty_out),
69368       invbal_value_ending = (invbal_value_beginning + invbal_value_in - invbal_value_out),
69369       invbal_nn_ending = (invbal_nn_beginning + invbal_nn_in - invbal_nn_out),
69370       invbal_nnval_ending = (invbal_nnval_beginning + invbal_nnval_in - invbal_nnval_out),
69371       invbal_dirty=true
69372     WHERE (invbal_id=_invbalid);
69373   ELSE
69374
69375 --  No existing invbal, make one
69376     SELECT NEXTVAL('invbal_invbal_id_seq') INTO _invbalid;
69377       INSERT INTO invbal
69378         ( invbal_id, invbal_itemsite_id, invbal_period_id,
69379           invbal_qoh_beginning,
69380           invbal_qoh_ending,
69381           invbal_qty_in,
69382           invbal_qty_out,
69383           invbal_value_beginning,
69384           invbal_value_ending,
69385           invbal_value_in,
69386           invbal_value_out,
69387           invbal_nn_beginning,
69388           invbal_nn_ending,
69389           invbal_nn_in,
69390           invbal_nn_out,
69391           invbal_nnval_beginning,
69392           invbal_nnval_ending,
69393           invbal_nnval_in,
69394           invbal_nnval_out,
69395           invbal_dirty )
69396       VALUES
69397         ( _invbalid, _r.invhist_itemsite_id, _r.period_id,
69398          -- Netable
69399           0, 
69400           _r.invhist_invqty * _r.sense,
69401           CASE WHEN (_r.sense > 0) THEN _r.invhist_invqty
69402                ELSE 0
69403           END,
69404           CASE WHEN (_r.sense < 0) THEN (_r.invhist_invqty)
69405                ELSE 0
69406           END,
69407           0,
69408           _r.invhist_invqty * _r.invhist_unitcost * _r.sense,
69409           CASE WHEN (_r.sense > 0) THEN _r.invhist_invqty * _r.invhist_unitcost
69410                ELSE 0
69411           END,
69412           CASE WHEN (_r.sense < 0) THEN (_r.invhist_invqty  * _r.invhist_unitcost)
69413                ELSE 0
69414           END,
69415           -- Non netable
69416           0, 
69417           CASE WHEN (_r.invhist_transtype='NN') THEN _r.invhist_invqty * -1
69418                ELSE 0
69419           END,
69420           CASE WHEN (_r.sense > 0 AND _r.invhist_transtype='NN') THEN _r.invhist_invqty * -1
69421                ELSE 0
69422           END,
69423           CASE WHEN (_r.sense < 0 AND _r.invhist_transtype='NN') THEN _r.invhist_invqty * -1
69424                ELSE 0
69425           END,
69426           0,
69427           CASE WHEN (_r.invhist_transtype='NN') THEN _r.invhist_invqty * _r.invhist_unitcost * -1
69428                ELSE 0
69429           END,
69430           CASE WHEN (_r.sense > 0 AND _r.invhist_transtype='NN') THEN _r.invhist_invqty * -1 * _r.invhist_unitcost
69431                ELSE 0
69432           END,
69433           CASE WHEN (_r.sense < 0 AND _r.invhist_transtype='NN') THEN (_r.invhist_invqty  * -1 * _r.invhist_unitcost)
69434                ELSE 0
69435           END,
69436           true );
69437     END IF;
69438   ELSE
69439     RETURN FALSE;
69440   END IF;
69441
69442   RETURN TRUE;
69443
69444 END;
69445 $_$;
69446
69447
69448 ALTER FUNCTION public.postintoinvbalance(integer) OWNER TO admin;
69449
69450 --
69451 -- TOC entry 2000 (class 1255 OID 146566833)
69452 -- Dependencies: 4536 8
69453 -- Name: postintotrialbalance(integer); Type: FUNCTION; Schema: public; Owner: admin
69454 --
69455
69456 CREATE FUNCTION postintotrialbalance(integer) RETURNS integer
69457     LANGUAGE plpgsql
69458     AS $_$
69459 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69460 -- See www.xtuple.com/CPAL for the full text of the software license.
69461 DECLARE
69462   pSequence ALIAS FOR $1;
69463   _trialbalid INTEGER;
69464   _r RECORD;
69465
69466 BEGIN
69467
69468 --  March through all of the G/L Transactions for the passed sequence that are not posted
69469   FOR _r IN SELECT gltrans_id, gltrans_date, gltrans_accnt_id, gltrans_amount,
69470                    accnt_forwardupdate, period_id, period_closed, period_freeze
69471             FROM accnt, gltrans LEFT OUTER JOIN period ON (gltrans_date BETWEEN period_start AND period_end)
69472             WHERE ( (gltrans_accnt_id=accnt_id)
69473              AND (NOT gltrans_posted)
69474              AND (NOT gltrans_deleted)
69475              AND (gltrans_sequence=pSequence) ) LOOP
69476
69477 --  If we can post into a Trial Balance, do so
69478     IF ( (NOT _r.period_closed) AND ( (NOT _r.period_freeze) OR (checkPrivilege('PostFrozenPeriod')) ) ) THEN
69479
69480 --  Try to find an existing trialbal
69481       SELECT trialbal_id INTO _trialbalid
69482       FROM trialbal
69483       WHERE ( (trialbal_period_id=_r.period_id)
69484        AND (trialbal_accnt_id=_r.gltrans_accnt_id) );
69485       IF (FOUND) THEN
69486
69487 --  We found a trialbal, update it with the G/L Transaction
69488 --  Note - two stage update to avoid any funny value caching logic
69489         IF (_r.gltrans_amount > 0) THEN
69490           UPDATE trialbal
69491           SET trialbal_credits = (trialbal_credits + _r.gltrans_amount)
69492           WHERE (trialbal_id=_trialbalid);
69493         ELSE
69494           UPDATE trialbal
69495           SET trialbal_debits = (trialbal_debits + (_r.gltrans_amount * -1))
69496           WHERE (trialbal_id=_trialbalid);
69497         END IF;
69498
69499         UPDATE trialbal
69500         SET trialbal_ending = (trialbal_beginning - trialbal_debits + trialbal_credits),
69501             trialbal_dirty=TRUE
69502         WHERE (trialbal_id=_trialbalid);
69503       ELSE
69504
69505 --  No existing trialbal, make one
69506         SELECT NEXTVAL('trialbal_trialbal_id_seq') INTO _trialbalid;
69507         INSERT INTO trialbal
69508         ( trialbal_id, trialbal_accnt_id, trialbal_period_id,
69509           trialbal_beginning, trialbal_dirty,
69510           trialbal_ending,
69511           trialbal_credits,
69512           trialbal_debits )
69513         VALUES
69514         ( _trialbalid, _r.gltrans_accnt_id, _r.period_id,
69515           0, TRUE,
69516           _r.gltrans_amount,
69517           CASE WHEN (_r.gltrans_amount > 0) THEN _r.gltrans_amount
69518                ELSE 0
69519           END,
69520           CASE WHEN (_r.gltrans_amount < 0) THEN (_r.gltrans_amount * -1)
69521                ELSE 0
69522           END );
69523       END IF;
69524
69525 --  Forward update if we should
69526       IF (_r.accnt_forwardupdate AND fetchmetricbool('ManualForwardUpdate')) THEN
69527         PERFORM forwardUpdateTrialBalance(_trialbalid);
69528       END IF;
69529
69530 --  Mark the G/L Transaction as posted
69531       UPDATE gltrans
69532       SET gltrans_posted=TRUE
69533       WHERE (gltrans_id=_r.gltrans_id);
69534
69535     END IF;
69536
69537   END LOOP;
69538
69539   RETURN 1;
69540
69541 END;
69542 $_$;
69543
69544
69545 ALTER FUNCTION public.postintotrialbalance(integer) OWNER TO admin;
69546
69547 --
69548 -- TOC entry 2012 (class 1255 OID 146566834)
69549 -- Dependencies: 4536 8
69550 -- Name: postinvhist(integer); Type: FUNCTION; Schema: public; Owner: admin
69551 --
69552
69553 CREATE FUNCTION postinvhist(integer) RETURNS boolean
69554     LANGUAGE plpgsql
69555     AS $_$
69556 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69557 -- See www.xtuple.com/CPAL for the full text of the software license.
69558 DECLARE
69559   pInvhistId ALIAS FOR $1;
69560   _r RECORD;
69561 BEGIN
69562
69563     IF ( SELECT metric_value
69564         FROM metric
69565         WHERE ((metric_name = 'EnableAsOfQOH')
69566         AND (metric_value = 't'))) THEN
69567       IF (NOT postIntoInvBalance(pInvhistId)) THEN
69568         RAISE EXCEPTION 'Post into Inventory Balance for invhist_id=% was unsuccessful',pInvhistId;
69569       END IF;
69570     END IF;
69571
69572     --Update itemsite qoh and change posted flag
69573     UPDATE itemsite SET 
69574       itemsite_qtyonhand = (itemsite_qtyonhand + (invhist_invqty * invhistSense(invhist_id))),
69575       itemsite_value = itemsite_value + invhist_value_after - invhist_value_before
69576     FROM invhist
69577     WHERE ( (itemsite_id=invhist_itemsite_id)
69578     AND (invhist_id=pInvhistId)
69579     AND (NOT invhist_posted) );
69580
69581     --Flag as posted
69582     UPDATE invhist SET
69583       invhist_posted=TRUE
69584     WHERE ( (invhist_id=pInvhistId)
69585     AND (invhist_posted=FALSE) );
69586
69587 RETURN TRUE;
69588
69589 END;
69590 $_$;
69591
69592
69593 ALTER FUNCTION public.postinvhist(integer) OWNER TO admin;
69594
69595 --
69596 -- TOC entry 2013 (class 1255 OID 146566835)
69597 -- Dependencies: 4536 8
69598 -- Name: postinvoice(integer); Type: FUNCTION; Schema: public; Owner: admin
69599 --
69600
69601 CREATE FUNCTION postinvoice(integer) RETURNS integer
69602     LANGUAGE plpgsql
69603     AS $_$
69604 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69605 -- See www.xtuple.com/CPAL for the full text of the software license.
69606 DECLARE
69607   pInvcheadid ALIAS FOR $1;
69608   _return INTEGER;
69609
69610 BEGIN
69611
69612   SELECT postInvoice(pInvcheadid, fetchJournalNumber('AR-IN')) INTO _return;
69613
69614   RETURN _return;
69615
69616 END;
69617 $_$;
69618
69619
69620 ALTER FUNCTION public.postinvoice(integer) OWNER TO admin;
69621
69622 --
69623 -- TOC entry 2014 (class 1255 OID 146566836)
69624 -- Dependencies: 4536 8
69625 -- Name: postinvoice(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
69626 --
69627
69628 CREATE FUNCTION postinvoice(integer, integer) RETURNS integer
69629     LANGUAGE plpgsql
69630     AS $_$
69631 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69632 -- See www.xtuple.com/CPAL for the full text of the software license.
69633 DECLARE
69634   pInvcheadid ALIAS FOR $1;
69635   pJournalNumber ALIAS FOR $2;
69636   _itemlocSeries INTEGER;
69637   _return INTEGER;
69638
69639 BEGIN
69640
69641   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
69642   SELECT postInvoice(pInvcheadid, pJournalNumber, _itemlocseries) INTO _return;
69643
69644   RETURN _return;
69645
69646 END;
69647 $_$;
69648
69649
69650 ALTER FUNCTION public.postinvoice(integer, integer) OWNER TO admin;
69651
69652 --
69653 -- TOC entry 2015 (class 1255 OID 146566837)
69654 -- Dependencies: 4536 8
69655 -- Name: postinvoice(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
69656 --
69657
69658 CREATE FUNCTION postinvoice(integer, integer, integer) RETURNS integer
69659     LANGUAGE plpgsql
69660     AS $_$
69661 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
69662 -- See www.xtuple.com/CPAL for the full text of the software license.
69663 DECLARE
69664   pInvcheadid ALIAS FOR $1;
69665   pJournalNumber ALIAS FOR $2;
69666   pItemlocSeries ALIAS FOR $3;
69667   _aropenid INTEGER;
69668   _cohistid INTEGER;
69669   _itemlocSeries INTEGER := 0;
69670   _invhistid INTEGER := 0;
69671   _amount NUMERIC;
69672   _roundedBase NUMERIC;
69673   _sequence INTEGER;
69674   _r RECORD;
69675   _p RECORD;
69676   _test INTEGER;
69677   _totalAmount          NUMERIC := 0;
69678   _totalRoundedBase     NUMERIC := 0;
69679   _totalAmountBase      NUMERIC := 0;
69680   _appliedAmount        NUMERIC := 0;
69681   _commissionDue        NUMERIC := 0;
69682   _tmpAccntId INTEGER;
69683   _tmpCurrId  INTEGER;
69684   _firstExchDate        DATE;
69685   _glDate               DATE;
69686   _exchGain             NUMERIC := 0;
69687
69688 BEGIN
69689
69690   IF ( ( SELECT invchead_posted
69691          FROM invchead
69692          WHERE (invchead_id=pInvcheadid) ) ) THEN
69693     RETURN -10;
69694   END IF;
69695
69696 --  Cache some parameters
69697   SELECT invchead.*, fetchGLSequence() AS sequence,
69698          findFreightAccount(invchead_cust_id) AS freightaccntid,
69699          findARAccount(invchead_cust_id) AS araccntid,
69700          ( SELECT COALESCE(SUM(taxhist_tax), 0)
69701            FROM invcheadtax
69702            WHERE ( (taxhist_parent_id = invchead_id)
69703              AND   (taxhist_taxtype_id = getFreightTaxtypeId()) ) ) AS freighttax,
69704          ( SELECT COALESCE(SUM(taxhist_tax), 0)
69705            FROM invcheadtax
69706            WHERE ( (taxhist_parent_id = invchead_id)
69707              AND   (taxhist_taxtype_id = getAdjustmentTaxtypeId()) ) ) AS adjtax
69708        INTO _p 
69709   FROM invchead
69710   WHERE (invchead_id=pInvcheadid);
69711
69712   _itemlocSeries = pItemlocSeries;
69713
69714   _glDate := COALESCE(_p.invchead_gldistdate, _p.invchead_invcdate);
69715
69716   IF (_p.invchead_salesrep_id < 0) THEN
69717     RAISE NOTICE 'Patch negative invchead_salesrep_id until invchead_salesrep_id is a true fkey';
69718     _p.invchead_salesrep_id := NULL;
69719   END IF;
69720
69721 -- the 1st MC iteration used the cohead_orderdate so we could get curr exch
69722 -- gain/loss between the sales and invoice dates, but see issue 3892.  leave
69723 -- this condition TRUE until we make this configurable or decide not to.
69724   IF TRUE THEN
69725       _firstExchDate := _p.invchead_invcdate;
69726   ELSE
69727 -- can we save a select by using: _firstExchDate := _p.invchead_orderdate;
69728       SELECT cohead_orderdate INTO _firstExchDate
69729       FROM cohead JOIN invchead ON (cohead_number = invchead_ordernumber)
69730       WHERE (invchead_id = pInvcheadid);
69731   END IF;
69732
69733 --  Start by handling taxes
69734   FOR _r IN SELECT tax_sales_accnt_id, 
69735               round(sum(taxdetail_tax),2) AS tax,
69736               currToBase(_p.invchead_curr_id, round(sum(taxdetail_tax),2), _firstExchDate) AS taxbasevalue
69737             FROM tax 
69738              JOIN calculateTaxDetailSummary('I', pInvcheadid, 'T') ON (taxdetail_tax_id=tax_id)
69739             GROUP BY tax_id, tax_sales_accnt_id LOOP
69740
69741     PERFORM insertIntoGLSeries( _p.sequence, 'A/R', 'IN', _p.invchead_invcnumber,
69742                                 _r.tax_sales_accnt_id, 
69743                                 _r.taxbasevalue,
69744                                 _glDate, _p.invchead_billto_name );
69745
69746     _totalAmount := _totalAmount + _r.tax;
69747     _totalRoundedBase := _totalRoundedBase + _r.taxbasevalue;  
69748   END LOOP;
69749
69750 -- Update item tax records with posting data
69751     UPDATE invcitemtax SET 
69752       taxhist_docdate=_firstExchDate,
69753       taxhist_distdate=_glDate,
69754       taxhist_curr_id=_p.invchead_curr_id,
69755       taxhist_curr_rate=curr_rate,
69756       taxhist_journalnumber=pJournalNumber
69757     FROM invchead
69758      JOIN invcitem ON (invchead_id=invcitem_invchead_id), 
69759      curr_rate
69760     WHERE ((invchead_id=pInvcheadId)
69761       AND (taxhist_parent_id=invcitem_id)
69762       AND (_p.invchead_curr_id=curr_id)
69763       AND ( _firstExchDate BETWEEN curr_effective 
69764                            AND curr_expires) );
69765
69766 -- Update Invchead taxes (Freight and Adjustments) with posting data
69767     UPDATE invcheadtax SET 
69768       taxhist_docdate=_firstExchDate,
69769       taxhist_distdate=_glDate,
69770       taxhist_curr_id=_p.invchead_curr_id,
69771       taxhist_curr_rate=curr_rate,
69772       taxhist_journalnumber=pJournalNumber
69773     FROM curr_rate
69774     WHERE ((taxhist_parent_id=pInvcheadid)
69775       AND (_p.invchead_curr_id=curr_id)
69776       AND ( _firstExchDate BETWEEN curr_effective 
69777                            AND curr_expires) );
69778
69779 --  March through the Non-Misc. Invcitems
69780   FOR _r IN SELECT *
69781             FROM invoiceitem
69782             WHERE ( (invcitem_invchead_id = pInvcheadid)
69783               AND   (invcitem_item_id <> -1) ) LOOP
69784
69785 --  Cache the amount due for this line
69786     _amount := _r.extprice;
69787
69788     IF (_amount > 0) THEN
69789 --  Credit the Sales Account for the invcitem item
69790       IF (_r.invcitem_rev_accnt_id IS NOT NULL) THEN
69791         SELECT getPrjAccntId(_p.invchead_prj_id, _r.invcitem_rev_accnt_id)
69792         INTO _tmpAccntId;
69793       ELSEIF (_r.itemsite_id IS NULL) THEN
69794         SELECT getPrjAccntId(_p.invchead_prj_id, salesaccnt_sales_accnt_id) 
69795         INTO _tmpAccntId
69796         FROM salesaccnt
69797         WHERE (salesaccnt_id=findSalesAccnt(_r.invcitem_item_id, 'I', _p.invchead_cust_id,
69798                                             _p.invchead_saletype_id, _p.invchead_shipzone_id));
69799       ELSE
69800         SELECT getPrjAccntId(_p.invchead_prj_id, salesaccnt_sales_accnt_id) 
69801         INTO _tmpAccntId
69802         FROM salesaccnt
69803         WHERE (salesaccnt_id=findSalesAccnt(_r.itemsite_id, 'IS', _p.invchead_cust_id,
69804                                             _p.invchead_saletype_id, _p.invchead_shipzone_id));
69805       END IF;
69806
69807 --  If the Sales Account Assignment was not found then punt
69808       IF (NOT FOUND) THEN
69809         PERFORM deleteGLSeries(_p.sequence);
69810         DELETE FROM cohist
69811          WHERE ((cohist_sequence=_p.sequence)
69812            AND  (cohist_invcnumber=_p.invchead_invcnumber));
69813         RETURN -11;
69814       END IF;
69815
69816       _roundedBase := round(currToBase(_p.invchead_curr_id, _amount, _firstExchDate), 2);
69817       SELECT insertIntoGLSeries( _p.sequence, 'A/R', 'IN',
69818                                  _p.invchead_invcnumber, _tmpAccntId,
69819                                  _roundedBase, _glDate, _p.invchead_billto_name ) INTO _test;
69820
69821       _totalAmount := (_totalAmount + _amount);
69822       _totalRoundedBase := _totalRoundedBase + _roundedBase;
69823       _commissionDue := (_commissionDue + (_amount * _p.invchead_commission));
69824     END IF;
69825
69826     _totalAmount := _totalAmount;
69827     _totalRoundedBase := _totalRoundedBase;
69828
69829 --  Record Sales History for this S/O Item
69830     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
69831     INSERT INTO cohist
69832     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
69833       cohist_shipdate, cohist_shipvia,
69834       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
69835       cohist_doctype, cohist_invcnumber, cohist_invcdate,
69836       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
69837       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
69838       cohist_billtoname, cohist_billtoaddress1,
69839       cohist_billtoaddress2, cohist_billtoaddress3,
69840       cohist_billtocity, cohist_billtostate, cohist_billtozip,
69841       cohist_shiptoname, cohist_shiptoaddress1,
69842       cohist_shiptoaddress2, cohist_shiptoaddress3,
69843       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
69844       cohist_curr_id, cohist_sequence, cohist_taxtype_id, cohist_taxzone_id,
69845       cohist_shipzone_id, cohist_saletype_id )
69846     VALUES
69847     ( _cohistid, _p.invchead_cust_id, _r.itemsite_id, _p.invchead_shipto_id,
69848       _p.invchead_shipdate, _p.invchead_shipvia,
69849       COALESCE(_p.invchead_ordernumber, _r.cohead_number), _p.invchead_ponumber, _p.invchead_orderdate,
69850       'I', _p.invchead_invcnumber, _p.invchead_invcdate,
69851       _r.qty, _r.unitprice, _r.unitcost,
69852       _p.invchead_salesrep_id, (_p.invchead_commission * _r.extprice), FALSE,
69853       _p.invchead_billto_name, _p.invchead_billto_address1,
69854       _p.invchead_billto_address2, _p.invchead_billto_address3,
69855       _p.invchead_billto_city, _p.invchead_billto_state, _p.invchead_billto_zipcode,
69856       _p.invchead_shipto_name, _p.invchead_shipto_address1,
69857       _p.invchead_shipto_address2, _p.invchead_shipto_address3,
69858       _p.invchead_shipto_city, _p.invchead_shipto_state,
69859       _p.invchead_shipto_zipcode, _p.invchead_curr_id,
69860       _p.sequence, _r.invcitem_taxtype_id, _p.invchead_taxzone_id,
69861       _p.invchead_shipzone_id, _p.invchead_saletype_id );
69862     INSERT INTO cohisttax
69863     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
69864       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
69865       taxhist_percent, taxhist_amount, taxhist_tax,
69866       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
69867       taxhist_journalnumber )
69868     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
69869            taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
69870            taxhist_percent, taxhist_amount, taxhist_tax,
69871            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
69872            taxhist_journalnumber
69873     FROM invcitemtax
69874     WHERE (taxhist_parent_id=_r.invcitem_id);
69875
69876   END LOOP;
69877
69878 --  March through the Misc. Invcitems
69879   FOR _r IN SELECT *
69880             FROM invoiceitem JOIN salescat ON (salescat_id = invcitem_salescat_id)
69881             WHERE ( (invcitem_item_id = -1)
69882               AND   (invcitem_invchead_id=pInvcheadid) ) LOOP
69883
69884 --  Cache the amount due for this line and the commission due for such
69885     _amount := _r.extprice;
69886
69887     IF (_amount > 0) THEN
69888 --  Credit the Sales Account for the invcitem item
69889       _roundedBase = round(currToBase(_p.invchead_curr_id, _amount,
69890                                       _firstExchDate), 2);
69891       SELECT insertIntoGLSeries( _p.sequence, 'A/R', 'IN', _p.invchead_invcnumber,
69892                                  getPrjAccntId(_p.invchead_prj_id, COALESCE(_r.invcitem_rev_accnt_id, _r.salescat_sales_accnt_id)), 
69893                                  _roundedBase,
69894                                  _glDate, _p.invchead_billto_name ) INTO _test;
69895       IF (_test < 0) THEN
69896         PERFORM deleteGLSeries(_p.sequence);
69897         DELETE FROM cohist
69898          WHERE ((cohist_sequence=_p.sequence)
69899            AND  (cohist_invcnumber=_p.invchead_invcnumber));
69900         RETURN _test;
69901       END IF;
69902
69903       _totalAmount := (_totalAmount + _amount);
69904       _totalRoundedBase :=  _totalRoundedBase + _roundedBase;
69905       _commissionDue := (_commissionDue + (_amount * _p.invchead_commission));
69906     END IF;
69907
69908 --  Record Sales History for this S/O Item
69909     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
69910     INSERT INTO cohist
69911     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
69912       cohist_misc_type, cohist_misc_descrip,
69913       cohist_shipdate, cohist_shipvia,
69914       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
69915       cohist_doctype, cohist_invcnumber, cohist_invcdate,
69916       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
69917       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
69918       cohist_billtoname, cohist_billtoaddress1,
69919       cohist_billtoaddress2, cohist_billtoaddress3,
69920       cohist_billtocity, cohist_billtostate, cohist_billtozip,
69921       cohist_shiptoname, cohist_shiptoaddress1,
69922       cohist_shiptoaddress2, cohist_shiptoaddress3,
69923       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
69924       cohist_curr_id, cohist_sequence, cohist_taxtype_id, cohist_taxzone_id,
69925       cohist_shipzone_id, cohist_saletype_id )
69926     VALUES
69927     ( _cohistid, _p.invchead_cust_id, -1, _p.invchead_shipto_id,
69928       'M', (_r.invcitem_number || '-' || _r.invcitem_descrip),
69929       _p.invchead_shipdate, _p.invchead_shipvia,
69930       COALESCE(_p.invchead_ordernumber, _r.cohead_number), _p.invchead_ponumber, _p.invchead_orderdate,
69931       'I', _p.invchead_invcnumber, _p.invchead_invcdate,
69932       _r.qty, _r.unitprice, 0,
69933       _p.invchead_salesrep_id, (_p.invchead_commission * _r.extprice), FALSE,
69934       _p.invchead_billto_name, _p.invchead_billto_address1,
69935       _p.invchead_billto_address2, _p.invchead_billto_address3,
69936       _p.invchead_billto_city, _p.invchead_billto_state, _p.invchead_billto_zipcode,
69937       _p.invchead_shipto_name, _p.invchead_shipto_address1,
69938       _p.invchead_shipto_address2, _p.invchead_shipto_address3,
69939       _p.invchead_shipto_city, _p.invchead_shipto_state,
69940       _p.invchead_shipto_zipcode, _p.invchead_curr_id,
69941       _p.sequence, _r.invcitem_taxtype_id, _p.invchead_taxzone_id,
69942       _p.invchead_shipzone_id, _p.invchead_saletype_id );
69943     INSERT INTO cohisttax
69944     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
69945       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
69946       taxhist_percent, taxhist_amount, taxhist_tax,
69947       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
69948       taxhist_journalnumber )
69949     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
69950            taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
69951            taxhist_percent, taxhist_amount, taxhist_tax,
69952            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
69953            taxhist_journalnumber
69954     FROM invcitemtax
69955     WHERE (taxhist_parent_id=_r.invcitem_id);
69956
69957   END LOOP;
69958
69959 --  Credit the Freight Account for Freight Charges
69960   IF (_p.invchead_freight <> 0) THEN
69961     IF (_p.freightaccntid <> -1) THEN
69962       _roundedBase = round(currToBase(_p.invchead_curr_id, _p.invchead_freight,
69963                                       _firstExchDate), 2);
69964       SELECT insertIntoGLSeries( _p.sequence, 'A/R', 'IN', _p.invchead_invcnumber,
69965                                  getPrjAccntId(_p.invchead_prj_id,_p.freightaccntid), 
69966                                  _roundedBase,
69967                                  _glDate, _p.invchead_billto_name ) INTO _test;
69968
69969 --  Cache the Freight Amount distributed
69970         _totalAmount := (_totalAmount + _p.invchead_freight);
69971         _totalRoundedBase := _totalRoundedBase + _roundedBase;
69972     ELSE
69973       _test := -14;
69974     END IF;
69975
69976 --  If the Freight Account was not found then punt
69977     IF (_test < 0) THEN
69978       PERFORM deleteGLSeries(_p.sequence);
69979       DELETE FROM cohist
69980        WHERE ((cohist_sequence=_p.sequence)
69981          AND  (cohist_invcnumber=_p.invchead_invcnumber));
69982       RETURN _test;
69983     END IF;
69984
69985 --  Record Sales History for the Freight
69986     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
69987     INSERT INTO cohist
69988     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
69989       cohist_misc_type, cohist_misc_descrip,
69990       cohist_shipdate, cohist_shipvia,
69991       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
69992       cohist_doctype, cohist_invcnumber, cohist_invcdate,
69993       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
69994       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
69995       cohist_billtoname, cohist_billtoaddress1,
69996       cohist_billtoaddress2, cohist_billtoaddress3,
69997       cohist_billtocity, cohist_billtostate, cohist_billtozip,
69998       cohist_shiptoname, cohist_shiptoaddress1,
69999       cohist_shiptoaddress2, cohist_shiptoaddress3,
70000       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
70001       cohist_curr_id, cohist_sequence, cohist_taxtype_id, cohist_taxzone_id,
70002       cohist_shipzone_id, cohist_saletype_id )
70003     VALUES
70004     ( _cohistid, _p.invchead_cust_id, -1, _p.invchead_shipto_id,
70005       'F', 'Freight',
70006       _p.invchead_shipdate, _p.invchead_shipvia,
70007       _p.invchead_ordernumber, _p.invchead_ponumber, _p.invchead_orderdate,
70008       'I', _p.invchead_invcnumber, _p.invchead_invcdate,
70009       1, _p.invchead_freight, _p.invchead_freight,
70010       _p.invchead_salesrep_id, 0, FALSE,
70011       _p.invchead_billto_name, _p.invchead_billto_address1,
70012       _p.invchead_billto_address2, _p.invchead_billto_address3,
70013       _p.invchead_billto_city, _p.invchead_billto_state, _p.invchead_billto_zipcode,
70014       _p.invchead_shipto_name, _p.invchead_shipto_address1,
70015       _p.invchead_shipto_address2, _p.invchead_shipto_address3,
70016       _p.invchead_shipto_city, _p.invchead_shipto_state,
70017       _p.invchead_shipto_zipcode, _p.invchead_curr_id,
70018       _p.sequence, getFreightTaxtypeId(), _p.invchead_taxzone_id,
70019       _p.invchead_shipzone_id, _p.invchead_saletype_id );
70020     INSERT INTO cohisttax
70021     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
70022       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
70023       taxhist_percent, taxhist_amount, taxhist_tax,
70024       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
70025       taxhist_journalnumber )
70026     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
70027            taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
70028            taxhist_percent, taxhist_amount, taxhist_tax,
70029            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
70030            taxhist_journalnumber
70031     FROM invcheadtax
70032     WHERE ( (taxhist_parent_id=_p.invchead_id)
70033       AND   (taxhist_taxtype_id=getFreightTaxtypeId()) );
70034
70035   END IF;
70036
70037 --  Credit the Misc. Account for Miscellaneous Charges
70038   IF (_p.invchead_misc_amount <> 0) THEN
70039     _roundedBase := round(currToBase(_p.invchead_curr_id, _p.invchead_misc_amount,
70040                                      _firstExchDate), 2);
70041     SELECT insertIntoGLSeries( _p.sequence, 'A/R', 'IN', _p.invchead_invcnumber,
70042                                getPrjAccntId(_p.invchead_prj_id, _p.invchead_misc_accnt_id), 
70043                                _roundedBase,
70044                                _glDate, _p.invchead_billto_name ) INTO _test;
70045
70046 --  If the Misc. Charges Account was not found then punt
70047     IF (_test < 0) THEN
70048       PERFORM deleteGLSeries(_p.sequence);
70049       DELETE FROM cohist
70050        WHERE ((cohist_sequence=_p.sequence)
70051          AND  (cohist_invcnumber=_p.invchead_invcnumber));
70052       RETURN _test;
70053     END IF;
70054
70055 --  Cache the Misc. Amount distributed
70056     _totalAmount := (_totalAmount + _p.invchead_misc_amount);
70057     _totalRoundedBase := _totalRoundedBase + _roundedBase;
70058
70059 --  Record Sales History for the Misc. Charge
70060     INSERT INTO cohist
70061     ( cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
70062       cohist_misc_type, cohist_misc_descrip, cohist_misc_id,
70063       cohist_shipdate, cohist_shipvia,
70064       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
70065       cohist_doctype, cohist_invcnumber, cohist_invcdate,
70066       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
70067       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
70068       cohist_billtoname, cohist_billtoaddress1,
70069       cohist_billtoaddress2, cohist_billtoaddress3,
70070       cohist_billtocity, cohist_billtostate, cohist_billtozip,
70071       cohist_shiptoname, cohist_shiptoaddress1,
70072       cohist_shiptoaddress2, cohist_shiptoaddress3,
70073       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
70074       cohist_curr_id, cohist_sequence,
70075       cohist_shipzone_id, cohist_saletype_id )
70076     VALUES
70077     ( _p.invchead_cust_id, -1, _p.invchead_shipto_id,
70078       'M', _p.invchead_misc_descrip, _p.invchead_misc_accnt_id,
70079       _p.invchead_shipdate, _p.invchead_shipvia,
70080       _p.invchead_ordernumber, _p.invchead_ponumber, _p.invchead_orderdate,
70081       'I', _p.invchead_invcnumber, _p.invchead_invcdate,
70082       1, _p.invchead_misc_amount, _p.invchead_misc_amount,
70083       _p.invchead_salesrep_id, 0, FALSE,
70084       _p.invchead_billto_name, _p.invchead_billto_address1,
70085       _p.invchead_billto_address2, _p.invchead_billto_address3,
70086       _p.invchead_billto_city, _p.invchead_billto_state, _p.invchead_billto_zipcode,
70087       _p.invchead_shipto_name, _p.invchead_shipto_address1,
70088       _p.invchead_shipto_address2, _p.invchead_shipto_address3,
70089       _p.invchead_shipto_city, _p.invchead_shipto_state,
70090       _p.invchead_shipto_zipcode, _p.invchead_curr_id,
70091       _p.sequence,
70092       _p.invchead_shipzone_id, _p.invchead_saletype_id );
70093
70094   END IF;
70095
70096 --  Record Sales History for the Tax Adjustment
70097   IF (_p.adjtax <> 0) THEN
70098     SELECT nextval('cohist_cohist_id_seq') INTO _cohistid;
70099     INSERT INTO cohist
70100     ( cohist_id, cohist_cust_id, cohist_itemsite_id, cohist_shipto_id,
70101       cohist_misc_type, cohist_misc_descrip,
70102       cohist_shipdate, cohist_shipvia,
70103       cohist_ordernumber, cohist_ponumber, cohist_orderdate,
70104       cohist_doctype, cohist_invcnumber, cohist_invcdate,
70105       cohist_qtyshipped, cohist_unitprice, cohist_unitcost,
70106       cohist_salesrep_id, cohist_commission, cohist_commissionpaid,
70107       cohist_billtoname, cohist_billtoaddress1,
70108       cohist_billtoaddress2, cohist_billtoaddress3,
70109       cohist_billtocity, cohist_billtostate, cohist_billtozip,
70110       cohist_shiptoname, cohist_shiptoaddress1,
70111       cohist_shiptoaddress2, cohist_shiptoaddress3,
70112       cohist_shiptocity, cohist_shiptostate, cohist_shiptozip,
70113       cohist_curr_id, cohist_sequence, cohist_taxtype_id, cohist_taxzone_id,
70114       cohist_shipzone_id, cohist_saletype_id )
70115     VALUES
70116     ( _cohistid, _p.invchead_cust_id, -1, _p.invchead_shipto_id,
70117       'T', 'Misc Tax Adjustment',
70118       _p.invchead_shipdate, _p.invchead_shipvia,
70119       _p.invchead_ordernumber, _p.invchead_ponumber, _p.invchead_orderdate,
70120       'I', _p.invchead_invcnumber, _p.invchead_invcdate,
70121       1, 0.0, 0.0,
70122       _p.invchead_salesrep_id, 0, FALSE,
70123       _p.invchead_billto_name, _p.invchead_billto_address1,
70124       _p.invchead_billto_address2, _p.invchead_billto_address3,
70125       _p.invchead_billto_city, _p.invchead_billto_state, _p.invchead_billto_zipcode,
70126       _p.invchead_shipto_name, _p.invchead_shipto_address1,
70127       _p.invchead_shipto_address2, _p.invchead_shipto_address3,
70128       _p.invchead_shipto_city, _p.invchead_shipto_state,
70129       _p.invchead_shipto_zipcode, _p.invchead_curr_id,
70130       _p.sequence, getAdjustmentTaxtypeId(), _p.invchead_taxzone_id,
70131       _p.invchead_shipzone_id, _p.invchead_saletype_id );
70132     INSERT INTO cohisttax
70133     ( taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
70134       taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
70135       taxhist_percent, taxhist_amount, taxhist_tax,
70136       taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
70137       taxhist_journalnumber )
70138     SELECT _cohistid, taxhist_taxtype_id, taxhist_tax_id,
70139            taxhist_basis, taxhist_basis_tax_id, taxhist_sequence,
70140            taxhist_percent, taxhist_amount, taxhist_tax,
70141            taxhist_docdate, taxhist_distdate, taxhist_curr_id, taxhist_curr_rate,
70142            taxhist_journalnumber
70143     FROM invcheadtax
70144     WHERE ( (taxhist_parent_id=_p.invchead_id)
70145       AND   (taxhist_taxtype_id=getAdjustmentTaxtypeId()) );
70146
70147   END IF;
70148
70149 -- ToDo: handle rounding errors
70150     _exchGain := currGain(_p.invchead_curr_id, _totalAmount,
70151                           _firstExchDate, _glDate);
70152     IF (_exchGain <> 0) THEN
70153         SELECT insertIntoGLSeries( _p.sequence, 'A/R', 'IN',
70154                                    _p.invchead_invcnumber, getGainLossAccntId(_p.araccntid),
70155                                    round(_exchGain, 2) * -1,
70156                                    _glDate, _p.invchead_billto_name ) INTO _test ;
70157         IF (_test < 0) THEN
70158           PERFORM deleteGLSeries(_p.sequence);
70159           DELETE FROM cohist
70160            WHERE ((cohist_sequence=_p.sequence)
70161              AND  (cohist_invcnumber=_p.invchead_invcnumber));
70162           RETURN _test;
70163         END IF;
70164     END IF;
70165
70166 --  Debit A/R for the total Amount
70167   IF (_totalRoundedBase <> 0) THEN
70168     IF (_p.araccntid != -1) THEN
70169       PERFORM insertIntoGLSeries( _p.sequence, 'A/R', 'IN', _p.invchead_invcnumber,
70170                                   _p.araccntid, round(_totalRoundedBase * -1, 2),
70171                                   _glDate, _p.invchead_billto_name );
70172     ELSE
70173       PERFORM deleteGLSeries(_p.sequence);
70174       DELETE FROM cohist
70175        WHERE ((cohist_sequence=_p.sequence)
70176          AND  (cohist_invcnumber=_p.invchead_invcnumber));
70177       RETURN -17;
70178     END IF;
70179   END IF;
70180
70181 --  Commit the GLSeries;
70182   SELECT postGLSeries(_p.sequence, pJournalNumber) INTO _test;
70183   IF (_test < 0) THEN
70184     PERFORM deleteGLSeries(_p.sequence);
70185     DELETE FROM cohist
70186      WHERE ((cohist_sequence=_p.sequence)
70187        AND  (cohist_invcnumber=_p.invchead_invcnumber));
70188     RETURN _test;
70189   END IF;
70190
70191 --  Create the Invoice aropen item
70192   SELECT nextval('aropen_aropen_id_seq') INTO _aropenid;
70193   INSERT INTO aropen
70194   ( aropen_id, aropen_username, aropen_journalnumber,
70195     aropen_open, aropen_posted,
70196     aropen_cust_id, aropen_ponumber,
70197     aropen_docnumber, aropen_applyto, aropen_doctype,
70198     aropen_docdate, aropen_duedate, aropen_distdate, aropen_terms_id,
70199     aropen_amount, aropen_paid,
70200     aropen_salesrep_id, aropen_commission_due, aropen_commission_paid,
70201     aropen_ordernumber, aropen_notes, aropen_cobmisc_id,
70202     aropen_curr_id )
70203   VALUES
70204   ( _aropenid, getEffectiveXtUser(), pJournalNumber,
70205     TRUE, FALSE,
70206     _p.invchead_cust_id, _p.invchead_ponumber,
70207     _p.invchead_invcnumber, _p.invchead_invcnumber, 'I',
70208     _p.invchead_invcdate, determineDueDate(_p.invchead_terms_id, _p.invchead_invcdate), _glDate, _p.invchead_terms_id,
70209     round(_totalAmount, 2), 0, 
70210     _p.invchead_salesrep_id, _commissionDue, FALSE,
70211     _p.invchead_ordernumber::text, _p.invchead_notes, pInvcheadid,
70212     _p.invchead_curr_id );
70213
70214 -- Handle the Inventory and G/L Transactions for any billed Inventory where invcitem_updateinv is true
70215   FOR _r IN SELECT itemsite_id AS itemsite_id, invcitem_id,
70216                    (invcitem_billed * invcitem_qty_invuomratio) AS qty,
70217                    invchead_invcnumber, invchead_cust_id AS cust_id, item_number,
70218                    invchead_saletype_id AS saletype_id, invchead_shipzone_id AS shipzone_id,
70219                    invchead_prj_id, itemsite_costmethod
70220             FROM invchead JOIN invcitem ON ( (invcitem_invchead_id=invchead_id) AND
70221                                              (invcitem_billed <> 0) AND
70222                                              (invcitem_updateinv) )
70223                           JOIN itemsite ON ( (itemsite_item_id=invcitem_item_id) AND
70224                                              (itemsite_warehous_id=invcitem_warehous_id) )
70225                           JOIN item ON (item_id=invcitem_item_id)
70226             WHERE (invchead_id=pInvcheadid) LOOP
70227
70228 --  Issue billed stock from inventory
70229     IF (_itemlocSeries = 0) THEN
70230       _itemlocSeries := NEXTVAL('itemloc_series_seq');
70231     END IF;
70232     IF (_r.itemsite_costmethod != 'J') THEN
70233       SELECT postInvTrans(itemsite_id, 'SH', _r.qty,
70234                          'S/O', 'IN', _r.invchead_invcnumber, '',
70235                          ('Invoice Billed ' || _r.item_number),
70236                          getPrjAccntId(_r.invchead_prj_id, resolveCOSAccount(itemsite_id, _r.cust_id, _r.saletype_id, _r.shipzone_id)),
70237                          costcat_asset_accnt_id, _itemlocSeries, _glDate) INTO _invhistid
70238       FROM itemsite, costcat
70239       WHERE ( (itemsite_costcat_id=costcat_id)
70240        AND (itemsite_id=_r.itemsite_id) );
70241     ELSE
70242       RAISE DEBUG 'postInvoice(%, %, %) tried to postInvTrans a %-costed item',
70243                   pInvcheadid, pJournalNumber, pItemlocSeries,
70244                   _r.itemsite_costmethod;
70245     END IF;
70246
70247   END LOOP;
70248
70249 --  Mark the invoice as posted
70250   UPDATE invchead
70251   SET invchead_posted=TRUE, invchead_gldistdate=_glDate
70252   WHERE (invchead_id=pInvcheadid);
70253  
70254   IF (_totalAmount > 0) THEN
70255     -- get a list of allocated CMs
70256     FOR _r IN SELECT aropen_id,
70257                      CASE WHEN((aropen_amount - aropen_paid) >=
70258                                 aropenalloc_amount / (1 / aropen_curr_rate / 
70259                                 currRate(aropenalloc_curr_id,_firstExchDate))) THEN
70260                               aropenalloc_amount / (1 / aropen_curr_rate / 
70261                                 currRate(aropenalloc_curr_id,_firstExchDate))
70262                           ELSE (aropen_amount - aropen_paid)
70263                      END AS balance,
70264                      aropen_curr_id, aropen_curr_rate,
70265                      aropenalloc_doctype, aropenalloc_doc_id
70266                 FROM aropenalloc, aropen
70267                WHERE ( (aropenalloc_aropen_id=aropen_id)
70268                  AND   ((aropenalloc_doctype='S' AND aropenalloc_doc_id=(SELECT cohead_id
70269                                                                            FROM cohead
70270                                                                           WHERE cohead_number=_p.invchead_ordernumber)) OR
70271                         (aropenalloc_doctype='I' AND aropenalloc_doc_id=_p.invchead_id)) ) LOOP
70272
70273       _appliedAmount := _r.balance;
70274       IF (_totalAmount < _appliedAmount / (1 / currRate(_r.aropen_curr_id,_firstExchDate) /
70275                         _r.aropen_curr_rate)) THEN
70276         _appliedAmount := _totalAmount;
70277         _tmpCurrId := _p.invchead_curr_id;
70278       ELSE
70279         _tmpCurrId := _r.aropen_curr_id;
70280       END IF;
70281
70282       -- ignore if no appliable balance
70283       IF (_appliedAmount > 0) THEN
70284         -- create an arcreditapply record linking the source c/m and the target invoice
70285         -- for an amount that is equal to the balance on the invoice or the balance on
70286         -- c/m whichever is greater.
70287         INSERT INTO arcreditapply
70288               (arcreditapply_source_aropen_id, arcreditapply_target_aropen_id,
70289                arcreditapply_amount, arcreditapply_curr_id, arcreditapply_reftype, arcreditapply_ref_id)
70290         VALUES(_r.aropen_id, _aropenid, _appliedAmount, _tmpCurrId, 'S',  _r.aropenalloc_doc_id);
70291
70292         -- call postARCreditMemoApplication(aropen_id of C/M)
70293         SELECT postARCreditMemoApplication(_r.aropen_id) into _test;
70294
70295         -- if no error decrement the balance and contiue on
70296         IF (_test >= 0) THEN
70297           _totalAmount := _totalAmount - currToCurr(_tmpCurrId, _p.invchead_curr_id,
70298                                                     _appliedAmount, _firstExchDate);
70299         END IF;
70300
70301         -- delete the allocation
70302         DELETE FROM aropenalloc
70303         WHERE (aropenalloc_doctype='I')
70304           AND (aropenalloc_doc_id=_p.invchead_id);
70305
70306       END IF;
70307     END LOOP;
70308   END IF;
70309
70310   RETURN _itemlocSeries;
70311
70312 END;
70313 $_$;
70314
70315
70316 ALTER FUNCTION public.postinvoice(integer, integer, integer) OWNER TO admin;
70317
70318 --
70319 -- TOC entry 2016 (class 1255 OID 146566839)
70320 -- Dependencies: 4536 8
70321 -- Name: postinvoices(boolean); Type: FUNCTION; Schema: public; Owner: admin
70322 --
70323
70324 CREATE FUNCTION postinvoices(boolean) RETURNS integer
70325     LANGUAGE plpgsql
70326     AS $_$
70327 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70328 -- See www.xtuple.com/CPAL for the full text of the software license.
70329 DECLARE
70330   pPostUnprinted ALIAS FOR $1;
70331 BEGIN
70332   RETURN postInvoices(pPostUnprinted, FALSE);
70333 END;
70334 $_$;
70335
70336
70337 ALTER FUNCTION public.postinvoices(boolean) OWNER TO admin;
70338
70339 --
70340 -- TOC entry 2017 (class 1255 OID 146566840)
70341 -- Dependencies: 4536 8
70342 -- Name: postinvoices(boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
70343 --
70344
70345 CREATE FUNCTION postinvoices(boolean, boolean) RETURNS integer
70346     LANGUAGE plpgsql
70347     AS $_$
70348 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70349 -- See www.xtuple.com/CPAL for the full text of the software license.
70350 DECLARE
70351   pPostUnprinted ALIAS FOR $1;
70352   pInclZeros     ALIAS FOR $2;
70353 BEGIN
70354   RETURN postInvoices(pPostUnprinted, pInclZeros, fetchJournalNumber('AR-IN'));
70355 END;
70356 $_$;
70357
70358
70359 ALTER FUNCTION public.postinvoices(boolean, boolean) OWNER TO admin;
70360
70361 --
70362 -- TOC entry 2018 (class 1255 OID 146566841)
70363 -- Dependencies: 4536 8
70364 -- Name: postinvoices(boolean, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
70365 --
70366
70367 CREATE FUNCTION postinvoices(boolean, boolean, integer) RETURNS integer
70368     LANGUAGE plpgsql
70369     AS $_$
70370 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70371 -- See www.xtuple.com/CPAL for the full text of the software license.
70372 DECLARE
70373   pPostUnprinted ALIAS FOR $1;
70374   pInclZeros     ALIAS FOR $2;
70375   pJournalNumber ALIAS FOR $3;
70376   _invcheadid    INTEGER;
70377   _itemlocSeries INTEGER;
70378   _counter INTEGER;
70379   _r RECORD;
70380
70381 BEGIN
70382
70383   _itemlocSeries := 0;
70384
70385   IF (pInclZeros) THEN
70386
70387     FOR _invcheadid IN
70388       SELECT invchead_id
70389       FROM invchead
70390       WHERE ( (NOT invchead_posted)
70391        AND (checkInvoiceSitePrivs(invchead_id))
70392        AND (pPostUnprinted OR invchead_printed) ) LOOP
70393
70394       SELECT postInvoice(_invcheadid, pJournalNumber, _itemlocSeries) INTO _itemlocSeries;
70395       IF (_itemlocSeries < 0) THEN
70396         RETURN _itemlocSeries;
70397       END IF;
70398     END LOOP;
70399
70400   ELSE
70401
70402     FOR _invcheadid IN
70403       SELECT invchead_id
70404       FROM invchead LEFT OUTER JOIN invcitem ON (invchead_id=invcitem_invchead_id)
70405                     LEFT OUTER JOIN item ON (invcitem_item_id=item_id)  
70406       WHERE((NOT invchead_posted)
70407         AND (checkInvoiceSitePrivs(invchead_id))
70408         AND (pPostUnprinted OR invchead_printed))
70409       GROUP BY invchead_id, invchead_freight, invchead_misc_amount
70410       HAVING (COALESCE(SUM(round((invcitem_billed * invcitem_qty_invuomratio) * (invcitem_price /  
70411               CASE WHEN (item_id IS NULL) THEN 1 
70412               ELSE invcitem_price_invuomratio END), 2)),0)
70413              + invchead_freight + invchead_misc_amount) > 0 LOOP
70414
70415       SELECT postInvoice(_invcheadid, pJournalNumber, _itemlocSeries) INTO _itemlocSeries;
70416       IF (_itemlocSeries < 0) THEN
70417         RETURN _itemlocSeries;
70418       END IF;
70419     END LOOP;
70420
70421   END IF;
70422
70423   RETURN _itemlocSeries;
70424
70425 END;
70426 $_$;
70427
70428
70429 ALTER FUNCTION public.postinvoices(boolean, boolean, integer) OWNER TO admin;
70430
70431 --
70432 -- TOC entry 2019 (class 1255 OID 146566842)
70433 -- Dependencies: 4536 8
70434 -- Name: postinvtrans(integer, text, numeric, text, text, text, text, text, integer, integer, integer, timestamp with time zone, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
70435 --
70436
70437 CREATE FUNCTION postinvtrans(pitemsiteid integer, ptranstype text, pqty numeric, pmodule text, pordertype text, pordernumber text, pdocnumber text, pcomments text, pdebitid integer, pcreditid integer, pitemlocseries integer, ptimestamp timestamp with time zone DEFAULT now(), pcostovrld numeric DEFAULT NULL::numeric, pinvhistid integer DEFAULT NULL::integer) RETURNS integer
70438     LANGUAGE plpgsql
70439     AS $$
70440 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70441 -- See www.xtuple.com/CPAL for the full text of the software license.
70442 -- pInvhistid is the original transaction to be returned, reversed, etc.
70443 DECLARE
70444   _creditid          INTEGER;
70445   _debitid           INTEGER;
70446   _glreturn          INTEGER;
70447   _invhistid         INTEGER;
70448   _itemlocdistid     INTEGER;
70449   _r                 RECORD;
70450   _sense             INTEGER;  -- direction in which to adjust inventory QOH
70451   _t                 RECORD;
70452   _timestamp         TIMESTAMP WITH TIME ZONE;
70453   _xferwhsid         INTEGER;
70454
70455 BEGIN
70456
70457   --  Cache item and itemsite info  
70458   SELECT CASE WHEN(itemsite_costmethod IN ('A','J')) THEN COALESCE(abs(pCostOvrld / pQty), avgcost(itemsite_id))
70459               ELSE stdCost(itemsite_item_id)
70460          END AS cost,
70461          itemsite_costmethod,
70462          itemsite_qtyonhand,
70463          itemsite_warehous_id,
70464          ( (item_type = 'R') OR (itemsite_controlmethod = 'N') ) AS nocontrol,
70465          (itemsite_controlmethod IN ('L', 'S')) AS lotserial,
70466          (itemsite_loccntrl) AS loccntrl,
70467          itemsite_freeze AS frozen INTO _r
70468   FROM itemsite JOIN item ON (item_id=itemsite_item_id)
70469   WHERE (itemsite_id=pItemsiteid);
70470
70471   --Post the Inventory Transactions
70472   IF (_r.nocontrol) THEN
70473     RETURN -1; -- non-fatal error so dont throw an exception?
70474   END IF;
70475
70476   IF (COALESCE(pItemlocSeries,0) = 0) THEN
70477     RAISE EXCEPTION 'Transaction series must be provided';
70478   END IF;
70479
70480   SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
70481
70482   IF ((pTimestamp IS NULL) OR (CAST(pTimestamp AS date)=CURRENT_DATE)) THEN
70483     _timestamp := CURRENT_TIMESTAMP;
70484   ELSE
70485     _timestamp := pTimestamp;
70486   END IF;
70487
70488   IF (pTransType = 'TS' OR pTransType = 'TR') THEN
70489     SELECT * INTO _t FROM tohead WHERE (tohead_number=pDocNumber);
70490     IF (pTransType = 'TS') THEN
70491       _xferwhsid := CASE
70492           WHEN (_t.tohead_src_warehous_id=_r.itemsite_warehous_id) THEN _t.tohead_trns_warehous_id
70493           WHEN (_t.tohead_trns_warehous_id=_r.itemsite_warehous_id AND pComments ~* 'recall') THEN _t.tohead_src_warehous_id
70494           WHEN (_t.tohead_trns_warehous_id=_r.itemsite_warehous_id) THEN _t.tohead_dest_warehous_id
70495           WHEN (_t.tohead_dest_warehous_id=_r.itemsite_warehous_id) THEN _t.tohead_trns_warehous_id
70496           ELSE NULL
70497           END;
70498     ELSIF (pTransType = 'TR') THEN
70499       _xferwhsid := CASE
70500           WHEN (_t.tohead_src_warehous_id=_r.itemsite_warehous_id) THEN _t.tohead_trns_warehous_id
70501           WHEN (_t.tohead_trns_warehous_id=_r.itemsite_warehous_id AND pComments ~* 'recall') THEN _t.tohead_dest_warehous_id
70502           WHEN (_t.tohead_trns_warehous_id=_r.itemsite_warehous_id) THEN _t.tohead_src_warehous_id
70503           WHEN (_t.tohead_dest_warehous_id=_r.itemsite_warehous_id) THEN _t.tohead_trns_warehous_id
70504           ELSE NULL
70505           END;
70506     END IF;
70507   END IF;
70508
70509
70510   -- increase inventory: AD RM RT RP RR RS RX RB TR
70511   -- decrease inventory: IM IB IT SH SI EX RI
70512   -- TS and TR are special: shipShipment and recallShipment should not change
70513   -- QOH at the Transfer Order src whs (as this was done by issueToShipping)
70514   -- but postReceipt should change QOH at the transit whs
70515   IF (pTransType='TS') THEN
70516     _sense := CASE WHEN (SELECT tohead_trns_warehous_id=_r.itemsite_warehous_id
70517                          FROM tohead
70518                          WHERE (tohead_number=pDocNumber)) THEN -1
70519                          ELSE 0
70520                          END;
70521   ELSIF (pTransType='TR') THEN
70522     _sense := CASE WHEN (SELECT tohead_src_warehous_id=_r.itemsite_warehous_id
70523                          FROM tohead
70524                          WHERE (tohead_number=pDocNumber)) THEN 0
70525                          ELSE 1
70526                          END;
70527   ELSIF (pTransType IN ('IM', 'IB', 'IT', 'SH', 'SI', 'EX', 'RI')) THEN
70528     _sense := -1;
70529
70530   ELSE
70531     _sense := 1;
70532   END IF;
70533
70534   IF((_r.itemsite_costmethod='A') AND (_r.itemsite_qtyonhand + round(_sense * pQty, 6)) < 0) THEN
70535     -- Can not let average costed itemsites go negative
70536     RAISE EXCEPTION 'This transaction will cause an Average Costed item to go negative which is not allowed [xtuple: postinvtrans, -2]';
70537   END IF;
70538
70539   INSERT INTO invhist
70540   ( invhist_id, invhist_itemsite_id, invhist_transtype, invhist_transdate,
70541       invhist_invqty, invhist_qoh_before,
70542       invhist_qoh_after,
70543       invhist_costmethod, invhist_value_before, invhist_value_after,
70544       invhist_ordtype, invhist_ordnumber, invhist_docnumber, invhist_comments,
70545       invhist_invuom, invhist_unitcost, invhist_xfer_warehous_id, invhist_posted,
70546       invhist_series )
70547   SELECT
70548     _invhistid, itemsite_id, pTransType, _timestamp,
70549     pQty, itemsite_qtyonhand,
70550     (itemsite_qtyonhand + (_sense * pQty)),
70551     itemsite_costmethod, itemsite_value, itemsite_value + (_r.cost * _sense * pQty),
70552     pOrderType, pOrderNumber, pDocNumber, pComments,
70553     uom_name, _r.cost, _xferwhsid, FALSE, pItemlocSeries
70554   FROM itemsite, item, uom
70555   WHERE ( (itemsite_item_id=item_id)
70556    AND (item_inv_uom_id=uom_id)
70557    AND (itemsite_id=pItemsiteid) );
70558
70559   IF (pCreditid IN (SELECT accnt_id FROM accnt)) THEN
70560     _creditid = pCreditid;
70561   ELSE
70562     SELECT warehous_default_accnt_id INTO _creditid
70563     FROM itemsite, whsinfo
70564     WHERE ( (itemsite_warehous_id=warehous_id)
70565       AND  (itemsite_id=pItemsiteid) );
70566   END IF;
70567
70568   IF (pDebitid IN (SELECT accnt_id FROM accnt)) THEN
70569     _debitid = pDebitid;
70570   ELSE
70571     SELECT warehous_default_accnt_id INTO _debitid
70572     FROM itemsite, whsinfo
70573     WHERE ( (itemsite_warehous_id=warehous_id)
70574       AND  (itemsite_id=pItemsiteid) );
70575   END IF;
70576
70577   --  Post the G/L Transaction
70578   IF (_creditid <> _debitid) THEN
70579     SELECT insertGLTransaction(pModule, pOrderType, pOrderNumber, pComments,
70580                                _creditid, _debitid, _invhistid,
70581                                (_r.cost * pQty), _timestamp::DATE, FALSE) INTO _glreturn;
70582   END IF;
70583
70584   --  Distribute this if this itemsite is controlled
70585   IF ( _r.lotserial OR _r.loccntrl ) THEN
70586
70587     _itemlocdistid := nextval('itemlocdist_itemlocdist_id_seq');
70588     INSERT INTO itemlocdist
70589     ( itemlocdist_id,
70590       itemlocdist_itemsite_id,
70591       itemlocdist_source_type,
70592       itemlocdist_reqlotserial,
70593       itemlocdist_distlotserial,
70594       itemlocdist_expiration,
70595       itemlocdist_qty,
70596       itemlocdist_series,
70597       itemlocdist_invhist_id,
70598       itemlocdist_order_type,
70599       itemlocdist_order_id )
70600     SELECT _itemlocdistid,
70601            pItemsiteid,
70602            'O',
70603            (((pQty * _sense) > 0)  AND _r.lotserial),
70604            ((pQty * _sense) < 0),
70605            endOfTime(),
70606            (_sense * pQty),
70607            pItemlocSeries,
70608            _invhistid,
70609            pOrderType, 
70610            CASE WHEN pOrderType='SO' THEN getSalesLineItemId(pOrderNumber)
70611                 ELSE NULL
70612            END;
70613
70614     -- populate distributions if invhist_id parameter passed to undo
70615     IF (pInvhistid IS NOT NULL) THEN
70616       INSERT INTO itemlocdist
70617         ( itemlocdist_itemlocdist_id, itemlocdist_source_type, itemlocdist_source_id,
70618           itemlocdist_itemsite_id, itemlocdist_ls_id, itemlocdist_expiration,
70619           itemlocdist_qty, itemlocdist_series, itemlocdist_invhist_id ) 
70620       SELECT _itemlocdistid, 'L', COALESCE(invdetail_location_id, -1),
70621              invhist_itemsite_id, invdetail_ls_id,  COALESCE(invdetail_expiration, endoftime()),
70622              (invdetail_qty * -1.0), pItemlocSeries, _invhistid
70623       FROM invhist JOIN invdetail ON (invdetail_invhist_id=invhist_id)
70624       WHERE (invhist_id=pInvhistid);
70625
70626       IF ( _r.lotserial)  THEN          
70627         INSERT INTO lsdetail 
70628           ( lsdetail_itemsite_id, lsdetail_ls_id, lsdetail_created,
70629             lsdetail_source_type, lsdetail_source_id, lsdetail_source_number ) 
70630         SELECT invhist_itemsite_id, invdetail_ls_id, CURRENT_TIMESTAMP,
70631                'I', _itemlocdistid, ''
70632         FROM invhist JOIN invdetail ON (invdetail_invhist_id=invhist_id)
70633         WHERE (invhist_id=pInvhistid);
70634       END IF;
70635
70636       PERFORM distributeitemlocseries(pItemlocSeries);
70637       
70638     END IF;
70639
70640   END IF;   -- end of distributions
70641
70642   -- These records will be used for posting G/L transactions to trial balance after records committed.
70643   -- If we try to do it now concurrency locking prevents any transactions while
70644   -- user enters item distribution information.  Cant have that.
70645   INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
70646   VALUES ( _glreturn, pItemlocSeries );
70647
70648   RETURN _invhistid;
70649
70650 END;
70651 $$;
70652
70653
70654 ALTER FUNCTION public.postinvtrans(pitemsiteid integer, ptranstype text, pqty numeric, pmodule text, pordertype text, pordernumber text, pdocnumber text, pcomments text, pdebitid integer, pcreditid integer, pitemlocseries integer, ptimestamp timestamp with time zone, pcostovrld numeric, pinvhistid integer) OWNER TO admin;
70655
70656 --
70657 -- TOC entry 2020 (class 1255 OID 146566844)
70658 -- Dependencies: 4536 8
70659 -- Name: postitemlocseries(integer); Type: FUNCTION; Schema: public; Owner: admin
70660 --
70661
70662 CREATE FUNCTION postitemlocseries(integer) RETURNS boolean
70663     LANGUAGE plpgsql
70664     AS $_$
70665 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70666 -- See www.xtuple.com/CPAL for the full text of the software license.
70667 DECLARE
70668   pItemlocseries ALIAS FOR $1;
70669   _result INTEGER;
70670
70671 BEGIN
70672
70673   PERFORM postIntoTrialBalance(itemlocpost_glseq)
70674   FROM (
70675     SELECT DISTINCT itemlocpost_glseq, gltrans_accnt_id
70676     FROM itemlocpost
70677       JOIN gltrans ON (itemlocpost_glseq=gltrans_sequence)
70678     WHERE (itemlocpost_itemlocseries=pItemlocseries)
70679     ORDER BY gltrans_accnt_id
70680   ) AS data;
70681   
70682   PERFORM postInvHist(invhist_id)
70683   FROM invhist
70684     JOIN itemsite ON (invhist_itemsite_id=itemsite_id)
70685   WHERE ( (invhist_series=pItemlocseries)
70686   AND ( NOT invhist_posted) 
70687   AND ( NOT itemsite_freeze) );
70688
70689   DELETE FROM itemlocpost WHERE (itemlocpost_itemlocseries=pItemlocseries);
70690
70691   RETURN TRUE;
70692   
70693 END;
70694 $_$;
70695
70696
70697 ALTER FUNCTION public.postitemlocseries(integer) OWNER TO admin;
70698
70699 --
70700 -- TOC entry 2024 (class 1255 OID 146566845)
70701 -- Dependencies: 4536 8
70702 -- Name: postjournals(integer); Type: FUNCTION; Schema: public; Owner: admin
70703 --
70704
70705 CREATE FUNCTION postjournals(integer) RETURNS integer
70706     LANGUAGE plpgsql
70707     AS $_$
70708 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70709 -- See www.xtuple.com/CPAL for the full text of the software license.
70710 DECLARE
70711   pSequence     ALIAS FOR $1;
70712   _transCount INTEGER := 0;
70713   _journalnumber INTEGER := fetchJournalNumber('J/P');
70714   _sequence INTEGER := fetchGLSequence();
70715   _sltrans RECORD;
70716 BEGIN
70717
70718 --  Make sure that we balance
70719   IF (SELECT SUM(sltrans_amount) != 0
70720       FROM sltrans
70721       WHERE ((NOT sltrans_posted )
70722        AND (sltrans_sequence=pSequence))) THEN
70723      RAISE EXCEPTION 'Can not post journals. Transactions do not balance in selected date range.';
70724   END IF;
70725
70726 --  March through the sltrans members, posting them one at a time
70727   FOR _sltrans IN SELECT sltrans_source, sltrans_accnt_id,
70728                           SUM(sltrans_amount) as amount
70729                      FROM sltrans
70730                     WHERE ((sltrans_amount<>0.0)
70731                       AND  (NOT sltrans_posted)
70732                       AND  (sltrans_sequence=pSequence))
70733                     GROUP BY sltrans_source, sltrans_accnt_id LOOP
70734
70735 -- refuse to accept postings into closed periods
70736     IF (SELECT BOOL_AND(COALESCE(period_closed, FALSE))
70737         FROM accnt LEFT OUTER JOIN
70738              period ON (CURRENT_DATE BETWEEN period_start AND period_end)
70739         WHERE (accnt_id = _sltrans.sltrans_accnt_id)) THEN
70740       RAISE EXCEPTION 'Cannot post to closed period (%).', _sltrans.sltrans_distdate;
70741       RETURN -4;        -- remove raise exception when all callers check return code
70742     END IF;
70743
70744 -- refuse to accept postings into frozen periods without proper priv
70745     IF (SELECT NOT BOOL_AND(checkPrivilege('PostFrozenPeriod')) AND
70746                BOOL_AND(COALESCE(period_freeze, FALSE))
70747         FROM accnt LEFT OUTER JOIN
70748              period ON (CURRENT_DATE BETWEEN period_start AND period_end)
70749         WHERE (accnt_id = _sltrans.sltrans_accnt_id)) THEN
70750       RAISE EXCEPTION 'Cannot post to frozen period (%).', _sltrans.sltrans_distdate;
70751       RETURN -4;        -- remove raise exception when all callers check return code
70752     END IF;
70753
70754     IF (_sltrans.amount != 0) THEN
70755        INSERT INTO gltrans
70756         ( gltrans_posted, gltrans_exported, gltrans_created, gltrans_date,
70757           gltrans_sequence, gltrans_accnt_id, gltrans_source, gltrans_notes,
70758           gltrans_doctype, gltrans_docnumber, gltrans_amount, gltrans_journalnumber, gltrans_rec )
70759         VALUES
70760         ( FALSE, FALSE, CURRENT_TIMESTAMP, CURRENT_DATE,
70761           _sequence, _sltrans.sltrans_accnt_id, _sltrans.sltrans_source, 'Journal Posting',
70762           'JP', _journalnumber, _sltrans.amount, _journalnumber, TRUE );
70763       
70764       _transCount := _transCount + 1;
70765     END IF;
70766   END LOOP;
70767
70768 --  Update all of the posted sltrans members
70769   UPDATE sltrans SET
70770     sltrans_posted=true,
70771     sltrans_gltrans_journalnumber=_journalnumber
70772   WHERE ((NOT sltrans_posted)
70773     AND (sltrans_sequence=pSequence));
70774
70775   PERFORM postIntoTrialBalance(_sequence);
70776
70777   RETURN _journalnumber;
70778
70779 END;
70780 $_$;
70781
70782
70783 ALTER FUNCTION public.postjournals(integer) OWNER TO admin;
70784
70785 --
70786 -- TOC entry 2025 (class 1255 OID 146566846)
70787 -- Dependencies: 4536 8
70788 -- Name: postjournals(text[], date, date, date); Type: FUNCTION; Schema: public; Owner: admin
70789 --
70790
70791 CREATE FUNCTION postjournals(text[], date, date, date) RETURNS SETOF integer
70792     LANGUAGE plpgsql
70793     AS $_$
70794 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70795 -- See www.xtuple.com/CPAL for the full text of the software license.
70796 DECLARE
70797   pSources              ALIAS FOR $1;
70798   pStartDate            ALIAS FOR $2;
70799   pEndDate              ALIAS FOR $3;
70800   pDistDate             ALIAS FOR $4;
70801   _i INTEGER;
70802 BEGIN
70803   FOR _i IN 1..ARRAY_UPPER(pSources,1)
70804   LOOP
70805     RETURN NEXT postJournals(pSources[_i], pStartDate, pEndDate, pDistDate);
70806   END LOOP;
70807   RETURN;
70808 END;
70809 $_$;
70810
70811
70812 ALTER FUNCTION public.postjournals(text[], date, date, date) OWNER TO admin;
70813
70814 --
70815 -- TOC entry 2026 (class 1255 OID 146566847)
70816 -- Dependencies: 4536 8
70817 -- Name: postjournals(text, date, date, date); Type: FUNCTION; Schema: public; Owner: admin
70818 --
70819
70820 CREATE FUNCTION postjournals(text, date, date, date) RETURNS integer
70821     LANGUAGE plpgsql
70822     AS $_$
70823 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70824 -- See www.xtuple.com/CPAL for the full text of the software license.
70825 DECLARE
70826   pSource               ALIAS FOR $1;
70827   pStartDate            ALIAS FOR $2;
70828   pEndDate              ALIAS FOR $3;
70829   pDistDate             ALIAS FOR $4;
70830   _transCount INTEGER := 0;
70831   _journalnumber INTEGER := fetchJournalNumber('J/P');
70832   _sequence INTEGER := fetchGLSequence();
70833   _sltrans RECORD;
70834 BEGIN
70835
70836 --  Make sure that we balance
70837   IF (SELECT SUM(sltrans_amount) != 0
70838       FROM sltrans
70839       WHERE ((NOT sltrans_posted )
70840        AND (sltrans_source=pSource)
70841        AND (sltrans_date BETWEEN pStartDate AND pEndDate))) THEN
70842      RAISE EXCEPTION 'Can not post journals. Transactions do not balance in selected date range.';
70843   END IF;
70844
70845 --  March through the sltrans members, posting them one at a time
70846   FOR _sltrans IN SELECT sltrans_source, sltrans_accnt_id,
70847                           SUM(sltrans_amount) as amount
70848                      FROM sltrans
70849                     WHERE ((sltrans_amount<>0.0)
70850                       AND  (NOT sltrans_posted)
70851                       AND  (sltrans_source=pSource)
70852                       AND  (sltrans_date BETWEEN pStartDate AND pEndDate))
70853                     GROUP BY sltrans_source, sltrans_accnt_id LOOP
70854
70855 -- refuse to accept postings into frozen periods if any of the accounts disallow it
70856     IF (SELECT NOT BOOL_AND(checkPrivilege('PostFrozenPeriod')) AND
70857                BOOL_AND(COALESCE(period_freeze, FALSE))
70858         FROM accnt LEFT OUTER JOIN
70859              period ON (pDistDate BETWEEN period_start AND period_end)
70860         WHERE (accnt_id = _sltrans.sltrans_accnt_id)) THEN
70861       RAISE EXCEPTION 'Cannot post to frozen period (%).', _sltrans.sltrans_distdate;
70862       RETURN -4;        -- remove raise exception when all callers check return code
70863     END IF;
70864
70865     IF (_sltrans.amount != 0) THEN
70866        INSERT INTO gltrans
70867         ( gltrans_posted, gltrans_exported, gltrans_created, gltrans_date,
70868           gltrans_sequence, gltrans_accnt_id, gltrans_source, gltrans_notes,
70869           gltrans_doctype, gltrans_docnumber, gltrans_amount, gltrans_journalnumber )
70870         VALUES
70871         ( FALSE, FALSE, CURRENT_TIMESTAMP, pDistDate,
70872           _sequence, _sltrans.sltrans_accnt_id, _sltrans.sltrans_source, 'Journal Posting',
70873           'JP', _journalnumber, _sltrans.amount, _journalnumber );
70874       
70875       _transCount := _transCount + 1;
70876     END IF;
70877   END LOOP;
70878
70879 --  Update all of the posted sltrans members
70880   UPDATE sltrans SET
70881     sltrans_posted=true,
70882     sltrans_gltrans_journalnumber=_journalnumber
70883   WHERE ((NOT sltrans_posted)
70884     AND (sltrans_source=pSource)
70885     AND (sltrans_date BETWEEN pStartDate AND pEndDate));
70886
70887   PERFORM postIntoTrialBalance(_sequence);
70888
70889   RETURN _journalnumber;
70890
70891 END;
70892 $_$;
70893
70894
70895 ALTER FUNCTION public.postjournals(text, date, date, date) OWNER TO admin;
70896
70897 --
70898 -- TOC entry 2028 (class 1255 OID 146566849)
70899 -- Dependencies: 4536 8
70900 -- Name: postmessage(text, text); Type: FUNCTION; Schema: public; Owner: admin
70901 --
70902
70903 CREATE FUNCTION postmessage(text, text) RETURNS integer
70904     LANGUAGE plpgsql
70905     AS $_$
70906 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70907 -- See www.xtuple.com/CPAL for the full text of the software license.
70908 DECLARE
70909   pUsername ALIAS FOR $1;
70910   pText ALIAS FOR $2;
70911   _msgid INTEGER;
70912
70913 BEGIN
70914
70915   SELECT NEXTVAL('msg_msg_id_seq') INTO _msgid;
70916   INSERT INTO msg
70917   (msg_id, msg_posted, msg_scheduled, msg_expires, msg_username, msg_text)
70918   VALUES
70919   (_msgid, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, endOfTime(), getEffectiveXtUser(), pText);
70920
70921   INSERT INTO msguser
70922   ( msguser_msg_id, msguser_username )
70923   VALUES
70924   ( _msgid, pUsername );
70925
70926   NOTIFY "messagePosted";
70927
70928   RETURN _msgid;
70929
70930 END;
70931 $_$;
70932
70933
70934 ALTER FUNCTION public.postmessage(text, text) OWNER TO admin;
70935
70936 --
70937 -- TOC entry 2027 (class 1255 OID 146566848)
70938 -- Dependencies: 4536 8
70939 -- Name: postmessage(timestamp without time zone, timestamp without time zone, text); Type: FUNCTION; Schema: public; Owner: admin
70940 --
70941
70942 CREATE FUNCTION postmessage(timestamp without time zone, timestamp without time zone, text) RETURNS integer
70943     LANGUAGE plpgsql
70944     AS $_$
70945 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70946 -- See www.xtuple.com/CPAL for the full text of the software license.
70947 DECLARE
70948   pScheduled ALIAS FOR $1;
70949   pExpires ALIAS FOR $2;
70950   pText ALIAS FOR $3;
70951   _msgid INTEGER;
70952
70953 BEGIN
70954
70955   SELECT NEXTVAL('msg_msg_id_seq') INTO _msgid;
70956   INSERT INTO msg
70957   (msg_id, msg_posted, msg_scheduled, msg_expires, msg_username, msg_text)
70958   VALUES
70959   (_msgid, CURRENT_TIMESTAMP, pScheduled, pExpires, getEffectiveXtUser(), pText);
70960
70961   INSERT INTO msguser
70962   ( msguser_msg_id, msguser_username )
70963   SELECT _msgid, usr_username
70964   FROM usr
70965   WHERE (usr_username <> getEffectiveXtUser());
70966
70967   NOTIFY "messagePosted";
70968
70969   RETURN _msgid;
70970
70971 END;
70972 $_$;
70973
70974
70975 ALTER FUNCTION public.postmessage(timestamp without time zone, timestamp without time zone, text) OWNER TO admin;
70976
70977 --
70978 -- TOC entry 2029 (class 1255 OID 146566850)
70979 -- Dependencies: 4536 8
70980 -- Name: postmessage(timestamp without time zone, timestamp without time zone, text, text); Type: FUNCTION; Schema: public; Owner: admin
70981 --
70982
70983 CREATE FUNCTION postmessage(timestamp without time zone, timestamp without time zone, text, text) RETURNS integer
70984     LANGUAGE plpgsql
70985     AS $_$
70986 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
70987 -- See www.xtuple.com/CPAL for the full text of the software license.
70988 DECLARE
70989   pScheduled ALIAS FOR $1;
70990   pExpires ALIAS FOR $2;
70991   pUsername ALIAS FOR $3;
70992   pText ALIAS FOR $4;
70993   _msgid INTEGER;
70994
70995 BEGIN
70996
70997   SELECT NEXTVAL('msg_msg_id_seq') INTO _msgid;
70998   INSERT INTO msg
70999   (msg_id, msg_posted, msg_scheduled, msg_expires, msg_username, msg_text)
71000   VALUES
71001   (_msgid, CURRENT_TIMESTAMP, pScheduled, pExpires, getEffectiveXtUser(), pText);
71002
71003   INSERT INTO msguser
71004   ( msguser_msg_id, msguser_username )
71005   VALUES
71006   ( _msgid, pUsername );
71007
71008   NOTIFY "messagePosted";
71009
71010   RETURN _msgid;
71011
71012 END;
71013 $_$;
71014
71015
71016 ALTER FUNCTION public.postmessage(timestamp without time zone, timestamp without time zone, text, text) OWNER TO admin;
71017
71018 --
71019 -- TOC entry 2030 (class 1255 OID 146566851)
71020 -- Dependencies: 4536 8
71021 -- Name: postmisccount(integer, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
71022 --
71023
71024 CREATE FUNCTION postmisccount(pitemsiteid integer, pqty numeric, pcomments text) RETURNS integer
71025     LANGUAGE plpgsql
71026     AS $_$
71027 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71028 -- See www.xtuple.com/CPAL for the full text of the software license.
71029 DECLARE
71030   pItemsiteid ALIAS FOR $1;
71031   pQty ALIAS FOR $2;
71032   pComments ALIAS FOR $3;
71033   _invcntid INTEGER;
71034   _result INTEGER;
71035
71036 BEGIN
71037
71038 --  Make sure the passed itemsite points to a real item
71039   IF ( ( SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
71040          FROM itemsite, item
71041          WHERE ( (itemsite_item_id=item_id)
71042           AND (itemsite_id=pItemsiteid) ) ) ) THEN
71043     RETURN 0;
71044   END IF;
71045
71046   SELECT invcnt_id INTO _invcntid
71047   FROM invcnt
71048   WHERE ( (NOT invcnt_posted)
71049    AND (invcnt_itemsite_id=pItemsiteid) );
71050
71051   IF (_invcntid IS NULL) THEN
71052     _invcntid := NEXTVAL('invcnt_invcnt_id_seq');
71053
71054     INSERT INTO invcnt
71055      ( invcnt_id, invcnt_itemsite_id, invcnt_tagdate,
71056        invcnt_qoh_before, invcnt_qoh_after,
71057        invcnt_tag_username, invcnt_cntdate, invcnt_cnt_username,
71058        invcnt_postdate, invcnt_post_username, invcnt_posted,
71059        invcnt_priority, invcnt_comments )
71060     SELECT _invcntid, pItemsiteid, now(),
71061            itemsite_qtyonhand, pQty,
71062            getEffectiveXtUser(), now(), getEffectiveXtUser(),
71063            now(), getEffectiveXtUser(), FALSE,
71064            FALSE, pComments
71065     FROM itemsite
71066     WHERE (itemsite_id=pItemsiteid);
71067
71068     SELECT postCountTag(_invcntid, FALSE) INTO _result;
71069     IF (_result < 0) THEN
71070       DELETE FROM invcnt
71071       WHERE (invcnt_id=_invcntid);
71072     END IF;
71073
71074     RETURN _result;
71075   ELSE
71076     RETURN -2;
71077   END IF;
71078
71079 END;
71080 $_$;
71081
71082
71083 ALTER FUNCTION public.postmisccount(pitemsiteid integer, pqty numeric, pcomments text) OWNER TO admin;
71084
71085 --
71086 -- TOC entry 2011 (class 1255 OID 146566852)
71087 -- Dependencies: 4536 8
71088 -- Name: postpogltransactions(); Type: FUNCTION; Schema: public; Owner: admin
71089 --
71090
71091 CREATE FUNCTION postpogltransactions() RETURNS boolean
71092     LANGUAGE plpgsql
71093     AS $$
71094 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71095 -- See www.xtuple.com/CPAL for the full text of the software license.
71096 BEGIN
71097
71098   UPDATE gltrans
71099   SET gltrans_exported=TRUE
71100   WHERE ( (NOT gltrans_exported)
71101    AND (gltrans_source='A/P')
71102    AND (gltrans_doctype IN ('VO')) );
71103
71104   RETURN TRUE;
71105
71106 END;
71107 $$;
71108
71109
71110 ALTER FUNCTION public.postpogltransactions() OWNER TO admin;
71111
71112 --
71113 -- TOC entry 2021 (class 1255 OID 146566853)
71114 -- Dependencies: 4536 8
71115 -- Name: postporeceipt(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
71116 --
71117
71118 CREATE FUNCTION postporeceipt(integer, integer) RETURNS integer
71119     LANGUAGE plpgsql
71120     AS $_$
71121 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71122 -- See www.xtuple.com/CPAL for the full text of the software license.
71123 BEGIN
71124   RETURN postReceipt($1, $2);
71125 END;
71126 $_$;
71127
71128
71129 ALTER FUNCTION public.postporeceipt(integer, integer) OWNER TO admin;
71130
71131 --
71132 -- TOC entry 2022 (class 1255 OID 146566854)
71133 -- Dependencies: 4536 8
71134 -- Name: postporeceipts(integer); Type: FUNCTION; Schema: public; Owner: admin
71135 --
71136
71137 CREATE FUNCTION postporeceipts(integer) RETURNS integer
71138     LANGUAGE plpgsql
71139     AS $_$
71140 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71141 -- See www.xtuple.com/CPAL for the full text of the software license.
71142 BEGIN
71143   RETURN postReceipts('PO', $1, NULL);
71144 END;
71145 $_$;
71146
71147
71148 ALTER FUNCTION public.postporeceipts(integer) OWNER TO admin;
71149
71150 --
71151 -- TOC entry 2023 (class 1255 OID 146566855)
71152 -- Dependencies: 4536 8
71153 -- Name: postporeturncreditmemo(integer); Type: FUNCTION; Schema: public; Owner: admin
71154 --
71155
71156 CREATE FUNCTION postporeturncreditmemo(integer) RETURNS integer
71157     LANGUAGE plpgsql
71158     AS $_$
71159 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71160 -- See www.xtuple.com/CPAL for the full text of the software license.
71161 DECLARE
71162   pPorejectId ALIAS FOR $1;
71163
71164 BEGIN
71165   RETURN postPoReturnCreditMemo(pPorejectId, NULL);
71166 END;
71167 $_$;
71168
71169
71170 ALTER FUNCTION public.postporeturncreditmemo(integer) OWNER TO admin;
71171
71172 --
71173 -- TOC entry 2031 (class 1255 OID 146566856)
71174 -- Dependencies: 4536 8
71175 -- Name: postporeturncreditmemo(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
71176 --
71177
71178 CREATE FUNCTION postporeturncreditmemo(integer, numeric) RETURNS integer
71179     LANGUAGE plpgsql
71180     AS $_$
71181 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71182 -- See www.xtuple.com/CPAL for the full text of the software license.
71183 DECLARE
71184   pPorejectId ALIAS FOR $1;
71185   pAmount ALIAS FOR $2;
71186   _p RECORD;
71187   _a RECORD;
71188   _itemsiteId INTEGER;
71189   _docNumber TEXT;
71190   _sequence INTEGER;
71191   _journalNumber INTEGER;
71192   _apopenid INTEGER;
71193   _exchGainItem NUMERIC;
71194   _itemAmount_base NUMERIC;
71195   _itemAmount NUMERIC;
71196   _glseriesTotal NUMERIC;
71197   _tmpTotal NUMERIC;
71198   _test INTEGER;
71199   _exchDate DATE;
71200   _tax RECORD;
71201   _taxAmount NUMERIC := 0;
71202   _taxAmount_base NUMERIC;
71203   _apaccntid INTEGER;
71204
71205 BEGIN
71206 --Set things up
71207   SELECT NEXTVAL('apopen_apopen_id_seq') INTO _apopenid;
71208   SELECT fetchGLSequence() INTO _sequence;
71209   SELECT fetchJournalNumber('AP-MISC') INTO _journalNumber;
71210   SELECT fetchapmemonumber() INTO _docNumber;
71211   _glseriesTotal := 0;
71212
71213 --Get poreject data
71214   SELECT pohead_vend_id, pohead_number, pohead_curr_id, pohead_orderdate, pohead_taxzone_id,
71215          poitem_id, poitem_itemsite_id,poitem_expcat_id, poitem_taxtype_id,
71216         itemsite_costcat_id, poreject_qty, poreject_date,
71217         ('Return of Item ' || COALESCE(item_number,poitem_vend_item_number)
71218            || ', qty. ' || formatqty(poreject_qty)) AS notes,
71219         poreject_value AS value,
71220         currToBase(pohead_curr_id,(poitem_unitprice * poreject_qty),CURRENT_DATE) AS itemAmount_base,
71221         (poitem_unitprice * poreject_qty) AS itemAmount
71222         INTO _p
71223   FROM pohead, poreject, poitem
71224         LEFT OUTER JOIN itemsite ON (poitem_itemsite_id=itemsite_id)
71225         LEFT OUTER JOIN item ON (itemsite_item_id=item_id)
71226   WHERE ((poreject_poitem_id=poitem_id)
71227   AND (pohead_id=poitem_pohead_id)
71228   AND (poreject_id=pPorejectId));
71229
71230   _itemAmount := _p.itemAmount;
71231   _itemAmount_base := _p.itemAmount_base;
71232   IF (pAmount IS NOT NULL) THEN
71233     _itemAmount := pAmount;
71234     _itemAmount_base := currToBase(_p.pohead_curr_id, pAmount, CURRENT_DATE);
71235   END IF;
71236   
71237
71238 --  Grab the G/L Accounts
71239   IF (COALESCE(_p.poitem_itemsite_id, -1) = -1) THEN
71240     SELECT pp.accnt_id AS pp_accnt_id,
71241            lb.accnt_id AS lb_accnt_id INTO _a
71242     FROM expcat, accnt AS pp, accnt AS lb
71243     WHERE ( (expcat_purchprice_accnt_id=pp.accnt_id)
71244      AND (expcat_liability_accnt_id=lb.accnt_id)
71245      AND (expcat_id=_p.poitem_expcat_id) );
71246     IF (NOT FOUND) THEN
71247       RAISE EXCEPTION 'Cannot Post Credit Memo due to unassigned G/L Accounts.';
71248     END IF;
71249   ELSE
71250     SELECT pp.accnt_id AS pp_accnt_id,
71251            lb.accnt_id AS lb_accnt_id INTO _a
71252     FROM costcat, accnt AS pp, accnt AS lb
71253     WHERE ( (costcat_purchprice_accnt_id=pp.accnt_id)
71254      AND (costcat_liability_accnt_id=lb.accnt_id)
71255      AND (costcat_id=_p.itemsite_costcat_id) );
71256     IF (NOT FOUND) THEN
71257       RAISE EXCEPTION 'Cannot Post Credit Memo due to unassigned G/L Accounts.';
71258     END IF;
71259   END IF;
71260
71261 --  AP Open Item record
71262     INSERT INTO apopen
71263     ( apopen_id, apopen_username, apopen_journalnumber,
71264       apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_ponumber,
71265       apopen_docdate, apopen_duedate, apopen_distdate, apopen_terms_id,
71266       apopen_amount, apopen_paid, apopen_open, apopen_notes, apopen_accnt_id, apopen_curr_id,
71267       apopen_closedate )
71268     VALUES
71269     ( _apopenid, getEffectiveXtUser(), _journalNumber,
71270       _p.pohead_vend_id, _docNumber, 'C', _p.pohead_number,
71271       CURRENT_DATE, CURRENT_DATE, CURRENT_DATE, -1,
71272       round(_itemAmount, 2), 0, (round(_itemAmount, 2) <> 0), _p.notes, -1, _p.pohead_curr_id,
71273       CASE WHEN (round(_itemAmount, 2) = 0) THEN _p.poreject_date END );
71274
71275 -- Taxes
71276     FOR _tax IN
71277       SELECT taxdetail_tax_id, sum(taxdetail_tax) AS taxdetail_tax,
71278         currToBase(_p.pohead_curr_id, round(sum(taxdetail_tax),2), current_date) AS taxbasevalue
71279       FROM calculateTaxDetail(_p.pohead_taxzone_id, _p.poitem_taxtype_id,
71280                                current_date, _p.pohead_curr_id, 
71281                                _itemAmount) 
71282       GROUP BY taxdetail_tax_id
71283     LOOP
71284       INSERT INTO apopentax (taxhist_basis,taxhist_percent,taxhist_amount,taxhist_docdate, taxhist_tax_id, taxhist_tax, 
71285                              taxhist_taxtype_id, taxhist_parent_id, taxhist_journalnumber ) 
71286       VALUES (0, 0, 0, current_date, _tax.taxdetail_tax_id, _tax.taxdetail_tax, getadjustmenttaxtypeid(), 
71287               _apopenid, _journalNumber);
71288
71289       _taxAmount := _taxAmount + _tax.taxdetail_tax;
71290  
71291     END LOOP;
71292
71293     _taxAmount_base := addTaxToGLSeries(_sequence,
71294                        'A/P', 'CM', _docNumber,
71295                        _p.pohead_curr_id, current_date, current_date,
71296                       'apopentax', _apopenid,
71297                       _p.notes);
71298
71299     UPDATE apopen SET apopen_amount = round(_itemAmount + _taxAmount,2)
71300     WHERE (apopen_id = _apopenid);
71301
71302 --  Distribute from the clearing account
71303     PERFORM insertIntoGLSeries( _sequence, 'A/P', 'CM', _docNumber,
71304                 _a.lb_accnt_id,
71305                 round(_p.value, 2),
71306                 current_date, _p.notes );
71307     _glseriesTotal := _glseriesTotal + round(_p.value, 2);
71308
71309 --  Distribute the remaining variance to the Purchase Price Variance account
71310     IF (round(_itemAmount_base, 2) <> round(_p.value, 2)) THEN
71311       _tmpTotal := round(_itemAmount_base, 2) - round(_p.value, 2);
71312       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'CM', _docNumber,
71313                                   _a.pp_accnt_id,
71314                                   _tmpTotal,
71315                                   current_date, _p.notes );
71316         _glseriesTotal := _glseriesTotal + _tmpTotal;
71317     END IF;
71318
71319 --  Post the reject item for this P/O Item as Invoiced
71320     UPDATE poreject
71321     SET poreject_invoiced=TRUE
71322     WHERE poreject_id=pPorejectId;
71323
71324 --  Update the qty vouchered field
71325     UPDATE poitem
71326        SET poitem_qty_vouchered = (poitem_qty_vouchered - _p.poreject_qty)
71327      WHERE (poitem_id=_p.poitem_id);
71328
71329 --  Post to A/P
71330   SELECT findAPAccount(_p.pohead_vend_id) INTO _apaccntid;
71331   IF (NOT FOUND) THEN
71332     RAISE EXCEPTION 'Cannot Post Credit Memo due to an unassigned A/P Account.';
71333   END IF;
71334
71335   SELECT insertIntoGLSeries( _sequence, 'A/P', 'CM', _docNumber,
71336                              _apaccntid, round(_itemAmount_base + _taxAmount_base, 2) *-1,
71337                              current_date, _p.notes ) INTO _test;
71338   IF (NOT FOUND) THEN
71339     RAISE EXCEPTION 'Cannot Post Credit Memo.';
71340   END IF;
71341
71342 -- Clean up loose ends
71343
71344   _glseriesTotal := _glseriesTotal + round(_itemAmount_base, 2)*-1;
71345
71346   IF (round(_glseriesTotal, 2) != 0) THEN
71347         PERFORM insertIntoGLSeries(_sequence, 'A/P', 'CM',
71348             'Currency Exchange Rounding - ' || _docNumber,
71349             getGainLossAccntId(_apaccntid), round(_glseriesTotal, 2) * -1,
71350            current_date, _p.notes);
71351   END IF;
71352
71353 --  Post it all
71354   PERFORM postGLSeries(_sequence, _journalNumber);
71355
71356   RETURN _journalNumber;
71357
71358 END;
71359 $_$;
71360
71361
71362 ALTER FUNCTION public.postporeturncreditmemo(integer, numeric) OWNER TO admin;
71363
71364 --
71365 -- TOC entry 1953 (class 1255 OID 146566858)
71366 -- Dependencies: 4536 8
71367 -- Name: postporeturns(integer); Type: FUNCTION; Schema: public; Owner: admin
71368 --
71369
71370 CREATE FUNCTION postporeturns(integer) RETURNS integer
71371     LANGUAGE plpgsql
71372     AS $_$
71373 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71374 -- See www.xtuple.com/CPAL for the full text of the software license.
71375 DECLARE
71376   pPoheadid ALIAS FOR $1;
71377   _itemlocSeries INTEGER;
71378   _p RECORD;
71379   _returnval    INTEGER;
71380
71381 BEGIN
71382
71383   _itemlocSeries := 0;
71384
71385   SELECT postPoReturns(pPoheadid,false) INTO _itemlocseries;
71386
71387   RETURN _itemlocSeries;
71388
71389 END;
71390 $_$;
71391
71392
71393 ALTER FUNCTION public.postporeturns(integer) OWNER TO admin;
71394
71395 --
71396 -- TOC entry 1954 (class 1255 OID 146566859)
71397 -- Dependencies: 4536 8
71398 -- Name: postporeturns(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
71399 --
71400
71401 CREATE FUNCTION postporeturns(integer, boolean) RETURNS integer
71402     LANGUAGE plpgsql
71403     AS $_$
71404 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71405 -- See www.xtuple.com/CPAL for the full text of the software license.
71406 DECLARE
71407   pPoheadid ALIAS FOR $1;
71408   pCreateMemo ALIAS FOR $2;
71409   _itemlocSeries INTEGER;
71410   _p RECORD;
71411   _returnval    INTEGER;
71412   _tmp        INTEGER;
71413   _pricevar   NUMERIC := 0.00;
71414   _invhistid            INTEGER;
71415   _journalNumber INTEGER := fetchJournalNumber('GL-MISC');
71416
71417 BEGIN
71418
71419   _itemlocSeries := 0;
71420
71421   FOR _p IN SELECT pohead_number, pohead_curr_id, poreject_id, poitem_prj_id,
71422                    poreject_poitem_id, poitem_id, poitem_expcat_id, poitem_linenumber,
71423                    currToBase(COALESCE(recv_purchcost_curr_id, pohead_curr_id),
71424                               COALESCE(recv_purchcost, poitem_unitprice),
71425                               pohead_orderdate) AS poitem_unitprice_base,
71426                    COALESCE(itemsite_id, -1) AS itemsiteid, poitem_invvenduomratio,
71427                    SUM(poreject_qty) AS totalqty,
71428                    itemsite_item_id, itemsite_costmethod, itemsite_controlmethod, recv_date
71429             FROM pohead JOIN poitem ON (poitem_pohead_id=pohead_id)
71430                         JOIN poreject ON (poreject_poitem_id=poitem_id AND NOT poreject_posted) 
71431                         LEFT OUTER JOIN itemsite ON (poitem_itemsite_id=itemsite_id)
71432                         LEFT OUTER JOIN recv ON (recv_id=poreject_recv_id)
71433             WHERE (pohead_id=pPoheadid)
71434             GROUP BY poreject_id, pohead_number, poreject_poitem_id, poitem_id, poitem_prj_id,
71435                      poitem_expcat_id, poitem_linenumber, poitem_unitprice, pohead_curr_id,
71436                      pohead_orderdate, itemsite_id, poitem_invvenduomratio,
71437                      itemsite_item_id, itemsite_costmethod, itemsite_controlmethod, recv_date,
71438                      recv_purchcost_curr_id, recv_purchcost LOOP
71439
71440     IF (_p.itemsiteid = -1) THEN
71441         SELECT insertGLTransaction( 'S/R', 'PO', _p.pohead_number, 'Return Non-Inventory to P/O',
71442                                      expcat_liability_accnt_id, 
71443                                      getPrjAccntId(_p.poitem_prj_id, expcat_exp_accnt_id), -1,
71444                                      round(_p.poitem_unitprice_base * _p.totalqty * -1, 2),
71445                                      CURRENT_DATE ) INTO _returnval
71446         FROM expcat
71447         WHERE (expcat_id=_p.poitem_expcat_id);
71448
71449         UPDATE poreject
71450         SET poreject_posted=TRUE, poreject_value= round(_p.poitem_unitprice_base * _p.totalqty, 2)
71451         WHERE (poreject_id=_p.poreject_id);
71452
71453     ELSEIF (_p.itemsite_controlmethod='N') THEN
71454       SELECT insertGLTransaction('S/R', 'PO', _p.pohead_number, 'Return Non-Controlled Inventory from PO',
71455                                  costcat_liability_accnt_id,
71456                                  getPrjAccntId(_p.poitem_prj_id, costcat_exp_accnt_id), -1,
71457                                  round((_p.poitem_unitprice_base * _p.totalqty * -1), 2),
71458                                  CURRENT_DATE ) INTO _returnval
71459       FROM itemsite, costcat
71460       WHERE((itemsite_costcat_id=costcat_id)
71461         AND (itemsite_id=_p.itemsiteid));
71462       IF (_returnval = -3) THEN -- zero value transaction
71463         _returnval := 0;
71464       END IF;
71465       UPDATE poreject
71466       SET poreject_posted=TRUE, poreject_value= round(_p.poitem_unitprice_base * _p.totalqty, 2)
71467       WHERE (poreject_id=_p.poreject_id);
71468     ELSE
71469       IF (_itemlocSeries = 0) THEN
71470         SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
71471       END IF;
71472
71473       SELECT postInvTrans( itemsite_id, 'RP', (_p.totalqty * _p.poitem_invvenduomratio * -1),
71474                            'S/R', 'PO', (_p.pohead_number || '-' || _p.poitem_linenumber::TEXT), '', 'Return Inventory to P/O',
71475                            costcat_asset_accnt_id, costcat_liability_accnt_id, _itemlocSeries, CURRENT_TIMESTAMP) INTO _returnval
71476       FROM itemsite, costcat
71477       WHERE ( (itemsite_costcat_id=costcat_id)
71478        AND (itemsite_id=_p.itemsiteid) );
71479
71480       UPDATE poreject
71481       SET poreject_posted=TRUE, poreject_value=(invhist_unitcost *_p.totalqty * _p.poitem_invvenduomratio)
71482       FROM invhist
71483       WHERE ((poreject_id=_p.poreject_id)
71484       AND (invhist_id=_returnval));
71485
71486     END IF;
71487
71488     IF (_returnval < 0) THEN
71489       RETURN _returnval;
71490     END IF;
71491
71492
71493     UPDATE poitem
71494     SET poitem_qty_returned=(poitem_qty_returned + _p.totalqty),
71495         poitem_status='O'
71496     WHERE (poitem_id=_p.poitem_id);
71497
71498       IF (fetchMetricBool('RecordPPVonReceipt')) THEN -- If the 'Purchase Price Variance on Receipt' option is true
71499          _invhistid := _returnval;
71500          -- Find the difference in the purchase price value expected from the P/O and the value of the transaction
71501          SELECT ((_p.poitem_unitprice_base * poitem_qty_returned) - (invhist_value_before - invhist_value_after)) INTO _pricevar
71502          FROM invhist, poitem
71503          WHERE ((invhist_id = _invhistid)
71504            AND  (poitem_id=_p.poitem_id));
71505
71506          -- If difference exists then
71507          IF (_pricevar <> 0.00) THEN
71508            -- Record an additional GL Transaction for the purchase price variance
71509            SELECT insertGLTransaction( _journalNumber,
71510                 'S/R', 'PO', _p.pohead_number,
71511                                        'Purchase price variance adjusted for P/O ' || _p.pohead_number || ' for item ' || _p.poitem_linenumber::TEXT,
71512                                        costcat_liability_accnt_id,
71513                                        getPrjAccntId(_p.poitem_prj_id, costcat_purchprice_accnt_id), -1,
71514                                        _pricevar,
71515                                        CURRENT_DATE, false ) INTO _tmp
71516            FROM itemsite, costcat, poitem
71517            WHERE ((itemsite_costcat_id=costcat_id)
71518               AND (itemsite_id=poitem_itemsite_id) );
71519            IF (NOT FOUND) THEN
71520              RAISE EXCEPTION 'Could not insert G/L transaction: no cost category found for itemsite_id %',
71521              _p.itemsiteid;
71522            ELSIF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
71523              RETURN _tmp;
71524            ELSE
71525              -- Posting to trial balance is deferred to prevent locking
71526              INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
71527              VALUES ( _tmp, _itemlocSeries );
71528            END IF;
71529          END IF;
71530        END IF;
71531
71532     IF (pCreateMemo) THEN
71533         SELECT postPoReturnCreditMemo(_p.poreject_id) INTO _returnval;
71534     END IF;
71535
71536     IF (_returnval < 0) THEN
71537       RETURN _returnval;
71538     END IF;
71539
71540   END LOOP;
71541
71542   RETURN _itemlocSeries;
71543
71544 END;
71545 $_$;
71546
71547
71548 ALTER FUNCTION public.postporeturns(integer, boolean) OWNER TO admin;
71549
71550 --
71551 -- TOC entry 2032 (class 1255 OID 146566861)
71552 -- Dependencies: 4536 8
71553 -- Name: postproduction(integer, numeric, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
71554 --
71555
71556 CREATE FUNCTION postproduction(integer, numeric, boolean, boolean) RETURNS integer
71557     LANGUAGE plpgsql
71558     AS $_$
71559 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71560 -- See www.xtuple.com/CPAL for the full text of the software license.
71561 BEGIN
71562   RAISE NOTICE 'postProduction(INTEGER, NUMERIC, BOOLEAN, BOOLEAN) is deprecated. please use postProduction(INTEGER, NUMERIC, BOOLEAN, INTEGER, TIMESTAMP WITH TIME ZONE) instead';
71563   RETURN postProduction($1, $2, $3, 0, now());
71564 END;
71565 $_$;
71566
71567
71568 ALTER FUNCTION public.postproduction(integer, numeric, boolean, boolean) OWNER TO admin;
71569
71570 --
71571 -- TOC entry 2033 (class 1255 OID 146566862)
71572 -- Dependencies: 4536 8
71573 -- Name: postproduction(integer, numeric, boolean, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
71574 --
71575
71576 CREATE FUNCTION postproduction(integer, numeric, boolean, boolean, integer) RETURNS integer
71577     LANGUAGE plpgsql
71578     AS $_$
71579 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71580 -- See www.xtuple.com/CPAL for the full text of the software license.
71581 BEGIN
71582   RAISE NOTICE 'postProduction(INTEGER, NUMERIC, BOOLEAN, BOOLEAN, INTEGER) is deprecated. please use postProduction(INTEGER, NUMERIC, BOOLEAN, INTEGER, TIMESTAMP WITH TIME ZONE) instead';
71583   RETURN postProduction($1, $2, $3, $5, now());
71584 END;
71585 $_$;
71586
71587
71588 ALTER FUNCTION public.postproduction(integer, numeric, boolean, boolean, integer) OWNER TO admin;
71589
71590 --
71591 -- TOC entry 2035 (class 1255 OID 146566864)
71592 -- Dependencies: 4536 8
71593 -- Name: postproduction(integer, numeric, boolean, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
71594 --
71595
71596 CREATE FUNCTION postproduction(integer, numeric, boolean, integer, timestamp with time zone) RETURNS integer
71597     LANGUAGE plpgsql
71598     AS $_$
71599 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71600 -- See www.xtuple.com/CPAL for the full text of the software license.
71601 DECLARE
71602   pWoid          ALIAS FOR $1;
71603   pQty           ALIAS FOR $2;
71604   pBackflush     ALIAS FOR $3;
71605   pItemlocSeries ALIAS FOR $4;
71606   pGlDistTS      ALIAS FOR $5;
71607   _test          INTEGER;
71608   _invhistid     INTEGER;
71609   _itemlocSeries INTEGER;
71610   _parentQty     NUMERIC;
71611   _r             RECORD;
71612   _sense         TEXT;
71613   _wipPost       NUMERIC;
71614   _woNumber      TEXT;
71615   _ucost         NUMERIC;
71616
71617 BEGIN
71618
71619   IF (pQty = 0) THEN
71620     RETURN 0;
71621   ELSIF (pQty > 0) THEN
71622     _sense = 'from';
71623   ELSE
71624     _sense = 'to';
71625   END IF;
71626
71627   IF ( ( SELECT wo_status
71628          FROM wo
71629          WHERE (wo_id=pWoid) ) NOT IN  ('R','E','I') ) THEN
71630     RETURN -1;
71631   END IF;
71632
71633 --  Make sure that all Component Item Sites exist
71634   SELECT bomitem_id INTO _test
71635   FROM wo, bomitem, itemsite
71636   WHERE ( (wo_itemsite_id=itemsite_id)
71637    AND (itemsite_item_id=bomitem_parent_item_id)
71638    AND (woEffectiveDate(wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
71639    AND (wo_id=pWoid)
71640    AND (bomitem_rev_id=wo_bom_rev_id)
71641    AND (bomitem_item_id NOT IN
71642         ( SELECT component.itemsite_item_id
71643           FROM itemsite AS component, itemsite AS parent
71644           WHERE ( (wo_itemsite_id=parent.itemsite_id)
71645            AND (parent.itemsite_item_id=bomitem_parent_item_id)
71646            AND (bomitem_item_id=component.itemsite_item_id)
71647            AND (woEffectiveDate(wo_startdate) BETWEEN bomitem_effective AND (bomitem_expires - 1))
71648            AND (bomitem_rev_id=wo_bom_rev_id)
71649            AND (component.itemsite_active)
71650            AND (component.itemsite_warehous_id=parent.itemsite_warehous_id) ) ) ) )
71651   LIMIT 1;
71652   IF (FOUND AND pBackflush) THEN
71653     RETURN -2;
71654   END IF;
71655
71656   SELECT formatWoNumber(pWoid) INTO _woNumber;
71657
71658   SELECT roundQty(item_fractional, pQty) INTO _parentQty
71659   FROM wo, itemsite, item
71660   WHERE ((wo_itemsite_id=itemsite_id)
71661    AND (itemsite_item_id=item_id)
71662    AND (wo_id=pWoid));
71663
71664 --  Create the material receipt transaction
71665   IF (pItemlocSeries = 0) THEN
71666     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
71667   ELSE
71668     _itemlocSeries = pItemlocSeries;
71669   END IF;
71670
71671   IF (pBackflush) THEN
71672     FOR _r IN SELECT womatl_id, womatl_qtyiss + 
71673                      (CASE 
71674                        WHEN (womatl_qtywipscrap >  ((womatl_qtyfxd + (_parentQty + wo_qtyrcv) * womatl_qtyper) * womatl_scrap)) THEN
71675                          (womatl_qtyfxd + (_parentQty + wo_qtyrcv) * womatl_qtyper) * womatl_scrap
71676                        ELSE 
71677                          womatl_qtywipscrap 
71678                       END) AS consumed,
71679                      (womatl_qtyfxd + ((_parentQty + wo_qtyrcv) * womatl_qtyper)) * (1 + womatl_scrap) AS expected
71680               FROM womatl, wo, itemsite, item
71681               WHERE ((womatl_issuemethod IN ('L', 'M'))
71682                 AND  (womatl_wo_id=pWoid)
71683                 AND  (womatl_wo_id=wo_id)
71684                 AND  (womatl_itemsite_id=itemsite_id)
71685                 AND  (itemsite_item_id=item_id)) LOOP
71686       -- Don't issue more than should have already been consumed at this point
71687       IF (pQty > 0) THEN
71688         IF (noNeg(_r.expected - _r.consumed) > 0) THEN
71689           SELECT issueWoMaterial(_r.womatl_id, noNeg(_r.expected - _r.consumed), _itemlocSeries, pGlDistTS) INTO _itemlocSeries;
71690         END IF;
71691       ELSE
71692         -- Used by postMiscProduction of disassembly
71693         SELECT returnWoMaterial(_r.womatl_id, (_r.expected * -1.0), _itemlocSeries, CURRENT_TIMESTAMP, true) INTO _itemlocSeries;
71694       END IF;
71695
71696       UPDATE womatl
71697       SET womatl_issuemethod='L'
71698       WHERE ( (womatl_issuemethod='M')
71699        AND (womatl_id=_r.womatl_id) );
71700
71701     END LOOP;
71702   END IF;
71703
71704   SELECT CASE WHEN (pQty < 0 AND itemsite_costmethod='S') THEN stdcost(itemsite_item_id) * pQty
71705               WHEN (pQty < 0) THEN avgcost(itemsite_id) * pQty
71706               WHEN (wo_cosmethod = 'D') THEN wo_wipvalue
71707               ELSE  round((wo_wipvalue - (wo_postedvalue / wo_qtyord * (wo_qtyord -
71708                     CASE WHEN (wo_qtyord < wo_qtyrcv + pQty) THEN wo_qtyord
71709                          ELSE wo_qtyrcv + pQty
71710                     END ))),2)
71711          END INTO _wipPost
71712   FROM wo
71713     JOIN itemsite ON (wo_itemsite_id=itemsite_id)
71714   WHERE (wo_id=pWoid);
71715
71716   SELECT postInvTrans( itemsite_id, 'RM', _parentQty,
71717                        'W/O', 'WO', _woNumber, '', ('Receive Inventory ' || item_number || ' ' || _sense || ' Manufacturing'),
71718                        costcat_asset_accnt_id, getPrjAccntId(wo_prj_id, costcat_wip_accnt_id), _itemlocSeries, pGlDistTS,
71719                        -- the following is only actually used when the item is average or job costed
71720                        _wipPost ) INTO _invhistid
71721   FROM wo, itemsite, item, costcat
71722   WHERE ( (wo_itemsite_id=itemsite_id)
71723    AND (itemsite_item_id=item_id)
71724    AND (itemsite_costcat_id=costcat_id)
71725    AND (wo_id=pWoid) );
71726
71727   IF (pQty < 0 ) THEN
71728     _wipPost := _wipPost * -1;
71729   END IF;
71730   
71731 --  Increase this W/O's received qty decrease its WIP value
71732   UPDATE wo
71733   SET wo_qtyrcv = (wo_qtyrcv + _parentQty),
71734       wo_wipvalue = (wo_wipvalue - (CASE WHEN (itemsite_costmethod IN ('A','J'))
71735                                                THEN _wipPost
71736                                          WHEN (itemsite_costmethod='S')
71737                                                THEN (stdcost(itemsite_item_id) * _parentQty)
71738                                          ELSE 0.0  END))
71739   FROM itemsite, item
71740   WHERE ((wo_itemsite_id=itemsite_id)
71741    AND (itemsite_item_id=item_id)
71742    AND (wo_id=pWoid));
71743
71744 --  ROB Increase this W/O's WIP value for custom costing
71745   SELECT SUM(itemcost_stdcost * _parentQty) INTO _ucost 
71746   FROM wo JOIN itemsite ON (itemsite_id=wo_itemsite_id)
71747           JOIN itemcost ON (itemcost_item_id=itemsite_item_id)
71748           JOIN costelem ON ((costelem_id=itemcost_costelem_id) AND
71749                             (costelem_exp_accnt_id IS NOT NULL) AND
71750                             (NOT costelem_sys))
71751   WHERE (wo_id=pWoid);
71752
71753   UPDATE wo
71754   SET wo_wipvalue = (wo_wipvalue + coalesce(_ucost,0))
71755   WHERE (wo_id=pWoid);
71756
71757 --  ROB Distribute to G/L - create Cost Variance, debit WIP
71758   PERFORM insertGLTransaction( 'W/O', 'WO', _woNumber,
71759                                ('Post Other Cost ' || item_number || ' ' || _sense || ' Manufacturing'),
71760                                getPrjAccntId(wo_prj_id, costelem_exp_accnt_id), 
71761                                getPrjAccntId(wo_prj_id,costcat_wip_accnt_id), _invhistid,
71762                                (itemcost_stdcost * _parentQty),
71763                                 pGlDistTS::DATE )
71764 FROM wo, costelem, itemcost, costcat, itemsite, item
71765 WHERE 
71766   ((wo_id=pWoid) AND
71767   (wo_itemsite_id=itemsite_id) AND
71768   (itemsite_item_id=item_id) AND
71769   (costelem_id = itemcost_costelem_id) AND
71770   (itemcost_item_id = itemsite_item_id) AND
71771   (itemsite_costcat_id = costcat_id) AND
71772   (costelem_exp_accnt_id) IS NOT NULL  AND 
71773   (costelem_sys = false));
71774 --End
71775
71776
71777 --  Make sure the W/O is at issue status
71778   UPDATE wo
71779   SET wo_status='I'
71780   WHERE (wo_id=pWoid);
71781
71782   RETURN _itemlocSeries;
71783
71784 END;
71785 $_$;
71786
71787
71788 ALTER FUNCTION public.postproduction(integer, numeric, boolean, integer, timestamp with time zone) OWNER TO admin;
71789
71790 --
71791 -- TOC entry 2034 (class 1255 OID 146566863)
71792 -- Dependencies: 4536 8
71793 -- Name: postproduction(integer, numeric, boolean, boolean, integer, text, text); Type: FUNCTION; Schema: public; Owner: admin
71794 --
71795
71796 CREATE FUNCTION postproduction(integer, numeric, boolean, boolean, integer, text, text) RETURNS integer
71797     LANGUAGE plpgsql
71798     AS $_$
71799 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
71800 -- See www.xtuple.com/CPAL for the full text of the software license.
71801 BEGIN
71802   RAISE NOTICE 'postProduction(INTEGER, NUMERIC, BOOLEAN, BOOLEAN, INTEGER, TEXT, TEXT) is deprecated. please use postProduction(INTEGER, NUMERIC, BOOLEAN, INTEGER, TIMESTAMP WITH TIME ZONE) instead';
71803   RETURN postProduction($1, $2, $3, $5, now());
71804 END;
71805 $_$;
71806
71807
71808 ALTER FUNCTION public.postproduction(integer, numeric, boolean, boolean, integer, text, text) OWNER TO admin;
71809
71810 --
71811 -- TOC entry 2036 (class 1255 OID 146566866)
71812 -- Dependencies: 4536 8
71813 -- Name: postreceipt(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
71814 --
71815
71816 CREATE FUNCTION postreceipt(integer, integer) RETURNS integer
71817     LANGUAGE plpgsql
71818     AS $_$
71819 -- Copyright (c) 1999-2011 by OpenMFG LLC, d/b/a xTuple. 
71820 -- See www.xtuple.com/CPAL for the full text of the software license.
71821 DECLARE
71822   precvid               ALIAS FOR $1;
71823   _itemlocSeries        INTEGER := COALESCE($2, 0);
71824   _freightAccnt         INTEGER;
71825   _glDate               TIMESTAMP WITH TIME ZONE;
71826   _o                    RECORD;
71827   _ordertypeabbr        TEXT;
71828   _r                    RECORD;
71829   _ra                   RECORD;
71830   _recvinvqty          NUMERIC := 0.00;
71831   _recvvalue            NUMERIC := 0.00;
71832   _pricevar            NUMERIC := 0.00;
71833   _tmp                  INTEGER;
71834   _toitemitemid         INTEGER;
71835   _coheadid             INTEGER;
71836   _coitemid             INTEGER;
71837   _linenumber          INTEGER;
71838   _invhistid            INTEGER;
71839   _shipheadid           INTEGER;
71840   _ship                 BOOLEAN;
71841   _i                    RECORD;
71842
71843 BEGIN
71844   SELECT recv_id, recv_order_type, recv_orderitem_id, recv_qty,
71845          round(currToBase(recv_freight_curr_id, recv_freight, recv_date::DATE),
71846                2) AS recv_freight_base,
71847          recv_freight, recv_freight_curr_id, recv_date, recv_gldistdate,
71848          itemsite_id, itemsite_item_id, item_inv_uom_id, itemsite_costmethod,
71849          itemsite_controlmethod, vend_name, item_number, item_fractional
71850          INTO _r
71851   FROM recv LEFT OUTER JOIN itemsite ON (recv_itemsite_id=itemsite_id)
71852             LEFT OUTER JOIN item ON (itemsite_item_id=item_id)
71853             LEFT OUTER JOIN vendinfo ON (recv_vend_id=vend_id)
71854   WHERE ((recv_id=precvid)
71855     AND  (NOT recv_posted));
71856
71857   IF (NOT FOUND) THEN
71858     IF (_itemlocSeries = 0) THEN
71859       RETURN -10;
71860     END IF;
71861     RETURN _itemlocSeries;
71862
71863   ELSEIF (_r.recv_qty <= 0) THEN
71864     RETURN -11;
71865
71866   ELSIF (_r.recv_order_type ='PO') THEN
71867     _ordertypeabbr := ('P/O for ' || _r.vend_name || ' for item ' || _r.item_number);
71868
71869     SELECT pohead_number AS orderhead_number, poitem_id AS orderitem_id,
71870            poitem_linenumber AS orderitem_linenumber,
71871            currToBase(pohead_curr_id,
71872                       COALESCE(recv_purchcost, poitem_unitprice),
71873                       recv_date::DATE) AS item_unitprice_base,
71874            poitem_invvenduomratio AS invvenduomratio,
71875            pohead_orderdate AS orderdate, pohead_dropship,
71876            poitem_prj_id AS prj_id INTO _o
71877     FROM recv, pohead, poitem
71878     WHERE ((recv_orderitem_id=poitem_id)
71879       AND  (poitem_pohead_id=pohead_id)
71880       AND  (NOT recv_posted)
71881       AND  (recv_id=precvid));
71882   ELSIF (_r.recv_order_type ='RA') THEN
71883     _ordertypeabbr := 'R/A for item ' || _r.item_number;
71884     
71885     SELECT rahead_id AS orderhead_id, rahead_number AS orderhead_number, raitem_id AS orderitem_id,
71886            raitem_linenumber AS orderitem_linenumber,
71887            currToBase(rahead_curr_id, raitem_unitprice,
71888                     recv_date::DATE) AS item_unitprice_base,
71889            raitem_qty_invuomratio AS invvenduomratio,
71890            rahead_authdate AS orderdate,
71891            raitem_unitcost AS unitcost,
71892            rahead_prj_id AS prj_id INTO _o
71893     FROM recv, rahead, raitem
71894     WHERE ((recv_orderitem_id=raitem_id)
71895       AND  (raitem_rahead_id=rahead_id)
71896       AND  (NOT recv_posted)
71897       AND  (recv_id=precvid));
71898   ELSIF (_r.recv_order_type ='TO') THEN
71899      _ordertypeabbr := 'T/O for item ' || _r.item_number;
71900
71901     SELECT tohead_number AS orderhead_number, toitem_id AS orderitem_id,
71902            toitem_linenumber AS orderitem_linenumber,
71903            toitem_stdcost AS item_unitprice_base,
71904            1.0 AS invvenduomratio,
71905            tohead_orderdate AS orderdate,
71906            NULL AS prj_id INTO _o
71907     FROM recv, tohead, toitem
71908     WHERE ((recv_orderitem_id=toitem_id)
71909       AND  (toitem_tohead_id=tohead_id)
71910       AND  (NOT recv_posted)
71911       AND  (recv_id=precvid));
71912   ELSE
71913     RETURN -13; -- don't know how to handle this order type
71914   END IF;
71915
71916   IF (NOT FOUND) THEN
71917     IF (_itemlocSeries = 0) THEN
71918       RETURN -10;
71919     END IF;
71920     RETURN _itemlocSeries;
71921   END IF;
71922
71923   IF (_itemlocSeries = 0) THEN
71924     _itemlocSeries := NEXTVAL('itemloc_series_seq');
71925   ELSEIF (_itemlocSeries < 0) THEN
71926     RETURN _itemlocSeries;
71927   END IF;
71928
71929   _glDate := COALESCE(_r.recv_gldistdate, _r.recv_date);
71930   _recvinvqty := roundQty(_r.item_fractional, (_r.recv_qty * _o.invvenduomratio));
71931
71932   IF ( (_r.recv_order_type = 'PO') AND
71933         (_r.itemsite_id = -1 OR _r.itemsite_id IS NULL OR _r.itemsite_controlmethod = 'N') ) THEN
71934
71935     IF (_r.itemsite_id IS NOT NULL) THEN
71936       SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'), 
71937                                   'S/R', _r.recv_order_type, _o.orderhead_number,
71938                                   'Receive Non-Controlled Inventory from ' || _ordertypeabbr,
71939                                    costcat_liability_accnt_id,
71940                                    getPrjAccntId(_o.prj_id, costcat_exp_accnt_id), -1,
71941                                    round((_o.item_unitprice_base * _r.recv_qty),2),
71942                                    _glDate::DATE, false ) INTO _tmp
71943       FROM poitem, itemsite, costcat
71944       WHERE((poitem_itemsite_id=itemsite_id)
71945         AND (itemsite_costcat_id=costcat_id)
71946         AND (poitem_id=_o.orderitem_id));
71947     ELSE
71948       SELECT insertGLTransaction(fetchJournalNumber('GL-MISC'),
71949                                   'S/R', _r.recv_order_type, _o.orderhead_number,
71950                                   'Receive Non-Inventory from ' || 'P/O for ' || _r.vend_name || ' for ' || expcat_code,
71951                                    expcat_liability_accnt_id,
71952                                    getPrjAccntId(_o.prj_id, expcat_exp_accnt_id), -1,
71953                                    round((_o.item_unitprice_base * _r.recv_qty),2),
71954                                    _glDate::DATE, false ) INTO _tmp
71955       FROM poitem, expcat
71956       WHERE((poitem_expcat_id=expcat_id)
71957         AND (poitem_id=_o.orderitem_id));
71958     END IF;
71959       
71960
71961     IF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
71962       RETURN _tmp;
71963     ELSE
71964       -- Posting to trial balance is deferred to prevent locking
71965       INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
71966       VALUES ( _tmp, _itemlocSeries );
71967       
71968     END IF;
71969
71970     SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'),
71971                                 'S/R', _r.recv_order_type, _o.orderhead_number,
71972                                 'Receive Non-Inventory Freight from ' || _ordertypeabbr,
71973                                  expcat_liability_accnt_id,
71974                                  getPrjAccntId(_o.prj_id, expcat_freight_accnt_id), -1,
71975                                  _r.recv_freight_base,
71976                                  _glDate::DATE, false ),
71977            expcat_freight_accnt_id INTO _tmp, _freightAccnt
71978     FROM poitem, expcat
71979     WHERE((poitem_expcat_id=expcat_id)
71980       AND (poitem_id=_o.orderitem_id));
71981
71982     IF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
71983       RETURN _tmp;
71984     ELSE
71985       -- Posting to trial balance is deferred to prevent locking
71986       INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
71987       VALUES ( _tmp, _itemlocSeries );
71988     END IF;
71989
71990     _recvvalue := ROUND((_o.item_unitprice_base * _r.recv_qty),2);
71991
71992     UPDATE poitem
71993     SET poitem_qty_received = (poitem_qty_received + _r.recv_qty),
71994         poitem_freight_received = (poitem_freight_received + _r.recv_freight_base)
71995     WHERE (poitem_id=_o.orderitem_id);
71996
71997   ELSEIF ( (_r.recv_order_type = 'RA') AND
71998            (_r.itemsite_id = -1 OR _r.itemsite_id IS NULL) ) THEN
71999     RAISE NOTICE 'itemsite controlmethod is %, cannot post receipt.', _r.itemsite_controlmethod;
72000     RETURN -14; -- otherwise how do we get the accounts?
72001
72002   ELSEIF ( (_r.recv_order_type = 'TO') AND
72003            (_r.itemsite_id = -1 OR _r.itemsite_id IS NULL) ) THEN
72004     RAISE NOTICE 'itemsite missing';
72005     RETURN -14; -- otherwise how do we get the accounts?
72006
72007   ELSE  -- not ELSIF: some code is shared between diff order types
72008     IF (_r.recv_order_type = 'PO') THEN
72009       SELECT postInvTrans( itemsite_id, 'RP'::TEXT,
72010                            _recvinvqty,
72011                            'S/R'::TEXT,
72012                            _r.recv_order_type::TEXT, _o.orderhead_number::TEXT || '-' || _o.orderitem_linenumber::TEXT,
72013                            ''::TEXT,
72014                            'Receive Inventory from ' || _ordertypeabbr,
72015                            costcat_asset_accnt_id, costcat_liability_accnt_id,
72016                            _itemlocSeries,
72017                            _glDate,
72018                            round((_o.item_unitprice_base * _r.recv_qty),2) -- always passing this in since it is ignored if it is not average costed item
72019                            ) INTO _tmp
72020       FROM itemsite, costcat
72021       WHERE ( (itemsite_costcat_id=costcat_id)
72022        AND (itemsite_id=_r.itemsite_id) );
72023       IF (NOT FOUND) THEN
72024         RAISE EXCEPTION 'Could not post inventory transaction: no cost category found for itemsite_id %',
72025           _r.itemsite_id;
72026       ELSIF (_tmp < -1) THEN -- less than -1 because -1 means it is a none controlled item
72027         IF(_tmp = -3) THEN
72028           RETURN -12; -- The GL trans value was 0 which means we likely do not have a std cost
72029         END IF;
72030         RETURN _tmp;
72031       END IF;
72032
72033       -- If the 'Purchase Price Variance on Receipt' option is true
72034       IF (fetchMetricBool('RecordPPVonReceipt')) THEN
72035         _invhistid := _tmp;
72036         -- Find the difference in the purchase price value expected from the P/O and the value of the transaction
72037         SELECT ((_o.item_unitprice_base * _r.recv_qty) - (invhist_value_after - invhist_value_before)) INTO _pricevar
72038         FROM invhist
72039         WHERE (invhist_id = _invhistid);
72040
72041         -- If difference exists then
72042         IF (_pricevar <> 0.00) THEN
72043           -- Record an additional GL Transaction for the purchase price variance
72044           SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'),
72045                                        'S/R', _r.recv_order_type, _o.orderhead_number,
72046                                       'Purchase price variance adjusted for P/O ' || _o.orderhead_number || ' for item ' || _r.item_number,
72047                                       costcat_liability_accnt_id,
72048                                       getPrjAccntId(_o.prj_id, costcat_purchprice_accnt_id), -1,
72049                                       _pricevar,
72050                                       _glDate::DATE, false ) INTO _tmp
72051           FROM itemsite, costcat
72052           WHERE ((itemsite_costcat_id=costcat_id)
72053              AND (itemsite_id=_r.itemsite_id) );
72054           IF (NOT FOUND) THEN
72055             RAISE EXCEPTION 'Could not insert G/L transaction: no cost category found for itemsite_id %',
72056             _r.itemsite_id;
72057           ELSIF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
72058             RETURN _tmp;
72059           ELSE
72060             -- Posting to trial balance is deferred to prevent locking
72061             INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
72062             VALUES ( _tmp, _itemlocSeries );
72063           END IF;
72064         END IF;
72065       END IF;
72066
72067       SELECT insertGLTransaction(fetchJournalNumber('GL-MISC'),
72068                                   'S/R', _r.recv_order_type, _o.orderhead_number,
72069                                   'Receive Inventory Freight from ' || _o.orderhead_number || ' for item ' || _r.item_number,
72070                                    costcat_liability_accnt_id,
72071                                    getPrjAccntId(_o.prj_id, costcat_freight_accnt_id), -1,
72072                                    _r.recv_freight_base,
72073                                    _glDate::DATE, false ),
72074              costcat_freight_accnt_id INTO _tmp, _freightAccnt
72075       FROM itemsite, costcat
72076       WHERE ( (itemsite_costcat_id=costcat_id)
72077        AND (itemsite_id=_r.itemsite_id) );
72078       IF (NOT FOUND) THEN
72079         RAISE EXCEPTION 'Could not insert G/L transaction: no cost category found for itemsite_id %',
72080           _r.itemsite_id;
72081       ELSIF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
72082         RETURN _tmp;
72083       ELSE
72084           -- Posting to trial balance is deferred to prevent locking
72085           INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
72086           VALUES ( _tmp, _itemlocSeries );
72087       END IF;
72088
72089       UPDATE poitem
72090       SET poitem_qty_received = (poitem_qty_received + _r.recv_qty),
72091           poitem_freight_received = (poitem_freight_received + _r.recv_freight_base)
72092       WHERE (poitem_id=_o.orderitem_id);
72093
72094     ELSIF (_r.recv_order_type = 'RA') THEN
72095       SELECT rahead.*, raitem.* INTO _ra
72096             FROM rahead, raitem
72097         WHERE ((rahead_id=raitem_rahead_id)
72098         AND  (raitem_id=_r.recv_orderitem_id));
72099
72100       IF (_r.itemsite_controlmethod = 'N') THEN
72101         SELECT insertGLTransaction( fetchJournalNumber('GL-MISC'), 
72102                                     'S/R', _r.recv_order_type, _o.orderhead_number,
72103                                     'Receive Non-Controlled Inventory from ' || _ordertypeabbr,
72104                                     costcat_liability_accnt_id,
72105                                     getPrjAccntId(_o.prj_id, costcat_exp_accnt_id), -1,
72106                                     round((_o.item_unitprice_base * _r.recv_qty),2),
72107                                     _glDate::DATE, false ) INTO _tmp
72108         FROM itemsite JOIN costcat ON (costcat_id=itemsite_costcat_id)
72109         WHERE(itemsite_id=_r.itemsite_id);
72110         IF (NOT FOUND) THEN
72111           RAISE EXCEPTION 'Could not post inventory transaction: no cost category found for itemsite_id %', _r.itemsite_id;
72112 --        ELSIF (_tmp < -1) THEN
72113 --          RETURN _tmp;
72114         END IF;
72115       ELSE
72116         SELECT postInvTrans(_r.itemsite_id, 'RR',
72117                             _recvinvqty,
72118                             'S/R',
72119                             _r.recv_order_type, _ra.rahead_number::TEXT || '-' || _ra.raitem_linenumber::TEXT,
72120                             '',
72121                             'Receive Inventory from ' || _ordertypeabbr,
72122                             costcat_asset_accnt_id,
72123                             CASE WHEN(COALESCE(_ra.raitem_cos_accnt_id, -1) != -1) THEN 
72124                                   getPrjAccntId(_o.prj_id, _ra.raitem_cos_accnt_id)
72125                                  WHEN (_ra.raitem_warranty) THEN 
72126                                   getPrjAccntId(_o.prj_id, resolveCOWAccount(_r.itemsite_id, _ra.rahead_cust_id, _ra.rahead_saletype_id, _ra.rahead_shipzone_id))
72127                                  ELSE
72128                                   getPrjAccntId(_o.prj_id, resolveCORAccount(_r.itemsite_id, _ra.rahead_cust_id, _ra.rahead_saletype_id, _ra.rahead_shipzone_id))
72129                             END,
72130                             _itemlocSeries, _glDate, COALESCE(_o.unitcost,stdcost(itemsite_item_id)) * _recvinvqty) INTO _tmp
72131         FROM itemsite, costcat
72132         WHERE ( (itemsite_costcat_id=costcat_id)
72133          AND (itemsite_id=_r.itemsite_id) );
72134
72135         IF (NOT FOUND) THEN
72136           RAISE EXCEPTION 'Could not post inventory transaction: no cost category found for itemsite_id %', _r.itemsite_id;
72137         ELSIF (_tmp < -1) THEN -- less than -1 because -1 means it is a none controlled item
72138           IF(_tmp = -3) THEN
72139             RAISE NOTICE 'The GL trans value was 0 which means we likely do not have a std cost';
72140             RETURN -12; -- The GL trans value was 0 which means we likely do not have a std cost
72141           END IF;
72142           RETURN _tmp;
72143         END IF;
72144       END IF;
72145
72146       INSERT INTO rahist (rahist_itemsite_id, rahist_date,
72147                           rahist_descrip,
72148                           rahist_qty, rahist_uom_id,
72149                           rahist_source, rahist_source_id, rahist_rahead_id
72150           ) VALUES (_r.itemsite_id, _glDate,
72151                       'Receive Inventory from ' || _ordertypeabbr,
72152                       _recvinvqty, _r.item_inv_uom_id,
72153                       'RR', _r.recv_id, _ra.rahead_id
72154                   );
72155
72156       SELECT insertGLTransaction(fetchJournalNumber('GL-MISC'),
72157                                   'S/R', _r.recv_order_type, _o.orderhead_number,
72158                                   'Receive Inventory Freight from ' || _o.orderhead_number || ' for item ' || _r.item_number,
72159                                    costcat_liability_accnt_id,
72160                                    getPrjAccntId(_o.prj_id, costcat_freight_accnt_id), -1,
72161                                    _r.recv_freight_base,
72162                                    _glDate::DATE, false ),
72163              costcat_freight_accnt_id INTO _tmp, _freightAccnt
72164       FROM itemsite, costcat
72165       WHERE ( (itemsite_costcat_id=costcat_id)
72166        AND (itemsite_id=_r.itemsite_id) );
72167       IF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
72168             RETURN _tmp;
72169       ELSE
72170         -- Posting to trial balance is deferred to prevent locking
72171         INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
72172         VALUES ( _tmp, _itemlocSeries );
72173       END IF;
72174
72175       INSERT INTO rahist (rahist_date, rahist_descrip,
72176                           rahist_source, rahist_source_id,
72177                           rahist_curr_id, rahist_amount,
72178                           rahist_rahead_id
72179           ) VALUES (_glDate, 'Receive Inventory Freight from ' || _ordertypeabbr,
72180                   'RR', _r.recv_id, _r.recv_freight_curr_id, _r.recv_freight,
72181                   _ra.rahead_id
72182           );
72183
72184       UPDATE raitem
72185       SET raitem_qtyreceived = (raitem_qtyreceived + _r.recv_qty)
72186       WHERE (raitem_id=_o.orderitem_id);
72187       
72188 -- Expire date doesn't mean anything once the RA is received 
72189 -- WARNING: INSERTING 'NULL' MIGHT CAUSE PROBLEMS!!
72190       UPDATE rahead
72191       SET rahead_expiredate = NULL
72192       WHERE (rahead_id=_o.orderhead_id);
72193
72194 --  Look for 'ship' lines
72195     SELECT (count(*) > 0) INTO _ship
72196     FROM raitem
72197     WHERE ((raitem_disposition = 'S')
72198      AND (raitem_new_coitem_id IS NULL)
72199      AND (raitem_rahead_id=_ra.rahead_id));
72200
72201 --  If receiving a qty on a shippable and upon receipt item, create coitem
72202       IF ((_ra.rahead_timing='R') AND
72203           (_ship OR (
72204           (_ra.raitem_disposition IN ('P','V')) AND
72205           (_ra.raitem_new_coitem_id IS NULL) AND
72206           (_ra.raitem_qtyauthorized > 0)))) THEN
72207
72208           IF (_ra.rahead_new_cohead_id IS NOT NULL) THEN
72209             _coheadid = _ra.rahead_new_cohead_id;
72210           ELSE  
72211 --  No header, so create a Sales Order header first.
72212             SELECT nextval('cohead_cohead_id_seq') INTO _coheadid;
72213
72214             INSERT INTO cohead (
72215               cohead_id,cohead_number,cohead_cust_id,cohead_custponumber,
72216               cohead_orderdate,cohead_salesrep_id,cohead_terms_id,
72217               cohead_shipvia,cohead_shipto_id,cohead_shiptoname,
72218               cohead_shiptoaddress1,cohead_shiptoaddress2,cohead_shiptoaddress3,
72219               cohead_shiptocity,cohead_shiptostate,cohead_shiptozipcode,
72220               cohead_shiptocountry,cohead_freight,cohead_shiptophone,
72221               cohead_shipto_cntct_id, cohead_shipto_cntct_honorific,
72222               cohead_shipto_cntct_first_name, cohead_shipto_cntct_middle,
72223               cohead_shipto_cntct_last_name, cohead_shipto_cntct_suffix,
72224               cohead_shipto_cntct_phone, cohead_shipto_cntct_title,
72225               cohead_shipto_cntct_fax, cohead_shipto_cntct_email,
72226               cohead_shipchrg_id, cohead_shipform_id,cohead_billtoname,
72227               cohead_billtoaddress1,cohead_billtoaddress2,cohead_billtoaddress3,
72228               cohead_billtocity,cohead_billtostate,cohead_billtozipcode,
72229               cohead_billtocountry,cohead_misc_accnt_id,cohead_misc_descrip,
72230               cohead_commission,cohead_holdtype,cohead_prj_id,cohead_shipcomplete,
72231               cohead_curr_id,cohead_taxzone_id,cohead_saletype_id,cohead_shipzone_id)
72232             SELECT _coheadid,fetchsonumber(),rahead_cust_id,rahead_custponumber,
72233               current_date,rahead_salesrep_id,COALESCE(cohead_terms_id,cust_terms_id),
72234               COALESCE(cohead_shipvia,cust_shipvia),rahead_shipto_id,rahead_shipto_name,
72235               rahead_shipto_address1,rahead_shipto_address2,rahead_shipto_address3,
72236               rahead_shipto_city,rahead_shipto_state,rahead_shipto_zipcode,
72237               rahead_shipto_country,0,COALESCE(cohead_shiptophone,''),
72238               cntct_id, cntct_honorific,
72239               cntct_first_name, cntct_middle,
72240               cntct_last_name, cntct_suffix,
72241               cntct_phone, cntct_title,
72242               cntct_fax, cntct_email,
72243               COALESCE(cohead_shipchrg_id,cust_shipchrg_id),
72244               COALESCE(cohead_shipform_id,cust_shipform_id),
72245               rahead_billtoname,rahead_billtoaddress1,rahead_billtoaddress2,rahead_billtoaddress3,
72246               rahead_billtocity,rahead_billtostate,rahead_billtozip,
72247               rahead_billtocountry,NULL,'',rahead_commission, 'N', rahead_prj_id,
72248               COALESCE(cohead_shipcomplete,
72249                 CASE WHEN cust_partialship THEN 
72250                   false 
72251                 ELSE true
72252                 END),rahead_curr_id,rahead_taxzone_id,rahead_saletype_id,rahead_shipzone_id
72253             FROM rahead
72254               JOIN custinfo ON (rahead_cust_id=cust_id)
72255               LEFT OUTER JOIN cohead ON (rahead_orig_cohead_id=cohead_id)
72256               LEFT OUTER JOIN shiptoinfo ON (rahead_shipto_id=shipto_id)
72257               LEFT OUTER JOIN cntct ON (shipto_cntct_id=cntct_id)
72258             WHERE (rahead_id=_ra.rahead_id);
72259
72260             UPDATE rahead SET rahead_new_cohead_id=_coheadid WHERE rahead_id=_ra.rahead_id;
72261             
72262           END IF;
72263                   
72264 -- Now enter the line item(s)
72265         IF (_ra.raitem_disposition IN ('P','V')) AND
72266            (_ra.raitem_new_coitem_id IS NULL) AND
72267            (_ra.raitem_qtyauthorized > 0) THEN
72268            
72269           SELECT nextval('coitem_coitem_id_seq') INTO _coitemid;
72270
72271           SELECT COALESCE(MAX(coitem_linenumber),0)+1 INTO _linenumber
72272           FROM coitem
72273           WHERE (coitem_cohead_id=_coheadid);
72274       
72275           INSERT INTO coitem (
72276             coitem_id,coitem_cohead_id,coitem_linenumber,coitem_itemsite_id,
72277             coitem_status,coitem_scheddate,coitem_promdate, coitem_qtyord,
72278             coitem_unitcost,coitem_price,coitem_custprice,coitem_qtyshipped,
72279             coitem_order_id,coitem_memo,coitem_qtyreturned,
72280             coitem_taxtype_id,coitem_qty_uom_id,coitem_qty_invuomratio,
72281             coitem_price_uom_id,coitem_price_invuomratio,coitem_warranty,
72282             coitem_cos_accnt_id,coitem_order_type, coitem_custpn)
72283           SELECT _coitemid,_coheadid,_linenumber,_ra.raitem_coitem_itemsite_id,
72284               'O',_ra.raitem_scheddate,_ra.raitem_scheddate,_ra.raitem_qtyauthorized,
72285               stdcost(itemsite_item_id),COALESCE(_ra.raitem_saleprice,0),0,0,
72286               -1,_ra.raitem_notes,0,
72287               _ra.raitem_taxtype_id,_ra.raitem_qty_uom_id,_ra.raitem_qty_invuomratio,
72288               _ra.raitem_price_uom_id,_ra.raitem_price_invuomratio,_ra.raitem_warranty,
72289               _ra.raitem_cos_accnt_id,
72290               CASE WHEN itemsite_createwo THEN 'W' ELSE NULL END, _ra.raitem_custpn
72291           FROM itemsite
72292           WHERE (itemsite_id=_ra.raitem_coitem_itemsite_id);
72293
72294           UPDATE raitem SET raitem_new_coitem_id=_coitemid WHERE (raitem_id=_ra.raitem_id);
72295         END IF;
72296         
72297         -- Create items to ship that have no direct relation to receipts.
72298         IF (_ship) THEN
72299           FOR _i IN
72300             SELECT raitem_id FROM raitem
72301             WHERE ((raitem_rahead_id=_ra.rahead_id)
72302               AND (raitem_disposition = 'S')
72303               AND (raitem_new_coitem_id IS NULL))
72304           LOOP
72305
72306             SELECT nextval('coitem_coitem_id_seq') INTO _coitemid;
72307
72308             SELECT COALESCE(MAX(coitem_linenumber),0)+1 INTO _linenumber
72309               FROM coitem
72310             WHERE (coitem_cohead_id=_coheadid);
72311       
72312             INSERT INTO coitem (
72313               coitem_id,coitem_cohead_id,coitem_linenumber,coitem_itemsite_id,
72314               coitem_status,coitem_scheddate,coitem_promdate, coitem_qtyord,
72315               coitem_unitcost,coitem_price,coitem_custprice,coitem_qtyshipped,
72316               coitem_order_id,coitem_memo,coitem_qtyreturned,
72317               coitem_taxtype_id,coitem_qty_uom_id,coitem_qty_invuomratio,
72318               coitem_price_uom_id,coitem_price_invuomratio,coitem_warranty,
72319               coitem_cos_accnt_id,coitem_order_type,coitem_custpn)
72320             SELECT _coitemid,_coheadid,_linenumber,raitem_coitem_itemsite_id,
72321               'O',raitem_scheddate,raitem_scheddate,raitem_qtyauthorized,
72322               stdcost(itemsite_item_id),COALESCE(raitem_saleprice,0),0,0,
72323               -1,raitem_notes,0,
72324               raitem_taxtype_id,raitem_qty_uom_id,raitem_qty_invuomratio,
72325               raitem_price_uom_id,raitem_price_invuomratio,raitem_warranty,
72326               raitem_cos_accnt_id,
72327               CASE WHEN itemsite_createwo THEN 'W' ELSE NULL END,raitem_custpn
72328             FROM raitem
72329               JOIN itemsite ON (itemsite_id=raitem_itemsite_id)
72330             WHERE (raitem_id=_i.raitem_id);
72331                         
72332             UPDATE raitem SET raitem_new_coitem_id=_coitemid WHERE (raitem_id=_i.raitem_id);
72333
72334           END LOOP;
72335         END IF;
72336       END IF;
72337
72338
72339     ELSIF (_r.recv_order_type = 'TO' AND fetchMetricBool('MultiWhs')) THEN
72340       SELECT interWarehouseTransfer(toitem_item_id, tohead_trns_warehous_id,
72341             tohead_dest_warehous_id, _r.recv_qty, 
72342             'TO', formatToNumber(toitem_id), 'Receive from Transit To Dest Warehouse', _itemlocSeries, _glDate ) INTO _tmp
72343       FROM tohead, toitem
72344       WHERE ((tohead_id=toitem_tohead_id)
72345         AND  (toitem_id=_r.recv_orderitem_id));     
72346
72347       IF (_tmp < 0) THEN
72348             RETURN _tmp;
72349       END IF;
72350
72351       SELECT insertGLTransaction(fetchJournalNumber('GL-MISC'), 
72352                                   'S/R', _r.recv_order_type, _o.orderhead_number,
72353                                   'Receive Inventory Freight from ' || _o.orderhead_number || ' for item ' || _r.item_number,
72354                                    costcat_toliability_accnt_id,
72355                                    costcat_freight_accnt_id, -1,
72356                                    _r.recv_freight_base,
72357                                    _glDate::DATE, false ),
72358              costcat_freight_accnt_id INTO _tmp, _freightAccnt
72359       FROM itemsite, costcat
72360       WHERE ( (itemsite_costcat_id=costcat_id)
72361        AND (itemsite_id=_r.itemsite_id) );
72362       IF (_tmp < 0 AND _tmp != -3) THEN -- error but not 0-value transaction
72363             RETURN _tmp;
72364       ELSE
72365         -- Posting to trial balance is deferred to prevent locking
72366         INSERT INTO itemlocpost ( itemlocpost_glseq, itemlocpost_itemlocseries)
72367         VALUES ( _tmp, _itemlocSeries );
72368       END IF;
72369
72370       UPDATE toitem
72371       SET toitem_qty_received = (toitem_qty_received + _r.recv_qty),
72372           toitem_freight_received = (toitem_freight_received +
72373                                       currToCurr(_r.recv_freight_curr_id,
72374                                                  toitem_freight_curr_id,
72375                                                  _r.recv_freight, _glDate::DATE))
72376       WHERE (toitem_id=_o.orderitem_id);
72377
72378     END IF;
72379     IF(_r.itemsite_costmethod='A') THEN
72380       _recvvalue := ROUND((_o.item_unitprice_base * _r.recv_qty),2);
72381     ELSIF (fetchMetricBool('RecordPPVonReceipt')) THEN
72382       _recvvalue := ROUND((_o.item_unitprice_base * _r.recv_qty), 2);
72383     ELSE
72384       _recvvalue := ROUND(stdcost(_r.itemsite_item_id) * _recvinvqty, 2);
72385     END IF;
72386   END IF;
72387
72388   UPDATE recv
72389   SET recv_value=_recvvalue, recv_recvcost=_recvvalue / recv_qty, recv_posted=TRUE, recv_gldistdate=_glDate::DATE
72390   WHERE (recv_id=precvid);
72391   
72392   IF (_r.recv_order_type = 'PO') THEN
72393     -- If this is a drop-shipped PO, then Issue the item to Shipping and Ship the item
72394     IF (_o.pohead_dropship = TRUE) THEN
72395
72396       -- Generate the PoItemDropShipped event
72397       PERFORM postEvent('PoItemDropShipped', 'P', poitem_id,
72398                         itemsite_warehous_id,
72399                         (pohead_number || '-' || poitem_linenumber || ': ' || item_number),
72400                         NULL, NULL, NULL, NULL)
72401       FROM poitem JOIN itemsite ON (itemsite_id=poitem_itemsite_id)
72402                   JOIN item ON (item_id=itemsite_item_id)
72403                   JOIN pohead ON (pohead_id=poitem_pohead_id)
72404       WHERE (poitem_id=_o.orderitem_id)
72405         AND (poitem_duedate <= (CURRENT_DATE + itemsite_eventfence));
72406
72407     END IF;
72408   END IF;
72409   RETURN _itemlocSeries;
72410
72411 END;
72412 $_$;
72413
72414
72415 ALTER FUNCTION public.postreceipt(integer, integer) OWNER TO admin;
72416
72417 --
72418 -- TOC entry 2037 (class 1255 OID 146566868)
72419 -- Dependencies: 4536 8
72420 -- Name: postreceipts(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
72421 --
72422
72423 CREATE FUNCTION postreceipts(text, integer, integer) RETURNS integer
72424     LANGUAGE plpgsql
72425     AS $_$
72426 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72427 -- See www.xtuple.com/CPAL for the full text of the software license.
72428 DECLARE
72429   pordertype            ALIAS FOR $1;
72430   porderid              ALIAS FOR $2;
72431   _itemlocSeries        INTEGER := $3;
72432   _qtyToRecv            NUMERIC;
72433   _r                    RECORD;
72434
72435 BEGIN
72436
72437   SELECT SUM(qtyToReceive(pordertype, recv_orderitem_id)) INTO _qtyToRecv
72438   FROM recv, orderitem
72439   WHERE ((recv_orderitem_id=orderitem_id)
72440     AND  (recv_order_type=pordertype)
72441     AND  (orderitem_orderhead_type=pordertype)
72442     AND  (orderitem_orderhead_id=porderid));
72443
72444   IF (_qtyToRecv <= 0) THEN
72445     RETURN -11;
72446   END IF;
72447
72448   IF (_itemlocSeries IS NULL OR _itemlocSeries <= 0) THEN
72449     _itemlocSeries := NEXTVAL('itemloc_series_seq');
72450   END IF;
72451
72452   FOR _r IN SELECT postReceipt(recv_id, _itemlocSeries) AS postResult
72453             FROM recv, orderitem
72454             WHERE ((recv_orderitem_id=orderitem_id)
72455               AND  (orderitem_orderhead_id=porderid)
72456               AND  (orderitem_orderhead_type=pordertype)
72457               AND  (NOT recv_posted)
72458 -- Check for multiple users receiving the same order
72459               AND  (recv_trans_usr_name=getEffectiveXtUser())
72460               AND  (recv_order_type=pordertype)) LOOP
72461     IF (_r.postResult < 0 AND _r.postResult != -11) THEN
72462       RETURN _r.postResult; -- fail on 1st error but ignore lines with qty == 0
72463     END IF;
72464   END LOOP;
72465
72466   RETURN _itemlocSeries;
72467 END;
72468 $_$;
72469
72470
72471 ALTER FUNCTION public.postreceipts(text, integer, integer) OWNER TO admin;
72472
72473 --
72474 -- TOC entry 2038 (class 1255 OID 146566869)
72475 -- Dependencies: 4536 8
72476 -- Name: postsogltransactions(); Type: FUNCTION; Schema: public; Owner: admin
72477 --
72478
72479 CREATE FUNCTION postsogltransactions() RETURNS boolean
72480     LANGUAGE plpgsql
72481     AS $$
72482 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72483 -- See www.xtuple.com/CPAL for the full text of the software license.
72484 BEGIN
72485
72486   UPDATE gltrans
72487   SET gltrans_exported=TRUE
72488   WHERE ( (NOT gltrans_exported)
72489    AND (gltrans_source='A/R')
72490    AND (gltrans_doctype IN ('IN', 'CM')) );
72491
72492   RETURN TRUE;
72493
72494 END;
72495 $$;
72496
72497
72498 ALTER FUNCTION public.postsogltransactions() OWNER TO admin;
72499
72500 --
72501 -- TOC entry 2039 (class 1255 OID 146566870)
72502 -- Dependencies: 4536 8
72503 -- Name: postsoitemproduction(integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
72504 --
72505
72506 CREATE FUNCTION postsoitemproduction(integer, timestamp with time zone) RETURNS integer
72507     LANGUAGE plpgsql
72508     AS $_$
72509 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72510 -- See www.xtuple.com/CPAL for the full text of the software license.
72511 DECLARE
72512   pSoitemId      ALIAS FOR $1;
72513   pGlDistTS      ALIAS FOR $2;
72514   _qty NUMERIC;
72515   
72516 BEGIN
72517   -- Issuing all, so determine line balance
72518   SELECT noNeg( coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned - 
72519               ( SELECT COALESCE(SUM(shipitem_qty), 0)
72520                 FROM shipitem, shiphead
72521                 WHERE ((shipitem_orderitem_id=coitem_id)
72522                   AND  (shipitem_shiphead_id=shiphead_id)
72523                   AND  (NOT shiphead_shipped) ) ) ) INTO _qty
72524   FROM coitem
72525   WHERE (coitem_id=pSoitemId);
72526
72527   RETURN postSoItemProduction($1, _qty, $2);
72528 END;
72529 $_$;
72530
72531
72532 ALTER FUNCTION public.postsoitemproduction(integer, timestamp with time zone) OWNER TO admin;
72533
72534 --
72535 -- TOC entry 2040 (class 1255 OID 146566871)
72536 -- Dependencies: 4536 8
72537 -- Name: postsoitemproduction(integer, numeric, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
72538 --
72539
72540 CREATE FUNCTION postsoitemproduction(integer, numeric, timestamp with time zone) RETURNS integer
72541     LANGUAGE plpgsql
72542     AS $_$
72543 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72544 -- See www.xtuple.com/CPAL for the full text of the software license.
72545 DECLARE
72546   pSoitemId ALIAS FOR $1;
72547   pQty ALIAS FOR $2;
72548   pGlDistTS ALIAS FOR $3;
72549   _itemlocSeries INTEGER := 0;
72550   
72551 BEGIN
72552   --If this cost method is not Job then we are using the wrong function
72553   IF (NOT EXISTS(SELECT itemsite_costmethod
72554              FROM coitem,itemsite
72555              WHERE ((coitem_id=pSoitemId)
72556                 AND (coitem_itemsite_id=itemsite_id)
72557                 AND (itemsite_costmethod = 'J')))) THEN
72558     RAISE EXCEPTION 'The postSoLineBalanceProduction function may only be used with Job costed item sites';
72559   END IF;
72560
72561   IF (pQty > 0) THEN
72562     SELECT COALESCE(postProduction(wo_id, (pQty * coitem_qty_invuomratio), true, 0, pGlDistTS),-1) INTO _itemlocSeries
72563     FROM wo, coitem
72564     WHERE ((wo_ordid=pSoItemid)
72565      AND (wo_ordtype='S')
72566      AND (coitem_id=pSoItemid));
72567     
72568     UPDATE wo SET wo_status = 'C'
72569     WHERE ((wo_ordid=pSoItemid)
72570      AND (wo_ordtype='S')
72571      AND (wo_qtyrcv >= wo_qtyord));
72572   END IF;
72573
72574   RETURN _itemlocSeries;
72575 END;
72576 $_$;
72577
72578
72579 ALTER FUNCTION public.postsoitemproduction(integer, numeric, timestamp with time zone) OWNER TO admin;
72580
72581 --
72582 -- TOC entry 2041 (class 1255 OID 146566872)
72583 -- Dependencies: 4536 8
72584 -- Name: poststandardjournal(integer, date); Type: FUNCTION; Schema: public; Owner: admin
72585 --
72586
72587 CREATE FUNCTION poststandardjournal(integer, date) RETURNS integer
72588     LANGUAGE plpgsql
72589     AS $_$
72590 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72591 -- See www.xtuple.com/CPAL for the full text of the software license.
72592 DECLARE
72593   pStdjrnlid ALIAS FOR $1;
72594   pDate ALIAS FOR $2;
72595   _returnValue INTEGER;
72596
72597 BEGIN
72598
72599   SELECT postStandardJournal(pStdjrnlid, pDate, FALSE, fetchGLSequence()) INTO _returnValue;
72600
72601   RETURN _returnValue;
72602
72603 END;
72604 $_$;
72605
72606
72607 ALTER FUNCTION public.poststandardjournal(integer, date) OWNER TO admin;
72608
72609 --
72610 -- TOC entry 2042 (class 1255 OID 146566873)
72611 -- Dependencies: 4536 8
72612 -- Name: poststandardjournal(integer, date, integer); Type: FUNCTION; Schema: public; Owner: admin
72613 --
72614
72615 CREATE FUNCTION poststandardjournal(integer, date, integer) RETURNS integer
72616     LANGUAGE plpgsql
72617     AS $_$
72618 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72619 -- See www.xtuple.com/CPAL for the full text of the software license.
72620 DECLARE
72621   pStdjrnlid ALIAS FOR $1;
72622   pDate ALIAS FOR $2;
72623   pGlSequence ALIAS FOR $3;
72624
72625 BEGIN
72626
72627   RETURN postStandardJournal(pStdjrnlid, pDate, FALSE, pGLSequence);
72628
72629 END;
72630 $_$;
72631
72632
72633 ALTER FUNCTION public.poststandardjournal(integer, date, integer) OWNER TO admin;
72634
72635 --
72636 -- TOC entry 2043 (class 1255 OID 146566874)
72637 -- Dependencies: 4536 8
72638 -- Name: poststandardjournal(integer, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
72639 --
72640
72641 CREATE FUNCTION poststandardjournal(integer, date, boolean) RETURNS integer
72642     LANGUAGE plpgsql
72643     AS $_$
72644 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72645 -- See www.xtuple.com/CPAL for the full text of the software license.
72646 DECLARE
72647   pStdjrnlid ALIAS FOR $1;
72648   pDate ALIAS FOR $2;
72649   pReverse ALIAS FOR $3;
72650   _returnValue INTEGER;
72651
72652 BEGIN
72653
72654   RETURN postStandardJournal(pStdjrnlid, pDate, pReverse, fetchGLSequence());
72655
72656 END;
72657 $_$;
72658
72659
72660 ALTER FUNCTION public.poststandardjournal(integer, date, boolean) OWNER TO admin;
72661
72662 --
72663 -- TOC entry 2045 (class 1255 OID 146566875)
72664 -- Dependencies: 4536 8
72665 -- Name: poststandardjournal(integer, date, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
72666 --
72667
72668 CREATE FUNCTION poststandardjournal(integer, date, boolean, integer) RETURNS integer
72669     LANGUAGE plpgsql
72670     AS $_$
72671 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72672 -- See www.xtuple.com/CPAL for the full text of the software license.
72673 DECLARE
72674   pStdjrnlid ALIAS FOR $1;
72675   pDate ALIAS FOR $2;
72676   pReverse ALIAS FOR $3;
72677   pGlSequence ALIAS FOR $4;
72678
72679 BEGIN
72680
72681   INSERT INTO glseries
72682   ( glseries_sequence, glseries_source, glseries_doctype, glseries_docnumber,
72683     glseries_notes, glseries_accnt_id, glseries_amount, glseries_distdate )
72684   SELECT pGlSequence, 'G/L', 'ST', stdjrnl_name,
72685          stdjrnlitem_notes, stdjrnlitem_accnt_id,
72686          CASE WHEN (pReverse=TRUE) THEN (stdjrnlitem_amount * -1)
72687               ELSE stdjrnlitem_amount
72688          END,
72689          pDate
72690   FROM stdjrnlitem, stdjrnl
72691   WHERE ( (stdjrnlitem_stdjrnl_id=stdjrnl_id)
72692    AND (stdjrnl_id=pStdjrnlid) );
72693
72694   RETURN pGlSequence;
72695
72696 END;
72697 $_$;
72698
72699
72700 ALTER FUNCTION public.poststandardjournal(integer, date, boolean, integer) OWNER TO admin;
72701
72702 --
72703 -- TOC entry 2046 (class 1255 OID 146566876)
72704 -- Dependencies: 4536 8
72705 -- Name: poststandardjournalgroup(integer, date); Type: FUNCTION; Schema: public; Owner: admin
72706 --
72707
72708 CREATE FUNCTION poststandardjournalgroup(integer, date) RETURNS integer
72709     LANGUAGE plpgsql
72710     AS $_$
72711 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72712 -- See www.xtuple.com/CPAL for the full text of the software license.
72713 DECLARE
72714   pStdjrnlgrpid ALIAS FOR $1;
72715   pDate ALIAS FOR $2;
72716 BEGIN
72717   RETURN postStandardJournalGroup(pStdjrnlgrpid, pDate, FALSE);
72718 END;
72719 $_$;
72720
72721
72722 ALTER FUNCTION public.poststandardjournalgroup(integer, date) OWNER TO admin;
72723
72724 --
72725 -- TOC entry 2047 (class 1255 OID 146566877)
72726 -- Dependencies: 4536 8
72727 -- Name: poststandardjournalgroup(integer, date, boolean); Type: FUNCTION; Schema: public; Owner: admin
72728 --
72729
72730 CREATE FUNCTION poststandardjournalgroup(integer, date, boolean) RETURNS integer
72731     LANGUAGE plpgsql
72732     AS $_$
72733 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72734 -- See www.xtuple.com/CPAL for the full text of the software license.
72735 DECLARE
72736   pStdjrnlgrpid ALIAS FOR $1;
72737   pDate ALIAS FOR $2;
72738   pReverse ALIAS FOR $3;
72739   _r RECORD;
72740   _glSequence INTEGER := -1;
72741
72742 BEGIN
72743
72744   FOR _r IN SELECT stdjrnlgrpitem_id, stdjrnlgrpitem_stdjrnl_id
72745             FROM stdjrnlgrpitem
72746             WHERE ( (stdjrnlgrpitem_stdjrnlgrp_id=pStdjrnlgrpid)
72747              AND (CURRENT_DATE BETWEEN stdjrnlgrpitem_effective AND (stdjrnlgrpitem_expires - 1))
72748              AND ( (stdjrnlgrpitem_toapply = -1)
72749               OR (stdjrnlgrpitem_toapply > stdjrnlgrpitem_applied) ) ) LOOP
72750
72751     IF (_glSequence = -1) THEN
72752       SELECT fetchGLSequence() INTO _glSequence;
72753     END IF;
72754
72755     PERFORM postStandardJournal(_r.stdjrnlgrpitem_stdjrnl_id, pDate, pReverse, _glSequence);
72756
72757     UPDATE stdjrnlgrpitem
72758     SET stdjrnlgrpitem_applied=(stdjrnlgrpitem_applied + 1)
72759     WHERE (stdjrnlgrpitem_id=_r.stdjrnlgrpitem_id);
72760
72761   END LOOP;
72762
72763   RETURN _glSequence;
72764
72765 END;
72766 $_$;
72767
72768
72769 ALTER FUNCTION public.poststandardjournalgroup(integer, date, boolean) OWNER TO admin;
72770
72771 --
72772 -- TOC entry 2048 (class 1255 OID 146566878)
72773 -- Dependencies: 4536 8
72774 -- Name: postvalueintoinvbalance(integer, date, numeric, numeric, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
72775 --
72776
72777 CREATE FUNCTION postvalueintoinvbalance(integer, date, numeric, numeric, numeric, numeric) RETURNS boolean
72778     LANGUAGE plpgsql
72779     AS $_$
72780 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72781 -- See www.xtuple.com/CPAL for the full text of the software license.
72782 DECLARE
72783   pItemsiteId ALIAS FOR $1;
72784   pDate ALIAS FOR $2;
72785   pQoh ALIAS FOR $3;
72786   pNn ALIAS FOR $4;
72787   pOldCost ALIAS FOR $5;
72788   pNewCost ALIAS FOR $6;
72789   _invbalid INTEGER;
72790   _r RECORD;
72791   _count INTEGER;
72792   _valChange NUMERIC;
72793   _nnvalChange NUMERIC;
72794
72795 BEGIN
72796
72797 --  Grab the costhist record to post
72798   SELECT period_id INTO _r
72799   FROM period
72800   WHERE (pDate BETWEEN period_start AND period_end);
72801
72802   GET DIAGNOSTICS _count = ROW_COUNT;
72803   
72804 --  Find an inventory balance to post into
72805   IF ( _count > 0 ) THEN
72806 --  Try to find an existing invbal
72807     SELECT invbal_id INTO _invbalid
72808     FROM invbal
72809     WHERE ( (invbal_period_id=_r.period_id)
72810       AND (invbal_itemsite_id=pItemsiteId) );
72811
72812     GET DIAGNOSTICS _count = ROW_COUNT;
72813     IF (_count = 0) THEN
72814       -- Wasn't there, so forward update
72815       PERFORM forwardUpdateItemsite(pItemsiteId);
72816
72817       --  Try to find an existing invbal again
72818       SELECT invbal_id INTO _invbalid
72819       FROM invbal
72820       WHERE ( (invbal_period_id=_r.period_id)
72821         AND (invbal_itemsite_id=pItemsiteId) );
72822
72823       GET DIAGNOSTICS _count = ROW_COUNT;
72824       IF (_count = 0) THEN
72825         RAISE EXCEPTION 'An inventory balance record was not found for updating standard costs';
72826       END IF;
72827     END IF;
72828
72829     _valChange := round((pNewCost - pOldCost) * pQoh, 2);
72830     _nnvalChange := round((pNewCost - pOldCost) * pNn, 2);
72831     
72832 --  We found an invbal, update it with the change
72833     IF (_valChange > 0) THEN
72834       UPDATE invbal SET 
72835         invbal_value_in = (invbal_value_in + _valChange)
72836       WHERE (invbal_id=_invbalid);
72837     ELSE
72838       UPDATE invbal SET 
72839         invbal_value_out = (invbal_value_out - _valChange)
72840       WHERE (invbal_id=_invbalid);
72841     END IF;
72842
72843     IF (_nnvalChange > 0) THEN
72844       UPDATE invbal SET 
72845         invbal_nnval_in = (invbal_nnval_in + _nnvalChange)
72846       WHERE (invbal_id=_invbalid);
72847     ELSE
72848       UPDATE invbal SET 
72849         invbal_nnval_out = (invbal_nnval_out - _nnvalChange)
72850       WHERE (invbal_id=_invbalid);
72851     END IF;
72852
72853     UPDATE invbal SET 
72854       invbal_value_ending = (invbal_value_beginning + invbal_value_in - invbal_value_out),
72855       invbal_nnval_ending = (invbal_nnval_beginning + invbal_nnval_in - invbal_nnval_out),
72856       invbal_dirty=true
72857     WHERE (invbal_id=_invbalid);  
72858
72859   ELSE
72860     RAISE EXCEPTION 'No period exists for date %.', pDate;
72861   END IF;
72862
72863   RETURN TRUE;
72864
72865 END;
72866 $_$;
72867
72868
72869 ALTER FUNCTION public.postvalueintoinvbalance(integer, date, numeric, numeric, numeric, numeric) OWNER TO admin;
72870
72871 --
72872 -- TOC entry 2049 (class 1255 OID 146566879)
72873 -- Dependencies: 4536 8
72874 -- Name: postvoucher(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
72875 --
72876
72877 CREATE FUNCTION postvoucher(integer, boolean) RETURNS integer
72878     LANGUAGE plpgsql
72879     AS $_$
72880 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72881 -- See www.xtuple.com/CPAL for the full text of the software license.
72882 DECLARE
72883   pVoheadid ALIAS FOR $1;
72884   pPostCosts ALIAS FOR $2;
72885
72886 BEGIN
72887   RETURN postVoucher(pVoheadid, fetchJournalNumber('AP-VO'), pPostCosts);
72888 END;
72889 $_$;
72890
72891
72892 ALTER FUNCTION public.postvoucher(integer, boolean) OWNER TO admin;
72893
72894 --
72895 -- TOC entry 2050 (class 1255 OID 146566880)
72896 -- Dependencies: 4536 8
72897 -- Name: postvoucher(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
72898 --
72899
72900 CREATE FUNCTION postvoucher(integer, integer, boolean) RETURNS integer
72901     LANGUAGE plpgsql
72902     AS $_$
72903 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
72904 -- See www.xtuple.com/CPAL for the full text of the software license.
72905 DECLARE
72906   pVoheadid ALIAS FOR $1;
72907   pJournalNumber ALIAS FOR $2;
72908   pPostCosts ALIAS FOR $3;
72909   _sequence INTEGER;
72910   _totalAmount_base NUMERIC;
72911   _totalAmount NUMERIC;
72912   _itemAmount_base NUMERIC;
72913   _itemAmount NUMERIC;
72914   _totalDiscountableAmount NUMERIC;
72915   _test INTEGER;
72916   _a RECORD;
72917   _d RECORD;
72918   _g RECORD;
72919   _p RECORD;
72920   _r RECORD;
72921   _costx RECORD;
72922   _pPostCosts BOOLEAN;
72923   _pExplain BOOLEAN;
72924   _pLowLevel BOOLEAN;
72925   _exchGainFreight NUMERIC;
72926   _taxBaseValue NUMERIC;
72927   _firstExchDateFreight DATE;
72928   _tmpTotal             NUMERIC;
72929   _glDate               DATE;
72930
72931 BEGIN
72932
72933   RAISE DEBUG 'postVoucher(%, %, %)', pVoheadid, pJournalNumber, pPostCosts;
72934
72935   _pPostCosts := TRUE;
72936   _totalAmount_base := 0;
72937   _totalAmount := 0;
72938   _totalDiscountableAmount := 0;
72939   SELECT fetchGLSequence() INTO _sequence;
72940
72941 --  Cache Voucher Infomation
72942   SELECT vohead.*,
72943          vend_number || '-' || vend_name || ' ' || vohead_reference
72944                                                           AS glnotes,
72945          COALESCE(pohead_orderdate, vohead_docdate) AS pohead_orderdate,
72946          COALESCE(pohead_curr_id, vohead_curr_id) AS pohead_curr_id INTO _p
72947   FROM vendinfo, vohead LEFT OUTER JOIN pohead ON (vohead_pohead_id = pohead_id)
72948   WHERE ( (vohead_id=pVoheadid)
72949   AND (vend_id=vohead_vend_id) )
72950   FOR UPDATE OF vohead;
72951
72952   IF (_p.vohead_posted) THEN
72953     RAISE EXCEPTION 'Cannot post Voucher #% as it is already posted [xtuple: postVoucher, -10, %]',
72954                         _p.vohead_number, _p.vohead_number;
72955   END IF;
72956
72957   _glDate := COALESCE(_p.vohead_gldistdate, _p.vohead_distdate);
72958
72959 --  If the vohead_distdate is NULL, assume that this is a NULL vohead and quietly delete it
72960   IF (_p.vohead_distdate IS NULL) THEN
72961     DELETE FROM vohead WHERE vohead_id = pVoheadid;
72962     RETURN 0;
72963   END IF;
72964   IF (_p.vohead_amount <= 0) THEN
72965     RAISE EXCEPTION 'Cannot Post Voucher #% for a negative or zero amount (%) [xtuple: postVoucher, -1, %, %]',
72966                         _p.vohead_number, _p.vohead_amount,
72967                         _p.vohead_number, _p.vohead_amount;
72968   END IF;
72969
72970 -- there is no currency gain/loss on items, see issue 3892,
72971 -- but there might be on freight, which is first encountered at p/o receipt
72972   SELECT recv_date::DATE INTO _firstExchDateFreight
72973       FROM recv
72974       WHERE (recv_vohead_id = pVoheadid);
72975
72976   SELECT round(SUM(amount),4) INTO _tmpTotal
72977   FROM (
72978   SELECT SUM(vodist_amount) AS amount
72979     FROM vodist
72980    WHERE ( (vodist_vohead_id=pVoheadid)
72981      AND   (vodist_tax_id=-1) )
72982   UNION ALL
72983   SELECT SUM(voitem_freight) AS amount
72984     FROM voitem
72985    WHERE (voitem_vohead_id=pVoheadid)
72986   UNION ALL
72987   SELECT SUM(tax*-1)
72988   FROM 
72989     (SELECT round(sum(taxdetail_tax),2) AS tax,
72990               currToBase(_p.vohead_curr_id, round(sum(taxdetail_tax),2), _p.vohead_docdate) AS taxbasevalue
72991      FROM tax 
72992      JOIN calculateTaxDetailSummary('VO', pVoheadid, 'T') ON (taxdetail_tax_id=tax_id)
72993      GROUP BY tax_id, tax_sales_accnt_id
72994     ) AS taxdata
72995   ) AS data;
72996
72997   IF (_tmpTotal IS NULL OR _tmpTotal <= 0) THEN
72998     RAISE EXCEPTION 'Cannot Post Voucher #% with negative or zero distributions (%) [xtuple: postVoucher, -2, %, %]',
72999                         _p.vohead_number, _tmpTotal,
73000                         _p.vohead_number, _tmpTotal;
73001   END IF;
73002
73003   IF (_tmpTotal > _p.vohead_amount) THEN
73004     RAISE EXCEPTION 'Cannot Post Voucher #% with distributions greater than the voucher amount (% > %) [xtuple: postVoucher, -3, %, %, %]',
73005                         _p.vohead_number, _tmpTotal, _p.vohead_amount,
73006                         _p.vohead_number, _tmpTotal, _p.vohead_amount;
73007   END IF;
73008
73009   IF (_tmpTotal < _p.vohead_amount) THEN
73010     RAISE EXCEPTION 'Cannot Post Voucher #% with distributions less than the voucher amount (% < %) [xtuple: postVoucher, -4, %, %, %]',
73011                         _p.vohead_number, _tmpTotal, _p.vohead_amount,
73012                         _p.vohead_number, _tmpTotal, _p.vohead_amount;
73013   END IF;
73014
73015   SELECT DISTINCT poitem_linenumber INTO _test
73016     FROM vodist, voitem, poitem 
73017    WHERE ( (vodist_poitem_id=poitem_id)
73018      AND   (voitem_poitem_id=poitem_id)
73019      AND   (voitem_vohead_id=vodist_vohead_id)
73020      AND   ((poitem_qty_received - poitem_qty_vouchered) = 0)
73021      AND   (vodist_vohead_id=pVoheadid) )
73022    LIMIT 1;
73023   IF (FOUND) THEN
73024     RAISE EXCEPTION 'Cannot Post Voucher #% as one or more of the line items have already been fully vouchered. Check P/O Line #% [postVoucher, -6, %, %]',
73025          _p.vohead_number, _test,
73026          _p.vohead_number, _test;
73027   END IF;
73028
73029 --  Start by handling taxes
73030   FOR _r IN SELECT tax_sales_accnt_id, 
73031               round(sum(taxdetail_tax),2) AS tax,
73032               currToBase(_p.vohead_curr_id, round(sum(taxdetail_tax),2), _p.vohead_docdate) AS taxbasevalue
73033             FROM tax 
73034              JOIN calculateTaxDetailSummary('VO', pVoheadid, 'T') ON (taxdetail_tax_id=tax_id)
73035             GROUP BY tax_id, tax_sales_accnt_id LOOP
73036
73037     PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', _p.vohead_number,
73038                                 _r.tax_sales_accnt_id, 
73039                                 _r.taxbasevalue,
73040                                 _glDate, _p.glnotes );
73041
73042     RAISE DEBUG 'postVoucher: _r.tax=%', _r.tax;
73043
73044     _totalAmount_base := (_totalAmount_base - _r.taxbasevalue);
73045     _totalAmount := (_totalAmount - _r.tax);
73046      
73047   END LOOP;
73048
73049 -- Update item tax records with posting data
73050     UPDATE voitemtax SET 
73051       taxhist_docdate=_p.vohead_docdate,
73052       taxhist_distdate=_glDate,
73053       taxhist_curr_id=_p.vohead_curr_id,
73054       taxhist_curr_rate=curr_rate,
73055       taxhist_journalnumber=pJournalNumber
73056     FROM vohead
73057      JOIN voitem ON (vohead_id=voitem_vohead_id), 
73058      curr_rate
73059     WHERE ((vohead_id=pVoheadId)
73060       AND (taxhist_parent_id=voitem_id)
73061       AND (_p.vohead_curr_id=curr_id)
73062       AND (_p.vohead_docdate BETWEEN curr_effective 
73063                            AND curr_expires) );
73064
73065 -- Update Misc distributions with posting data
73066     UPDATE voheadtax SET 
73067       taxhist_docdate=_p.vohead_docdate,
73068       taxhist_distdate=_glDate,
73069       taxhist_curr_id=_p.vohead_curr_id,
73070       taxhist_curr_rate=curr_rate,
73071       taxhist_journalnumber=pJournalNumber
73072     FROM curr_rate
73073     WHERE ((taxhist_parent_id=pVoheadid)
73074       AND (_p.vohead_curr_id=curr_id)
73075       AND (_p.vohead_docdate BETWEEN curr_effective 
73076                            AND curr_expires) );
73077
73078 --  Loop through the vodist records for the passed vohead that
73079 --  are posted against a P/O Item
73080   FOR _g IN SELECT DISTINCT poitem_id, voitem_id, voitem_qty, poitem_expcat_id,
73081                             poitem_invvenduomratio, poitem_prj_id,
73082                             COALESCE(itemsite_id, -1) AS itemsiteid,
73083                             COALESCE(itemsite_costcat_id, -1) AS costcatid,
73084                             COALESCE(itemsite_item_id, -1) AS itemsite_item_id,
73085                             (SELECT SUM(value) 
73086                              FROM (
73087                                 SELECT SUM(recv_value) AS value
73088                                 FROM recv
73089                                 WHERE (recv_voitem_id=voitem_id)
73090                              UNION
73091                                 SELECT SUM(poreject_value)*-1 AS value
73092                                 FROM poreject
73093                                 WHERE (poreject_voitem_id=voitem_id)) as data)
73094                            AS value_base,
73095                            (poitem_freight_received - poitem_freight_vouchered) /
73096                                (poitem_qty_received - poitem_qty_vouchered) * voitem_qty AS vouchered_freight,
73097                             currToBase(_p.pohead_curr_id,
73098                                        (poitem_freight_received - poitem_freight_vouchered) /
73099                                        (poitem_qty_received - poitem_qty_vouchered) * voitem_qty,
73100                                         _firstExchDateFreight ) AS vouchered_freight_base,
73101                             voitem_freight,
73102                             currToBase(_p.vohead_curr_id, voitem_freight,
73103                                        _p.vohead_distdate) AS voitem_freight_base
73104             FROM vodist, voitem,
73105                  poitem LEFT OUTER JOIN itemsite ON (poitem_itemsite_id=itemsite_id)
73106             WHERE ( (vodist_poitem_id=poitem_id)
73107              AND (voitem_poitem_id=poitem_id)
73108              AND (voitem_vohead_id=vodist_vohead_id)
73109              AND (vodist_vohead_id=pVoheadid)) LOOP
73110
73111 --  Grab the G/L Accounts
73112     IF (_g.costcatid = -1) THEN
73113       SELECT getPrjAccntId(_g.poitem_prj_id, pp.accnt_id) AS pp_accnt_id,
73114              lb.accnt_id AS lb_accnt_id,
73115              fr.accnt_id AS freight_accnt_id INTO _a
73116       FROM expcat, accnt AS pp, accnt AS lb, accnt AS fr
73117       WHERE ( (expcat_purchprice_accnt_id=pp.accnt_id)
73118        AND (expcat_liability_accnt_id=lb.accnt_id)
73119        AND (expcat_freight_accnt_id=fr.accnt_id)
73120        AND (expcat_id=_g.poitem_expcat_id) );
73121       IF (NOT FOUND) THEN
73122         RAISE EXCEPTION 'Cannot Post Voucher #% due to unassigned G/L Accounts [xtuple: postVoucher, -7, %]',
73123                         _p.vohead_number, _p.vohead_number;
73124       END IF;
73125     ELSE
73126       SELECT getPrjAccntId(_g.poitem_prj_id, costcat_purchprice_accnt_id) AS pp_accnt_id,
73127              getPrjAccntId(_g.poitem_prj_id, costcat_liability_accnt_id) AS lb_accnt_id,
73128              getPrjAccntId(_g.poitem_prj_id, costcat_freight_accnt_id) AS freight_accnt_id
73129       INTO _a
73130       FROM costcat
73131       WHERE (costcat_id=_g.costcatid);
73132       IF (NOT FOUND) THEN
73133         RAISE EXCEPTION 'Cannot Post Voucher #% due to unassigned G/L Accounts [xtuple: postVoucher, -8, %]',
73134                         _p.vohead_number, _p.vohead_number;
73135       END IF;
73136     END IF;
73137
73138 --  Clear the Item Amount accumulator
73139     _itemAmount_base := 0;
73140     _itemAmount := 0;
73141
73142 --  Figure out the total posted value for this line item
73143     FOR _d IN SELECT vodist_id, vodist_amount, vodist_discountable,
73144                      _p.vohead_curr_id, vodist_costelem_id,
73145                      currToBase(_p.vohead_curr_id, vodist_amount,
73146                                 _p.vohead_distdate) AS vodist_amount_base
73147               FROM vodist
73148               WHERE ( (vodist_vohead_id=pVoheadid)
73149                AND (vodist_poitem_id=_g.poitem_id) ) LOOP
73150
73151        _pExplain := FALSE;
73152        SELECT * INTO _costx
73153          FROM itemcost
73154         WHERE ( (itemcost_item_id = _g.itemsite_item_id)
73155           AND   (itemcost_costelem_id = _d.vodist_costelem_id) );
73156
73157        IF (FOUND) THEN
73158          _pExplain := _costx.itemcost_lowlevel;
73159        END IF;
73160
73161 --  Post the cost to the Actual if requested
73162 --      IF ( (pPostCosts) AND (_d.vodist_costelem_id <> -1) ) THEN
73163       IF ( (_d.vodist_costelem_id <> -1) AND (_g.itemsite_item_id <> -1) ) THEN
73164         PERFORM updateCost( _g.itemsite_item_id, _d.vodist_costelem_id,
73165                             _pExplain, (_d.vodist_amount / (_g.voitem_qty * _g.poitem_invvenduomratio)),
73166                             _p.vohead_curr_id );
73167       END IF;
73168
73169 --  Add the Distribution Amount to the Item Amount
73170       RAISE DEBUG 'postVoucher: _d.vodist_amount=%', _d.vodist_amount;
73171
73172       _itemAmount_base := _itemAmount_base + ROUND(_d.vodist_amount_base, 2);
73173       _itemAmount := _itemAmount + _d.vodist_amount;
73174       IF (_d.vodist_discountable) THEN
73175         _totalDiscountableAmount := (_totalDiscountableAmount + _d.vodist_amount);
73176       END IF;
73177
73178     END LOOP;
73179
73180 --  Distribute from the clearing account
73181     PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
73182                 _a.lb_accnt_id,
73183                 round(_g.value_base + _g.vouchered_freight_base, 2) * -1,
73184                 _glDate, _p.glnotes );
73185
73186
73187 --  Attribute the correct portion to currency gain/loss
73188     _exchGainFreight := 0;
73189     SELECT currGain(_p.pohead_curr_id, _g.vouchered_freight,
73190                     _firstExchDateFreight, _p.vohead_distdate )
73191                     INTO _exchGainFreight;
73192     IF (round(_exchGainFreight, 2) <> 0) THEN
73193         PERFORM insertIntoGLSeries(_sequence, 'A/P', 'VO',
73194             text(_p.vohead_number),
73195             getGainLossAccntId(_a.lb_accnt_id), round(_exchGainFreight, 2),
73196            _glDate, _p.glnotes);
73197     END IF;
73198
73199 --  Distribute the remaining variance to the Purchase Price Variance account
73200     IF (round(_itemAmount_base, 2) <> round(_g.value_base, 2)) THEN
73201       _tmpTotal := round(_itemAmount_base, 2) - round(_g.value_base, 2);
73202       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
73203                                   _a.pp_accnt_id,
73204                                   _tmpTotal * -1,
73205                                   _glDate, _p.glnotes );
73206     END IF;
73207
73208 --  Distribute the remaining freight variance to the Purchase Price Variance account
73209     IF (round(_g.voitem_freight_base + _exchGainFreight, 2) <> round(_g.vouchered_freight_base, 2)) THEN
73210       _tmpTotal := round(_g.voitem_freight_base + _exchGainFreight, 2) - round(_g.vouchered_freight_base, 2);
73211       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
73212         _a.freight_accnt_id,
73213               _tmpTotal * -1,
73214               _glDate, _p.glnotes );
73215     END IF;
73216
73217 --  Add the distribution amount to the total amount to distribute
73218     RAISE DEBUG 'postVoucher: _itemAmount=%', _itemAmount;
73219
73220     _totalAmount_base := (_totalAmount_base + _itemAmount_base + _g.voitem_freight_base);
73221     _totalAmount := (_totalAmount + _itemAmount + _g.voitem_freight);
73222
73223 --  Post all the Tagged Receivings for this P/O Item as Invoiced and
73224 --  record the purchase and receive costs
73225 --  Comment out because recv cost is set at receiving now.
73226     UPDATE recv
73227     SET recv_invoiced=TRUE,
73228         recv_recvcost_curr_id=basecurrid(),
73229         recv_recvcost=round(_g.value_base / _g.voitem_qty, 2)
73230     FROM poitem
73231     WHERE ((recv_orderitem_id=poitem_id)
73232       AND  (recv_order_type='PO')
73233       AND  (recv_orderitem_id=_g.poitem_id)
73234       AND  (recv_vohead_id=pVoheadid) );
73235
73236 --  Post all the Tagged Rejections for this P/O Item as Invoiced
73237     UPDATE poreject
73238     SET poreject_invoiced=TRUE
73239     WHERE ( (poreject_poitem_id=_g.poitem_id)
73240      AND (poreject_vohead_id=pVoheadid) );
73241
73242 --  Update the qty and freight vouchered fields
73243     UPDATE poitem
73244        SET poitem_qty_vouchered = (poitem_qty_vouchered + _g.voitem_qty),
73245            poitem_freight_vouchered = (poitem_freight_vouchered + _g.vouchered_freight)
73246      WHERE (poitem_id=_g.poitem_id);
73247
73248   END LOOP;
73249
73250 --  Loop through the vodist records for the passed vohead that
73251 --  are not posted against a P/O Item
73252 --  Skip the tax distributions
73253   FOR _d IN SELECT vodist_id, vodist_discountable,
73254                    currToBase(_p.vohead_curr_id, vodist_amount,
73255                               _p.vohead_distdate) AS vodist_amount_base,
73256                    vodist_amount,
73257                    vodist_accnt_id, vodist_expcat_id
73258             FROM vodist
73259             WHERE ( (vodist_vohead_id=pVoheadid)
73260              AND (vodist_poitem_id=-1)
73261              AND (vodist_tax_id=-1) ) LOOP
73262
73263 --  Distribute from the misc. account
73264     IF (_d.vodist_accnt_id = -1) THEN
73265       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
73266                           expcat_exp_accnt_id,
73267                           round(_d.vodist_amount_base, 2) * -1,
73268                           _glDate, _p.glnotes )
73269          FROM expcat
73270         WHERE (expcat_id=_d.vodist_expcat_id);
73271     ELSE
73272       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
73273                           _d.vodist_accnt_id,
73274                           round(_d.vodist_amount_base, 2) * -1,
73275                           _glDate, _p.glnotes );
73276     END IF;
73277
73278 --  Add the Distribution Amount to the Total Amount
73279     RAISE DEBUG 'postVoucher: _d.vodist_amount=%', _d.vodist_amount;
73280
73281     _totalAmount_base := _totalAmount_base + ROUND(_d.vodist_amount_base, 2);
73282     _totalAmount := _totalAmount + _d.vodist_amount;
73283     IF (_d.vodist_discountable) THEN
73284       _totalDiscountableAmount := (_totalDiscountableAmount + _d.vodist_amount);
73285     END IF;
73286
73287   END LOOP;
73288
73289   SELECT insertIntoGLSeries( _sequence, 'A/P', 'VO', text(vohead_number),
73290                              accnt_id, round(_totalAmount_base, 2),
73291                              _glDate, _p.glnotes ) INTO _test
73292   FROM vohead LEFT OUTER JOIN accnt ON (accnt_id=findAPAccount(vohead_vend_id))
73293   WHERE ( (findAPAccount(vohead_vend_id)=0 OR accnt_id > 0) -- G/L interface might be disabled
73294     AND (vohead_id=pVoheadid) );
73295   IF (NOT FOUND) THEN
73296     RAISE EXCEPTION 'Cannot Post Voucher #% due to an unassigned A/P Account [xtuple: postVoucher, -9, %]',
73297                     _p.vohead_number, _p.vohead_number;
73298   END IF;
73299
73300   PERFORM postGLSeries(_sequence, pJournalNumber);
73301
73302 --  Create the A/P Open Item
73303   RAISE DEBUG 'postVoucher: _totalAmount=%, _totalDiscountableAmount=%',
73304                 _totalAmount, _totalDiscountableAmount;
73305
73306   INSERT INTO apopen
73307   ( apopen_journalnumber, apopen_docdate, apopen_duedate, apopen_distdate, apopen_open,
73308     apopen_terms_id, apopen_vend_id, apopen_doctype,
73309     apopen_docnumber, apopen_invcnumber, apopen_ponumber, apopen_reference,
73310     apopen_amount, apopen_paid, apopen_notes, apopen_username, apopen_posted,
73311     apopen_curr_id, apopen_discountable_amount )
73312 -- TODO: 
73313   SELECT pJournalNumber, vohead_docdate, vohead_duedate, _glDate, TRUE,
73314          vohead_terms_id, vohead_vend_id, 'V',
73315          vohead_number, vohead_invcnumber, COALESCE(TEXT(pohead_number), 'Misc.'), vohead_reference,
73316          round(_totalAmount, 2), 0, '', getEffectiveXtUser(), FALSE,
73317          vohead_curr_id, round(_totalDiscountableAmount, 2)
73318   FROM vohead LEFT OUTER JOIN pohead ON (vohead_pohead_id=pohead_id)
73319   WHERE (vohead_id=pVoheadid);
73320
73321 --  Close all of the P/O Items that should be closed by this Voucher
73322   UPDATE poitem
73323   SET poitem_status='C'
73324   FROM voitem
73325   WHERE ( (voitem_poitem_id=poitem_id)
73326    AND (voitem_close)
73327    AND (voitem_vohead_id=pVoheadid) );
73328
73329 --  Check the P/O items and if they are all closed go ahead
73330 --  and close the P/O head.
73331   IF ( (SELECT (count(*) < 1)
73332           FROM vohead, poitem
73333          WHERE ((vohead_pohead_id=poitem_pohead_id)
73334            AND  (poitem_status<>'C')
73335            AND  (vohead_id=pVoheadid) ) ) ) THEN
73336     PERFORM closePo(vohead_pohead_id)
73337        FROM vohead
73338       WHERE (vohead_id=pVoheadid);
73339   END IF;
73340
73341 --  Set the vohead as posted
73342   UPDATE vohead
73343   SET vohead_posted=TRUE, vohead_gldistdate=_glDate
73344   WHERE (vohead_id=pVoheadid);
73345
73346   RETURN pJournalNumber;
73347
73348 END;
73349 $_$;
73350
73351
73352 ALTER FUNCTION public.postvoucher(integer, integer, boolean) OWNER TO admin;
73353
73354 --
73355 -- TOC entry 2051 (class 1255 OID 146566882)
73356 -- Dependencies: 4536 8
73357 -- Name: postvouchers(boolean); Type: FUNCTION; Schema: public; Owner: admin
73358 --
73359
73360 CREATE FUNCTION postvouchers(boolean) RETURNS integer
73361     LANGUAGE plpgsql
73362     AS $_$
73363 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73364 -- See www.xtuple.com/CPAL for the full text of the software license.
73365 DECLARE
73366   pPostCosts ALIAS FOR $1;
73367   _journalNumber INTEGER;
73368
73369 BEGIN
73370
73371   SELECT fetchJournalNumber('AP-VO') INTO _journalNumber;
73372
73373   PERFORM postVoucher(vohead_id, _journalNumber, pPostCosts)
73374   FROM vohead
73375   WHERE (NOT vohead_posted);
73376
73377   RETURN _journalNumber;
73378
73379 END;
73380 $_$;
73381
73382
73383 ALTER FUNCTION public.postvouchers(boolean) OWNER TO admin;
73384
73385 --
73386 -- TOC entry 2052 (class 1255 OID 146566883)
73387 -- Dependencies: 4536 8
73388 -- Name: primarykeyfields(text, text); Type: FUNCTION; Schema: public; Owner: admin
73389 --
73390
73391 CREATE FUNCTION primarykeyfields(text, text) RETURNS text[]
73392     LANGUAGE plpgsql STABLE
73393     AS $_$ 
73394 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73395 -- See www.xtuple.com/CPAL for the full text of the software license.
73396 DECLARE
73397   pSchema       ALIAS FOR $1;
73398   pRelation     ALIAS FOR $2;
73399   _colname      TEXT;
73400   _counter      INTEGER := 0;
73401   _result       TEXT[];
73402
73403 BEGIN
73404   EXECUTE 'SELECT ARRAY(SELECT attname
73405                          FROM pg_attribute
73406                          JOIN pg_class idx ON (attrelid         = idx.oid)
73407                          JOIN pg_namespace ON (idx.relnamespace = pg_namespace.oid)
73408                          JOIN pg_index     ON (idx.oid          = indexrelid)
73409                          JOIN pg_class tab ON (indrelid         = tab.oid)
73410                         WHERE NOT attisdropped
73411                           AND nspname = ''' || pSchema || ''' 
73412                           AND indisprimary
73413                           AND LOWER(tab.relname) = ''' || pRelation || '''
73414                        ORDER BY attnum);'
73415   INTO _result;
73416
73417   RETURN _result;
73418 END;
73419 $_$;
73420
73421
73422 ALTER FUNCTION public.primarykeyfields(text, text) OWNER TO admin;
73423
73424 --
73425 -- TOC entry 9070 (class 0 OID 0)
73426 -- Dependencies: 2052
73427 -- Name: FUNCTION primarykeyfields(text, text); Type: COMMENT; Schema: public; Owner: admin
73428 --
73429
73430 COMMENT ON FUNCTION primarykeyfields(text, text) IS 'Return an array containing the names of the primary key fields of pSchema.pRelation. The first key field is in _result[1].';
73431
73432
73433 --
73434 -- TOC entry 2053 (class 1255 OID 146566884)
73435 -- Dependencies: 2856 4536 8
73436 -- Name: prj(); Type: FUNCTION; Schema: public; Owner: admin
73437 --
73438
73439 CREATE FUNCTION prj() RETURNS SETOF prj
73440     LANGUAGE plpgsql
73441     AS $$
73442 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73443 -- See www.xtuple.com/CPAL for the full text of the software license.
73444 DECLARE
73445   _row prj%ROWTYPE;
73446   _priv TEXT;
73447   _grant BOOLEAN;
73448
73449 BEGIN
73450   -- This query will give us the most permissive privilege the user has been granted
73451   SELECT privilege, granted INTO _priv, _grant
73452   FROM privgranted 
73453   WHERE privilege IN ('MaintainAllProjects','ViewAllProjects','MaintainPersonalProjects','ViewPersonalProjects')
73454   ORDER BY granted DESC, sequence
73455   LIMIT 1;
73456
73457   -- If have an 'All' privilege return all results
73458   IF (_priv ~ 'All' AND _grant) THEN
73459     FOR _row IN 
73460       SELECT * FROM prj
73461     LOOP
73462       RETURN NEXT _row;
73463     END LOOP;
73464   -- Otherwise if have any other grant, must be personal privilege.
73465   ELSIF (_grant) THEN
73466     FOR _row IN 
73467       SELECT * FROM prj 
73468       WHERE getEffectiveXtUser() IN (prj_owner_username, prj_username)
73469     LOOP
73470       RETURN NEXT _row;
73471     END LOOP;
73472   END IF;
73473
73474   RETURN;
73475
73476 END;
73477 $$;
73478
73479
73480 ALTER FUNCTION public.prj() OWNER TO admin;
73481
73482 --
73483 -- TOC entry 9071 (class 0 OID 0)
73484 -- Dependencies: 2053
73485 -- Name: FUNCTION prj(); Type: COMMENT; Schema: public; Owner: admin
73486 --
73487
73488 COMMENT ON FUNCTION prj() IS 'A table function that returns Project results according to privilege settings.';
73489
73490
73491 --
73492 -- TOC entry 232 (class 1259 OID 146566885)
73493 -- Dependencies: 6041 8
73494 -- Name: prjtask; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
73495 --
73496
73497 CREATE TABLE prjtask (
73498     prjtask_id integer NOT NULL,
73499     prjtask_number text NOT NULL,
73500     prjtask_name text NOT NULL,
73501     prjtask_descrip text,
73502     prjtask_prj_id integer NOT NULL,
73503     prjtask_anyuser boolean,
73504     prjtask_status character(1) NOT NULL,
73505     prjtask_hours_budget numeric(18,6) NOT NULL,
73506     prjtask_hours_actual numeric(18,6) NOT NULL,
73507     prjtask_exp_budget numeric(16,4) NOT NULL,
73508     prjtask_exp_actual numeric(16,4) NOT NULL,
73509     prjtask_owner_username text,
73510     prjtask_start_date date,
73511     prjtask_due_date date,
73512     prjtask_assigned_date date,
73513     prjtask_completed_date date,
73514     prjtask_username text,
73515     CONSTRAINT prjtask_prjtask_status_check CHECK ((prjtask_status = ANY (ARRAY['P'::bpchar, 'O'::bpchar, 'C'::bpchar])))
73516 );
73517
73518
73519 ALTER TABLE public.prjtask OWNER TO admin;
73520
73521 --
73522 -- TOC entry 9072 (class 0 OID 0)
73523 -- Dependencies: 232
73524 -- Name: TABLE prjtask; Type: COMMENT; Schema: public; Owner: admin
73525 --
73526
73527 COMMENT ON TABLE prjtask IS 'Project Task information';
73528
73529
73530 --
73531 -- TOC entry 2056 (class 1255 OID 146566892)
73532 -- Dependencies: 2882 4536 8
73533 -- Name: prjtask(); Type: FUNCTION; Schema: public; Owner: admin
73534 --
73535
73536 CREATE FUNCTION prjtask() RETURNS SETOF prjtask
73537     LANGUAGE plpgsql
73538     AS $$
73539 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73540 -- See www.xtuple.com/CPAL for the full text of the software license.
73541 DECLARE
73542   _row prjtask%ROWTYPE;
73543   _priv TEXT;
73544   _grant BOOLEAN;
73545
73546 BEGIN
73547   -- This query will give us the most permissive privilege the user has been granted
73548   SELECT privilege, granted INTO _priv, _grant
73549   FROM privgranted 
73550   WHERE privilege IN ('MaintainAllProjects','ViewAllProjects','MaintainPersonalProjects','ViewPersonalProjects')
73551   ORDER BY granted DESC, sequence
73552   LIMIT 1;
73553
73554   -- If have an 'All' privilege return all results
73555   IF (_priv ~ 'All' AND _grant) THEN
73556     FOR _row IN 
73557       SELECT * FROM prjtask
73558     LOOP
73559       RETURN NEXT _row;
73560     END LOOP;
73561   -- Otherwise if have any other grant, must be personal privilege.
73562   ELSIF (_grant) THEN
73563     FOR _row IN 
73564       SELECT prjtask.* FROM prjtask
73565       JOIN prj ON prj_id=prjtask_prj_id
73566       WHERE getEffectiveXtUser() IN (prjtask_owner_username,prjtask_username,prj_username,prj_owner_username)
73567     LOOP
73568       RETURN NEXT _row;
73569     END LOOP;
73570   END IF;
73571
73572   RETURN;
73573
73574 END;
73575 $$;
73576
73577
73578 ALTER FUNCTION public.prjtask() OWNER TO admin;
73579
73580 --
73581 -- TOC entry 9074 (class 0 OID 0)
73582 -- Dependencies: 2056
73583 -- Name: FUNCTION prjtask(); Type: COMMENT; Schema: public; Owner: admin
73584 --
73585
73586 COMMENT ON FUNCTION prjtask() IS 'A table function that returns Project results according to privilege settings.';
73587
73588
73589 --
73590 -- TOC entry 2057 (class 1255 OID 146566893)
73591 -- Dependencies: 4536 8
73592 -- Name: purgecreditmemos(date); Type: FUNCTION; Schema: public; Owner: admin
73593 --
73594
73595 CREATE FUNCTION purgecreditmemos(date) RETURNS boolean
73596     LANGUAGE plpgsql
73597     AS $_$
73598 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73599 -- See www.xtuple.com/CPAL for the full text of the software license.
73600 DECLARE
73601   pCutoffDate ALIAS FOR $1;
73602
73603 BEGIN
73604
73605   DELETE FROM cmitem
73606   WHERE (cmitem_id IN ( SELECT cmitem_id
73607                         FROM cmitem, cmhead
73608                         WHERE ( (cmitem_cmhead_id=cmhead_id)
73609                           AND   (cmhead_posted)
73610                           AND   (cmhead_printed)
73611                           AND   (cmhead_docdate<=pCutoffDate)
73612                           AND   (checkCreditMemoSitePrivs(cmhead_id)) ) ) );
73613
73614   DELETE FROM cmhead
73615   WHERE ( (cmhead_posted)
73616     AND   (cmhead_printed)
73617     AND   (cmhead_docdate<=pCutoffDate)
73618     AND   (checkCreditMemoSitePrivs(cmhead_id)) );
73619
73620   RETURN TRUE;
73621
73622 END;
73623 $_$;
73624
73625
73626 ALTER FUNCTION public.purgecreditmemos(date) OWNER TO admin;
73627
73628 --
73629 -- TOC entry 2058 (class 1255 OID 146566894)
73630 -- Dependencies: 4536 8
73631 -- Name: purgecrmacctmerge(integer); Type: FUNCTION; Schema: public; Owner: admin
73632 --
73633
73634 CREATE FUNCTION purgecrmacctmerge(integer) RETURNS integer
73635     LANGUAGE plpgsql
73636     AS $_$
73637 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73638 -- See www.xtuple.com/CPAL for the full text of the software license.
73639 DECLARE
73640   pDestid       ALIAS FOR $1;
73641   _result       INTEGER := 0;
73642   _tmpcount     INTEGER := 0;
73643 BEGIN
73644   IF EXISTS(SELECT 1
73645               FROM crmacctsel
73646              WHERE crmacctsel_dest_crmacct_id=pDestid) THEN
73647     DELETE FROM crmacctsel WHERE crmacctsel_dest_crmacct_id = pDestid;
73648     GET DIAGNOSTICS _result = ROW_COUNT;
73649
73650   ELSIF EXISTS(SELECT 1
73651                  FROM mrgundo
73652                 WHERE mrgundo_base_schema='public'
73653                   AND mrgundo_base_table='crmacct'
73654                   AND mrgundo_base_id=pDestid) THEN
73655
73656     DELETE FROM crmacct
73657      WHERE crmacct_id IN (
73658               SELECT mrgundo_pkey_id
73659                 FROM mrgundo
73660                WHERE mrgundo_schema   = 'public'
73661                  AND mrgundo_table    = 'crmacct'
73662                  and mrgundo_pkey_col = 'crmacct_id'
73663                  AND mrgundo_col IS NULL
73664                  AND mrgundo_base_schema = 'public'
73665                  AND mrgundo_base_table  = 'crmacct'
73666                  AND mrgundo_base_id     = pDestid)
73667         AND crmacct_id != pDestid;
73668     GET DIAGNOSTICS _result = ROW_COUNT;
73669
73670     DELETE FROM mrgundo
73671      WHERE mrgundo_base_schema ='public'
73672        AND mrgundo_base_table  ='crmacct'
73673        AND mrgundo_base_id     = pDestid;
73674     GET DIAGNOSTICS _tmpcount = ROW_COUNT;
73675
73676     _result := _result + _tmpcount;
73677   END IF;
73678
73679   RETURN _result;
73680 END;
73681 $_$;
73682
73683
73684 ALTER FUNCTION public.purgecrmacctmerge(integer) OWNER TO admin;
73685
73686 --
73687 -- TOC entry 2059 (class 1255 OID 146566895)
73688 -- Dependencies: 4536 8
73689 -- Name: purgeinvoicerecord(date, integer); Type: FUNCTION; Schema: public; Owner: admin
73690 --
73691
73692 CREATE FUNCTION purgeinvoicerecord(date, integer) RETURNS text
73693     LANGUAGE plpgsql
73694     AS $_$
73695 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
73696 -- See www.xtuple.com/CPAL for the full text of the software license.
73697 DECLARE
73698   pCutoffDate ALIAS FOR $1;
73699   pInvcheadId ALIAS FOR $2;
73700   _r RECORD;
73701   _ra RECORD;
73702   _raheadid INTEGER;
73703   _result INTEGER;
73704   _debug BOOLEAN := FALSE;
73705
73706 BEGIN
73707
73708 -- Purge records where the entire Invoice, Billing, Shipper, Sales Order
73709 -- chain of associated documents are closed and complete
73710
73711   FOR _r IN
73712   SELECT invchead_id, cobmisc_id, shiphead_id, ordershipped.cohead_id AS ordship_id, orderinvoiced.cohead_id AS ordinv_id
73713     FROM invchead LEFT OUTER JOIN invcitem ON (invcitem_invchead_id=invchead_id)
73714                   LEFT OUTER JOIN cobmisc ON (cobmisc_invcnumber::TEXT=invchead_invcnumber)
73715                   LEFT OUTER JOIN shipitem ON (shipitem_invcitem_id=invcitem_id)
73716                   LEFT OUTER JOIN shiphead ON (shiphead_id=shipitem_shiphead_id)
73717                   LEFT OUTER JOIN cohead ordershipped ON (ordershipped.cohead_id=shiphead_order_id)
73718                   LEFT OUTER JOIN coitem ON (coitem_id=invcitem_coitem_id)
73719                   LEFT OUTER JOIN cohead orderinvoiced ON (orderinvoiced.cohead_id=coitem_cohead_id)
73720    WHERE ( (invchead_id = pInvcheadId)
73721      AND   (invchead_posted)
73722      AND   (checkInvoiceSitePrivs(invchead_id)) )
73723   GROUP BY invchead_id, cobmisc_id, shiphead_id, ordship_id, ordinv_id LOOP
73724
73725 -- Check Billing
73726
73727 -- Billing header (cobmisc) must be posted
73728     SELECT cobmisc_id INTO _result
73729       FROM cobmisc
73730      WHERE ( (cobmisc_id=_r.cobmisc_id) AND (NOT cobmisc_posted) );
73731     IF (FOUND) THEN
73732       RETURN 'Billing not closed';
73733     END IF;
73734
73735 -- Billing line items (cobill), associated Invoice line items, and
73736 -- associated Sales Order line items must be closed, posted, and after cutoff date
73737     SELECT cobill_id INTO _result
73738       FROM cobill JOIN invcitem ON (invcitem_id=cobill_invcitem_id)
73739                   JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
73740                                      ((NOT invchead_posted) OR (invchead_invcdate > pCutoffDate)) )
73741                   JOIN coitem ON ( (coitem_id=cobill_coitem_id) AND
73742                                    (coitem_status NOT IN ('C', 'X')) )
73743      WHERE (cobill_cobmisc_id=_r.cobmisc_id);
73744     IF (FOUND) THEN
73745       RETURN 'Invoice/Sales Order associated with Billing not closed';
73746     END IF;
73747
73748 -- Check Shipping
73749
73750 -- Shipping header (shiphead) must be shipped
73751     SELECT shiphead_id INTO _result
73752       FROM shiphead
73753      WHERE ( (shiphead_id=_r.shiphead_id) AND (NOT shiphead_shipped) );
73754     IF (FOUND) THEN
73755       RETURN 'Shipper not closed';
73756     END IF;
73757
73758 -- Shipping line items (shipitem) and associated Sales Order line items
73759 -- must be closed
73760     SELECT shiphead_id INTO _result
73761       FROM shiphead, cohead, coitem
73762      WHERE ( (shiphead_id=_r.shiphead_id)
73763        AND   ( (shiphead_order_type='SO') AND (shiphead_order_id=cohead_id) )
73764        AND   (coitem_cohead_id=cohead_id)
73765        AND   (coitem_status NOT IN ('C', 'X')) );
73766     IF (FOUND) THEN
73767       RETURN 'Sales Order associated with Shipper not closed';
73768     END IF;
73769
73770 -- Shipping line items (shipitem) and associated Invoices must be posted
73771 -- and after cutoff date
73772     SELECT shiphead_id INTO _result
73773       FROM shiphead JOIN shipitem ON (shipitem_shiphead_id=shiphead_id)
73774                     JOIN invcitem ON (invcitem_id=shipitem_invcitem_id)
73775                     JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
73776                                        ((NOT invchead_posted) OR (invchead_invcdate > pCutoffDate)) )
73777      WHERE (shiphead_id=_r.shiphead_id);
73778     IF (FOUND) THEN
73779       RETURN 'Invoice associated with Shipper not closed';
73780     END IF;
73781
73782 -- Check Sales Order
73783
73784 -- Sales Order line items (coitem) must be closed
73785     SELECT cohead_id INTO _result
73786       FROM cohead JOIN coitem ON ( (coitem_cohead_id=cohead_id) AND
73787                                    (coitem_status NOT IN ('C', 'X')) )
73788      WHERE (cohead_id=_r.ordship_id);
73789     IF (FOUND) THEN
73790       RETURN 'Shipped Sales Order not closed';
73791     END IF;
73792     SELECT cohead_id INTO _result
73793       FROM cohead JOIN coitem ON ( (coitem_cohead_id=cohead_id) AND
73794                                    (coitem_status NOT IN ('C', 'X')) )
73795      WHERE (cohead_id=_r.ordinv_id);
73796     IF (FOUND) THEN
73797       RETURN 'Invoiced Sales Order not closed';
73798     END IF;
73799
73800     IF (fetchMetricBool('MultiWhs')) THEN
73801     -- Check Original Return Authorization and cross check to New Sales Order
73802       SELECT rahead_id INTO _result
73803         FROM rahead JOIN raitem ON ( (raitem_rahead_id=rahead_id) AND
73804                                      (raitem_status NOT IN ('C', 'X')) )
73805                     JOIN coitem ON ( (coitem_id=raitem_new_coitem_id) AND
73806                                      (coitem_status NOT IN ('C', 'X')) )
73807                     JOIN invcitem ON (invcitem_coitem_id=coitem_id)
73808                     JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
73809                                        ((NOT invchead_posted) OR (invchead_invcdate > pCutoffDate)) )
73810        WHERE (rahead_orig_cohead_id=_r.ordship_id);
73811       IF (FOUND) THEN
73812         RETURN 'Shipped Original Return Authorization not closed';
73813       END IF;
73814       SELECT rahead_id INTO _result
73815         FROM rahead JOIN raitem ON ( (raitem_rahead_id=rahead_id) AND
73816                                      (raitem_status NOT IN ('C', 'X')) )
73817                     JOIN coitem ON ( (coitem_id=raitem_new_coitem_id) AND
73818                                      (coitem_status NOT IN ('C', 'X')) )
73819                     JOIN invcitem ON (invcitem_coitem_id=coitem_id)
73820                     JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
73821                                        ((NOT invchead_posted) OR (invchead_invcdate > pCutoffDate)) )
73822        WHERE (rahead_orig_cohead_id=_r.ordinv_id);
73823       IF (FOUND) THEN
73824         RETURN 'Invoiced Original Return Authorization not closed';
73825       END IF;
73826
73827   -- Check New Return Authorization
73828       SELECT rahead_id INTO _result
73829         FROM rahead JOIN raitem ON ( (raitem_rahead_id=rahead_id) AND
73830                                      (NOT raitem_status IN ('C', 'X')) )
73831                     JOIN coitem ON ( (coitem_id=raitem_orig_coitem_id) AND
73832                                      (NOT coitem_status IN ('C', 'X')) )
73833                     JOIN invcitem ON (invcitem_coitem_id=coitem_id)
73834                     JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
73835                                        ((NOT invchead_posted) OR (invchead_invcdate > pCutoffDate)) )
73836        WHERE (rahead_new_cohead_id=_r.ordship_id);
73837       IF (FOUND) THEN
73838         RETURN 'Shipped New Return Authorization not closed';
73839       END IF;
73840       SELECT rahead_id INTO _result
73841         FROM rahead JOIN raitem ON ( (raitem_rahead_id=rahead_id) AND
73842                                      (NOT raitem_status IN ('C', 'X')) )
73843                     JOIN coitem ON ( (coitem_id=raitem_orig_coitem_id) AND
73844                                      (NOT coitem_status IN ('C', 'X')) )
73845                     JOIN invcitem ON (invcitem_coitem_id=coitem_id)
73846                     JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
73847                                        ((NOT invchead_posted) OR (invchead_invcdate > pCutoffDate)) )
73848        WHERE (rahead_new_cohead_id=_r.ordinv_id);
73849       IF (FOUND) THEN
73850         RETURN 'Invoiced New Return Authorization not closed';
73851       END IF;
73852     END IF;
73853
73854 -- Check Lot/Serial Registration
73855
73856     IF (fetchMetricBool('MultiWhs')) THEN
73857   -- Registration associated with Sales Order must be expired
73858       SELECT lsreg_id INTO _result
73859         FROM lsreg
73860        WHERE ( (lsreg_cohead_id=_r.ordship_id)
73861          AND   (lsreg_expiredate > CURRENT_DATE) );
73862       IF (FOUND) THEN
73863         RETURN 'Shipped Sales Order Lot/Serial Registration not closed';
73864       END IF;
73865       SELECT lsreg_id INTO _result
73866         FROM lsreg
73867        WHERE ( (lsreg_cohead_id=_r.ordinv_id)
73868          AND   (lsreg_expiredate > CURRENT_DATE) );
73869       IF (FOUND) THEN
73870         RETURN 'Invoiced Sales Order Lot/Serial Registration not closed';
73871       END IF;
73872
73873   -- Registration associated with Shipping must be expired
73874       SELECT lsreg_id INTO _result
73875         FROM lsreg
73876        WHERE ( (lsreg_cohead_id=_r.shiphead_id)
73877          AND   (lsreg_expiredate > CURRENT_DATE) );
73878       IF (FOUND) THEN
73879         RETURN 'Shipper Lot/Serial Registration not closed';
73880       END IF;
73881     END IF;
73882
73883     IF (fetchMetricBool('MultiWhs')) THEN
73884   -- Registration associated with Original Return Authorization must be expired
73885       SELECT rahead_id INTO _result
73886         FROM rahead JOIN raitem ON (raitem_rahead_id=rahead_id)
73887                     JOIN raitemls ON (raitemls_raitem_id=raitem_id)
73888                     JOIN lsreg ON ( (lsreg_ls_id=raitemls_ls_id) AND
73889                                     (lsreg_expiredate > CURRENT_DATE) )
73890        WHERE (rahead_orig_cohead_id=_r.ordship_id);
73891       IF (FOUND) THEN
73892         RETURN 'Shipped Original Return Authorization Lot/Serial Registration not closed';
73893       END IF;
73894       SELECT rahead_id INTO _result
73895         FROM rahead JOIN raitem ON (raitem_rahead_id=rahead_id)
73896                     JOIN raitemls ON (raitemls_raitem_id=raitem_id)
73897                     JOIN lsreg ON ( (lsreg_ls_id=raitemls_ls_id) AND
73898                                     (lsreg_expiredate > CURRENT_DATE) )
73899        WHERE (rahead_orig_cohead_id=_r.ordinv_id);
73900       IF (FOUND) THEN
73901         RETURN 'Invoiced Original Return Authorization Lot/Serial Registration not closed';
73902       END IF;
73903
73904   -- Registration associated with New Return Authorization must be expired
73905       SELECT rahead_id INTO _result
73906         FROM rahead JOIN raitem ON (raitem_rahead_id=rahead_id)
73907                     JOIN raitemls ON (raitemls_raitem_id=raitem_id)
73908                     JOIN lsreg ON ( (lsreg_ls_id=raitemls_ls_id) AND
73909                                     (lsreg_expiredate > CURRENT_DATE) )
73910        WHERE (rahead_new_cohead_id=_r.ordship_id);
73911       IF (FOUND) THEN
73912         RETURN 'Shipped New Return Authorization Lot/Serial Registration not closed';
73913       END IF;
73914       SELECT rahead_id INTO _result
73915         FROM rahead JOIN raitem ON (raitem_rahead_id=rahead_id)
73916                     JOIN raitemls ON (raitemls_raitem_id=raitem_id)
73917                     JOIN lsreg ON ( (lsreg_ls_id=raitemls_ls_id) AND
73918                                     (lsreg_expiredate > CURRENT_DATE) )
73919        WHERE (rahead_new_cohead_id=_r.ordinv_id);
73920       IF (FOUND) THEN
73921         RETURN 'Invoiced New Return Authorization Lot/Serial Registration not closed';
73922       END IF;
73923     END IF;
73924
73925 -- Cash Advances associated with Sales Order cannot exist
73926     SELECT aropenalloc_doc_id INTO _result   
73927       FROM aropenalloc
73928      WHERE ((aropenalloc_doctype='S')
73929        AND  (aropenalloc_doc_id=_r.ordship_id));
73930     IF (FOUND) THEN
73931       RETURN 'Shipped Cash Advance not closed';
73932     END IF;
73933     SELECT aropenalloc_doc_id INTO _result   
73934       FROM aropenalloc
73935      WHERE ((aropenalloc_doctype='S')
73936        AND  (aropenalloc_doc_id=_r.ordinv_id));
73937     IF (FOUND) THEN
73938       RETURN 'Invoiced Cash Advance not closed';
73939     END IF;
73940
73941   END LOOP;
73942
73943 -- Everything is OK, delete the chain
73944   FOR _r IN
73945   SELECT invchead_id, cobmisc_id, shiphead_id, ordershipped.cohead_id AS ordship_id, orderinvoiced.cohead_id AS ordinv_id
73946     FROM invchead LEFT OUTER JOIN invcitem ON (invcitem_invchead_id=invchead_id)
73947                   LEFT OUTER JOIN cobmisc ON (cobmisc_invcnumber::TEXT=invchead_invcnumber)
73948                   LEFT OUTER JOIN shipitem ON (shipitem_invcitem_id=invcitem_id)
73949                   LEFT OUTER JOIN shiphead ON (shiphead_id=shipitem_shiphead_id)
73950                   LEFT OUTER JOIN cohead ordershipped ON (ordershipped.cohead_id=shiphead_order_id)
73951                   LEFT OUTER JOIN coitem ON (coitem_id=invcitem_coitem_id)
73952                   LEFT OUTER JOIN cohead orderinvoiced ON (orderinvoiced.cohead_id=coitem_cohead_id)
73953    WHERE ( (invchead_id = pInvcheadId)
73954      AND   (invchead_posted)
73955      AND   (checkInvoiceSitePrivs(invchead_id)) )
73956   GROUP BY invchead_id, cobmisc_id, shiphead_id, ordship_id, ordinv_id LOOP
73957
73958     IF (fetchMetricBool('MultiWhs')) THEN
73959       FOR _ra IN
73960         SELECT rahead_id
73961         FROM rahead
73962         WHERE (rahead_orig_cohead_id=_r.ordship_id) LOOP
73963         IF (_debug) THEN
73964           RAISE NOTICE 'Deleting Original Return head id %', _ra.rahead_id;
73965         END IF;
73966         DELETE FROM raitemls WHERE (raitemls_raitem_id IN (SELECT raitem_id
73967                                                            FROM raitem
73968                                                            WHERE (raitem_rahead_id=_ra.rahead_id)));
73969         DELETE FROM rahist WHERE (rahist_rahead_id=_ra.rahead_id);
73970         DELETE FROM raitem WHERE (raitem_rahead_id=_ra.rahead_id);
73971         DELETE FROM rahead WHERE (rahead_id=_ra.rahead_id);
73972       END LOOP;
73973       FOR _ra IN
73974         SELECT rahead_id
73975         FROM rahead
73976         WHERE (rahead_orig_cohead_id=_r.ordinv_id) LOOP
73977         IF (_debug) THEN
73978           RAISE NOTICE 'Deleting Original Return head id %', _ra.rahead_id;
73979         END IF;
73980         DELETE FROM raitemls WHERE (raitemls_raitem_id IN (SELECT raitem_id
73981                                                            FROM raitem
73982                                                            WHERE (raitem_rahead_id=_ra.rahead_id)));
73983         DELETE FROM rahist WHERE (rahist_rahead_id=_ra.rahead_id);
73984         DELETE FROM raitem WHERE (raitem_rahead_id=_ra.rahead_id);
73985         DELETE FROM rahead WHERE (rahead_id=_ra.rahead_id);
73986       END LOOP;
73987
73988       FOR _ra IN
73989         SELECT rahead_id
73990           FROM rahead
73991          WHERE (rahead_new_cohead_id=_r.ordship_id) LOOP
73992         IF (_debug) THEN
73993           RAISE NOTICE 'Deleting New Return head id %', _ra.rahead_id;
73994         END IF;
73995         DELETE FROM raitemls WHERE (raitemls_raitem_id IN (SELECT raitem_id
73996                                                            FROM raitem
73997                                                            WHERE (raitem_rahead_id=_ra.rahead_id)));
73998         DELETE FROM rahist WHERE (rahist_rahead_id=_ra.rahead_id);
73999         DELETE FROM raitem WHERE (raitem_rahead_id=_ra.rahead_id);
74000         DELETE FROM rahead WHERE (rahead_id=_ra.rahead_id);
74001       END LOOP;
74002       FOR _ra IN
74003         SELECT rahead_id
74004           FROM rahead
74005          WHERE (rahead_new_cohead_id=_r.ordinv_id) LOOP
74006         IF (_debug) THEN
74007           RAISE NOTICE 'Deleting New Return head id %', _ra.rahead_id;
74008         END IF;
74009         DELETE FROM raitemls WHERE (raitemls_raitem_id IN (SELECT raitem_id
74010                                                            FROM raitem
74011                                                            WHERE (raitem_rahead_id=_ra.rahead_id)));
74012         DELETE FROM rahist WHERE (rahist_rahead_id=_ra.rahead_id);
74013         DELETE FROM raitem WHERE (raitem_rahead_id=_ra.rahead_id);
74014         DELETE FROM rahead WHERE (rahead_id=_ra.rahead_id);
74015       END LOOP;
74016     END IF;
74017
74018     IF (fetchMetricBool('MultiWhs')) THEN
74019       IF (_debug) THEN
74020         RAISE NOTICE 'Deleting Lot/Serial Registrations';
74021       END IF;
74022       DELETE FROM lsreg WHERE (lsreg_cohead_id=_r.ordship_id);
74023       DELETE FROM lsreg WHERE (lsreg_cohead_id=_r.ordinv_id);
74024       DELETE FROM lsreg WHERE (lsreg_shiphead_id=_r.shiphead_id);
74025     END IF;
74026
74027     IF (_debug) THEN
74028       RAISE NOTICE 'Deleting Shipped Sales Order head id %', _r.ordship_id;
74029     END IF;
74030     DELETE FROM payco WHERE (payco_cohead_id=_r.ordship_id);
74031     -- Delete kit components first
74032     DELETE FROM coitem WHERE (coitem_cohead_id=_r.ordship_id AND coitem_subnumber > 0);
74033     DELETE FROM coitem WHERE (coitem_cohead_id=_r.ordship_id);
74034     DELETE FROM cohead WHERE (cohead_id=_r.ordship_id);
74035
74036     IF (_debug) THEN
74037       RAISE NOTICE 'Deleting Sales Order head id %', _r.ordinv_id;
74038     END IF;
74039     DELETE FROM payco WHERE (payco_cohead_id=_r.ordinv_id);
74040     -- Delete kit components first
74041     DELETE FROM coitem WHERE (coitem_cohead_id=_r.ordinv_id AND coitem_subnumber > 0);
74042     DELETE FROM coitem WHERE (coitem_cohead_id=_r.ordinv_id);
74043     DELETE FROM cohead WHERE (cohead_id=_r.ordinv_id);
74044
74045     IF (_debug) THEN
74046       RAISE NOTICE 'Deleting Ship head id %', _r.shiphead_id;
74047     END IF;
74048     DELETE FROM shipitem WHERE (shipitem_shiphead_id=_r.shiphead_id);
74049     DELETE FROM pack WHERE (pack_shiphead_id=_r.shiphead_id);
74050     DELETE FROM shiphead WHERE (shiphead_id=_r.shiphead_id);
74051
74052     IF (_debug) THEN
74053       RAISE NOTICE 'Deleting Billing head id %', _r.cobmisc_id;
74054     END IF;
74055     DELETE FROM cobill WHERE (cobill_cobmisc_id=_r.cobmisc_id);
74056     DELETE FROM cobmisc WHERE (cobmisc_id=_r.cobmisc_id);
74057   END LOOP;
74058   
74059 -- Everything is OK, delete the Invoice
74060   IF (_debug) THEN
74061     RAISE NOTICE 'Deleting Invoice head id %', _r.invchead_id;
74062   END IF;
74063   DELETE FROM invcitem WHERE (invcitem_invchead_id=_r.invchead_id);
74064   DELETE FROM invchead WHERE (invchead_id=_r.invchead_id);
74065
74066   RETURN 'Purged';
74067
74068 END;
74069 $_$;
74070
74071
74072 ALTER FUNCTION public.purgeinvoicerecord(date, integer) OWNER TO admin;
74073
74074 --
74075 -- TOC entry 2060 (class 1255 OID 146566897)
74076 -- Dependencies: 4536 8
74077 -- Name: purgeinvoicerecords(date); Type: FUNCTION; Schema: public; Owner: admin
74078 --
74079
74080 CREATE FUNCTION purgeinvoicerecords(date) RETURNS integer
74081     LANGUAGE plpgsql
74082     AS $_$
74083 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74084 -- See www.xtuple.com/CPAL for the full text of the software license.
74085 DECLARE
74086   pCutoffDate ALIAS FOR $1;
74087
74088 BEGIN
74089
74090 -- Remove the shipitem records
74091   DELETE FROM shipitem
74092   WHERE (shipitem_invcitem_id IN (SELECT invcitem_id 
74093                                   FROM invcitem 
74094                                   WHERE invcitem_invchead_id IN ( SELECT invchead_id
74095                                      FROM invchead
74096                                      WHERE ( (invchead_invcdate <= pCutoffDate)
74097                                      AND   (checkInvoiceSitePrivs(invchead_id))
74098                                      AND   (invchead_posted) ) ) ) );
74099
74100 -- Remove the cobill and cobmisc records
74101   DELETE FROM cobill
74102   WHERE (cobill_cobmisc_id IN ( SELECT cobmisc_id
74103                                 FROM cobmisc, invchead
74104                                 WHERE ( (invchead_invcnumber=cobmisc_invcnumber::TEXT)
74105                                   AND   (checkInvoiceSitePrivs(invchead_id))
74106                                   AND   (cobmisc_invcdate <= pCutoffDate)
74107                                   AND   (cobmisc_posted)) ) );
74108
74109   DELETE FROM cobmisc
74110   WHERE ( (checkInvoiceSitePrivs(getInvcheadId(cobmisc_invcnumber::TEXT)))
74111     AND   (cobmisc_invcdate <= pCutoffDate)
74112     AND   (cobmisc_posted) );
74113
74114 -- Remove the invchead and invcitem records
74115   DELETE FROM invcitem
74116   WHERE (invcitem_invchead_id IN ( SELECT invchead_id
74117                                    FROM invchead
74118                                    WHERE ( (invchead_invcdate <= pCutoffDate)
74119                                      AND   (checkInvoiceSitePrivs(invchead_id))
74120                                      AND   (invchead_posted) ) ) );
74121
74122   DELETE FROM invchead
74123   WHERE ( (invchead_invcdate <= pCutoffDate)
74124     AND   (checkInvoiceSitePrivs(invchead_id))
74125     AND   (invchead_posted) );
74126
74127   RETURN 1;
74128
74129 END;
74130 $_$;
74131
74132
74133 ALTER FUNCTION public.purgeinvoicerecords(date) OWNER TO admin;
74134
74135 --
74136 -- TOC entry 2061 (class 1255 OID 146566898)
74137 -- Dependencies: 4536 8
74138 -- Name: purgepostedcountslips(date, integer); Type: FUNCTION; Schema: public; Owner: admin
74139 --
74140
74141 CREATE FUNCTION purgepostedcountslips(date, integer) RETURNS integer
74142     LANGUAGE plpgsql
74143     AS $_$
74144 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74145 -- See www.xtuple.com/CPAL for the full text of the software license.
74146 DECLARE
74147   pCutoffDate ALIAS FOR $1;
74148   pWarehousid ALIAS FOR $2;
74149
74150 BEGIN
74151
74152   IF (pWarehousid = -1) THEN
74153     DELETE FROM cntslip
74154     WHERE (cntslip_id IN ( SELECT cntslip_id
74155                            FROM cntslip, invcnt
74156                            WHERE ( (cntslip_cnttag_id=invcnt_id)
74157                             AND (invcnt_posted)
74158                             AND (cntslip_posted)
74159                             AND (date(invcnt_postdate) <= pCutoffDate) ) ) );
74160
74161   ELSE
74162     DELETE FROM cntslip
74163     WHERE (cntslip_id IN ( SELECT cntslip_id
74164                            FROM invcnt, itemsite
74165                            WHERE ( (cntslip_cnttag_id=invcnt_id)
74166                             AND (invcnt_posted)
74167                             AND (cntslip_posted)
74168                             AND (invcnt_itemsite_id=itemsite_id)
74169                             AND (date(invcnt_postdate) <= pCutoffDate)
74170                             AND (itemsite_warehous_id=pWarehousid) ) ) );
74171   END IF;
74172
74173   RETURN 1;
74174
74175 END;
74176 $_$;
74177
74178
74179 ALTER FUNCTION public.purgepostedcountslips(date, integer) OWNER TO admin;
74180
74181 --
74182 -- TOC entry 2062 (class 1255 OID 146566899)
74183 -- Dependencies: 4536 8
74184 -- Name: purgepostedcounttags(date, integer); Type: FUNCTION; Schema: public; Owner: admin
74185 --
74186
74187 CREATE FUNCTION purgepostedcounttags(date, integer) RETURNS integer
74188     LANGUAGE plpgsql
74189     AS $_$
74190 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74191 -- See www.xtuple.com/CPAL for the full text of the software license.
74192 DECLARE
74193   pCutoffDate ALIAS FOR $1;
74194   pWarehousid ALIAS FOR $2;
74195
74196 BEGIN
74197
74198   IF (pWarehousid = -1) THEN
74199     DELETE FROM cntslip
74200     WHERE (cntslip_cnttag_id IN ( SELECT invcnt_id
74201                                   FROM invcnt
74202                                   WHERE ( (invcnt_posted)
74203                                    AND (date(invcnt_postdate) <= pCutoffDate) ) ) );
74204
74205     DELETE FROM invcnt
74206     WHERE ((invcnt_posted)
74207      AND (date(invcnt_postdate) <= pCutoffDate));
74208
74209   ELSE
74210     DELETE FROM cntslip
74211     WHERE (cntslip_cnttag_id IN ( SELECT invcnt_id
74212                                   FROM invcnt, itemsite
74213                                   WHERE ( (invcnt_posted)
74214                                    AND (invcnt_itemsite_id=itemsite_id)
74215                                    AND (date(invcnt_postdate) <= pCutoffDate)
74216                                    AND (itemsite_warehous_id=pWarehousid) ) ) );
74217
74218     DELETE FROM invcnt
74219     WHERE (invcnt_id IN ( SELECT invcnt_id 
74220                           FROM invcnt, itemsite
74221                           WHERE ( (invcnt_posted)
74222                            AND (invcnt_itemsite_id=itemsite_id)
74223                            AND (date(invcnt_postdate) <= pCutoffDate)
74224                            AND (itemsite_warehous_id=pWarehousid) ) ) );
74225   END IF;
74226
74227   RETURN 1;
74228
74229 END;
74230 $_$;
74231
74232
74233 ALTER FUNCTION public.purgepostedcounttags(date, integer) OWNER TO admin;
74234
74235 --
74236 -- TOC entry 2064 (class 1255 OID 146566900)
74237 -- Dependencies: 4536 8
74238 -- Name: purgeshipments(date); Type: FUNCTION; Schema: public; Owner: admin
74239 --
74240
74241 CREATE FUNCTION purgeshipments(date) RETURNS integer
74242     LANGUAGE plpgsql
74243     AS $_$
74244 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74245 -- See www.xtuple.com/CPAL for the full text of the software license.
74246 DECLARE
74247   pcutoff ALIAS FOR $1;
74248   _r RECORD;
74249
74250 BEGIN
74251
74252   -- Used for transfer orders shipments (which are never invoiced)
74253   FOR _r IN SELECT shiphead_id
74254               FROM shiphead
74255              WHERE ( (shiphead_order_type='TO')
74256                AND   (shiphead_shipped)
74257                AND   (shiphead_shipdate <= pcutoff) ) LOOP
74258     DELETE FROM shipitem WHERE (shipitem_shiphead_id=_r.shiphead_id);
74259     DELETE FROM shiphead WHERE (shiphead_id=_r.shiphead_id);
74260   END LOOP;
74261
74262   RETURN 0;
74263
74264 END;
74265 $_$;
74266
74267
74268 ALTER FUNCTION public.purgeshipments(date) OWNER TO admin;
74269
74270 --
74271 -- TOC entry 2065 (class 1255 OID 146566901)
74272 -- Dependencies: 4536 8
74273 -- Name: qtyallocated(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
74274 --
74275
74276 CREATE FUNCTION qtyallocated(integer, integer) RETURNS numeric
74277     LANGUAGE plpgsql
74278     AS $_$
74279 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74280 -- See www.xtuple.com/CPAL for the full text of the software license.
74281 DECLARE
74282   pItemsiteid ALIAS FOR $1;
74283   pLookAheaddays ALIAS FOR $2;
74284
74285 BEGIN
74286
74287   RETURN qtyAllocated(pItemsiteid, startOfTime(), (CURRENT_DATE + pLookAheadDays));
74288
74289 END;
74290 $_$;
74291
74292
74293 ALTER FUNCTION public.qtyallocated(integer, integer) OWNER TO admin;
74294
74295 --
74296 -- TOC entry 2066 (class 1255 OID 146566902)
74297 -- Dependencies: 4536 8
74298 -- Name: qtyallocated(integer, date); Type: FUNCTION; Schema: public; Owner: admin
74299 --
74300
74301 CREATE FUNCTION qtyallocated(integer, date) RETURNS numeric
74302     LANGUAGE plpgsql
74303     AS $_$
74304 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74305 -- See www.xtuple.com/CPAL for the full text of the software license.
74306 DECLARE
74307   pItemsiteid ALIAS FOR $1;
74308   pDate ALIAS FOR $2;
74309
74310 BEGIN
74311
74312   RETURN qtyAllocated(pItemsiteid, startOfTime(), pDate);
74313
74314 END;
74315 $_$;
74316
74317
74318 ALTER FUNCTION public.qtyallocated(integer, date) OWNER TO admin;
74319
74320 --
74321 -- TOC entry 2067 (class 1255 OID 146566903)
74322 -- Dependencies: 4536 8
74323 -- Name: qtyallocated(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
74324 --
74325
74326 CREATE FUNCTION qtyallocated(integer, date, date) RETURNS numeric
74327     LANGUAGE plpgsql STABLE
74328     AS $_$
74329 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74330 -- See www.xtuple.com/CPAL for the full text of the software license.
74331 DECLARE
74332   pItemsiteid ALIAS FOR $1;
74333   pStartDate ALIAS FOR $2;
74334   pEndDate ALIAS FOR $3;
74335
74336 BEGIN
74337  
74338   IF ( fetchMetricBool('MultiWhs')) THEN
74339     IF ( SELECT item_sold
74340          FROM itemsite, item
74341          WHERE ((itemsite_item_id=item_id)
74342          AND (itemsite_id=pItemsiteid)) ) THEN
74343       RETURN (allocatedForTo(pItemsiteid, pStartDate, pEndDate) +
74344               allocatedForWo(pItemsiteid, pStartDate, pEndDate) +
74345               allocatedForSo(pItemsiteid, pStartDate, pEndDate));
74346     ELSE
74347       RETURN (allocatedForTo(pItemsiteid, pStartDate, pEndDate) +
74348               allocatedForWo(pItemsiteid, pStartDate, pEndDate));
74349     END IF;
74350   ELSE
74351     IF ( SELECT item_sold
74352          FROM itemsite, item
74353          WHERE ((itemsite_item_id=item_id)
74354          AND (itemsite_id=pItemsiteid)) ) THEN
74355       RETURN (allocatedForWo(pItemsiteid, pStartDate, pEndDate) +
74356               allocatedForSo(pItemsiteid, pStartDate, pEndDate));
74357     ELSE
74358       RETURN (allocatedForWo(pItemsiteid, pStartDate, pEndDate));
74359     END IF;
74360   END IF;
74361 END;
74362 $_$;
74363
74364
74365 ALTER FUNCTION public.qtyallocated(integer, date, date) OWNER TO admin;
74366
74367 --
74368 -- TOC entry 2068 (class 1255 OID 146566904)
74369 -- Dependencies: 4536 8
74370 -- Name: qtyatshipping(integer); Type: FUNCTION; Schema: public; Owner: admin
74371 --
74372
74373 CREATE FUNCTION qtyatshipping(integer) RETURNS numeric
74374     LANGUAGE plpgsql
74375     AS $_$
74376 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74377 -- See www.xtuple.com/CPAL for the full text of the software license.
74378 BEGIN
74379   RETURN qtyAtShipping('SO', $1);
74380 END;
74381 $_$;
74382
74383
74384 ALTER FUNCTION public.qtyatshipping(integer) OWNER TO admin;
74385
74386 --
74387 -- TOC entry 2069 (class 1255 OID 146566905)
74388 -- Dependencies: 4536 8
74389 -- Name: qtyatshipping(text, integer); Type: FUNCTION; Schema: public; Owner: admin
74390 --
74391
74392 CREATE FUNCTION qtyatshipping(text, integer) RETURNS numeric
74393     LANGUAGE plpgsql
74394     AS $_$
74395 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74396 -- See www.xtuple.com/CPAL for the full text of the software license.
74397 BEGIN
74398   RETURN qtyAtShipping($1, $2, 'U');
74399 END;
74400 $_$;
74401
74402
74403 ALTER FUNCTION public.qtyatshipping(text, integer) OWNER TO admin;
74404
74405 --
74406 -- TOC entry 2070 (class 1255 OID 146566906)
74407 -- Dependencies: 4536 8
74408 -- Name: qtyatshipping(text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
74409 --
74410
74411 CREATE FUNCTION qtyatshipping(text, integer, text) RETURNS numeric
74412     LANGUAGE plpgsql STABLE
74413     AS $_$
74414 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74415 -- See www.xtuple.com/CPAL for the full text of the software license.
74416 DECLARE
74417   pordertype    ALIAS FOR $1;
74418   plineitemid   ALIAS FOR $2;
74419   pstatus       ALIAS FOR $3;
74420   _qty NUMERIC  := 0.0;
74421
74422 BEGIN
74423
74424 -- pstatus U=unshipped
74425 --         S=shipped
74426 --         B=both unshipped and shipped
74427
74428   IF (pordertype NOT IN ('SO', 'TO')) THEN
74429     RAISE EXCEPTION '% is not a valid order type', pordertype;
74430   END IF;
74431
74432   IF (pstatus NOT IN ('U', 'S', 'B')) THEN
74433     RAISE EXCEPTION '% is not a valid status', pstatus;
74434   END IF;
74435
74436   SELECT COALESCE(SUM(shipitem_qty), 0.0) INTO _qty
74437   FROM shipitem, shiphead
74438   WHERE ((shipitem_shiphead_id=shiphead_id)
74439     AND  (shiphead_order_type=pordertype)
74440     AND  (shipitem_orderitem_id=plineitemid)
74441     AND  (((shiphead_shipped) AND (pstatus IN ('S', 'B'))) OR ((NOT shiphead_shipped) AND (pstatus IN ('U', 'B'))))  );
74442
74443   RETURN _qty;
74444
74445 END;
74446 $_$;
74447
74448
74449 ALTER FUNCTION public.qtyatshipping(text, integer, text) OWNER TO admin;
74450
74451 --
74452 -- TOC entry 2071 (class 1255 OID 146566907)
74453 -- Dependencies: 4536 8
74454 -- Name: qtyavailable(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
74455 --
74456
74457 CREATE FUNCTION qtyavailable(integer, integer) RETURNS numeric
74458     LANGUAGE plpgsql STABLE
74459     AS $_$
74460 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74461 -- See www.xtuple.com/CPAL for the full text of the software license.
74462 DECLARE
74463   pItemsiteid ALIAS FOR $1;
74464   pLookAheadDays ALIAS FOR $2;
74465
74466 BEGIN
74467
74468   RETURN ( ( SELECT itemsite_qtyonhand
74469              FROM itemsite
74470              WHERE (itemsite_id=pItemsiteid) ) +
74471            (SELECT qtyOrdered(pItemsiteid, pLookAheadDays)) -
74472            (SELECT qtyAllocated(pitemsiteid, pLookAheadDays)) );
74473 END;
74474 $_$;
74475
74476
74477 ALTER FUNCTION public.qtyavailable(integer, integer) OWNER TO admin;
74478
74479 --
74480 -- TOC entry 2072 (class 1255 OID 146566908)
74481 -- Dependencies: 4536 8
74482 -- Name: qtyavailable(integer, date); Type: FUNCTION; Schema: public; Owner: admin
74483 --
74484
74485 CREATE FUNCTION qtyavailable(integer, date) RETURNS numeric
74486     LANGUAGE plpgsql STABLE
74487     AS $_$
74488 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74489 -- See www.xtuple.com/CPAL for the full text of the software license.
74490 DECLARE
74491   pItemsiteid ALIAS FOR $1;
74492   pDate ALIAS FOR $2;
74493
74494 BEGIN
74495
74496   RETURN ( ( SELECT itemsite_qtyonhand
74497              FROM itemsite
74498              WHERE (itemsite_id=pItemsiteid) ) +
74499            (SELECT qtyOrdered(pItemsiteid, (pDate - CURRENT_DATE))) -
74500            (SELECT qtyAllocated(pItemsiteid, (pDate - CURRENT_DATE))) );
74501 END;
74502 $_$;
74503
74504
74505 ALTER FUNCTION public.qtyavailable(integer, date) OWNER TO admin;
74506
74507 --
74508 -- TOC entry 2073 (class 1255 OID 146566909)
74509 -- Dependencies: 4536 8
74510 -- Name: qtyinshipment(text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
74511 --
74512
74513 CREATE FUNCTION qtyinshipment(text, integer, integer) RETURNS numeric
74514     LANGUAGE plpgsql
74515     AS $_$
74516 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74517 -- See www.xtuple.com/CPAL for the full text of the software license.
74518 DECLARE
74519   pordertype    ALIAS FOR $1;
74520   plineitemid   ALIAS FOR $2;
74521   pshipheadid   ALIAS FOR $3;
74522   _qty NUMERIC;
74523
74524 BEGIN
74525
74526   IF (pordertype NOT IN ('SO', 'TO')) THEN
74527     RAISE EXCEPTION '% is not a valid order type', pordertype;
74528   END IF;
74529
74530   IF (pshipheadid IS NULL) THEN
74531     RAISE EXCEPTION 'Cannot calculate quantity in a shipment with a NULL shipment';
74532   END IF;
74533
74534   SELECT SUM(COALESCE(shipitem_qty, 0.0)) INTO _qty
74535   FROM shipitem, shiphead
74536   WHERE ((shipitem_shiphead_id=shiphead_id)
74537       AND (shiphead_order_type=pordertype)
74538       AND (shipitem_orderitem_id=plineitemid)
74539       AND (shiphead_id=pshipheadid));
74540
74541   IF (NOT FOUND) THEN
74542     RAISE NOTICE 'Quantity of % item % is 0 because shipment % does not exist.',
74543                   pordertype, plineitemid, pshipheadid;
74544   END IF;
74545
74546   RETURN _qty;
74547
74548 END;
74549 $_$;
74550
74551
74552 ALTER FUNCTION public.qtyinshipment(text, integer, integer) OWNER TO admin;
74553
74554 --
74555 -- TOC entry 2076 (class 1255 OID 146566910)
74556 -- Dependencies: 4536 8
74557 -- Name: qtylocation(integer, integer, date, date, integer, text, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
74558 --
74559
74560 CREATE FUNCTION qtylocation(integer, integer, date, date, integer, text, integer, integer) RETURNS numeric
74561     LANGUAGE plpgsql
74562     AS $_$
74563 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74564 -- See www.xtuple.com/CPAL for the full text of the software license.
74565 DECLARE
74566   pLocationId  ALIAS FOR $1;
74567   pLsId        ALIAS FOR $2;
74568   pExpiration  ALIAS FOR $3;
74569   pWarranty    ALIAS FOR $4;
74570   pItemsiteId  ALIAS FOR $5;
74571   pOrderType   ALIAS FOR $6;
74572   pOrderId     ALIAS FOR $7;
74573   pItemlocdistId ALIAS FOR $8;
74574   _qty         NUMERIC = 0.0;
74575   _qtyDist     NUMERIC = 0.0;
74576   _qtyReserved NUMERIC = 0.0;
74577
74578 BEGIN
74579 -- Summarize itemloc qty for this location/itemsite
74580   SELECT COALESCE(SUM(itemloc_qty), 0) INTO _qty
74581     FROM itemloc
74582    WHERE ( (itemloc_itemsite_id=pItemsiteId)
74583      AND (itemloc_location_id=pLocationId)
74584      AND (COALESCE(itemloc_ls_id, -1)=COALESCE(pLsId, itemloc_ls_id, -1))
74585      AND (COALESCE(itemloc_expiration, endoftime())=COALESCE(pExpiration, itemloc_expiration, endoftime()))
74586      AND (COALESCE(itemloc_warrpurc, endoftime())=COALESCE(pWarranty, itemloc_warrpurc, endoftime())) );
74587
74588 -- Summarize qty distributed but not yet committed by previous distributions
74589   SELECT COALESCE(SUM(loc.itemlocdist_qty), 0) INTO _qtyDist
74590     FROM itemlocdist loc
74591       JOIN itemlocdist ls ON ((ls.itemlocdist_source_type='O')
74592                           AND (ls.itemlocdist_id=loc.itemlocdist_itemlocdist_id))
74593    WHERE ( (ls.itemlocdist_itemsite_id=pItemsiteId)
74594      AND (loc.itemlocdist_source_type='L')
74595      AND (loc.itemlocdist_source_id=pLocationId)
74596      AND (COALESCE(ls.itemlocdist_ls_id, -1)=COALESCE(pLsId, ls.itemlocdist_ls_id, -1))
74597      AND (COALESCE(ls.itemlocdist_expiration, endoftime())=COALESCE(pExpiration, ls.itemlocdist_expiration, endoftime()))
74598      AND (COALESCE(ls.itemlocdist_warranty, endoftime())=COALESCE(pWarranty, ls.itemlocdist_warranty, endoftime()))
74599      AND (ls.itemlocdist_id != pItemlocdistId ) );
74600
74601 -- Summarize reserved qty for this location/itemsite
74602 -- that is reserved for a different order
74603   IF (fetchMetricBool('EnableSOReservationsByLocation')) THEN
74604     SELECT COALESCE(SUM(reserve_qty), 0) INTO _qtyReserved
74605       FROM itemloc JOIN reserve ON ( (reserve_supply_id=itemloc_id AND reserve_supply_type='I')
74606                                     AND  ((reserve_demand_type <> COALESCE(pOrderType, '')) OR
74607                                           (reserve_demand_id <> COALESCE(pOrderId, -1))) )
74608      WHERE ( (itemloc_itemsite_id=pItemsiteId)
74609        AND (itemloc_location_id=pLocationId)
74610        AND (COALESCE(itemloc_ls_id, -1)=COALESCE(pLsId, itemloc_ls_id, -1))
74611        AND (COALESCE(itemloc_expiration, endoftime())=COALESCE(pExpiration, itemloc_expiration, endoftime()))
74612        AND (COALESCE(itemloc_warrpurc, endoftime())=COALESCE(pWarranty, itemloc_warrpurc, endoftime())) );
74613   END IF;
74614
74615   RETURN (_qty + _qtyDist - _qtyReserved);
74616
74617 END;
74618 $_$;
74619
74620
74621 ALTER FUNCTION public.qtylocation(integer, integer, date, date, integer, text, integer, integer) OWNER TO admin;
74622
74623 --
74624 -- TOC entry 2077 (class 1255 OID 146566911)
74625 -- Dependencies: 4536 8
74626 -- Name: qtyordered(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
74627 --
74628
74629 CREATE FUNCTION qtyordered(integer, integer) RETURNS numeric
74630     LANGUAGE plpgsql
74631     AS $_$
74632 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74633 -- See www.xtuple.com/CPAL for the full text of the software license.
74634 DECLARE
74635   pItemsiteid ALIAS FOR $1;
74636   pLookahead ALIAS FOR $2;
74637   _itemType TEXT;
74638   _result NUMERIC;
74639
74640 BEGIN
74641
74642   RETURN qtyOrdered(pItemsiteid, startOfTime(), (CURRENT_DATE + pLookahead));
74643
74644 END;
74645 $_$;
74646
74647
74648 ALTER FUNCTION public.qtyordered(integer, integer) OWNER TO admin;
74649
74650 --
74651 -- TOC entry 2078 (class 1255 OID 146566912)
74652 -- Dependencies: 4536 8
74653 -- Name: qtyordered(integer, date); Type: FUNCTION; Schema: public; Owner: admin
74654 --
74655
74656 CREATE FUNCTION qtyordered(integer, date) RETURNS numeric
74657     LANGUAGE plpgsql
74658     AS $_$
74659 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74660 -- See www.xtuple.com/CPAL for the full text of the software license.
74661 DECLARE
74662   pItemsiteid ALIAS FOR $1;
74663   pDate ALIAS FOR $2;
74664
74665 BEGIN
74666
74667   RETURN qtyOrdered(pItemsiteid, startOfTime(), pDate);
74668
74669 END;
74670 $_$;
74671
74672
74673 ALTER FUNCTION public.qtyordered(integer, date) OWNER TO admin;
74674
74675 --
74676 -- TOC entry 2079 (class 1255 OID 146566913)
74677 -- Dependencies: 4536 8
74678 -- Name: qtyordered(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
74679 --
74680
74681 CREATE FUNCTION qtyordered(integer, date, date) RETURNS numeric
74682     LANGUAGE plpgsql
74683     AS $_$
74684 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74685 -- See www.xtuple.com/CPAL for the full text of the software license.
74686 DECLARE
74687   pItemsiteid ALIAS FOR $1;
74688   pStartDate ALIAS FOR $2;
74689   pEndDate ALIAS FOR $3;
74690   _itemType TEXT;
74691
74692 BEGIN
74693
74694   SELECT item_type INTO _itemType
74695   FROM item, itemsite
74696   WHERE ( (itemsite_item_id=item_id)
74697    AND (itemsite_id=pItemsiteid) );
74698
74699   IF ( SELECT metric_value
74700         FROM metric
74701         WHERE ((metric_name = 'MultiWhs')
74702         AND (metric_value = 't'))) THEN
74703     RETURN orderedByPo(pItemsiteid, pStartDate, pEndDate) +
74704            orderedByWo(pItemsiteid, pStartDate, pEndDate) +
74705            orderedByTo(pItemsiteid, pStartDate, pEndDate);
74706   ELSE
74707     RETURN orderedByPo(pItemsiteid, pStartDate, pEndDate) +
74708            orderedByWo(pItemsiteid, pStartDate, pEndDate);
74709
74710   END IF;
74711
74712 END;
74713 $_$;
74714
74715
74716 ALTER FUNCTION public.qtyordered(integer, date, date) OWNER TO admin;
74717
74718 --
74719 -- TOC entry 2080 (class 1255 OID 146566914)
74720 -- Dependencies: 4536 8
74721 -- Name: qtypr(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
74722 --
74723
74724 CREATE FUNCTION qtypr(integer, integer) RETURNS numeric
74725     LANGUAGE plpgsql
74726     AS $_$
74727 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74728 -- See www.xtuple.com/CPAL for the full text of the software license.
74729 DECLARE
74730   pItemsiteid ALIAS FOR $1;
74731   pLookahead ALIAS FOR $2; 
74732
74733 BEGIN
74734   RETURN qtypr(pItemsiteid, startOfTime(), (CURRENT_DATE + pLookahead));
74735 END;
74736 $_$;
74737
74738
74739 ALTER FUNCTION public.qtypr(integer, integer) OWNER TO admin;
74740
74741 --
74742 -- TOC entry 2081 (class 1255 OID 146566915)
74743 -- Dependencies: 4536 8
74744 -- Name: qtypr(integer, date); Type: FUNCTION; Schema: public; Owner: admin
74745 --
74746
74747 CREATE FUNCTION qtypr(integer, date) RETURNS numeric
74748     LANGUAGE plpgsql
74749     AS $_$
74750 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74751 -- See www.xtuple.com/CPAL for the full text of the software license.
74752 DECLARE
74753   pItemsiteid ALIAS FOR $1;
74754   pDate ALIAS FOR $2;
74755
74756 BEGIN
74757   RETURN qtypr(pItemsiteid, startOfTime(), pDate);
74758 END;
74759 $_$;
74760
74761
74762 ALTER FUNCTION public.qtypr(integer, date) OWNER TO admin;
74763
74764 --
74765 -- TOC entry 2082 (class 1255 OID 146566916)
74766 -- Dependencies: 4536 8
74767 -- Name: qtypr(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
74768 --
74769
74770 CREATE FUNCTION qtypr(integer, date, date) RETURNS numeric
74771     LANGUAGE plpgsql
74772     AS $_$
74773 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74774 -- See www.xtuple.com/CPAL for the full text of the software license.
74775 DECLARE
74776   pItemsiteid ALIAS FOR $1;
74777   pStartDate ALIAS FOR $2;
74778   pEndDate ALIAS FOR $3;
74779   _prtotal NUMERIC;
74780
74781 BEGIN
74782
74783 SELECT SUM(pr_qtyreq) INTO _prtotal
74784   FROM pr
74785   WHERE ((pr_status = 'O')
74786     AND (pr_itemsite_id=pItemsiteid)
74787     AND (pr_duedate BETWEEN pStartDate AND pEndDate));
74788
74789  IF (_prtotal IS NULL) THEN
74790      RETURN 0.0;
74791  END IF;
74792
74793  RETURN _prtotal;
74794
74795 END;
74796 $_$;
74797
74798
74799 ALTER FUNCTION public.qtypr(integer, date, date) OWNER TO admin;
74800
74801 --
74802 -- TOC entry 2083 (class 1255 OID 146566917)
74803 -- Dependencies: 4536 8
74804 -- Name: qtyreserved(integer); Type: FUNCTION; Schema: public; Owner: admin
74805 --
74806
74807 CREATE FUNCTION qtyreserved(integer) RETURNS numeric
74808     LANGUAGE plpgsql
74809     AS $_$
74810 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74811 -- See www.xtuple.com/EULA for the full text of the software license.
74812 DECLARE
74813   pItemsiteid ALIAS FOR $1;
74814   _qty NUMERIC;
74815
74816 BEGIN
74817
74818   SELECT COALESCE(SUM(coitem_qtyreserved),0) INTO _qty
74819     FROM coitem
74820    WHERE(coitem_itemsite_id=pItemsiteid);
74821
74822   RETURN _qty;
74823 END;
74824 $_$;
74825
74826
74827 ALTER FUNCTION public.qtyreserved(integer) OWNER TO admin;
74828
74829 --
74830 -- TOC entry 2084 (class 1255 OID 146566918)
74831 -- Dependencies: 4536 8
74832 -- Name: qtytoreceive(text, integer); Type: FUNCTION; Schema: public; Owner: admin
74833 --
74834
74835 CREATE FUNCTION qtytoreceive(text, integer) RETURNS numeric
74836     LANGUAGE plpgsql
74837     AS $_$
74838 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74839 -- See www.xtuple.com/CPAL for the full text of the software license.
74840 DECLARE
74841   pordertype    ALIAS FOR $1;
74842   porderitemid  ALIAS FOR $2;
74843   _qty          NUMERIC;
74844
74845 BEGIN
74846   IF (pordertype = 'TO' AND NOT fetchMetricBool('MultiWhs')) THEN
74847     RETURN 0;
74848   END IF;
74849
74850   IF (pordertype = 'RA' AND NOT fetchMetricBool('EnableReturnAuth')) THEN
74851     RETURN 0;
74852   END IF;
74853
74854   SELECT SUM(recv_qty) INTO _qty
74855   FROM recv
74856   WHERE ((recv_orderitem_id=porderitemid)
74857     AND  (NOT recv_posted)
74858     AND  (recv_order_type=pordertype));
74859
74860   RETURN COALESCE(_qty, 0.0);
74861
74862 END;
74863 $_$;
74864
74865
74866 ALTER FUNCTION public.qtytoreceive(text, integer) OWNER TO admin;
74867
74868 --
74869 -- TOC entry 2085 (class 1255 OID 146566919)
74870 -- Dependencies: 4536 8
74871 -- Name: recallshipment(integer); Type: FUNCTION; Schema: public; Owner: admin
74872 --
74873
74874 CREATE FUNCTION recallshipment(integer) RETURNS integer
74875     LANGUAGE plpgsql
74876     AS $_$
74877 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74878 -- See www.xtuple.com/CPAL for the full text of the software license.
74879 BEGIN
74880   RETURN recallShipment($1, CURRENT_TIMESTAMP);
74881 END;
74882 $_$;
74883
74884
74885 ALTER FUNCTION public.recallshipment(integer) OWNER TO admin;
74886
74887 --
74888 -- TOC entry 2086 (class 1255 OID 146566920)
74889 -- Dependencies: 4536 8
74890 -- Name: recallshipment(integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
74891 --
74892
74893 CREATE FUNCTION recallshipment(integer, timestamp with time zone) RETURNS integer
74894     LANGUAGE plpgsql
74895     AS $_$
74896 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
74897 -- See www.xtuple.com/CPAL for the full text of the software license.
74898 DECLARE
74899   pshipheadid           ALIAS FOR $1;
74900   _timestamp            TIMESTAMP WITH TIME ZONE := $2;
74901   _allInvoiced          BOOLEAN;
74902   _invoicePosted        BOOLEAN;
74903   _in                   RECORD;
74904   _co                   RECORD;
74905   _cobill               RECORD;
74906   _h                    RECORD;
74907   _result               INTEGER;
74908   _invhistid            INTEGER;
74909   _itemlocSeries        INTEGER;
74910   _qty                  NUMERIC;
74911   _qtyToBill            NUMERIC;
74912   _shiphead             RECORD;
74913   _to                   RECORD;
74914   _ti                   RECORD;
74915   _value                NUMERIC;
74916
74917 BEGIN
74918
74919   IF (_timestamp IS NULL) THEN
74920     _timestamp := CURRENT_TIMESTAMP;
74921   END IF;
74922
74923   SELECT * INTO _shiphead
74924   FROM shiphead
74925   WHERE (shiphead_id=pshipheadid);
74926   IF (NOT FOUND OR NOT _shiphead.shiphead_shipped) THEN
74927     RETURN -1;
74928   END IF;
74929
74930   IF (_shiphead.shiphead_order_type = 'SO') THEN
74931     SELECT cohead_number AS head_number, cohead_cust_id AS cust_id, cohead_prj_id AS prj_id,
74932            cohead_saletype_id AS saletype_id, cohead_shipzone_id AS shipzone_id INTO _h
74933       FROM cohead
74934      WHERE (cohead_id=_shiphead.shiphead_order_id);
74935     IF (NOT FOUND) THEN
74936       RETURN -1;
74937     END IF;
74938
74939     SELECT COALESCE(BOOL_AND(shipitem_invoiced), FALSE) INTO _allInvoiced
74940      FROM cobill, shipitem
74941     WHERE ((cobill_coitem_id=shipitem_orderitem_id)
74942       AND  (shipitem_shiphead_id=pshipheadid));
74943
74944     IF (_allInvoiced AND NOT checkPrivilege('RecallInvoicedShipment')) THEN
74945       RETURN -2;
74946     END IF;
74947
74948     -- Check for any associated posted Invoices
74949     SELECT COALESCE(BOOL_AND(invchead_posted), FALSE) INTO _invoicePosted
74950     FROM shipitem JOIN invcitem ON (invcitem_id=shipitem_invcitem_id)
74951                   JOIN invchead ON (invchead_id=invcitem_invchead_id)
74952     WHERE (shipitem_shiphead_id=pshipheadid);
74953
74954     IF (_invoicePosted) THEN
74955       RETURN -4;
74956     END IF;
74957
74958     -- Delete any associated unposted Invoices
74959     FOR _in IN SELECT DISTINCT invchead_id
74960                  FROM shipitem JOIN invcitem ON (invcitem_id=shipitem_invcitem_id)
74961                                JOIN invchead ON ( (invchead_id=invcitem_invchead_id) AND
74962                                                   (NOT invchead_posted) )
74963                 WHERE (shipitem_shiphead_id=pshipheadid) LOOP
74964       SELECT deleteInvoice(_in.invchead_id) INTO _result;
74965       IF (_result < 0) THEN
74966         RETURN _result;
74967       END IF;
74968     END LOOP;
74969
74970     FOR _co IN SELECT coitem_id, coitem_itemsite_id, coitem_qty_invuomratio, coitem_warranty, coitem_cos_accnt_id,
74971                    itemsite_controlmethod
74972                  FROM coitem
74973                   JOIN itemsite ON (coitem_itemsite_id=itemsite_id)
74974                 WHERE(coitem_id IN (SELECT shipitem_orderitem_id
74975                                       FROM shipitem, shiphead
74976                                      WHERE((shipitem_shiphead_id=shiphead_id)
74977                                        AND (shiphead_shipped)
74978                                        AND (shiphead_id=pshipheadid)))) FOR UPDATE LOOP
74979
74980       SELECT SUM(shipitem_qty),SUM(COALESCE(shipitem_value, 0)) INTO _qty, _value
74981       FROM shipitem
74982       WHERE ( (shipitem_orderitem_id=_co.coitem_id)
74983        AND (shipitem_shiphead_id=pshipheadid) );
74984
74985       UPDATE coitem
74986       SET coitem_qtyshipped = (coitem_qtyshipped - _qty)
74987       WHERE (coitem_id=_co.coitem_id);
74988
74989       _qtyToBill := _qty;
74990       FOR _cobill IN SELECT cobill_id, cobill_qty
74991                          FROM cobill, shipitem
74992                         WHERE ((cobill_coitem_id=shipitem_orderitem_id)
74993                           AND  (shipitem_shiphead_id=pshipheadid)
74994                           AND  (cobill_coitem_id=_co.coitem_id)) FOR UPDATE LOOP
74995
74996         IF (noNeg(_cobill.cobill_qty - _qtyToBill) = 0) THEN
74997           DELETE FROM cobill WHERE (cobill_id=_cobill.cobill_id);
74998         ELSE
74999           UPDATE cobill
75000           SET cobill_qty = noNeg(cobill_qty - _qtyToBill)
75001           WHERE (cobill_id=_cobill.cobill_id);
75002         END IF;
75003
75004         _qtyToBill = _qtyToBill - _cobill.cobill_qty;
75005         EXIT WHEN (_qtyToBill <= 0.0);
75006       END LOOP;
75007
75008   --  Check to see if all of the cobills have been deleted for this cobmisc
75009       IF (EXISTS(SELECT cobmisc_id
75010                  FROM cobmisc JOIN cobill ON (cobill_cobmisc_id=cobmisc_id)
75011                  WHERE (cobmisc_cohead_id=_shiphead.shiphead_order_id AND NOT cobmisc_posted))) THEN
75012   --  Lines exist, update the freight
75013         UPDATE cobmisc SET cobmisc_freight = (cobmisc_freight - _shiphead.shiphead_freight)
75014         WHERE (cobmisc_cohead_id=_shiphead.shiphead_order_id AND NOT cobmisc_posted);
75015       ELSE
75016   --  No lines exist, delete the cobmisc
75017         DELETE FROM cobmisc
75018         WHERE (cobmisc_cohead_id=_shiphead.shiphead_order_id AND NOT cobmisc_posted);
75019       END IF;
75020
75021   --  Distribute to G/L, debit Shipping Asset, credit COS
75022       IF (_co.itemsite_controlmethod != 'N') THEN
75023         PERFORM insertGLTransaction( 'S/R', _shiphead.shiphead_order_type,
75024                                    _h.head_number::TEXT, 'Recall Shipment',
75025                                    CASE WHEN(COALESCE(_co.coitem_cos_accnt_id, -1) != -1)
75026                                           THEN getPrjAccntId(_h.prj_id, _co.coitem_cos_accnt_id)
75027                                         WHEN(_co.coitem_warranty = TRUE)
75028                                           THEN getPrjAccntId(_h.prj_id, resolveCOWAccount(itemsite_id, _h.cust_id, _h.saletype_id, _h.shipzone_id))
75029                                         ELSE getPrjAccntId(_h.prj_id, resolveCOSAccount(itemsite_id, _h.cust_id, _h.saletype_id, _h.shipzone_id))
75030                                    END,
75031                                    getPrjAccntId(_h.prj_id,costcat_shipasset_accnt_id), -1,
75032                                    _value,
75033                                    _timestamp::DATE )
75034         FROM itemsite, costcat
75035         WHERE ( (itemsite_costcat_id=costcat_id)
75036          AND (itemsite_id=_co.coitem_itemsite_id) );
75037        END IF;
75038
75039     END LOOP;
75040
75041 -- Kit billing selection
75042 -- Set kit billing qty to zero since kits are shipped complete
75043     FOR _cobill IN SELECT cobill_id, cobill_qty
75044                    FROM shipitem JOIN coitem sub ON (sub.coitem_id=shipitem_orderitem_id)
75045                                  JOIN coitem kit ON (kit.coitem_id <> sub.coitem_id AND
75046                                                      kit.coitem_cohead_id = sub.coitem_cohead_id AND
75047                                                      kit.coitem_linenumber = sub.coitem_linenumber AND
75048                                                      kit.coitem_subnumber = 0)
75049                                  JOIN cobill ON (cobill_coitem_id=kit.coitem_id)
75050                    WHERE (shipitem_shiphead_id=pshipheadid)
75051                      AND (sub.coitem_subnumber > 0)
75052                    GROUP BY cobill_id, cobill_qty
75053     LOOP
75054       UPDATE cobill SET cobill_qty = 0.0
75055       WHERE (cobill_id=_cobill.cobill_id);
75056     END LOOP;
75057
75058   ELSEIF (_shiphead.shiphead_order_type = 'TO') THEN
75059     SELECT * INTO _to
75060       FROM tohead
75061      WHERE (tohead_id=_shiphead.shiphead_order_id);
75062     IF (NOT FOUND) THEN
75063       RETURN -1;
75064     END IF;
75065     IF (_to.tohead_status = 'C') THEN
75066       RETURN -6;
75067     END IF;
75068
75069     FOR _ti IN SELECT toitem_id,
75070                       sis.itemsite_id AS src_itemsite_id,
75071                       tis.itemsite_id AS trns_itemsite_id,
75072                       scc.costcat_shipasset_accnt_id AS src_shipasset_accnt_id,
75073                       tcc.costcat_asset_accnt_id AS trns_asset_accnt_id,
75074                       itemcost(tis.itemsite_id) AS trns_cost,
75075                       SUM(shipitem_qty) AS recall_qty
75076                FROM shipitem JOIN toitem ON (toitem_id=shipitem_orderitem_id)
75077                              JOIN itemsite sis ON (sis.itemsite_item_id=toitem_item_id AND sis.itemsite_warehous_id=_to.tohead_src_warehous_id)
75078                              JOIN itemsite tis ON (tis.itemsite_item_id=toitem_item_id AND tis.itemsite_warehous_id=_to.tohead_trns_warehous_id)
75079                              JOIN costcat scc ON (scc.costcat_id=sis.itemsite_costcat_id)
75080                              JOIN costcat tcc ON (tcc.costcat_id=tis.itemsite_costcat_id)
75081                WHERE (shipitem_shiphead_id=pshipheadid)
75082                GROUP BY toitem_id, sis.itemsite_id, tis.itemsite_id,
75083                         scc.costcat_shipasset_accnt_id, tcc.costcat_asset_accnt_id
75084     LOOP
75085
75086       _itemlocSeries := NEXTVAL('itemloc_series_seq');
75087       
75088       SELECT postInvTrans(_ti.src_itemsite_id, 'TS', (_ti.recall_qty * -1.0), 'I/M',
75089                           _shiphead.shiphead_order_type, formatToNumber(_ti.toitem_id),
75090                           _to.tohead_number,
75091                           'Recall TO Shipment To Src Warehouse',
75092                           _ti.trns_asset_accnt_id,
75093                           _ti.src_shipasset_accnt_id,
75094                           _itemlocSeries, _timestamp,
75095                           (_ti.trns_cost * _ti.recall_qty * -1.0)) INTO _invhistid;
75096
75097       IF (_invhistid < 0) THEN
75098         RETURN _invhistid;
75099       END IF;
75100
75101       -- post the inventory history if lot/serial or location control
75102       PERFORM postItemlocseries(_itemlocSeries);
75103
75104       -- record inventory history and qoh changes at transit warehouse but
75105       -- there is only one g/l account to touch
75106       SELECT postInvTrans(_ti.trns_itemsite_id, 'TR', (_ti.recall_qty * -1.0), 'I/M',
75107                           _shiphead.shiphead_order_type, formatToNumber(_ti.toitem_id),
75108                           _to.tohead_number,
75109                           'Recall TO Shipment From Transit Warehouse',
75110                           _ti.trns_asset_accnt_id,
75111                           _ti.trns_asset_accnt_id,
75112                           _itemlocSeries, _timestamp,
75113                           (_ti.trns_cost * _ti.recall_qty * -1.0)) INTO _invhistid;
75114
75115       IF (_invhistid < 0) THEN
75116         RETURN _invhistid;
75117       END IF;
75118
75119       -- post the inventory history if lot/serial or location control
75120       PERFORM postItemlocseries(_itemlocSeries);
75121
75122       UPDATE toitem
75123       SET toitem_qty_shipped = (toitem_qty_shipped - _ti.recall_qty)
75124       WHERE (toitem_id=_ti.toitem_id);
75125
75126       UPDATE shipitem SET shipitem_shipdate=NULL,
75127                           shipitem_shipped=FALSE,
75128                           shipitem_value=(shipitem_qty * _ti.trns_cost)
75129       WHERE ((shipitem_orderitem_id=_ti.toitem_id)
75130         AND  (shipitem_shiphead_id=pshipheadid));
75131
75132       DELETE FROM recv
75133         WHERE ((recv_orderitem_id=_ti.toitem_id)
75134           AND  (recv_order_type='TO')
75135           AND  (NOT recv_posted));
75136
75137     END LOOP;
75138
75139   END IF;
75140
75141   UPDATE shiphead
75142   SET shiphead_shipped=FALSE
75143   WHERE (shiphead_id=pshipheadid);
75144
75145   RETURN _itemlocSeries;
75146
75147 END;
75148 $_$;
75149
75150
75151 ALTER FUNCTION public.recallshipment(integer, timestamp with time zone) OWNER TO admin;
75152
75153 --
75154 -- TOC entry 2087 (class 1255 OID 146566922)
75155 -- Dependencies: 4536 8
75156 -- Name: recallwo(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
75157 --
75158
75159 CREATE FUNCTION recallwo(integer, boolean) RETURNS integer
75160     LANGUAGE plpgsql
75161     AS $_$
75162 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75163 -- See www.xtuple.com/CPAL for the full text of the software license.
75164 DECLARE
75165   pWoid ALIAS FOR $1;
75166   recallChildren ALIAS FOR $2;
75167   returnCode INTEGER;
75168
75169 BEGIN
75170
75171   UPDATE wo
75172   SET wo_status='E'
75173   WHERE ((wo_status='R')
75174    AND (wo_id=pWoid));
75175
75176   IF (recallChildren) THEN
75177     returnCode := (SELECT MAX(recallWo(wo_id, TRUE))
75178                    FROM wo
75179                    WHERE ((wo_ordtype='W')
75180                     AND (wo_ordid=pWoid)));
75181   END IF;
75182
75183   RETURN 0;
75184 END;
75185 $_$;
75186
75187
75188 ALTER FUNCTION public.recallwo(integer, boolean) OWNER TO admin;
75189
75190 --
75191 -- TOC entry 2088 (class 1255 OID 146566923)
75192 -- Dependencies: 4536 8
75193 -- Name: receipts(text); Type: FUNCTION; Schema: public; Owner: admin
75194 --
75195
75196 CREATE FUNCTION receipts(text) RETURNS boolean
75197     LANGUAGE plpgsql
75198     AS $_$
75199 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75200 -- See www.xtuple.com/CPAL for the full text of the software license.
75201 DECLARE
75202   pTransType ALIAS FOR $1;
75203
75204 BEGIN
75205   IF (pTransType IN ('RM', 'RB', 'RT', 'RP', 'RR', 'RX', 'TR')) THEN
75206     RETURN TRUE;
75207   ELSE
75208     RETURN FALSE;
75209   END IF;
75210
75211 END;
75212 $_$;
75213
75214
75215 ALTER FUNCTION public.receipts(text) OWNER TO admin;
75216
75217 --
75218 -- TOC entry 2089 (class 1255 OID 146566924)
75219 -- Dependencies: 8
75220 -- Name: releaseapmemonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75221 --
75222
75223 CREATE FUNCTION releaseapmemonumber(integer) RETURNS boolean
75224     LANGUAGE sql
75225     AS $_$
75226 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75227 -- See www.xtuple.com/CPAL for the full text of the software license.
75228   SELECT releaseNumber('APMemoNumber', $1::INTEGER) > 0;
75229 $_$;
75230
75231
75232 ALTER FUNCTION public.releaseapmemonumber(integer) OWNER TO admin;
75233
75234 --
75235 -- TOC entry 1980 (class 1255 OID 146566925)
75236 -- Dependencies: 8
75237 -- Name: releasearmemonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75238 --
75239
75240 CREATE FUNCTION releasearmemonumber(integer) RETURNS boolean
75241     LANGUAGE sql
75242     AS $_$
75243 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75244 -- See www.xtuple.com/CPAL for the full text of the software license.
75245   select releaseNumber('ARMemoNumber', $1::INTEGER) > 0;
75246 $_$;
75247
75248
75249 ALTER FUNCTION public.releasearmemonumber(integer) OWNER TO admin;
75250
75251 --
75252 -- TOC entry 2044 (class 1255 OID 146566926)
75253 -- Dependencies: 8
75254 -- Name: releasecashrcptnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75255 --
75256
75257 CREATE FUNCTION releasecashrcptnumber(integer) RETURNS boolean
75258     LANGUAGE sql
75259     AS $_$
75260 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75261 -- See www.xtuple.com/CPAL for the full text of the software license.
75262   SELECT releaseNumber('CashRcptNumber', $1) > 0;
75263 $_$;
75264
75265
75266 ALTER FUNCTION public.releasecashrcptnumber(integer) OWNER TO admin;
75267
75268 --
75269 -- TOC entry 2054 (class 1255 OID 146566927)
75270 -- Dependencies: 8
75271 -- Name: releasecmnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75272 --
75273
75274 CREATE FUNCTION releasecmnumber(integer) RETURNS boolean
75275     LANGUAGE sql
75276     AS $_$
75277 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75278 -- See www.xtuple.com/CPAL for the full text of the software license.
75279   SELECT releaseNumber('CmNumber', $1) > 0;
75280 $_$;
75281
75282
75283 ALTER FUNCTION public.releasecmnumber(integer) OWNER TO admin;
75284
75285 --
75286 -- TOC entry 2055 (class 1255 OID 146566928)
75287 -- Dependencies: 8
75288 -- Name: releasecmnumber(text); Type: FUNCTION; Schema: public; Owner: admin
75289 --
75290
75291 CREATE FUNCTION releasecmnumber(text) RETURNS boolean
75292     LANGUAGE sql
75293     AS $_$
75294 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75295 -- See www.xtuple.com/CPAL for the full text of the software license.
75296   SELECT releaseNumber('CmNumber', $1::INTEGER) > 0;
75297 $_$;
75298
75299
75300 ALTER FUNCTION public.releasecmnumber(text) OWNER TO admin;
75301
75302 --
75303 -- TOC entry 2063 (class 1255 OID 146566929)
75304 -- Dependencies: 8
75305 -- Name: releasecrmaccountnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75306 --
75307
75308 CREATE FUNCTION releasecrmaccountnumber(integer) RETURNS boolean
75309     LANGUAGE sql
75310     AS $_$
75311 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75312 -- See www.xtuple.com/CPAL for the full text of the software license.
75313   SELECT releaseNumber('CRMAccountNumber', $1::INTEGER) > 0;
75314 $_$;
75315
75316
75317 ALTER FUNCTION public.releasecrmaccountnumber(integer) OWNER TO admin;
75318
75319 --
75320 -- TOC entry 2074 (class 1255 OID 146566930)
75321 -- Dependencies: 8
75322 -- Name: releaseincidentnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75323 --
75324
75325 CREATE FUNCTION releaseincidentnumber(integer) RETURNS boolean
75326     LANGUAGE sql
75327     AS $_$
75328 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75329 -- See www.xtuple.com/CPAL for the full text of the software license.
75330   SELECT releaseNumber('IncidentNumber', $1) = 1;
75331 $_$;
75332
75333
75334 ALTER FUNCTION public.releaseincidentnumber(integer) OWNER TO admin;
75335
75336 --
75337 -- TOC entry 2075 (class 1255 OID 146566931)
75338 -- Dependencies: 8
75339 -- Name: releaseinvcnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75340 --
75341
75342 CREATE FUNCTION releaseinvcnumber(integer) RETURNS boolean
75343     LANGUAGE sql
75344     AS $_$
75345 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75346 -- See www.xtuple.com/CPAL for the full text of the software license.
75347   SELECT releaseNumber('InvcNumber', $1) > 0;
75348 $_$;
75349
75350
75351 ALTER FUNCTION public.releaseinvcnumber(integer) OWNER TO admin;
75352
75353 --
75354 -- TOC entry 905 (class 1255 OID 146566932)
75355 -- Dependencies: 8
75356 -- Name: releaseinvcnumber(text); Type: FUNCTION; Schema: public; Owner: admin
75357 --
75358
75359 CREATE FUNCTION releaseinvcnumber(text) RETURNS boolean
75360     LANGUAGE sql
75361     AS $_$
75362 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75363 -- See www.xtuple.com/CPAL for the full text of the software license.
75364   SELECT releaseNumber('InvcNumber', $1::INTEGER) > 0;
75365 $_$;
75366
75367
75368 ALTER FUNCTION public.releaseinvcnumber(text) OWNER TO admin;
75369
75370 --
75371 -- TOC entry 2090 (class 1255 OID 146566933)
75372 -- Dependencies: 4536 8
75373 -- Name: releasenumber(text, integer); Type: FUNCTION; Schema: public; Owner: admin
75374 --
75375
75376 CREATE FUNCTION releasenumber(text, integer) RETURNS integer
75377     LANGUAGE plpgsql
75378     AS $_$
75379 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75380 -- See www.xtuple.com/CPAL for the full text of the software license.
75381 DECLARE
75382   psequence     ALIAS FOR $1;
75383   pnumber       ALIAS FOR $2;
75384 BEGIN
75385   IF (fetchMetricBool('EnableGaplessNumbering')) THEN
75386     -- drop the number back into the pool if it was not committed
75387     PERFORM clearNumberIssue(psequence, pnumber);
75388   END IF;
75389   
75390   UPDATE orderseq SET
75391     orderseq_number = LEAST(pnumber, orderseq_number)
75392   WHERE (orderseq_name=psequence);
75393
75394   RETURN 1;
75395 END;
75396 $_$;
75397
75398
75399 ALTER FUNCTION public.releasenumber(text, integer) OWNER TO admin;
75400
75401 --
75402 -- TOC entry 2091 (class 1255 OID 146566934)
75403 -- Dependencies: 8
75404 -- Name: releaseponumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75405 --
75406
75407 CREATE FUNCTION releaseponumber(integer) RETURNS boolean
75408     LANGUAGE sql
75409     AS $_$
75410 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75411 -- See www.xtuple.com/CPAL for the full text of the software license.
75412   SELECT releaseNumber('PoNumber', $1) > 0;
75413 $_$;
75414
75415
75416 ALTER FUNCTION public.releaseponumber(integer) OWNER TO admin;
75417
75418 --
75419 -- TOC entry 2092 (class 1255 OID 146566935)
75420 -- Dependencies: 8
75421 -- Name: releaseponumber(text); Type: FUNCTION; Schema: public; Owner: admin
75422 --
75423
75424 CREATE FUNCTION releaseponumber(text) RETURNS boolean
75425     LANGUAGE sql
75426     AS $_$
75427 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75428 -- See www.xtuple.com/CPAL for the full text of the software license.
75429   SELECT releaseNumber('PoNumber', $1::INTEGER) > 0;
75430 $_$;
75431
75432
75433 ALTER FUNCTION public.releaseponumber(text) OWNER TO admin;
75434
75435 --
75436 -- TOC entry 2093 (class 1255 OID 146566936)
75437 -- Dependencies: 8
75438 -- Name: releaseprnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75439 --
75440
75441 CREATE FUNCTION releaseprnumber(integer) RETURNS boolean
75442     LANGUAGE sql
75443     AS $_$
75444 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75445 -- See www.xtuple.com/CPAL for the full text of the software license.
75446   SELECT releaseNumber('PrNumber', $1) > 0;
75447 $_$;
75448
75449
75450 ALTER FUNCTION public.releaseprnumber(integer) OWNER TO admin;
75451
75452 --
75453 -- TOC entry 2094 (class 1255 OID 146566937)
75454 -- Dependencies: 4536 8
75455 -- Name: releasepurchaseorder(integer); Type: FUNCTION; Schema: public; Owner: admin
75456 --
75457
75458 CREATE FUNCTION releasepurchaseorder(integer) RETURNS integer
75459     LANGUAGE plpgsql
75460     AS $_$
75461 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75462 -- See www.xtuple.com/CPAL for the full text of the software license.
75463 DECLARE
75464   pPoheadid ALIAS FOR $1;
75465
75466 BEGIN
75467
75468   IF ( ( SELECT (COUNT(*) = 0)
75469          FROM poitem
75470          WHERE ( (poitem_pohead_id=pPoheadid)
75471            AND   (poitem_status='U') ) ) ) THEN
75472     RETURN -1;
75473   END IF;
75474
75475   IF ( ( SELECT (pohead_status='U')
75476          FROM pohead
75477          WHERE (pohead_id=pPoheadid) ) ) THEN
75478
75479     --update status and store the date that the order was released on
75480     UPDATE pohead
75481     SET pohead_status='O', pohead_released = current_date
75482     WHERE (pohead_id=pPoheadid);
75483
75484   END IF;
75485
75486   --update status and store the duedates at release
75487   UPDATE poitem
75488   SET poitem_status='O', poitem_rlsd_duedate = poitem_duedate
75489   WHERE (poitem_pohead_id=pPoheadid);
75490
75491   RETURN 1;
75492
75493 END;
75494 $_$;
75495
75496
75497 ALTER FUNCTION public.releasepurchaseorder(integer) OWNER TO admin;
75498
75499 --
75500 -- TOC entry 2095 (class 1255 OID 146566938)
75501 -- Dependencies: 8
75502 -- Name: releasequnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75503 --
75504
75505 CREATE FUNCTION releasequnumber(integer) RETURNS integer
75506     LANGUAGE sql
75507     AS $_$
75508 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75509 -- See www.xtuple.com/CPAL for the full text of the software license.
75510   SELECT releaseNumber('QuNumber', $1);
75511 $_$;
75512
75513
75514 ALTER FUNCTION public.releasequnumber(integer) OWNER TO admin;
75515
75516 --
75517 -- TOC entry 2096 (class 1255 OID 146566939)
75518 -- Dependencies: 8
75519 -- Name: releasequnumber(text); Type: FUNCTION; Schema: public; Owner: admin
75520 --
75521
75522 CREATE FUNCTION releasequnumber(text) RETURNS integer
75523     LANGUAGE sql
75524     AS $_$
75525 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75526 -- See www.xtuple.com/CPAL for the full text of the software license.
75527   SELECT releaseNumber('QuNumber', $1::INTEGER);
75528 $_$;
75529
75530
75531 ALTER FUNCTION public.releasequnumber(text) OWNER TO admin;
75532
75533 --
75534 -- TOC entry 2097 (class 1255 OID 146566940)
75535 -- Dependencies: 4536 8
75536 -- Name: releaseshipmentnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75537 --
75538
75539 CREATE FUNCTION releaseshipmentnumber(integer) RETURNS boolean
75540     LANGUAGE plpgsql
75541     AS $_$
75542 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75543 -- See www.xtuple.com/CPAL for the full text of the software license.
75544 DECLARE
75545   pNumber ALIAS FOR $1;
75546   _test INTEGER;
75547
75548 BEGIN
75549
75550 --  Check to see if a Shipment exists with the passed number
75551   SELECT shiphead_id INTO _test
75552   FROM shiphead
75553   WHERE (shiphead_number=pNumber);
75554
75555   IF (FOUND) THEN
75556     RETURN FALSE;
75557   END IF;
75558
75559 --  Check to see if ShipmentNumber orderseq has been incremented past the passed number
75560   SELECT orderseq_number INTO _test
75561   FROM orderseq
75562   WHERE (orderseq_name='ShipmentNumber');
75563
75564   IF ((_test - 1) <> pNumber) THEN
75565     RETURN FALSE;
75566   END IF;
75567
75568 --  Decrement the orderseq, releasing the passed number
75569   UPDATE orderseq
75570   SET orderseq_number = (orderseq_number - 1)
75571   WHERE (orderseq_name='ShipmentNumber');
75572
75573   RETURN TRUE;
75574
75575 END;
75576 $_$;
75577
75578
75579 ALTER FUNCTION public.releaseshipmentnumber(integer) OWNER TO admin;
75580
75581 --
75582 -- TOC entry 2098 (class 1255 OID 146566941)
75583 -- Dependencies: 4536 8
75584 -- Name: releasesohead(integer); Type: FUNCTION; Schema: public; Owner: admin
75585 --
75586
75587 CREATE FUNCTION releasesohead(integer) RETURNS boolean
75588     LANGUAGE plpgsql
75589     AS $_$
75590 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75591 -- See www.xtuple.com/CPAL for the full text of the software license.
75592 DECLARE
75593   pSoheadid ALIAS FOR $1;
75594
75595 BEGIN
75596
75597   DELETE FROM soheadlock
75598    WHERE ( (soheadlock_sohead_id=pSoheadid)
75599      AND   (soheadlock_username=getEffectiveXtUser())
75600      AND   (soheadlock_procpid=pg_backend_pid()) );
75601
75602   RETURN TRUE;
75603 END;
75604 $_$;
75605
75606
75607 ALTER FUNCTION public.releasesohead(integer) OWNER TO admin;
75608
75609 --
75610 -- TOC entry 2099 (class 1255 OID 146566942)
75611 -- Dependencies: 8
75612 -- Name: releasesonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75613 --
75614
75615 CREATE FUNCTION releasesonumber(integer) RETURNS integer
75616     LANGUAGE sql
75617     AS $_$
75618 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75619 -- See www.xtuple.com/CPAL for the full text of the software license.
75620   SELECT releaseNumber('SoNumber', $1);
75621 $_$;
75622
75623
75624 ALTER FUNCTION public.releasesonumber(integer) OWNER TO admin;
75625
75626 --
75627 -- TOC entry 2100 (class 1255 OID 146566943)
75628 -- Dependencies: 4536 8
75629 -- Name: releasesonumber(text); Type: FUNCTION; Schema: public; Owner: admin
75630 --
75631
75632 CREATE FUNCTION releasesonumber(text) RETURNS integer
75633     LANGUAGE plpgsql
75634     AS $_$
75635 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75636 -- See www.xtuple.com/CPAL for the full text of the software license.
75637 BEGIN
75638         IF (COALESCE($1, '') = '' OR $1 ~ '[^0-9]')
75639         THEN
75640         --do nothing;
75641         RETURN 1;
75642         ELSE
75643         RETURN releaseNumber('SoNumber', $1::INTEGER);
75644         
75645         END IF;
75646 END;
75647 $_$;
75648
75649
75650 ALTER FUNCTION public.releasesonumber(text) OWNER TO admin;
75651
75652 --
75653 -- TOC entry 2101 (class 1255 OID 146566944)
75654 -- Dependencies: 4536 8
75655 -- Name: releaseunusedbillingheader(integer); Type: FUNCTION; Schema: public; Owner: admin
75656 --
75657
75658 CREATE FUNCTION releaseunusedbillingheader(integer) RETURNS integer
75659     LANGUAGE plpgsql
75660     AS $_$
75661 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75662 -- See www.xtuple.com/CPAL for the full text of the software license.
75663 DECLARE
75664   pCobmiscid ALIAS FOR $1;
75665   _p RECORD;
75666
75667 BEGIN
75668
75669   IF ( ( SELECT cobmisc_posted
75670          FROM cobmisc
75671          WHERE (cobmisc_id=pCobmiscid) ) ) THEN
75672     RETURN -1;
75673   END IF;
75674
75675   SELECT cobill_id INTO _p
75676     FROM cobill
75677    WHERE (cobill_cobmisc_id=pCobmiscid)
75678    LIMIT 1;
75679   IF (FOUND) THEN
75680     RETURN -2;
75681   END IF;
75682
75683   DELETE FROM cobmisc
75684   WHERE (cobmisc_id=pCobmiscid);
75685
75686   RETURN 0;
75687 END;
75688 $_$;
75689
75690
75691 ALTER FUNCTION public.releaseunusedbillingheader(integer) OWNER TO admin;
75692
75693 --
75694 -- TOC entry 2102 (class 1255 OID 146566945)
75695 -- Dependencies: 8
75696 -- Name: releasevonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75697 --
75698
75699 CREATE FUNCTION releasevonumber(integer) RETURNS boolean
75700     LANGUAGE sql
75701     AS $_$
75702 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75703 -- See www.xtuple.com/CPAL for the full text of the software license.
75704   SELECT releaseNumber('VcNumber', $1) > 0;
75705 $_$;
75706
75707
75708 ALTER FUNCTION public.releasevonumber(integer) OWNER TO admin;
75709
75710 --
75711 -- TOC entry 2103 (class 1255 OID 146566946)
75712 -- Dependencies: 4536 8
75713 -- Name: releasewo(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
75714 --
75715
75716 CREATE FUNCTION releasewo(integer, boolean) RETURNS integer
75717     LANGUAGE plpgsql
75718     AS $_$
75719 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75720 -- See www.xtuple.com/CPAL for the full text of the software license.
75721 DECLARE
75722   pWoid ALIAS FOR $1;
75723   releaseChildren ALIAS FOR $2;
75724   returnCode INTEGER;
75725 BEGIN
75726   UPDATE wo
75727   SET wo_status='R'
75728   WHERE ((wo_status='E')
75729    AND (wo_id=pWoid));
75730
75731   IF (releaseChildren) THEN
75732     returnCode := (SELECT MAX(releaseWo(wo_id, TRUE))
75733                    FROM wo
75734                    WHERE ((wo_ordtype='W')
75735                     AND (wo_ordid=pWoid)));
75736   END IF;
75737
75738   RETURN 0;
75739 END;
75740 $_$;
75741
75742
75743 ALTER FUNCTION public.releasewo(integer, boolean) OWNER TO admin;
75744
75745 --
75746 -- TOC entry 2104 (class 1255 OID 146566947)
75747 -- Dependencies: 8
75748 -- Name: releasewonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
75749 --
75750
75751 CREATE FUNCTION releasewonumber(integer) RETURNS boolean
75752     LANGUAGE sql
75753     AS $_$
75754 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75755 -- See www.xtuple.com/CPAL for the full text of the software license.
75756   SELECT releaseNumber('WoNumber', $1) > 0;
75757 $_$;
75758
75759
75760 ALTER FUNCTION public.releasewonumber(integer) OWNER TO admin;
75761
75762 --
75763 -- TOC entry 930 (class 1255 OID 146566948)
75764 -- Dependencies: 4536 8
75765 -- Name: relocateinventory(integer, integer, integer, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
75766 --
75767
75768 CREATE FUNCTION relocateinventory(integer, integer, integer, numeric, text) RETURNS integer
75769     LANGUAGE plpgsql
75770     AS $_$
75771 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75772 -- See www.xtuple.com/CPAL for the full text of the software license.
75773 BEGIN
75774   RETURN relocateInventory($1, $2, $3, $4, $5, CURRENT_TIMESTAMP);
75775 END;
75776 $_$;
75777
75778
75779 ALTER FUNCTION public.relocateinventory(integer, integer, integer, numeric, text) OWNER TO admin;
75780
75781 --
75782 -- TOC entry 946 (class 1255 OID 146566949)
75783 -- Dependencies: 4536 8
75784 -- Name: relocateinventory(integer, integer, integer, numeric, text, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
75785 --
75786
75787 CREATE FUNCTION relocateinventory(integer, integer, integer, numeric, text, timestamp with time zone) RETURNS integer
75788     LANGUAGE plpgsql
75789     AS $_$
75790 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
75791 -- See www.xtuple.com/CPAL for the full text of the software license.
75792 DECLARE
75793   pSourceItemlocid      ALIAS FOR $1;
75794   pTargetLocationid     ALIAS FOR $2;
75795   pItemsiteid           ALIAS FOR $3;
75796   pQty                  ALIAS FOR $4;
75797   pComments             ALIAS FOR $5;
75798   _GlDistTS             TIMESTAMP WITH TIME ZONE := $6;
75799   _targetItemlocid      INTEGER;
75800   _invhistid            INTEGER;
75801   _p                    RECORD;
75802   _rsrv                 RECORD;
75803   _qty                  NUMERIC;
75804   _qtyunreserved        NUMERIC := 0.0;
75805   _qtytomove            NUMERIC := 0.0;
75806   _result               INTEGER := -1;
75807   _itemlocSeries        INTEGER := NEXTVAL('itemloc_series_seq');
75808
75809 BEGIN
75810
75811     IF ((_GlDistTS IS NULL) OR (CAST(_GlDistTS AS date)=CURRENT_DATE)) THEN
75812       _GlDistTS := CURRENT_TIMESTAMP;
75813     END IF;
75814
75815 --  Make sure the passed itemsite points to a real item
75816   IF ( ( SELECT (item_type IN ('R', 'F') OR itemsite_costmethod = 'J')
75817          FROM itemsite, item
75818          WHERE ( (itemsite_item_id=item_id)
75819           AND (itemsite_id=pItemsiteid) ) ) ) THEN
75820     RETURN 0;
75821   END IF;
75822
75823 --  Cache some parameters
75824   SELECT itemloc_ls_id,
75825          itemloc_itemsite_id AS itemsiteid,
75826          itemloc_expiration,
75827          itemloc_warrpurc,
75828          itemloc_qty,
75829          sourceloc.location_netable AS sourcenet,
75830          targetloc.location_netable AS targetnet INTO _p
75831   FROM itemloc, location AS sourceloc, location AS targetloc
75832   WHERE ( (itemloc_location_id=sourceloc.location_id)
75833    AND (targetloc.location_id=pTargetLocationid)
75834    AND (itemloc_id=pSourceItemlocid) );
75835
75836 --  Check to make sure the qty being transfered exists
75837   IF (_p.itemloc_qty < pQty) THEN
75838     RETURN -1;
75839   END IF;
75840
75841 --  Create the RL transaction
75842   SELECT NEXTVAL('invhist_invhist_id_seq') INTO _invhistid;
75843   INSERT INTO invhist
75844   ( invhist_id, invhist_itemsite_id,
75845     invhist_transtype, invhist_invqty,
75846     invhist_qoh_before, invhist_qoh_after,
75847     invhist_comments,   invhist_transdate,
75848     invhist_invuom, invhist_unitcost, invhist_costmethod,
75849     invhist_value_before, invhist_value_after, invhist_series) 
75850   SELECT _invhistid, itemsite_id,
75851          'RL', 0,
75852          itemsite_qtyonhand, itemsite_qtyonhand,
75853          pComments, _GlDistTS,
75854          uom_name,
75855          CASE WHEN (itemsite_costmethod='A') THEN avgcost(itemsite_id)
75856               ELSE stdCost(item_id)
75857          END, itemsite_costmethod,
75858          itemsite_value, itemsite_value, _itemlocSeries
75859   FROM item, itemsite, uom
75860   WHERE ((itemsite_item_id=item_id)
75861    AND (item_inv_uom_id=uom_id)
75862    AND (itemsite_controlmethod <> 'N')
75863    AND (itemsite_id=pItemsiteid));
75864
75865 --  Relocate the inventory from the source and record the transactions
75866   INSERT INTO invdetail
75867   ( invdetail_invhist_id, invdetail_location_id, invdetail_ls_id,
75868     invdetail_qty, invdetail_qty_before, invdetail_qty_after,
75869     invdetail_expiration, invdetail_warrpurc )
75870   SELECT _invhistid, itemloc_location_id, itemloc_ls_id,
75871          (pQty * -1), itemloc_qty, (itemloc_qty - pQty),
75872          itemloc_expiration, itemloc_warrpurc
75873   FROM itemloc
75874   WHERE (itemloc_id=pSourceItemlocid);
75875
75876   UPDATE itemloc
75877   SET itemloc_qty=(itemloc_qty - pQty)
75878   FROM itemsite
75879   WHERE ( (itemloc_itemsite_id=itemsite_id)
75880    AND (NOT itemsite_freeze)
75881    AND (itemloc_id=pSourceItemlocid) );
75882
75883 --  Check to see if any of the current Lot/Serial #/Expiration exists at the target location
75884   SELECT itemloc_id INTO _targetItemlocid
75885   FROM itemloc 
75886   WHERE ( (COALESCE(itemloc_ls_id, -1)=COALESCE(_p.itemloc_ls_id,-1))
75887    AND (COALESCE(itemloc_expiration,endOfTime())=COALESCE(_p.itemloc_expiration,endOfTime()))
75888    AND (COALESCE(itemloc_warrpurc,endOfTime())=COALESCE(_p.itemloc_warrpurc,endOfTime()))
75889    AND (itemloc_itemsite_id=pItemsiteid)
75890    AND (itemloc_location_id=pTargetLocationid) );
75891
75892   IF (NOT FOUND) THEN
75893     SELECT NEXTVAL('itemloc_itemloc_id_seq') INTO _targetItemlocid;
75894     INSERT INTO itemloc
75895     ( itemloc_id, itemloc_itemsite_id, itemloc_location_id,
75896       itemloc_ls_id, itemloc_expiration, itemloc_warrpurc, itemloc_qty )
75897     VALUES
75898     ( _targetItemlocid, pItemsiteid, pTargetLocationid,
75899       _p.itemloc_ls_id, _p.itemloc_expiration, _p.itemloc_warrpurc, 0 );
75900   END IF;
75901
75902 --  Relocate the inventory to the resultant target and record the transactions
75903   INSERT INTO invdetail
75904   ( invdetail_invhist_id, invdetail_location_id, invdetail_ls_id,
75905     invdetail_qty, invdetail_qty_before, invdetail_qty_after,
75906     invdetail_expiration, invdetail_warrpurc )
75907   SELECT _invhistid, pTargetLocationid, _p.itemloc_ls_id,
75908          pQty, itemloc_qty, (itemloc_qty + pQty), 
75909          _p.itemloc_expiration, _p.itemloc_warrpurc
75910   FROM itemloc
75911   WHERE (itemloc_id=_targetItemlocid);
75912
75913   UPDATE itemloc
75914   SET itemloc_qty=(itemloc_qty + pQty)
75915   FROM itemsite
75916   WHERE ( (itemloc_itemsite_id=itemsite_id)
75917    AND (NOT itemsite_freeze)
75918    AND (itemloc_id=_targetItemlocid) );
75919
75920   UPDATE invhist
75921   SET invhist_hasdetail=TRUE
75922   WHERE (invhist_id=_invhistid);
75923
75924 --  Post in incomming or outgoing NN transaction if required
75925   IF (_p.sourcenet <> _p.targetnet) THEN
75926     IF (_p.targetnet) THEN
75927       _qty = (pQty * -1);
75928     ELSE
75929       _qty = pQty;
75930     END IF;
75931
75932     INSERT INTO invhist
75933     ( invhist_itemsite_id,
75934       invhist_transtype, invhist_invqty,
75935       invhist_qoh_before, invhist_qoh_after,
75936       invhist_docnumber, invhist_comments, invhist_transdate,
75937       invhist_invuom, invhist_unitcost, invhist_costmethod,
75938       invhist_value_before, invhist_value_after, invhist_series) 
75939     SELECT itemsite_id,
75940            'NN', (_qty * -1),
75941            itemsite_qtyonhand, (itemsite_qtyonhand - _qty),
75942            '', '', _GlDistTS,
75943            uom_name,
75944            CASE WHEN (itemsite_costmethod='A') THEN avgcost(itemsite_id)
75945                 ELSE stdCost(item_id)
75946            END, itemsite_costmethod,
75947            itemsite_value, itemsite_value, _itemlocSeries
75948     FROM item, itemsite, uom
75949     WHERE ( (itemsite_item_id=item_id)
75950      ANd (item_inv_uom_id=uom_id)
75951      AND (itemsite_controlmethod <> 'N')
75952      AND (itemsite_id=_p.itemsiteid) );
75953
75954     UPDATE itemsite
75955     SET itemsite_qtyonhand = (itemsite_qtyonhand - _qty),
75956         itemsite_nnqoh = (itemsite_nnqoh + _qty)
75957     WHERE (itemsite_id=_p.itemsiteid);
75958   END IF;
75959
75960 --  Check to see if there is anything left at the target Itemloc and delete if not
75961 --  Could be zero if relocate increased a negative quantity to zero
75962   DELETE FROM itemloc
75963   WHERE ( (itemloc_qty=0)
75964    AND (itemloc_id=_targetItemlocid) );
75965
75966 --  Handle Reservations
75967   IF (fetchMetricBool('EnableSOReservationsByLocation')) THEN
75968     SELECT CASE WHEN (qtyReservedLocation(itemloc_id) > itemloc_qty)
75969                 THEN (qtyReservedLocation(itemloc_id) - itemloc_qty)
75970                 ELSE 0.0
75971                 END INTO _qtyunreserved
75972     FROM itemloc
75973     WHERE (itemloc_id=pSourceItemlocid);
75974     -- Move reservations as necessary
75975     WHILE (_qtyunreserved > 0.0) LOOP
75976       SELECT * INTO _rsrv
75977       FROM reserve
75978       WHERE ((reserve_supply_type='I')
75979         AND  (reserve_supply_id=pSourceItemlocid))
75980       ORDER BY reserve_qty;
75981       IF (NOT FOUND) THEN
75982         RAISE EXCEPTION 'Cannot find reservation to unreserve.';
75983       END IF;
75984       IF (_rsrv.reserve_qty > _qtyunreserved) THEN
75985         _qtytomove := _qtyunreserved;
75986       ELSE
75987         _qtytomove := _rsrv.reserve_qty;
75988       END IF;
75989       -- Unreserve Source Location
75990       SELECT unreserveSOLineQty(_rsrv.reserve_demand_id,
75991                                 _qtytomove,
75992                                 pSourceItemlocid) INTO _result;
75993       IF (_result < 0) THEN
75994         RAISE EXCEPTION 'unreserveSOLineQty failed with result=%, reserve_id=%, qty=%',
75995                         _result, _rsrv.reserve_id, _qtytomove;
75996       END IF;
75997       -- Reserve to new Location
75998       SELECT reserveSOLineQty(_rsrv.reserve_demand_id,
75999                               TRUE,
76000                               _qtytomove,
76001                               _targetItemlocid) INTO _result;
76002       IF (_result < 0) THEN
76003         RAISE EXCEPTION 'reserveSOLineQty failed with result=%, reserve_id=%, qty=%',
76004                         _result, _rsrv.reserve_id, _qtytomove;
76005       END IF;
76006       -- Calculate running total
76007       _qtyunreserved := _qtyunreserved - _qtytomove;
76008     END LOOP;
76009   END IF;
76010
76011 --  Check to see if there is anything left at the source Itemloc and delete if not
76012   DELETE FROM itemloc
76013   WHERE ( (itemloc_qty=0)
76014    AND (itemloc_id=pSourceItemlocid) );
76015
76016 --  Return the invhist_id
76017   RETURN _invhistid;
76018
76019 END;
76020 $_$;
76021
76022
76023 ALTER FUNCTION public.relocateinventory(integer, integer, integer, numeric, text, timestamp with time zone) OWNER TO admin;
76024
76025 --
76026 -- TOC entry 2105 (class 1255 OID 146566951)
76027 -- Dependencies: 4536 8
76028 -- Name: reopenbankreconciliation(integer); Type: FUNCTION; Schema: public; Owner: admin
76029 --
76030
76031 CREATE FUNCTION reopenbankreconciliation(integer) RETURNS integer
76032     LANGUAGE plpgsql
76033     AS $_$
76034 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76035 -- See www.xtuple.com/CPAL for the full text of the software license.
76036 DECLARE
76037   pBankrecid ALIAS FOR $1;
76038   _bankrecid INTEGER;
76039   _accntid INTEGER;
76040   _sequence INTEGER;
76041   _gltransid INTEGER;
76042   _r RECORD;
76043
76044 BEGIN
76045
76046 -- Check the accnt information to make sure it is valid
76047   SELECT accnt_id INTO _accntid
76048     FROM bankrec, bankaccnt, accnt
76049    WHERE ( (bankaccnt_accnt_id=accnt_id)
76050      AND   (bankrec_bankaccnt_id=bankaccnt_id)
76051      AND   (bankrec_id=pBankrecid) );
76052   IF ( NOT FOUND ) THEN
76053     RETURN -1;
76054   END IF;
76055
76056   SELECT bankrec_id INTO _bankrecid
76057     FROM bankrec
76058    WHERE (NOT bankrec_posted);
76059   IF (FOUND) THEN
76060   -- Delete any bankrecitem records for unposted periods
76061     DELETE FROM bankrecitem
76062      WHERE (bankrecitem_bankrec_id=_bankrecid);
76063   -- Delete any bankrec records for unposted period
76064     DELETE FROM bankrec
76065      WHERE (bankrec_id=_bankrecid);
76066   END IF;
76067
76068 -- Mark all the gltrans items that have been cleared as unreconciled.
76069   UPDATE gltrans
76070      SET gltrans_rec = FALSE
76071    WHERE ( (gltrans_id IN (SELECT bankrecitem_source_id
76072                              FROM bankrecitem
76073                             WHERE ((bankrecitem_source = 'GL')
76074                               AND  (bankrecitem_cleared)
76075                               AND  (bankrecitem_bankrec_id=pBankrecid) ) ) )
76076      AND   (gltrans_accnt_id=_accntid) ) ;
76077
76078 -- Mark all the sltrans items that have been cleared as unreconciled.
76079   UPDATE sltrans
76080      SET sltrans_rec = FALSE
76081    WHERE ( (sltrans_id IN (SELECT bankrecitem_source_id
76082                              FROM bankrecitem
76083                             WHERE ((bankrecitem_source = 'SL')
76084                               AND  (bankrecitem_cleared)
76085                               AND  (bankrecitem_bankrec_id=pBankrecid) ) ) )
76086      AND   (sltrans_accnt_id=_accntid) ) ;
76087
76088 -- Mark the bankrec record as unposted
76089   UPDATE bankrec SET 
76090     bankrec_posted = FALSE,
76091     bankrec_postdate = NULL
76092    WHERE (bankrec_id=pBankrecid);
76093
76094   RETURN pBankrecid;
76095 END;
76096 $_$;
76097
76098
76099 ALTER FUNCTION public.reopenbankreconciliation(integer) OWNER TO admin;
76100
76101 --
76102 -- TOC entry 2106 (class 1255 OID 146566952)
76103 -- Dependencies: 4536 8
76104 -- Name: reorderdate(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
76105 --
76106
76107 CREATE FUNCTION reorderdate(integer, integer, boolean) RETURNS date
76108     LANGUAGE plpgsql
76109     AS $_$
76110 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76111 -- See www.xtuple.com/CPAL for the full text of the software license.
76112 DECLARE
76113   pItemsiteid ALIAS FOR $1;
76114   pLookAhead ALIAS FOR $2;
76115   pIncludePlanned ALIAS FOR $3;
76116   _runningAvailability NUMERIC;
76117   _reorderLevel NUMERIC;
76118   _availability RECORD;
76119
76120 BEGIN
76121
76122 --  Make sure that we know how to handle the passed part
76123   IF ( SELECT (NOT (item_type IN ('M', 'P')))
76124        FROM item, itemsite
76125        WHERE ( (itemsite_item_id=item_id)
76126         AND (itemsite_id=pItemsiteid) ) ) THEN
76127     RETURN NULL;
76128   END IF;
76129
76130 --  Load the initial QOH
76131   SELECT itemsite_qtyonhand INTO _runningAvailability
76132   FROM itemsite
76133   WHERE (itemsite_id=pItemsiteid);
76134
76135 --  Grab the Reorder Level, if any
76136   IF ( ( SELECT itemsite_useparams
76137          FROM itemsite
76138          WHERE (itemsite_id=pItemsiteid) ) ) THEN
76139     SELECT itemsite_reorderlevel INTO _reorderLevel
76140     FROM itemsite
76141     WHERE (itemsite_id=pItemsiteid);
76142   ELSE
76143     _reorderLevel := 0;
76144   END IF;
76145
76146 --  If we are already below the Reorder Level then we should order ASAP
76147   IF (_runningAvailability <= _reorderLevel) THEN
76148     RETURN CURRENT_DATE;
76149   END IF;
76150
76151 --  Grab all of the availability trigger points
76152   FOR _availability IN SELECT 1 AS seq,
76153                               wo_duedate AS orderdate,
76154                               (noNeg(wo_qtyord - wo_qtyrcv)) AS balance
76155                        FROM wo
76156                        WHERE ((wo_status IN ('O', 'E', 'R', 'I'))
76157                         AND (wo_duedate <= (CURRENT_DATE + pLookAhead))
76158                         AND (wo_itemsite_id=pItemsiteid))
76159
76160                       UNION SELECT 2 AS seq,
76161                                    womatl_duedate AS orderdate,
76162                                    (noNeg(itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq - womatl_qtyiss)) * -1) AS balance
76163                       FROM womatl, wo, itemsite
76164                       WHERE ((wo_status IN ('O', 'E', 'R', 'I'))
76165                        AND (womatl_wo_id=wo_id)
76166                        AND (womatl_itemsite_id=itemsite_id)
76167                        AND (womatl_duedate <= (CURRENT_DATE + pLookahead))
76168                        AND (womatl_itemsite_id=pItemsiteid))
76169
76170                       UNION SELECT 1 AS seq,
76171                                    poitem_duedate AS orderdate,
76172                                    (noNeg(poitem_qty_ordered - poitem_qty_received) * poitem_invvenduomratio) AS balance
76173                       FROM pohead, poitem
76174                       WHERE ((poitem_pohead_id=pohead_id)
76175                        AND (poitem_status = 'O')
76176                        AND (poitem_duedate <= (CURRENT_DATE + pLookAhead))
76177                        AND (poitem_itemsite_id=pItemsiteid))
76178
76179                       UNION SELECT 2 AS seq,
76180                                    coitem_scheddate AS orderdate,
76181                                    (noNeg(coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) * -1) AS balance
76182                       FROM coitem, cohead
76183                       WHERE ((coitem_status = 'O')
76184                        AND (coitem_cohead_id=cohead_id)
76185                        AND (coitem_scheddate <= (CURRENT_DATE + pLookAhead))
76186                        AND (coitem_itemsite_id=pItemsiteid))
76187
76188                       UNION SELECT 2 AS seq,
76189                                    planord_startdate AS orderdate,
76190                                    (planreq_qty * -1) AS balance
76191                       FROM planreq, planord
76192                       WHERE ( (pIncludePlanned)
76193                        AND (planreq_source='P')
76194                        AND (planreq_source_id=planord_id)
76195                        AND (planord_startdate <= (CURRENT_DATE + pLookAhead))
76196                        AND (planord_itemsite_id=pItemsiteid) )
76197
76198                       UNION SELECT 1 AS seq,
76199                                    planord_duedate AS orderdate,
76200                                    planord_qty AS balance
76201                       FROM planord
76202                       WHERE ( (pIncludePlanned)
76203                        AND (planord_duedate <= (CURRENT_DATE + pLookAhead))
76204                        AND (planord_itemsite_id=pItemsiteid) )
76205
76206                       ORDER BY orderdate, seq LOOP
76207
76208 --  Calculate the new projected availability
76209     _runningAvailability := (_runningAvailability + _availability.balance);
76210
76211 --  Check to see if the project availability drop below the reorder level
76212     IF (_runningAvailability < _reorderLevel) THEN
76213       RETURN _availability.orderdate;
76214     END IF;
76215
76216   END LOOP;
76217
76218 --  The reorder level was not reached within the look ahead period
76219   RETURN NULL;
76220
76221 END;
76222 $_$;
76223
76224
76225 ALTER FUNCTION public.reorderdate(integer, integer, boolean) OWNER TO admin;
76226
76227 --
76228 -- TOC entry 2107 (class 1255 OID 146566953)
76229 -- Dependencies: 4536 8
76230 -- Name: replaceallvoidedapchecks(integer); Type: FUNCTION; Schema: public; Owner: admin
76231 --
76232
76233 CREATE FUNCTION replaceallvoidedapchecks(integer) RETURNS integer
76234     LANGUAGE plpgsql
76235     AS $_$
76236 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76237 -- See www.xtuple.com/CPAL for the full text of the software license.
76238 BEGIN
76239   RAISE NOTICE 'replaceAllVoidedAPChecks() is deprecated - use replaceAllVoidedChecks() instead';
76240   RETURN replaceAllVoidedChecks($1);
76241 END;
76242 $_$;
76243
76244
76245 ALTER FUNCTION public.replaceallvoidedapchecks(integer) OWNER TO admin;
76246
76247 --
76248 -- TOC entry 2108 (class 1255 OID 146566954)
76249 -- Dependencies: 4536 8
76250 -- Name: replaceallvoidedchecks(integer); Type: FUNCTION; Schema: public; Owner: admin
76251 --
76252
76253 CREATE FUNCTION replaceallvoidedchecks(integer) RETURNS integer
76254     LANGUAGE plpgsql
76255     AS $_$
76256 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76257 -- See www.xtuple.com/CPAL for the full text of the software license.
76258 DECLARE
76259   pBankaccntid  ALIAS FOR $1;
76260   _returnValue  INTEGER := 0;
76261
76262 BEGIN
76263
76264   SELECT MIN(replaceVoidedCheck(checkhead_id)) INTO _returnValue
76265     FROM checkhead
76266     WHERE ( (checkhead_void)
76267      AND (NOT checkhead_posted)
76268      AND (NOT checkhead_replaced)
76269      AND (NOT checkhead_deleted)
76270      AND (checkhead_bankaccnt_id=pBankaccntid) );
76271
76272   RETURN _returnValue;
76273
76274 END;
76275 $_$;
76276
76277
76278 ALTER FUNCTION public.replaceallvoidedchecks(integer) OWNER TO admin;
76279
76280 --
76281 -- TOC entry 2109 (class 1255 OID 146566955)
76282 -- Dependencies: 4536 8
76283 -- Name: replacevoidedapcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
76284 --
76285
76286 CREATE FUNCTION replacevoidedapcheck(integer) RETURNS integer
76287     LANGUAGE plpgsql
76288     AS $_$
76289 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76290 -- See www.xtuple.com/CPAL for the full text of the software license.
76291 BEGIN
76292   RAISE NOTICE 'replaceVoidedAPCheck() is deprecated - use replaceVoidedCheck()';
76293   RETURN replaceVoidedCheck($1);
76294 END;
76295 $_$;
76296
76297
76298 ALTER FUNCTION public.replacevoidedapcheck(integer) OWNER TO admin;
76299
76300 --
76301 -- TOC entry 2110 (class 1255 OID 146566956)
76302 -- Dependencies: 4536 8
76303 -- Name: replacevoidedcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
76304 --
76305
76306 CREATE FUNCTION replacevoidedcheck(integer) RETURNS integer
76307     LANGUAGE plpgsql
76308     AS $_$
76309 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76310 -- See www.xtuple.com/CPAL for the full text of the software license.
76311 DECLARE
76312   pCheckid      ALIAS FOR $1;
76313   _newCheckid   INTEGER;
76314
76315 BEGIN
76316   IF ( ( SELECT ( (NOT checkhead_void) OR checkhead_posted OR checkhead_replaced )
76317          FROM checkhead
76318          WHERE (checkhead_id=pCheckid) ) ) THEN
76319     RETURN -1;
76320   END IF;
76321
76322   -- has someone created a new check for one of the items while this was void?
76323   IF EXISTS (SELECT dup.checkitem_id
76324              FROM checkitem orig, checkitem dup, checkhead AS duphead
76325              WHERE ((COALESCE(orig.checkitem_aropen_id,-1)=COALESCE(dup.checkitem_aropen_id,-1))
76326                 AND (COALESCE(orig.checkitem_apopen_id,-1)=COALESCE(dup.checkitem_apopen_id,-1))
76327                 AND (orig.checkitem_checkhead_id!=dup.checkitem_checkhead_id)
76328                 AND (dup.checkitem_checkhead_id=duphead.checkhead_id)
76329                 AND (NOT duphead.checkhead_void)
76330                 AND (orig.checkitem_checkhead_id=pCheckid))) THEN
76331     RETURN -2;
76332   END IF;
76333
76334   SELECT NEXTVAL('checkhead_checkhead_id_seq') INTO _newCheckid;
76335
76336   INSERT INTO checkhead
76337   ( checkhead_id, checkhead_recip_id, checkhead_recip_type,
76338     checkhead_bankaccnt_id, checkhead_checkdate,
76339     checkhead_number, checkhead_amount,
76340     checkhead_for, checkhead_journalnumber,
76341     checkhead_notes,
76342     checkhead_misc, checkhead_expcat_id, checkhead_curr_id )
76343   SELECT _newCheckid, checkhead_recip_id, checkhead_recip_type,
76344          checkhead_bankaccnt_id, checkhead_checkdate,
76345          -1, -- fetchNextCheckNumber(checkhead_bankaccnt_id),
76346          checkhead_amount,
76347          checkhead_for, checkhead_journalnumber,
76348          checkhead_notes || '
76349 Replaces voided check ' || checkhead_number,
76350          checkhead_misc, checkhead_expcat_id, checkhead_curr_id
76351   FROM checkhead
76352   WHERE (checkhead_id=pCheckid);
76353
76354   INSERT INTO checkitem
76355   ( checkitem_checkhead_id, checkitem_amount, checkitem_discount,
76356     checkitem_ponumber, checkitem_vouchernumber, checkitem_invcnumber,
76357     checkitem_apopen_id, checkitem_aropen_id,
76358     checkitem_docdate, checkitem_curr_id, checkitem_curr_rate )
76359   SELECT _newCheckid, checkitem_amount, checkitem_discount,
76360          checkitem_ponumber, checkitem_vouchernumber, checkitem_invcnumber,
76361          checkitem_apopen_id, checkitem_aropen_id,
76362          checkitem_docdate, checkitem_curr_id, checkitem_curr_rate
76363   FROM checkitem
76364   WHERE (checkitem_checkhead_id=pCheckid);
76365
76366   UPDATE checkhead
76367   SET checkhead_replaced=TRUE
76368   WHERE (checkhead_id=pCheckid);
76369
76370   RETURN _newCheckid;
76371
76372 END;
76373 $_$;
76374
76375
76376 ALTER FUNCTION public.replacevoidedcheck(integer) OWNER TO admin;
76377
76378 --
76379 -- TOC entry 2111 (class 1255 OID 146566957)
76380 -- Dependencies: 4536 8
76381 -- Name: reprioritizewo(integer, integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
76382 --
76383
76384 CREATE FUNCTION reprioritizewo(integer, integer, boolean) RETURNS integer
76385     LANGUAGE plpgsql
76386     AS $_$
76387 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76388 -- See www.xtuple.com/CPAL for the full text of the software license.
76389 DECLARE
76390   pWoid ALIAS FOR $1;
76391   pPriority ALIAS FOR $2;
76392   pChangeChildren ALIAS FOR $3;
76393   _status CHAR(1);
76394   _result INTEGER;
76395
76396 BEGIN
76397
76398   SELECT wo_status INTO _status
76399   FROM wo
76400   WHERE (wo_id=pWoid);
76401
76402   IF (NOT (_status IN ('O', 'E','R','I'))) THEN
76403     return -1;
76404   END IF;
76405
76406   UPDATE wo
76407   SET wo_priority=pPriority
76408   WHERE (wo_id=pWoid);
76409
76410   IF ( (_status IN ('E','R','I')) AND (pChangeChildren) ) THEN
76411     SELECT COALESCE(MIN(reprioritizeWo(wo_id, pPriority, TRUE)), 1) INTO _result
76412     FROM wo
76413     WHERE ( (wo_ordtype='W')
76414      AND (wo_ordid=pWoid) );
76415   ELSE
76416     _result = 1;
76417   END IF;
76418
76419   RETURN _result;
76420
76421 END;
76422 $_$;
76423
76424
76425 ALTER FUNCTION public.reprioritizewo(integer, integer, boolean) OWNER TO admin;
76426
76427 --
76428 -- TOC entry 2113 (class 1255 OID 146566959)
76429 -- Dependencies: 4536 8
76430 -- Name: resetdbobjperms(); Type: FUNCTION; Schema: public; Owner: admin
76431 --
76432
76433 CREATE FUNCTION resetdbobjperms() RETURNS integer
76434     LANGUAGE plpgsql
76435     AS $$
76436 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76437 -- See www.xtuple.com/CPAL for the full text of the software license.
76438 DECLARE
76439   _count        INTEGER := 0;
76440 BEGIN
76441   SELECT SUM(resetDBObjPerms(nspname || '.' || relname)) INTO _count
76442   FROM pg_catalog.pg_class, pg_catalog.pg_namespace
76443   WHERE (relkind IN ('r', 'S', 'v')
76444     AND  (relnamespace=pg_namespace.oid)
76445     AND  (nspname IN ('public', 'api')));
76446
76447   RETURN _count;
76448 END;
76449 $$;
76450
76451
76452 ALTER FUNCTION public.resetdbobjperms() OWNER TO admin;
76453
76454 --
76455 -- TOC entry 2112 (class 1255 OID 146566958)
76456 -- Dependencies: 4536 8
76457 -- Name: resetdbobjperms(text); Type: FUNCTION; Schema: public; Owner: admin
76458 --
76459
76460 CREATE FUNCTION resetdbobjperms(text) RETURNS integer
76461     LANGUAGE plpgsql
76462     AS $_$
76463 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76464 -- See www.xtuple.com/CPAL for the full text of the software license.
76465 DECLARE
76466   pObjname      ALIAS FOR $1;
76467 BEGIN
76468   EXECUTE 'ALTER TABLE '   || pObjname || ' OWNER TO ' || getEffectiveXtUser() || ';';
76469   EXECUTE 'REVOKE ALL ON ' || pObjname || ' FROM PUBLIC;';
76470   EXECUTE 'GRANT  ALL ON ' || pObjname || ' TO GROUP xtrole;';
76471   RETURN 1;
76472 END;
76473 $_$;
76474
76475
76476 ALTER FUNCTION public.resetdbobjperms(text) OWNER TO admin;
76477
76478 --
76479 -- TOC entry 2115 (class 1255 OID 146566960)
76480 -- Dependencies: 4536 8
76481 -- Name: resetlowlevelcode(integer); Type: FUNCTION; Schema: public; Owner: admin
76482 --
76483
76484 CREATE FUNCTION resetlowlevelcode(integer) RETURNS integer
76485     LANGUAGE plpgsql
76486     AS $_$
76487 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76488 -- See www.xtuple.com/CPAL for the full text of the software license.
76489 DECLARE
76490
76491     pItemId ALIAS FOR $1;
76492     _result     INTEGER;
76493     _counterNum INTEGER := 1;
76494     _feedBackNum INTEGER := 1;
76495     _r                  RECORD;
76496
76497 BEGIN
76498     DELETE FROM costUpdate;
76499
76500     IF pItemId = -1 THEN        -- -1 is an invalid item_id => do them all
76501         INSERT INTO costUpdate ( costUpdate_item_id, costUpdate_item_type )
76502                         SELECT item_id, item_type
76503                         FROM   item;
76504
76505         -- Recalculate the Item Lowlevel codes
76506         WHILE _feedBackNum > 0 LOOP
76507             SELECT updateLowlevel(_counterNum) INTO _feedBackNum;
76508             _counterNum := _counterNum + 1;
76509         END LOOP;
76510
76511     ELSE
76512         INSERT INTO costUpdate ( costUpdate_item_id, costUpdate_item_type )
76513                         SELECT item_id, item_type
76514                         FROM   item
76515                         WHERE (item_id=pItemId);
76516       FOR _r IN SELECT item_id, bomdata_bomwork_level, item_type
76517                 FROM item,
76518                      indentedBOM(pItemId, getActiveRevId('BOM',pItemId),0,0)
76519                 WHERE (bomdata_item_id=item_id)
76520                 ORDER BY bomdata_bomwork_level LOOP
76521
76522         -- this only works because of the ORDER BY in the loop SELECT
76523         UPDATE costUpdate
76524         SET costupdate_lowlevel_code = _r.bomdata_bomwork_level
76525         WHERE (costupdate_item_id=_r.item_id);
76526
76527         IF (NOT FOUND) THEN
76528           INSERT INTO costUpdate (
76529             costUpdate_item_id, costUpdate_lowlevel_code, costUpdate_item_type
76530           ) VALUES (
76531             _r.item_id, _r.bomdata_bomwork_level, _r.item_type
76532           );
76533         END IF;
76534       END LOOP;
76535
76536     END IF;
76537
76538     SELECT count(*) INTO _result
76539     FROM costUpdate;
76540
76541     RETURN _result;
76542
76543 END;
76544 $_$;
76545
76546
76547 ALTER FUNCTION public.resetlowlevelcode(integer) OWNER TO admin;
76548
76549 --
76550 -- TOC entry 2116 (class 1255 OID 146566961)
76551 -- Dependencies: 4536 8
76552 -- Name: resetqohbalance(integer); Type: FUNCTION; Schema: public; Owner: admin
76553 --
76554
76555 CREATE FUNCTION resetqohbalance(integer) RETURNS integer
76556     LANGUAGE plpgsql
76557     AS $_$
76558 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76559 -- See www.xtuple.com/CPAL for the full text of the software license.
76560 BEGIN
76561   RETURN resetQOHBalance($1, CURRENT_TIMESTAMP);
76562 END;
76563 $_$;
76564
76565
76566 ALTER FUNCTION public.resetqohbalance(integer) OWNER TO admin;
76567
76568 --
76569 -- TOC entry 2117 (class 1255 OID 146566962)
76570 -- Dependencies: 4536 8
76571 -- Name: resetqohbalance(integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
76572 --
76573
76574 CREATE FUNCTION resetqohbalance(integer, timestamp with time zone) RETURNS integer
76575     LANGUAGE plpgsql
76576     AS $_$
76577 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76578 -- See www.xtuple.com/CPAL for the full text of the software license.
76579 DECLARE
76580   pItemsiteid   ALIAS FOR $1;
76581   pGlDistTS     ALIAS FOR $2;
76582   _invhistid    INTEGER;
76583   _itemlocSeries INTEGER;
76584
76585 BEGIN
76586
76587   IF ( ( SELECT ( (itemsite_controlmethod IN ('L', 'S')) OR
76588                   (item_type = 'R') OR
76589                   (itemsite_costmethod = 'J') OR
76590                   (itemsite_loccntrl) OR
76591                   (itemsite_qtyonhand > 0) )
76592          FROM itemsite, item
76593          WHERE ( (itemsite_item_id=item_id)
76594           AND (itemsite_id=pItemsiteid) ) ) ) THEN
76595     RETURN 0;
76596   END IF;
76597
76598   _itemlocSeries := NEXTVAL('itemloc_series_seq');
76599
76600   SELECT postInvTrans( itemsite_id, 'AD', (itemsite_qtyonhand * -1),
76601                        'I/M', '', '', 'RESET',
76602                        'Reset QOH Balance to 0',
76603                        costcat_asset_accnt_id, costcat_adjustment_accnt_id,
76604                        _itemlocSeries, pGlDistTS ) INTO _invhistid
76605   FROM itemsite, costcat
76606   WHERE ( (itemsite_costcat_id=costcat_id)
76607    AND (itemsite_id=pItemsiteid) );
76608
76609   PERFORM postItemLocSeries(_itemlocSeries);
76610
76611   RETURN _invhistid;
76612
76613 END;
76614 $_$;
76615
76616
76617 ALTER FUNCTION public.resetqohbalance(integer, timestamp with time zone) OWNER TO admin;
76618
76619 --
76620 -- TOC entry 2118 (class 1255 OID 146566963)
76621 -- Dependencies: 4536 8
76622 -- Name: resolvecosaccount(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76623 --
76624
76625 CREATE FUNCTION resolvecosaccount(integer, integer) RETURNS integer
76626     LANGUAGE plpgsql STABLE
76627     AS $_$
76628 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76629 -- See www.xtuple.com/CPAL for the full text of the software license.
76630 BEGIN
76631
76632   RETURN resolveCOSAccount($1, $2, -1, -1);
76633
76634 END;
76635 $_$;
76636
76637
76638 ALTER FUNCTION public.resolvecosaccount(integer, integer) OWNER TO admin;
76639
76640 --
76641 -- TOC entry 2119 (class 1255 OID 146566964)
76642 -- Dependencies: 4536 8
76643 -- Name: resolvecosaccount(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76644 --
76645
76646 CREATE FUNCTION resolvecosaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) RETURNS integer
76647     LANGUAGE plpgsql STABLE
76648     AS $$
76649 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76650 -- See www.xtuple.com/CPAL for the full text of the software license.
76651 DECLARE
76652   _salesaccntid INTEGER;
76653   _accntid INTEGER;
76654
76655 BEGIN
76656
76657   SELECT findSalesAccnt(pItemsiteid, 'IS', pCustid, pSaletypeid, pShipzoneid) INTO _salesaccntid;
76658   IF (_salesaccntid = -1) THEN
76659     SELECT getUnassignedAccntId() INTO _accntid;
76660   ELSE
76661     SELECT salesaccnt_cos_accnt_id INTO _accntid
76662     FROM salesaccnt
76663     WHERE (salesaccnt_id=_salesaccntid);
76664   END IF;
76665
76666   RETURN _accntid;
76667
76668 END;
76669 $$;
76670
76671
76672 ALTER FUNCTION public.resolvecosaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) OWNER TO admin;
76673
76674 --
76675 -- TOC entry 2120 (class 1255 OID 146566965)
76676 -- Dependencies: 4536 8
76677 -- Name: resolvecowaccount(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76678 --
76679
76680 CREATE FUNCTION resolvecowaccount(integer, integer) RETURNS integer
76681     LANGUAGE plpgsql STABLE
76682     AS $_$
76683 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76684 -- See www.xtuple.com/CPAL for the full text of the software license.
76685 BEGIN
76686
76687   RETURN resolveCOWAccount($1, $2, -1, -1);
76688
76689 END;
76690 $_$;
76691
76692
76693 ALTER FUNCTION public.resolvecowaccount(integer, integer) OWNER TO admin;
76694
76695 --
76696 -- TOC entry 2121 (class 1255 OID 146566966)
76697 -- Dependencies: 4536 8
76698 -- Name: resolvecowaccount(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76699 --
76700
76701 CREATE FUNCTION resolvecowaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) RETURNS integer
76702     LANGUAGE plpgsql
76703     AS $$
76704 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76705 -- See www.xtuple.com/CPAL for the full text of the software license.
76706 DECLARE
76707   _salesaccntid INTEGER;
76708   _accntid INTEGER;
76709
76710 BEGIN
76711
76712   SELECT findSalesAccnt(pItemsiteid, 'IS', pCustid, pSaletypeid, pShipzoneid) INTO _salesaccntid;
76713   IF (_salesaccntid = -1) THEN
76714     SELECT getUnassignedAccntId() INTO _accntid;
76715   ELSE
76716     SELECT salesaccnt_cow_accnt_id INTO _accntid
76717     FROM salesaccnt
76718     WHERE (salesaccnt_id=_salesaccntid);
76719   END IF;
76720
76721   RETURN _accntid;
76722
76723 END;
76724 $$;
76725
76726
76727 ALTER FUNCTION public.resolvecowaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) OWNER TO admin;
76728
76729 --
76730 -- TOC entry 2122 (class 1255 OID 146566967)
76731 -- Dependencies: 4536 8
76732 -- Name: resolvecreditaccount(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76733 --
76734
76735 CREATE FUNCTION resolvecreditaccount(integer, integer) RETURNS integer
76736     LANGUAGE plpgsql STABLE
76737     AS $_$
76738 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76739 -- See www.xtuple.com/CPAL for the full text of the software license.
76740 BEGIN
76741
76742   RETURN resolveCreditAccount($1, $2, -1, -1);
76743
76744 END;
76745 $_$;
76746
76747
76748 ALTER FUNCTION public.resolvecreditaccount(integer, integer) OWNER TO admin;
76749
76750 --
76751 -- TOC entry 2123 (class 1255 OID 146566968)
76752 -- Dependencies: 4536 8
76753 -- Name: resolvecreditaccount(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76754 --
76755
76756 CREATE FUNCTION resolvecreditaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) RETURNS integer
76757     LANGUAGE plpgsql
76758     AS $$
76759 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76760 -- See www.xtuple.com/CPAL for the full text of the software license.
76761 DECLARE
76762   _salesaccntid INTEGER;
76763   _accntid INTEGER;
76764
76765 BEGIN
76766
76767   SELECT findSalesAccnt(pItemsiteid, 'IS', pCustid, pSaletypeid, pShipzoneid) INTO _salesaccntid;
76768   IF (_salesaccntid = -1) THEN
76769     SELECT getUnassignedAccntId() INTO _accntid;
76770   ELSE
76771     SELECT salesaccnt_credit_accnt_id INTO _accntid
76772     FROM salesaccnt
76773     WHERE (salesaccnt_id=_salesaccntid);
76774   END IF;
76775
76776   RETURN _accntid;
76777
76778 END;
76779 $$;
76780
76781
76782 ALTER FUNCTION public.resolvecreditaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) OWNER TO admin;
76783
76784 --
76785 -- TOC entry 2124 (class 1255 OID 146566969)
76786 -- Dependencies: 4536 8
76787 -- Name: resolvesalesaccount(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76788 --
76789
76790 CREATE FUNCTION resolvesalesaccount(integer, integer) RETURNS integer
76791     LANGUAGE plpgsql STABLE
76792     AS $_$
76793 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76794 -- See www.xtuple.com/CPAL for the full text of the software license.
76795 BEGIN
76796
76797   RETURN resolveSalesAccount($1, $2, -1, -1);
76798
76799 END;
76800 $_$;
76801
76802
76803 ALTER FUNCTION public.resolvesalesaccount(integer, integer) OWNER TO admin;
76804
76805 --
76806 -- TOC entry 2126 (class 1255 OID 146566970)
76807 -- Dependencies: 4536 8
76808 -- Name: resolvesalesaccount(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
76809 --
76810
76811 CREATE FUNCTION resolvesalesaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) RETURNS integer
76812     LANGUAGE plpgsql
76813     AS $$
76814 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76815 -- See www.xtuple.com/CPAL for the full text of the software license.
76816 DECLARE
76817   _salesaccntid INTEGER;
76818   _accntid INTEGER;
76819
76820 BEGIN
76821
76822   SELECT findSalesAccnt(pItemsiteid, 'IS', pCustid, pSaletypeid, pShipzoneid) INTO _salesaccntid;
76823   IF (_salesaccntid = -1) THEN
76824     SELECT getUnassignedAccntId() INTO _accntid;
76825   ELSE
76826     SELECT salesaccnt_sales_accnt_id INTO _accntid
76827     FROM salesaccnt
76828     WHERE (salesaccnt_id=_salesaccntid);
76829   END IF;
76830
76831   RETURN _accntid;
76832
76833 END;
76834 $$;
76835
76836
76837 ALTER FUNCTION public.resolvesalesaccount(pitemsiteid integer, pcustid integer, psaletypeid integer, pshipzoneid integer) OWNER TO admin;
76838
76839 --
76840 -- TOC entry 2127 (class 1255 OID 146566971)
76841 -- Dependencies: 4536 8
76842 -- Name: restoresaleshistory(integer); Type: FUNCTION; Schema: public; Owner: admin
76843 --
76844
76845 CREATE FUNCTION restoresaleshistory(integer) RETURNS integer
76846     LANGUAGE plpgsql
76847     AS $_$
76848 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76849 -- See www.xtuple.com/CPAL for the full text of the software license.
76850 DECLARE
76851   pAsohistid ALIAS FOR $1;
76852
76853 BEGIN
76854
76855   INSERT INTO cohist ( cohist_id,
76856                        cohist_cust_id,
76857                        cohist_itemsite_id,
76858                        cohist_shipdate,
76859                        cohist_invcdate,
76860                        cohist_duedate,
76861                        cohist_promisedate,
76862                        cohist_ordernumber,
76863                        cohist_invcnumber,
76864                        cohist_qtyshipped,
76865                        cohist_unitprice,
76866                        cohist_unitcost,
76867                        cohist_billtoname,
76868                        cohist_billtoaddress1,
76869                        cohist_billtoaddress2,
76870                        cohist_billtoaddress3,
76871                        cohist_billtocity,
76872                        cohist_billtostate,
76873                        cohist_billtozip,
76874                        cohist_shiptoname,
76875                        cohist_shiptoaddress1,
76876                        cohist_shiptoaddress2,
76877                        cohist_shiptoaddress3,
76878                        cohist_shiptocity,
76879                        cohist_shiptostate,
76880                        cohist_shiptozip,
76881                        cohist_shipto_id,
76882                        cohist_shipvia,
76883                        cohist_salesrep_id,
76884                        cohist_misc_type,
76885                        cohist_misc_descrip,
76886                        cohist_misc_id,
76887                        cohist_commission,
76888                        cohist_commissionpaid,
76889                        cohist_doctype,
76890                        cohist_orderdate,
76891                        cohist_imported,
76892                        cohist_ponumber,
76893                        cohist_curr_id,
76894                        cohist_taxtype_id,
76895                        cohist_taxzone_id )
76896   SELECT asohist_id,
76897          CASE asohist_cust_id WHEN -1 THEN NULL ELSE asohist_cust_id END,
76898          asohist_itemsite_id,
76899          asohist_shipdate,
76900          asohist_invcdate,
76901          asohist_duedate,
76902          asohist_promisedate,
76903          asohist_ordernumber,
76904          asohist_invcnumber,
76905          asohist_qtyshipped,
76906          asohist_unitprice,
76907          asohist_unitcost,
76908          asohist_billtoname,
76909          asohist_billtoaddress1,
76910          asohist_billtoaddress2,
76911          asohist_billtoaddress3,
76912          asohist_billtocity,
76913          asohist_billtostate,
76914          asohist_billtozip,
76915          asohist_shiptoname,
76916          asohist_shiptoaddress1,
76917          asohist_shiptoaddress2,
76918          asohist_shiptoaddress3,
76919          asohist_shiptocity,
76920          asohist_shiptostate,
76921          asohist_shiptozip,
76922          asohist_shipto_id,
76923          asohist_shipvia,
76924          CASE asohist_salesrep_id WHEN -1 THEN NULL ELSE asohist_salesrep_id END,
76925          asohist_misc_type,
76926          asohist_misc_descrip,
76927          asohist_misc_id,
76928          asohist_commission,
76929          asohist_commissionpaid,
76930          asohist_doctype,
76931          asohist_orderdate,
76932          asohist_imported,
76933          asohist_ponumber,
76934          asohist_curr_id,
76935          asohist_taxtype_id,
76936          asohist_taxzone_id
76937   FROM asohist
76938   WHERE (asohist_id=pAsohistid);
76939
76940   INSERT INTO cohisttax ( taxhist_id,
76941                           taxhist_parent_id,
76942                           taxhist_taxtype_id,
76943                           taxhist_tax_id,
76944                           taxhist_basis,
76945                           taxhist_basis_tax_id,
76946                           taxhist_sequence,
76947                           taxhist_percent,
76948                           taxhist_amount,
76949                           taxhist_tax,
76950                           taxhist_docdate,
76951                           taxhist_distdate,
76952                           taxhist_curr_id,
76953                           taxhist_curr_rate,
76954                           taxhist_journalnumber )
76955   SELECT taxhist_id,
76956          taxhist_parent_id,
76957          taxhist_taxtype_id,
76958          taxhist_tax_id,
76959          taxhist_basis,
76960          taxhist_basis_tax_id,
76961          taxhist_sequence,
76962          taxhist_percent,
76963          taxhist_amount,
76964          taxhist_tax,
76965          taxhist_docdate,
76966          taxhist_distdate,
76967          taxhist_curr_id,
76968          taxhist_curr_rate,
76969          taxhist_journalnumber
76970   FROM asohisttax
76971   WHERE (taxhist_parent_id=pAsohistid);
76972
76973   DELETE FROM asohisttax
76974   WHERE (taxhist_parent_id=pAsohistid);
76975
76976   DELETE FROM asohist
76977   WHERE (asohist_id=pAsohistid);
76978
76979   RETURN pAsohistid;
76980
76981 END;
76982 $_$;
76983
76984
76985 ALTER FUNCTION public.restoresaleshistory(integer) OWNER TO admin;
76986
76987 --
76988 -- TOC entry 2128 (class 1255 OID 146566972)
76989 -- Dependencies: 4536 8
76990 -- Name: returncompleteshipment(integer); Type: FUNCTION; Schema: public; Owner: admin
76991 --
76992
76993 CREATE FUNCTION returncompleteshipment(integer) RETURNS integer
76994     LANGUAGE plpgsql
76995     AS $_$
76996 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
76997 -- See www.xtuple.com/CPAL for the full text of the software license.
76998 BEGIN
76999   RETURN returnCompleteShipment($1, 0, CURRENT_TIMESTAMP);
77000 END;
77001 $_$;
77002
77003
77004 ALTER FUNCTION public.returncompleteshipment(integer) OWNER TO admin;
77005
77006 --
77007 -- TOC entry 2129 (class 1255 OID 146566973)
77008 -- Dependencies: 4536 8
77009 -- Name: returncompleteshipment(integer, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
77010 --
77011
77012 CREATE FUNCTION returncompleteshipment(integer, integer, timestamp with time zone) RETURNS integer
77013     LANGUAGE plpgsql
77014     AS $_$
77015 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77016 -- See www.xtuple.com/CPAL for the full text of the software license.
77017 DECLARE
77018   pshipheadid           ALIAS FOR $1;
77019   _itemlocSeries        INTEGER := $2;
77020   _timestamp            TIMESTAMP WITH TIME ZONE := $3;
77021   _r RECORD;
77022   _result               RECORD;
77023   _shiphead_number      TEXT := '';
77024   _count                INTEGER := 0;
77025   _countsum             INTEGER := 0;
77026
77027 BEGIN
77028   FOR _r IN SELECT shipitem_id
77029             FROM shipitem, shiphead
77030             WHERE ( (shipitem_shiphead_id=shiphead_id)
77031              AND (NOT shiphead_shipped)
77032              AND (shiphead_id=pshipheadid) ) LOOP
77033     _itemlocSeries := returnShipmentTransaction(_r.shipitem_id, _itemlocSeries, _timestamp);
77034   END LOOP;
77035
77036   FOR _result IN SELECT shiphead_number
77037                    FROM shiphead
77038                   WHERE ( (shiphead_id=pshipheadid) ) LOOP
77039     _shiphead_number := _result.shiphead_number;
77040   END LOOP;
77041
77042   SELECT COUNT(*) INTO _count
77043     FROM shipdata
77044    WHERE(shipdata_shiphead_number=_shiphead_number);
77045
77046   SELECT COUNT(*) INTO _countsum
77047     FROM shipdatasum
77048    WHERE(shipdatasum_shiphead_number=_shiphead_number);
77049
77050   IF (_count > 0) THEN
77051     DELETE FROM shipdata
77052      WHERE(shipdata_shiphead_number=_shiphead_number);
77053   END IF;
77054   IF (_countsum > 0) THEN
77055     DELETE FROM shipdatasum
77056      WHERE(shipdatasum_shiphead_number=_shiphead_number);
77057   END IF;
77058
77059   DELETE FROM pack
77060    WHERE(pack_shiphead_id=pshipheadid);
77061   DELETE FROM shiphead
77062   WHERE (shiphead_id=pshipheadid);
77063
77064   RETURN _itemlocSeries;
77065
77066 END;
77067 $_$;
77068
77069
77070 ALTER FUNCTION public.returncompleteshipment(integer, integer, timestamp with time zone) OWNER TO admin;
77071
77072 --
77073 -- TOC entry 2131 (class 1255 OID 146566975)
77074 -- Dependencies: 4536 8
77075 -- Name: returnitemshipments(integer); Type: FUNCTION; Schema: public; Owner: admin
77076 --
77077
77078 CREATE FUNCTION returnitemshipments(integer) RETURNS integer
77079     LANGUAGE plpgsql
77080     AS $_$
77081 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77082 -- See www.xtuple.com/CPAL for the full text of the software license.
77083 BEGIN
77084   RETURN returnItemShipments('SO', $1, 0, CURRENT_TIMESTAMP);
77085 END;
77086 $_$;
77087
77088
77089 ALTER FUNCTION public.returnitemshipments(integer) OWNER TO admin;
77090
77091 --
77092 -- TOC entry 2130 (class 1255 OID 146566974)
77093 -- Dependencies: 4536 8
77094 -- Name: returnitemshipments(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
77095 --
77096
77097 CREATE FUNCTION returnitemshipments(integer, integer) RETURNS integer
77098     LANGUAGE plpgsql
77099     AS $_$
77100 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77101 -- See www.xtuple.com/CPAL for the full text of the software license.
77102 BEGIN
77103   RETURN returnItemShipments('SO', $1, $2, CURRENT_TIMESTAMP);
77104 END;
77105 $_$;
77106
77107
77108 ALTER FUNCTION public.returnitemshipments(integer, integer) OWNER TO admin;
77109
77110 --
77111 -- TOC entry 2132 (class 1255 OID 146566976)
77112 -- Dependencies: 4536 8
77113 -- Name: returnitemshipments(text, integer, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
77114 --
77115
77116 CREATE FUNCTION returnitemshipments(text, integer, integer, timestamp with time zone) RETURNS integer
77117     LANGUAGE plpgsql
77118     AS $_$
77119 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77120 -- See www.xtuple.com/CPAL for the full text of the software license.
77121 DECLARE
77122   pordertype            ALIAS FOR $1;
77123   pitemid               ALIAS FOR $2;
77124   _itemlocSeries        INTEGER                         := $3;
77125   _timestamp            TIMESTAMP WITH TIME ZONE        := $4;
77126   _invhistid INTEGER;
77127   _r RECORD;
77128
77129 BEGIN
77130
77131   IF (COALESCE(_itemlocSeries,0) = 0 ) THEN
77132     _itemlocSeries := NEXTVAL('itemloc_series_seq');
77133   END IF;
77134
77135   FOR _r IN 
77136     SELECT shipitem_id
77137     FROM shipitem
77138       JOIN shiphead ON (shiphead_id=shipitem_shiphead_id)
77139     WHERE ((NOT shiphead_shipped)
77140       AND  (shiphead_order_type=pordertype)
77141       AND  (shipitem_orderitem_id=pitemid))
77142   LOOP
77143
77144     SELECT returnShipmentTransaction(_r.shipitem_id, _itemlocSeries, _timestamp) INTO _itemlocSeries;
77145
77146     IF (_itemlocSeries < 0) THEN
77147       RETURN _itemlocSeries;
77148     END IF;
77149
77150   END LOOP;
77151
77152   RETURN _itemlocSeries;
77153
77154 END;
77155 $_$;
77156
77157
77158 ALTER FUNCTION public.returnitemshipments(text, integer, integer, timestamp with time zone) OWNER TO admin;
77159
77160 --
77161 -- TOC entry 2133 (class 1255 OID 146566977)
77162 -- Dependencies: 4536 8
77163 -- Name: returnshipmenttransaction(integer); Type: FUNCTION; Schema: public; Owner: admin
77164 --
77165
77166 CREATE FUNCTION returnshipmenttransaction(integer) RETURNS integer
77167     LANGUAGE plpgsql
77168     AS $_$
77169 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77170 -- See www.xtuple.com/CPAL for the full text of the software license.
77171 BEGIN
77172   RETURN returnShipmentTransaction($1, 0, CURRENT_TIMESTAMP);
77173 END;
77174 $_$;
77175
77176
77177 ALTER FUNCTION public.returnshipmenttransaction(integer) OWNER TO admin;
77178
77179 --
77180 -- TOC entry 2134 (class 1255 OID 146566978)
77181 -- Dependencies: 4536 8
77182 -- Name: returnshipmenttransaction(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
77183 --
77184
77185 CREATE FUNCTION returnshipmenttransaction(integer, integer) RETURNS integer
77186     LANGUAGE plpgsql
77187     AS $_$
77188 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77189 -- See www.xtuple.com/CPAL for the full text of the software license.
77190 BEGIN
77191   RETURN returnShipmentTransaction($1, $2, CURRENT_TIMESTAMP);
77192 END;
77193 $_$;
77194
77195
77196 ALTER FUNCTION public.returnshipmenttransaction(integer, integer) OWNER TO admin;
77197
77198 --
77199 -- TOC entry 2135 (class 1255 OID 146566979)
77200 -- Dependencies: 4536 8
77201 -- Name: returnshipmenttransaction(integer, integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
77202 --
77203
77204 CREATE FUNCTION returnshipmenttransaction(integer, integer, timestamp with time zone) RETURNS integer
77205     LANGUAGE plpgsql
77206     AS $_$
77207 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77208 -- See www.xtuple.com/CPAL for the full text of the software license.
77209 DECLARE
77210   pShipitemId           ALIAS FOR $1;
77211   pItemlocSeries        ALIAS FOR $2;
77212   pTimestamp            ALIAS FOR $3;
77213   _itemlocSeries        INTEGER;
77214   _invhistid            INTEGER;
77215   _reserveid            INTEGER;
77216   _coheadid             INTEGER;
77217   _rows                 INTEGER;
77218   _r                    RECORD;
77219   _rsrv                 RECORD;
77220
77221 BEGIN
77222
77223     IF (COALESCE(pItemlocSeries, 0) = 0 ) THEN
77224       _itemlocSeries := NEXTVAL('itemloc_series_seq');
77225     ELSE
77226       _itemlocSeries := pItemlocSeries;
77227     END IF;
77228   
77229     -- Find the shipment transaction record
77230     SELECT shipitem.*,
77231            shiphead_id, shiphead_number, shiphead_order_type, invhist_series,
77232            itemsite_loccntrl, itemsite_costmethod, itemsite_controlmethod,
77233            cohead_prj_id AS prj_id     
77234       INTO _r
77235     FROM shipitem
77236       JOIN shiphead ON (shiphead_id=shipitem_shiphead_id)
77237       JOIN invhist ON (invhist_id=shipitem_invhist_id)
77238       JOIN itemsite ON (itemsite_id=invhist_itemsite_id)
77239       LEFT OUTER JOIN cohead ON ((shiphead_order_type = 'SO') AND (shiphead_order_id = cohead_id))
77240     WHERE ((NOT shiphead_shipped)
77241       AND  (shipitem_id=pShipitemId));
77242       
77243     GET DIAGNOSTICS _rows = ROW_COUNT;
77244     IF (_rows = 0 ) THEN
77245       -- Was it a non-controlled sales order item?
77246       SELECT shipitem.*,
77247              shiphead_id, shiphead_number, shiphead_order_type,
77248              itemsite_loccntrl, itemsite_costmethod, itemsite_controlmethod,
77249              cohead_prj_id AS prj_id
77250       INTO _r
77251       FROM shipitem
77252         JOIN shiphead ON (shiphead_id=shipitem_shiphead_id)
77253         JOIN coitem ON (shipitem_orderitem_id=coitem_id)
77254         JOIN cohead ON (cohead_id=coitem_cohead_id)
77255         JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
77256       WHERE ((NOT shiphead_shipped)
77257         AND  (shipitem_id=pShipitemId)
77258         AND  (shiphead_order_type = 'SO'));
77259     END IF;
77260     
77261     GET DIAGNOSTICS _rows = ROW_COUNT;
77262     IF (_rows = 0 AND fetchmetricbool('MultiWhs') ) THEN
77263       -- Was it a non-controlled transfer order item?
77264       SELECT shipitem.*,
77265              shiphead_id, shiphead_number, shiphead_order_type,
77266              itemsite_loccntrl, itemsite_costmethod, itemsite_controlmethod,
77267              NULL AS prj_id
77268       INTO _r
77269       FROM shipitem
77270         JOIN shiphead ON (shiphead_id=shipitem_shiphead_id)
77271         JOIN toitem ON (shipitem_orderitem_id=toitem_id)
77272         JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
77273       WHERE ((NOT shiphead_shipped)
77274         AND  (shipitem_id=pShipitemId)
77275         AND  (shiphead_order_type = 'TO'));
77276     END IF;
77277     
77278     IF (_rows > 0 ) THEN  
77279       IF (_r.shiphead_order_type = 'SO') THEN
77280         -- Handle inventory transaction
77281         IF (_r.itemsite_controlmethod != 'N' OR _r.itemsite_costmethod = 'J') THEN
77282           SELECT postInvTrans( itemsite_id, 'RS', (_r.shipitem_qty * coitem_qty_invuomratio),
77283                                'S/R', _r.shiphead_order_type, formatSoNumber(_r.shipitem_orderitem_id),
77284                                shiphead_number, 'Return from Shipping',
77285                                costcat_asset_accnt_id, getPrjAccntId(_r.prj_id, costcat_shipasset_accnt_id),
77286                                _itemlocSeries, pTimestamp, _r.shipitem_value, _r.shipitem_invhist_id ) INTO _invhistid
77287           FROM coitem, itemsite, costcat, shiphead, shipitem
77288           WHERE ((coitem_itemsite_id=itemsite_id)
77289             AND  (itemsite_costcat_id=costcat_id)
77290             AND  (coitem_id=_r.shipitem_orderitem_id)
77291             AND  (shiphead_order_type=_r.shiphead_order_type)
77292             AND  (shiphead_id=shipitem_shiphead_id)
77293             AND  (shipitem_orderitem_id=_r.shipitem_orderitem_id));
77294  
77295           -- We know the distribution so post this through so the any w/o activity knows about it
77296           PERFORM postItemlocseries(_itemlocSeries);
77297         END IF;
77298  
77299         IF (_r.itemsite_costmethod = 'J') THEN   
77300           -- Reopen the work order
77301           UPDATE wo SET wo_status = 'I' WHERE ((wo_ordtype='S') AND (wo_ordid=_r.shipitem_orderitem_id));
77302           
77303           --  Job cost, so correct Production Posting referencing original receipt for reverse info.
77304           PERFORM correctProduction(wo_id, invhist_invqty, false, _itemlocSeries, pTimestamp, invhist_id)
77305           FROM wo, invhist
77306           WHERE ((wo_ordtype = 'S')
77307             AND  (wo_ordid = _r.shipitem_orderitem_id) 
77308             AND  (invhist_series=_r.invhist_series)
77309             AND  (invhist_transtype='RM'));
77310              
77311           --  Return eligble material
77312           PERFORM returnWoMaterial(womatlpost_womatl_id, _itemlocSeries, pTimestamp, womatlpost_invhist_id)
77313           FROM womatlpost, invhist m, invhist s 
77314           WHERE ((womatlpost_invhist_id=m.invhist_id)
77315             AND  (m.invhist_series=s.invhist_series)
77316             AND  (m.invhist_transtype='IM')
77317             AND  (s.invhist_id=_r.shipitem_invhist_id));
77318
77319         END IF; -- end Job Costing
77320
77321       ELSIF (_r.shiphead_order_type = 'TO') THEN
77322         SELECT postInvTrans(itemsite_id, 'RS', _r.shipitem_qty,
77323                             'S/R', _r.shiphead_order_type, formatToNumber(toitem_id),
77324                             tohead_number, 'Return from Shipping',
77325                             costcat_asset_accnt_id, costcat_shipasset_accnt_id,
77326                             _itemlocSeries, pTimestamp, _r.shipitem_value, _r.shipitem_invhist_id ) INTO _invhistid
77327         FROM toitem, tohead, itemsite, costcat
77328         WHERE ((toitem_item_id=itemsite_item_id)
77329           AND  (toitem_tohead_id=tohead_id)
77330           AND  (tohead_src_warehous_id=itemsite_warehous_id)
77331           AND  (itemsite_costcat_id=costcat_id)
77332           AND  (toitem_id=_r.shipitem_orderitem_id));
77333
77334       ELSE
77335         -- Don't know what kind of order this is
77336         RETURN -11;
77337       END IF;
77338
77339       UPDATE shiphead
77340       SET shiphead_sfstatus='D'
77341       WHERE ((shiphead_id=_r.shiphead_id)
77342         AND  (shiphead_sfstatus='P'));
77343
77344        -- Handle reservation if applicable
77345       IF (fetchmetricbool('EnableSOReservations')) THEN
77346         UPDATE coitem
77347           SET coitem_qtyreserved = (coitem_qtyreserved + shipitemrsrv_qty)
77348         FROM shipitemrsrv
77349         WHERE ((coitem_id=_r.shipitem_orderitem_id)
77350           AND  (shipitemrsrv_shipitem_id=_r.shipitem_id));
77351
77352         -- Handle location reservations if applicable
77353         FOR _rsrv IN
77354           SELECT *
77355           FROM shipitemlocrsrv
77356           WHERE (shipitemlocrsrv_shipitem_id=_r.shipitem_id)
77357         LOOP
77358           -- See if a reservation record still exists
77359           SELECT reserve_id INTO _reserveid
77360           FROM reserve JOIN itemloc ON (reserve_supply_id=itemloc_id)
77361           WHERE ((reserve_supply_type='I')
77362             AND  (reserve_demand_type = 'SO')
77363             AND  (reserve_demand_id = _r.shipitem_orderitem_id )
77364             AND  (itemloc_itemsite_id=_rsrv.shipitemlocrsrv_itemsite_id)
77365             AND  (itemloc_location_id=_rsrv.shipitemlocrsrv_location_id)
77366             AND  (COALESCE(itemloc_ls_id, -1)=COALESCE(_rsrv.shipitemlocrsrv_ls_id, -1))
77367             AND  (COALESCE(itemloc_expiration, endOfTime())=COALESCE(_rsrv.shipitemlocrsrv_expiration, endOfTime()))
77368             AND  (COALESCE(itemloc_warrpurc, endoftime())=COALESCE(_rsrv.shipitemlocrsrv_warrpurc, endoftime())) );
77369
77370           GET DIAGNOSTICS _rows = ROW_COUNT;
77371           IF (_rows > 0 ) THEN  
77372             -- Update existing
77373             UPDATE reserve
77374             SET reserve_qty = (reserve_qty + _rsrv.shipitemlocrsrv_qty)
77375             WHERE (reserve_id=_reserveid);
77376           ELSE
77377             -- Recreate record
77378             INSERT INTO reserve
77379             SELECT nextval('reserve_reserve_id_seq'), 'SO', _r.shipitem_orderitem_id,
77380                    'I', itemloc_id, _rsrv.shipitemlocrsrv_qty, 'R'
77381             FROM itemloc
77382             WHERE ((itemloc_itemsite_id=_rsrv.shipitemlocrsrv_itemsite_id)
77383               AND  (itemloc_location_id=_rsrv.shipitemlocrsrv_location_id)
77384               AND  (COALESCE(itemloc_ls_id, -1)=COALESCE(_rsrv.shipitemlocrsrv_ls_id, -1))
77385               AND  (COALESCE(itemloc_expiration, endOfTime())=COALESCE(_rsrv.shipitemlocrsrv_expiration, endOfTime()))
77386               AND  (COALESCE(itemloc_warrpurc, endoftime())=COALESCE(_rsrv.shipitemlocrsrv_warrpurc, endoftime())) );
77387           END IF;
77388         END LOOP;
77389       END IF;
77390       
77391       DELETE FROM shipitem WHERE (shipitem_id = _r.shipitem_id );
77392
77393       -- Clean up if this is the last shipitem on the shipment
77394       IF (NOT EXISTS(SELECT shipitem_shiphead_id
77395                      FROM shipitem
77396                      WHERE (shipitem_shiphead_id=_r.shiphead_id))) THEN
77397         DELETE FROM shipdata
77398          WHERE(shipdata_shiphead_number=_r.shiphead_number);
77399         DELETE FROM shipdatasum
77400          WHERE(shipdatasum_shiphead_number=_r.shiphead_number);
77401         DELETE FROM pack
77402          WHERE(pack_shiphead_id=_r.shiphead_id);
77403         DELETE FROM shiphead
77404          WHERE (shiphead_id=_r.shiphead_id);
77405       END IF;
77406
77407     END IF;
77408
77409     RETURN _itemlocSeries;
77410
77411 END;
77412 $_$;
77413
77414
77415 ALTER FUNCTION public.returnshipmenttransaction(integer, integer, timestamp with time zone) OWNER TO admin;
77416
77417 --
77418 -- TOC entry 2136 (class 1255 OID 146566981)
77419 -- Dependencies: 4536 8
77420 -- Name: returnwomaterial(integer, numeric, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
77421 --
77422
77423 CREATE FUNCTION returnwomaterial(integer, numeric, timestamp with time zone) RETURNS integer
77424     LANGUAGE plpgsql
77425     AS $_$
77426 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77427 -- See www.xtuple.com/CPAL for the full text of the software license.
77428 DECLARE
77429   pWomatlid ALIAS FOR $1;
77430   pQty ALIAS FOR $2;
77431   pGlDistTS ALIAS FOR $3;
77432   _itemlocSeries INTEGER;
77433
77434 BEGIN
77435
77436   SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
77437   RETURN returnWoMaterial(pWomatlid, pQty, _itemlocSeries, pGlDistTS);
77438
77439 END;
77440 $_$;
77441
77442
77443 ALTER FUNCTION public.returnwomaterial(integer, numeric, timestamp with time zone) OWNER TO admin;
77444
77445 --
77446 -- TOC entry 2138 (class 1255 OID 146566982)
77447 -- Dependencies: 4536 8
77448 -- Name: returnwomaterial(integer, integer, timestamp with time zone, integer); Type: FUNCTION; Schema: public; Owner: admin
77449 --
77450
77451 CREATE FUNCTION returnwomaterial(integer, integer, timestamp with time zone, integer) RETURNS integer
77452     LANGUAGE plpgsql
77453     AS $_$
77454 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77455 -- See www.xtuple.com/CPAL for the full text of the software license.
77456 DECLARE
77457   pWomatlid ALIAS FOR $1;
77458   pItemlocSeries ALIAS FOR $2;
77459   pGlDistTS ALIAS FOR $3;
77460   pInvhistId ALIAS FOR $4;
77461   _woNumber TEXT;
77462   _invhistid INTEGER;
77463   _itemlocSeries INTEGER;
77464   _invqty NUMERIC;
77465   _womatlqty NUMERIC;
77466   _cost NUMERIC := 0;
77467   _rows INTEGER;
77468
77469 BEGIN
77470
77471   _itemlocSeries := 0;
77472
77473   SELECT invhist_invqty, invhist_invqty * invhist_unitcost INTO _invqty, _cost
77474   FROM invhist
77475   WHERE (invhist_id=pInvhistId);
77476
77477   GET DIAGNOSTICS _rows = ROW_COUNT;
77478   
77479   IF (_rows = 0) THEN
77480     RAISE EXCEPTION 'No transaction found for invhist_id %', pInvhistId;
77481   END IF;
77482   
77483   SELECT itemuomtouom(itemsite_item_id, NULL, womatl_uom_id, _invqty)
77484     INTO _womatlqty
77485     FROM womatl, itemsite
77486     WHERE((womatl_itemsite_id=itemsite_id)
77487      AND (womatl_id=pWomatlid));
77488
77489   GET DIAGNOSTICS _rows = ROW_COUNT;
77490   
77491   IF (_rows = 0) THEN
77492     _womatlqty := _invqty;
77493   END IF;
77494
77495   IF ( SELECT (
77496          CASE WHEN (womatl_qtyreq >= 0) THEN
77497            womatl_qtyiss < _womatlqty
77498          ELSE
77499            womatl_qtyiss > _womatlqty
77500          END )
77501        FROM womatl
77502        WHERE ( womatl_id=pWomatlid ) ) THEN
77503     RETURN pItemlocSeries;
77504   END IF;
77505
77506   SELECT formatWoNumber(womatl_wo_id) INTO _woNumber
77507   FROM womatl
77508   WHERE (womatl_id=pWomatlid);
77509
77510   IF (pItemlocSeries = 0) THEN
77511     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
77512   ELSE
77513     _itemlocSeries = pItemlocSeries;
77514   END IF;
77515
77516   -- Post the transaction
77517   SELECT postInvTrans( ci.itemsite_id, 'IM', (_invqty * -1), 
77518                        'W/O', 'WO', _woNumber, '',
77519                        ('Return ' || item_number || ' from Work Order'),
77520                        getPrjAccntId(wo_prj_id, pc.costcat_wip_accnt_id), cc.costcat_asset_accnt_id, _itemlocSeries, pGlDistTS,
77521                        -- Cost will be ignored by Standard Cost items sites
77522                        _cost, pInvhistId) INTO _invhistid
77523     FROM womatl, wo,
77524          itemsite AS ci, costcat AS cc,
77525          itemsite AS pi, costcat AS pc,
77526          item
77527    WHERE((womatl_itemsite_id=ci.itemsite_id)
77528      AND (ci.itemsite_costcat_id=cc.costcat_id)
77529      AND (womatl_wo_id=wo_id)
77530      AND (wo_itemsite_id=pi.itemsite_id)
77531      AND (pi.itemsite_costcat_id=pc.costcat_id)
77532      AND (ci.itemsite_item_id=item_id)
77533      AND (womatl_id=pWomatlid) );
77534
77535 --  Create linkage to the transaction created
77536   INSERT INTO womatlpost (womatlpost_womatl_id,womatlpost_invhist_id)
77537               VALUES (pWomatlid,_invhistid);
77538
77539 --  Decrease the parent W/O's WIP value by the value of the returned components
77540   UPDATE wo
77541   SET wo_wipvalue = (wo_wipvalue - (CASE WHEN(itemsite_costmethod IN ('A','J'))
77542                                               THEN _cost
77543                                          WHEN(itemsite_costmethod='S')
77544                                               THEN stdcost(itemsite_item_id) * _invqty
77545                                          ELSE 0.0 END )),
77546       wo_postedvalue = (wo_postedvalue - (CASE WHEN(itemsite_costmethod IN ('A','J'))
77547                                                     THEN _cost
77548                                                WHEN(itemsite_costmethod='S')
77549                                                     THEN stdcost(itemsite_item_id) * _invqty
77550                                                ELSE 0.0 END ))
77551   FROM womatl, itemsite
77552   WHERE ( (wo_id=womatl_wo_id)
77553    AND (womatl_itemsite_id=itemsite_id)
77554    AND (womatl_id=pWomatlid) );
77555
77556   UPDATE womatl
77557   SET womatl_qtyiss = (womatl_qtyiss - _womatlqty),
77558       womatl_lastreturn = CURRENT_DATE
77559   WHERE (womatl_id=pWomatlid);
77560
77561   RETURN _itemlocSeries;
77562 END;
77563 $_$;
77564
77565
77566 ALTER FUNCTION public.returnwomaterial(integer, integer, timestamp with time zone, integer) OWNER TO admin;
77567
77568 --
77569 -- TOC entry 9075 (class 0 OID 0)
77570 -- Dependencies: 2138
77571 -- Name: FUNCTION returnwomaterial(integer, integer, timestamp with time zone, integer); Type: COMMENT; Schema: public; Owner: admin
77572 --
77573
77574 COMMENT ON FUNCTION returnwomaterial(integer, integer, timestamp with time zone, integer) IS 'Returns material by reversing a specific historical transaction';
77575
77576
77577 --
77578 -- TOC entry 2139 (class 1255 OID 146566983)
77579 -- Dependencies: 4536 8
77580 -- Name: returnwomaterial(integer, numeric, integer, timestamp with time zone, boolean); Type: FUNCTION; Schema: public; Owner: admin
77581 --
77582
77583 CREATE FUNCTION returnwomaterial(integer, numeric, integer, timestamp with time zone, boolean DEFAULT false) RETURNS integer
77584     LANGUAGE plpgsql
77585     AS $_$
77586 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77587 -- See www.xtuple.com/CPAL for the full text of the software license.
77588 DECLARE
77589   pWomatlid ALIAS FOR $1;
77590   pQty ALIAS FOR $2;
77591   pItemlocSeries ALIAS FOR $3;
77592   pGlDistTS ALIAS FOR $4;
77593   pReqStdCost ALIAS FOR $5;
77594   _woNumber TEXT;
77595   _invhistid INTEGER;
77596   _itemlocSeries INTEGER;
77597   _qty NUMERIC;
77598   _cost NUMERIC := 0;
77599
77600 BEGIN
77601
77602   _itemlocSeries := 0;
77603   
77604   IF ( SELECT (
77605          CASE WHEN (womatl_qtyreq >= 0) THEN
77606            womatl_qtyiss < pQty
77607          ELSE
77608            womatl_qtyiss > pQty
77609          END )
77610        FROM womatl
77611        WHERE ( womatl_id=pWomatlid ) ) THEN
77612     RETURN pItemlocSeries;
77613   END IF;
77614
77615   SELECT itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, pQty)
77616     INTO _qty
77617     FROM womatl, itemsite
77618    WHERE((womatl_itemsite_id=itemsite_id)
77619      AND (womatl_id=pWomatlid));
77620   IF (NOT FOUND) THEN
77621     _qty := pQty;
77622   END IF;
77623
77624   SELECT formatWoNumber(womatl_wo_id) INTO _woNumber
77625   FROM womatl
77626   WHERE (womatl_id=pWomatlid);
77627
77628   IF (pItemlocSeries = 0) THEN
77629     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
77630   ELSE
77631     _itemlocSeries = pItemlocSeries;
77632   END IF;
77633
77634   -- Get the cost average
77635   IF (pReqStdCost) THEN
77636     SELECT stdcost(itemsite_item_id) * _qty INTO _cost
77637     FROM womatl, itemsite
77638     WHERE((womatl_itemsite_id=itemsite_id)
77639       AND (womatl_id=pWomatlid));
77640   ELSE
77641     SELECT SUM(invhist_value_before - invhist_value_after) / SUM(invhist_qoh_before - invhist_qoh_after)  * _qty INTO _cost
77642     FROM invhist, womatlpost, womatl 
77643     WHERE((womatlpost_womatl_id=womatl_id) 
77644      AND (womatlpost_invhist_id=invhist_id) 
77645      AND (invhist_qoh_before > invhist_qoh_after)
77646      AND (womatl_id=pWomatlId));
77647   END IF;
77648
77649   _cost := COALESCE(_cost, 0); -- make sure it's not a null value
77650
77651   -- Post the transaction
77652   SELECT postInvTrans( ci.itemsite_id, 'IM', (_qty * -1), 
77653                        'W/O', 'WO', _woNumber, '',
77654                        ('Return ' || item_number || ' from Work Order'),
77655                        getPrjAccntId(wo_prj_id, pc.costcat_wip_accnt_id), cc.costcat_asset_accnt_id, _itemlocSeries, pGlDistTS,
77656                        -- Cost will be ignored by Standard Cost items sites
77657                        _cost) INTO _invhistid
77658     FROM womatl, wo,
77659          itemsite AS ci, costcat AS cc,
77660          itemsite AS pi, costcat AS pc,
77661          item
77662    WHERE((womatl_itemsite_id=ci.itemsite_id)
77663      AND (ci.itemsite_costcat_id=cc.costcat_id)
77664      AND (womatl_wo_id=wo_id)
77665      AND (wo_itemsite_id=pi.itemsite_id)
77666      AND (pi.itemsite_costcat_id=pc.costcat_id)
77667      AND (ci.itemsite_item_id=item_id)
77668      AND (womatl_id=pWomatlid) );
77669
77670 --  Create linkage to the transaction created
77671   IF (_invhistid != -1) THEN
77672     INSERT INTO womatlpost (womatlpost_womatl_id,womatlpost_invhist_id)
77673                 VALUES (pWomatlid,_invhistid);
77674   END IF;
77675
77676 --  Decrease the parent W/O's WIP value by the value of the returned components
77677   UPDATE wo
77678   SET wo_wipvalue = (wo_wipvalue - (CASE WHEN(itemsite_costmethod IN ('A','J'))
77679                                               THEN _cost
77680                                          WHEN(itemsite_costmethod='S')
77681                                               THEN stdcost(itemsite_item_id) * _qty
77682                                          ELSE 0.0 END )),
77683       wo_postedvalue = (wo_postedvalue - (CASE WHEN(itemsite_costmethod IN ('A','J'))
77684                                                     THEN _cost
77685                                                WHEN(itemsite_costmethod='S')
77686                                                     THEN stdcost(itemsite_item_id) * _qty
77687                                                ELSE 0.0 END ))
77688   FROM womatl, itemsite
77689   WHERE ( (wo_id=womatl_wo_id)
77690    AND (womatl_itemsite_id=itemsite_id)
77691    AND (womatl_id=pWomatlid) );
77692
77693   UPDATE womatl
77694   SET womatl_qtyiss = (womatl_qtyiss - pQty),
77695       womatl_lastreturn = CURRENT_DATE
77696   WHERE (womatl_id=pWomatlid);
77697
77698   RETURN _itemlocSeries;
77699
77700 END;
77701 $_$;
77702
77703
77704 ALTER FUNCTION public.returnwomaterial(integer, numeric, integer, timestamp with time zone, boolean) OWNER TO admin;
77705
77706 --
77707 -- TOC entry 2140 (class 1255 OID 146566984)
77708 -- Dependencies: 4536 8
77709 -- Name: returnwomaterialbatch(integer); Type: FUNCTION; Schema: public; Owner: admin
77710 --
77711
77712 CREATE FUNCTION returnwomaterialbatch(integer) RETURNS integer
77713     LANGUAGE plpgsql
77714     AS $_$
77715 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77716 -- See www.xtuple.com/CPAL for the full text of the software license.
77717 DECLARE
77718   pWoid ALIAS FOR $1;
77719   _itemlocSeries INTEGER;
77720   _woid INTEGER;
77721   _r RECORD;
77722
77723 BEGIN
77724
77725   SELECT wo_id INTO _woid
77726   FROM wo
77727   WHERE ( (wo_status IN ('E','I'))
77728    AND (wo_id=pWoid) );
77729
77730   IF (FOUND) THEN
77731     SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
77732
77733     FOR _r IN SELECT womatl_id, 
77734                 CASE WHEN wo_qtyord >= 0 THEN
77735                   womatl_qtyiss
77736                 ELSE
77737                   ((womatl_qtyreq - womatl_qtyiss) * -1)
77738                 END AS qty
77739               FROM wo, womatl, itemsite
77740               WHERE ((wo_id=womatl_wo_id)
77741               AND (womatl_itemsite_id=itemsite_id)
77742               AND ( (wo_qtyord < 0) OR (womatl_issuemethod IN ('S','M')) )
77743               AND (womatl_wo_id=pWoid)) LOOP
77744
77745       IF (_r.qty != 0) THEN
77746         PERFORM returnWoMaterial(_r.womatl_id, _r.qty, _itemlocSeries, now());
77747       END IF;
77748
77749     END LOOP;
77750
77751 --  Reset the W/O Status to E
77752     UPDATE wo
77753     SET wo_status='E'
77754     WHERE (wo_id=pWoid);
77755
77756     RETURN _itemlocSeries;
77757
77758   ELSE 
77759     RETURN -1;
77760   END IF;
77761
77762 END;
77763 $_$;
77764
77765
77766 ALTER FUNCTION public.returnwomaterialbatch(integer) OWNER TO admin;
77767
77768 --
77769 -- TOC entry 2141 (class 1255 OID 146566985)
77770 -- Dependencies: 4536 8
77771 -- Name: reversecashreceipt(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
77772 --
77773
77774 CREATE FUNCTION reversecashreceipt(integer, integer) RETURNS integer
77775     LANGUAGE plpgsql
77776     AS $_$
77777 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
77778 -- See www.xtuple.com/CPAL for the full text of the software license.
77779 DECLARE
77780   pCashrcptid ALIAS FOR $1;
77781   pJournalNumber ALIAS FOR $2;
77782   _p RECORD;
77783   _r RECORD;
77784   _postToAR NUMERIC;
77785   _postToMisc NUMERIC;
77786   _posted_base NUMERIC := 0;
77787   _posted NUMERIC := 0;
77788   _sequence INTEGER;
77789   _aropenid INTEGER;
77790   _arMemoNumber TEXT;
77791   _arAccntid INTEGER;
77792   _closed BOOLEAN;
77793   _debitAccntid INTEGER;
77794   _exchGain NUMERIC;
77795   _comment      TEXT;
77796
77797 BEGIN
77798   _posted := 0;
77799   _posted_base := 0;
77800
77801   SELECT fetchGLSequence() INTO _sequence;
77802
77803   SELECT accnt_id INTO _arAccntid
77804   FROM cashrcpt, accnt, salescat
77805   WHERE ((cashrcpt_salescat_id=salescat_id)
77806     AND  (salescat_ar_accnt_id=accnt_id)
77807     AND  (cashrcpt_id=pCashrcptid));
77808   IF (NOT FOUND) THEN
77809     SELECT accnt_id INTO _arAccntid
77810     FROM cashrcpt, accnt
77811     WHERE ( (findARAccount(cashrcpt_cust_id)=accnt_id)
77812      AND (cashrcpt_id=pCashrcptid) );
77813     IF (NOT FOUND) THEN
77814       RETURN -5;
77815     END IF;
77816   END IF;
77817
77818   SELECT cashrcpt_cust_id, ('Reverse Cash Receipt posting for ' || cust_number||'-'||cust_name) AS custnote,
77819          cashrcpt_fundstype, cashrcpt_number, cashrcpt_docnumber,
77820          cashrcpt_distdate, cashrcpt_amount, cashrcpt_discount,
77821          (cashrcpt_amount / cashrcpt_curr_rate) AS cashrcpt_amount_base,
77822          (cashrcpt_discount / cashrcpt_curr_rate) AS cashrcpt_discount_base,
77823          cashrcpt_notes,
77824          cashrcpt_bankaccnt_id AS bankaccnt_id,
77825          accnt_id AS prepaid_accnt_id,
77826          cashrcpt_usecustdeposit,
77827          cashrcpt_curr_id, cashrcpt_curr_rate INTO _p
77828   FROM accnt, cashrcpt LEFT OUTER JOIN custinfo ON (cashrcpt_cust_id=cust_id)
77829   WHERE ( (findPrepaidAccount(cashrcpt_cust_id)=accnt_id)
77830    AND (cashrcpt_id=pCashrcptid) );
77831   IF (NOT FOUND) THEN
77832     RETURN -7;
77833   END IF;
77834
77835   IF (_p.cashrcpt_fundstype IN ('A', 'D', 'M', 'V')) THEN
77836     IF NOT EXISTS(SELECT ccpay_id
77837                   FROM ccpay
77838                   WHERE ((ccpay_order_number=CAST(pCashrcptid AS TEXT))
77839                      AND (ccpay_status IN ('C', 'A')))) THEN
77840       RETURN -8;
77841     END IF;
77842     _debitAccntid := findPrepaidAccount(_p.cashrcpt_cust_id);
77843   ELSE
77844     SELECT accnt_id INTO _debitAccntid
77845     FROM cashrcpt, bankaccnt, accnt
77846     WHERE ( (cashrcpt_bankaccnt_id=bankaccnt_id)
77847      AND (bankaccnt_accnt_id=accnt_id)
77848      AND (cashrcpt_id=pCashrcptid) );
77849     IF (NOT FOUND) THEN
77850       RETURN -6;
77851     END IF;
77852   END IF;
77853
77854 --  Determine the amount to post to A/R Open Items
77855   SELECT COALESCE(SUM(cashrcptitem_amount),0) INTO _postToAR
77856   FROM cashrcptitem JOIN aropen ON (aropen_id=cashrcptitem_aropen_id)
77857   WHERE ((cashrcptitem_cashrcpt_id=pCashrcptid)
77858    AND (cashrcptitem_applied));
77859   IF (NOT FOUND) THEN
77860     _postToAR := 0;
77861   END IF;
77862
77863 --  Determine the amount to post to Misc. Distributions
77864   SELECT COALESCE(SUM(cashrcptmisc_amount),0) INTO _postToMisc
77865   FROM cashrcptmisc
77866   WHERE (cashrcptmisc_cashrcpt_id=pCashrcptid);
77867   IF (NOT FOUND) THEN
77868     _postToMisc := 0;
77869   END IF;
77870
77871 --  Check to see if the C/R is over applied
77872   IF ((_postToAR + _postToMisc) > _p.cashrcpt_amount) THEN
77873     RETURN -1;
77874   END IF;
77875
77876 --  Check to see if the C/R is positive amount
77877   IF (_p.cashrcpt_amount <= 0) THEN
77878     RETURN -2;
77879   END IF;
77880
77881 --  Distribute A/R Applications
77882   FOR _r IN SELECT aropen_id, aropen_doctype, aropen_docnumber, aropen_docdate,
77883                    aropen_duedate, aropen_curr_id, aropen_curr_rate,
77884                    round(aropen_amount - aropen_paid, 2) <=
77885                       round(aropen_paid + 
77886                       currToCurr(_p.cashrcpt_curr_id, aropen_curr_id,abs(cashrcptitem_amount + cashrcptitem_discount),_p.cashrcpt_distdate),2)
77887                                AS closed,
77888                    cashrcptitem_id, cashrcptitem_amount, cashrcptitem_discount,
77889                    (cashrcptitem_amount / _p.cashrcpt_curr_rate) AS cashrcptitem_amount_base,
77890                    (cashrcptitem_discount / _p.cashrcpt_curr_rate) AS cashrcptitem_discount_base,
77891                    round(aropen_paid - 
77892                       currToCurr(_p.cashrcpt_curr_id, aropen_curr_id,abs(cashrcptitem_amount),_p.cashrcpt_distdate),2) AS new_paid,
77893                    round(currToCurr(_p.cashrcpt_curr_id, aropen_curr_id,abs(cashrcptitem_discount),_p.cashrcpt_distdate),2) AS new_discount
77894             FROM cashrcptitem JOIN aropen ON (cashrcptitem_aropen_id=aropen_id)
77895             WHERE ((cashrcptitem_cashrcpt_id=pCashrcptid)
77896               AND (cashrcptitem_applied)) LOOP
77897
77898 --  Handle discount 
77899     IF (_r.cashrcptitem_discount_base > 0) THEN
77900       PERFORM reverseCashReceiptDisc(_r.cashrcptitem_id, pJournalNumber);
77901     END IF;
77902      
77903 --  Update the aropen item to post the paid amount
77904     UPDATE aropen
77905     SET aropen_paid = _r.new_paid - _r.new_discount,
77906         aropen_open = TRUE,
77907         aropen_closedate = NULL
77908     WHERE (aropen_id=_r.aropen_id);
77909
77910 --  Cache the running amount posted
77911     _posted_base := _posted_base + _r.cashrcptitem_amount_base;
77912     _posted := _posted + _r.cashrcptitem_amount;
77913
77914 --  Record the cashrcpt application
77915     IF (_r.aropen_doctype IN ('I','D')) THEN
77916       INSERT INTO arapply
77917       ( arapply_cust_id,
77918         arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
77919         arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
77920         arapply_fundstype, arapply_refnumber, arapply_reftype, arapply_ref_id,
77921         arapply_applied, arapply_closed,
77922         arapply_postdate, arapply_distdate, arapply_journalnumber, arapply_username,
77923         arapply_curr_id
77924        )
77925       VALUES
77926       ( _p.cashrcpt_cust_id,
77927         -1, 'K', _p.cashrcpt_number,
77928         _r.aropen_id, _r.aropen_doctype, _r.aropen_docnumber,
77929         _p.cashrcpt_fundstype, _p.cashrcpt_docnumber, 'CRA', _r.cashrcptitem_id,
77930         (round(_r.cashrcptitem_amount, 2) * -1.0), _r.closed,
77931         CURRENT_DATE, _p.cashrcpt_distdate, pJournalNumber, getEffectiveXtUser(), _p.cashrcpt_curr_id );
77932     ELSE
77933       INSERT INTO arapply
77934       ( arapply_cust_id,
77935         arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
77936         arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
77937         arapply_fundstype, arapply_refnumber, arapply_reftype, arapply_ref_id,
77938         arapply_applied, arapply_closed, arapply_postdate, arapply_distdate,
77939         arapply_journalnumber, arapply_username, arapply_curr_id )
77940       VALUES
77941       ( _p.cashrcpt_cust_id,
77942         _r.aropen_id, _r.aropen_doctype, _r.aropen_docnumber,
77943         -1, 'R', _p.cashrcpt_number,
77944         '', '', 'CRA', _r.cashrcptitem_id,
77945         (round(abs(_r.cashrcptitem_amount), 2) * -1.0), _r.closed,
77946         CURRENT_DATE, _p.cashrcpt_distdate, pJournalNumber, getEffectiveXtUser(), _p.cashrcpt_curr_id );
77947     END IF;
77948
77949     _exchGain := arCurrGain(_r.aropen_id,_p.cashrcpt_curr_id, abs(_r.cashrcptitem_amount),
77950                            _p.cashrcpt_distdate);
77951
77952     PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR',
77953                         (_r.aropen_doctype || '-' || _r.aropen_docnumber),
77954                         CASE WHEN _r.aropen_doctype != 'R' THEN _arAccntid
77955                         ELSE findDeferredAccount(_p.cashrcpt_cust_id) END, 
77956                         (round(_r.cashrcptitem_amount_base + _exchGain, 2) * -1.0),
77957                         _p.cashrcpt_distdate, _p.custnote );
77958
77959     IF (_exchGain <> 0) THEN
77960         PERFORM insertIntoGLSeries(_sequence, 'A/R', 'CR',
77961                _r.aropen_doctype || '-' || _r.aropen_docnumber,
77962                getGainLossAccntId(
77963                CASE WHEN _r.aropen_doctype != 'R' THEN _arAccntid
77964                ELSE findDeferredAccount(_p.cashrcpt_cust_id) END
77965                ), round(_exchGain, 2),
77966                _p.cashrcpt_distdate, _p.custnote);
77967
77968     END IF;
77969
77970   END LOOP;
77971
77972 --  Distribute Misc. Applications
77973   FOR _r IN SELECT cashrcptmisc_id, cashrcptmisc_accnt_id, cashrcptmisc_amount,
77974                    (cashrcptmisc_amount / _p.cashrcpt_curr_rate) AS cashrcptmisc_amount_base,
77975                    cashrcptmisc_notes
77976             FROM cashrcptmisc
77977             WHERE (cashrcptmisc_cashrcpt_id=pCashrcptid)  LOOP
77978
77979 --  Cache the running amount posted
77980     _posted_base := (_posted_base + _r.cashrcptmisc_amount_base);
77981     _posted := (_posted + _r.cashrcptmisc_amount);
77982
77983 --  Record the cashrcpt application
77984     INSERT INTO arapply
77985     ( arapply_cust_id,
77986       arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
77987       arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
77988       arapply_fundstype, arapply_refnumber,
77989       arapply_applied, arapply_closed,
77990       arapply_postdate, arapply_distdate, arapply_journalnumber, arapply_username,
77991       arapply_curr_id, arapply_reftype, arapply_ref_id )
77992     VALUES
77993     ( _p.cashrcpt_cust_id,
77994       -1, 'K', '',
77995       -1, 'Misc.', '',
77996       _p.cashrcpt_fundstype, _p.cashrcpt_docnumber,
77997       (round(_r.cashrcptmisc_amount, 2) * -1.0), TRUE,
77998       CURRENT_DATE, _p.cashrcpt_distdate, pJournalNumber, getEffectiveXtUser(), 
77999       _p.cashrcpt_curr_id, 'CRD', _r.cashrcptmisc_id );
78000
78001     PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR', _r.cashrcptmisc_notes,
78002                                 _r.cashrcptmisc_accnt_id,
78003                                 (round(_r.cashrcptmisc_amount_base, 2) * -1.0),
78004                                 _p.cashrcpt_distdate, _p.custnote );
78005
78006   END LOOP;
78007
78008 --  Post any remaining Cash to an A/R Debit Memo
78009 --  this credit memo may absorb an occasional currency exchange rounding error
78010   IF (round(_posted_base, 2) < round(_p.cashrcpt_amount_base, 2)) THEN
78011     _comment := ('Unapplied from ' || _p.cashrcpt_fundstype || '-' || _p.cashrcpt_docnumber);
78012     PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR',
78013                                 _comment,
78014                                 _p.prepaid_accnt_id,
78015                                 ((round(_p.cashrcpt_amount_base, 2) - round(_posted_base, 2)) * -1.0),
78016                                 _p.cashrcpt_distdate, _p.custnote );
78017     SELECT fetchArMemoNumber() INTO _arMemoNumber;
78018     -- Post A/R Debit Memo
78019     SELECT createARDebitMemo(NULL, _p.cashrcpt_cust_id, pJournalNumber, _arMemoNumber, '',
78020                               _p.cashrcpt_distdate, (_p.cashrcpt_amount - _posted),
78021                               _comment, -1, -1, -1, _p.cashrcpt_distdate, -1, NULL, 0,
78022                               _p.cashrcpt_curr_id) INTO _aropenid;
78023     -- Create Cash Receipt Item to capture posting
78024     INSERT INTO cashrcptitem
78025       ( cashrcptitem_cashrcpt_id, cashrcptitem_aropen_id, cashrcptitem_amount )
78026     VALUES
78027       ( pCashrcptid, _aropenid, ((_p.cashrcpt_amount - _posted) * 1.0) );
78028
78029   ELSIF (round(_posted_base, 2) > round(_p.cashrcpt_amount_base, 2)) THEN
78030     PERFORM insertIntoGLSeries(_sequence, 'A/R', 'CR',
78031                    'Currency Exchange Rounding - ' || _p.cashrcpt_docnumber,
78032                    getGainLossAccntId(_debitAccntid),
78033                    ((round(_posted_base, 2) - round((_p.cashrcpt_amount_base + _p.cashrcpt_discount_base), 2)) * 1.0),
78034                    _p.cashrcpt_distdate, _p.custnote);
78035   END IF;
78036
78037 --  Debit Cash
78038   PERFORM insertIntoGLSeries( _sequence, 'A/R', 'CR',
78039                     (_p.cashrcpt_fundstype || '-' || _p.cashrcpt_docnumber),
78040                      _debitAccntid, round(_p.cashrcpt_amount_base, 2),
78041                      _p.cashrcpt_distdate,
78042                      _p.custnote );
78043
78044   PERFORM postGLSeries(_sequence, pJournalNumber);
78045
78046 --  Update and void the posted cashrcpt
78047   UPDATE cashrcpt SET cashrcpt_posted=FALSE,
78048                       cashrcpt_posteddate=NULL,
78049                       cashrcpt_postedby=NULL,
78050                       cashrcpt_void=TRUE
78051   WHERE (cashrcpt_id=pCashrcptid);
78052
78053   RETURN 1;
78054
78055 END;
78056 $_$;
78057
78058
78059 ALTER FUNCTION public.reversecashreceipt(integer, integer) OWNER TO admin;
78060
78061 --
78062 -- TOC entry 2142 (class 1255 OID 146566987)
78063 -- Dependencies: 4536 8
78064 -- Name: reversecashreceiptdisc(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
78065 --
78066
78067 CREATE FUNCTION reversecashreceiptdisc(integer, integer) RETURNS integer
78068     LANGUAGE plpgsql
78069     AS $_$
78070 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78071 -- See www.xtuple.com/CPAL for the full text of the software license.
78072 DECLARE
78073   pCashrcptItemId ALIAS FOR $1;
78074   pJournalNumber ALIAS FOR $2;
78075   _r RECORD;
78076   _t RECORD;
78077   _v RECORD;
78078   _ardiscountid INTEGER;
78079   _arMemoNumber TEXT;
78080   _arAccntid INTEGER;
78081   _discountAccntid INTEGER;
78082   _comment      TEXT;
78083   _discprcnt NUMERIC;
78084   _check INTEGER;
78085
78086 BEGIN
78087
78088     -- Fetch base records for processing
78089     SELECT aropen_id, aropen_doctype, aropen_amount,
78090            cashrcptitem_discount,
78091            cashrcpt_cust_id, cashrcpt_distdate, cashrcpt_applydate,
78092            cashrcpt_curr_id, cashrcpt_fundstype, cashrcpt_docnumber,
78093            round(currToCurr(cashrcpt_curr_id, aropen_curr_id, cashrcptitem_discount, cashrcpt_distdate),2) AS aropen_discount
78094       INTO _r
78095     FROM cashrcptitem 
78096       JOIN cashrcpt ON (cashrcptitem_cashrcpt_id=cashrcpt_id)
78097       JOIN aropen ON ( (aropen_id=cashrcptitem_aropen_id) AND (aropen_doctype IN ('I', 'D')) )
78098     WHERE (cashrcptitem_id=pCashrcptItemId);
78099
78100     -- Get discount account
78101     _discountAccntid := findardiscountaccount(_r.cashrcpt_cust_id);
78102   
78103     IF (_r.cashrcptitem_discount > 0) THEN
78104       --  Determine discount percentage
78105       _discprcnt := _r.aropen_discount / _r.aropen_amount;
78106
78107       SELECT fetchArMemoNumber() INTO _arMemoNumber;
78108       _comment := 'Discount Credit Reversal from ' || _r.cashrcpt_fundstype || '-' || _r.cashrcpt_docnumber;
78109
78110       -- Create misc debit memo record
78111       _ardiscountid := nextval('aropen_aropen_id_seq');
78112       INSERT INTO aropen (
78113         aropen_id, aropen_docdate, aropen_duedate, aropen_doctype, 
78114         aropen_docnumber, aropen_curr_id, aropen_posted, aropen_amount ) 
78115       VALUES ( 
78116         _ardiscountid, _r.cashrcpt_distdate, _r.cashrcpt_distdate, 'D', 
78117         _arMemoNumber, _r.cashrcpt_curr_id, false,_r.cashrcptitem_discount);
78118         
78119       IF (fetchMetricBool('CreditTaxDiscount')) THEN
78120         --  proportional tax credits calculated and implemented for the debit memo generated by the discount
78121         IF (_r.aropen_doctype  = 'I') THEN
78122           -- Tax for invoices
78123           SELECT aropen_cobmisc_id AS invcheadid, 
78124                  invchead_curr_id, 
78125                  invchead_invcdate INTO _t
78126           FROM aropen
78127             LEFT OUTER JOIN invchead ON (aropen_cobmisc_id = invchead_id) 
78128             LEFT OUTER JOIN invcitem ON (invchead_id = invcitem_invchead_id)
78129           WHERE aropen_id = _r.aropen_id;
78130
78131           FOR _v IN SELECT tax_sales_accnt_id,
78132                            tax_id, 
78133                            round(sum(taxdetail_tax), 2) AS tax,
78134                            currToBase(_t.invchead_curr_id, round(sum(taxdetail_tax), 2), _t.invchead_invcdate) AS taxbasevalue
78135           FROM tax 
78136             JOIN calculateTaxDetailSummary('I', _t.invcheadid, 'T') ON (taxdetail_tax_id=tax_id)
78137             GROUP BY tax_id, tax_sales_accnt_id 
78138           LOOP
78139             INSERT INTO aropentax(
78140               taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
78141               taxhist_percent, taxhist_amount, taxhist_tax, 
78142               taxhist_docdate, taxhist_basis)
78143             VALUES (
78144               _ardiscountid, getadjustmenttaxtypeid(), _v.tax_id, 
78145               0.00, 0.00, (round((_v.tax * _discprcnt), 2)), 
78146               _r.cashrcpt_distdate, 0.00);
78147           END LOOP;
78148
78149         ELSIF (_r.aropen_doctype  = 'D') THEN
78150           -- Tax for debit memos
78151           INSERT INTO aropentax(
78152             taxhist_parent_id, taxhist_taxtype_id, taxhist_tax_id,
78153             taxhist_percent, taxhist_amount, taxhist_tax, 
78154             taxhist_docdate, taxhist_basis)
78155           SELECT
78156             _ardiscountid, taxhist_taxtype_id, taxhist_tax_id, 
78157             0.00, 0.00, (round((taxhist_tax * _discprcnt), 2)),  
78158             _r.cashrcpt_distdate, 0.00
78159           FROM aropentax
78160           WHERE (taxhist_parent_id=_r.aropen_id);
78161               
78162         END IF;
78163       END IF; -- End taxes
78164
78165       -- Create debit memo for discount
78166       SELECT createARDebitMemo(_ardiscountid, _r.cashrcpt_cust_id, pJournalNumber, _arMemoNumber, '',
78167                                 _r.cashrcpt_distdate, _r.cashrcptitem_discount,
78168                                 _comment, -1, -1, _discountAccntid, _r.cashrcpt_distdate,
78169                                 -1, NULL, 0, _r.cashrcpt_curr_id) INTO _ardiscountid;
78170
78171     END IF; -- End handle Discount
78172
78173     RETURN 1;
78174
78175 END;
78176 $_$;
78177
78178
78179 ALTER FUNCTION public.reversecashreceiptdisc(integer, integer) OWNER TO admin;
78180
78181 --
78182 -- TOC entry 2143 (class 1255 OID 146566988)
78183 -- Dependencies: 4536 8
78184 -- Name: reverseglseries(integer, date, text); Type: FUNCTION; Schema: public; Owner: admin
78185 --
78186
78187 CREATE FUNCTION reverseglseries(integer, date, text) RETURNS integer
78188     LANGUAGE plpgsql
78189     AS $_$
78190 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78191 -- See www.xtuple.com/CPAL for the full text of the software license.
78192 DECLARE
78193   pSequence ALIAS FOR $1;
78194   pDistDate ALIAS FOR $2;
78195   pNotes ALIAS FOR $3;
78196   _sequence INTEGER := fetchGLSequence();       
78197   _journal INTEGER;
78198
78199 BEGIN
78200
78201   IF (SELECT COUNT(gltrans_sequence) > 0 FROM gltrans WHERE gltrans_sequence = pSequence) THEN
78202     SELECT fetchJournalNumber(jrnluse_use) INTO _journal
78203     FROM gltrans
78204       JOIN jrnluse ON (gltrans_journalnumber=jrnluse_number)
78205     WHERE (gltrans_sequence=pSequence)
78206     LIMIT 1;
78207   
78208     INSERT INTO gltrans (gltrans_created, gltrans_posted, gltrans_exported,
78209                          gltrans_date, gltrans_sequence, gltrans_accnt_id,
78210                          gltrans_source, gltrans_docnumber, gltrans_misc_id,
78211                          gltrans_amount, gltrans_notes, gltrans_journalnumber,
78212                          gltrans_doctype)
78213                  SELECT  CURRENT_TIMESTAMP, FALSE, FALSE,
78214                          pDistDate, _sequence, gltrans_accnt_id,
78215                          gltrans_source, gltrans_docnumber, gltrans_misc_id,
78216                          (gltrans_amount * -1), pNotes, _journal,
78217                          gltrans_doctype
78218                     FROM gltrans
78219                    WHERE (gltrans_sequence=pSequence);
78220
78221     PERFORM postIntoTrialBalance(_sequence);
78222   ELSE
78223     SELECT fetchJournalNumber(jrnluse_use) INTO _journal
78224     FROM sltrans
78225       JOIN jrnluse ON (sltrans_journalnumber=jrnluse_number)
78226     WHERE (sltrans_sequence=pSequence)
78227     LIMIT 1;
78228     
78229     INSERT INTO sltrans (sltrans_created, sltrans_posted,
78230                          sltrans_date, sltrans_sequence, sltrans_accnt_id,
78231                          sltrans_source, sltrans_docnumber, sltrans_misc_id,
78232                          sltrans_amount, sltrans_notes, sltrans_journalnumber,
78233                          sltrans_doctype)
78234                  SELECT  CURRENT_TIMESTAMP, FALSE,
78235                          pDistDate, _sequence, sltrans_accnt_id,
78236                          sltrans_source, sltrans_docnumber, sltrans_misc_id,
78237                          (sltrans_amount * -1), pNotes, _journal,
78238                          sltrans_doctype
78239                     FROM sltrans
78240                    WHERE (sltrans_sequence=pSequence);
78241   END IF;
78242
78243   RETURN _journal;
78244 END;
78245 $_$;
78246
78247
78248 ALTER FUNCTION public.reverseglseries(integer, date, text) OWNER TO admin;
78249
78250 --
78251 -- TOC entry 2137 (class 1255 OID 146566989)
78252 -- Dependencies: 4536 8
78253 -- Name: revokeallmodulecmnttypesource(integer, text); Type: FUNCTION; Schema: public; Owner: admin
78254 --
78255
78256 CREATE FUNCTION revokeallmodulecmnttypesource(integer, text) RETURNS integer
78257     LANGUAGE plpgsql
78258     AS $_$
78259 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78260 -- See www.xtuple.com/CPAL for the full text of the software license.
78261 DECLARE
78262   pCmnttypeid ALIAS FOR $1;
78263   pModuleName ALIAS FOR $2;
78264
78265 BEGIN
78266
78267   DELETE FROM cmnttypesource
78268   WHERE (cmnttypesource_id IN ( SELECT cmnttypesource_id
78269                                 FROM cmnttypesource, source
78270                                 WHERE ( (cmnttypesource_source_id=source_id)
78271                                   AND (cmnttypesource_cmnttype_id=pCmnttypeid)
78272                                   AND (source_module=pModuleName) ) ) );
78273
78274   RETURN 1;
78275
78276 END;
78277 $_$;
78278
78279
78280 ALTER FUNCTION public.revokeallmodulecmnttypesource(integer, text) OWNER TO admin;
78281
78282 --
78283 -- TOC entry 2114 (class 1255 OID 146566990)
78284 -- Dependencies: 4536 8
78285 -- Name: revokeallmodulepriv(text, text); Type: FUNCTION; Schema: public; Owner: admin
78286 --
78287
78288 CREATE FUNCTION revokeallmodulepriv(text, text) RETURNS integer
78289     LANGUAGE plpgsql
78290     AS $_$
78291 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78292 -- See www.xtuple.com/CPAL for the full text of the software license.
78293 DECLARE
78294   pUsername ALIAS FOR $1;
78295   pModuleName ALIAS FOR $2;
78296
78297 BEGIN
78298
78299   DELETE FROM usrpriv
78300   WHERE (usrpriv_id IN ( SELECT usrpriv_id
78301                          FROM usrpriv, priv
78302                          WHERE ( (usrpriv_priv_id=priv_id)
78303                           AND (usrpriv_username=pUsername)
78304                           AND (priv_module=pModuleName) ) ) );
78305
78306   NOTIFY "usrprivUpdated";
78307
78308   RETURN 1;
78309
78310 END;
78311 $_$;
78312
78313
78314 ALTER FUNCTION public.revokeallmodulepriv(text, text) OWNER TO admin;
78315
78316 --
78317 -- TOC entry 2125 (class 1255 OID 146566991)
78318 -- Dependencies: 4536 8
78319 -- Name: revokeallmoduleprivgroup(integer, text); Type: FUNCTION; Schema: public; Owner: admin
78320 --
78321
78322 CREATE FUNCTION revokeallmoduleprivgroup(integer, text) RETURNS integer
78323     LANGUAGE plpgsql
78324     AS $_$
78325 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78326 -- See www.xtuple.com/CPAL for the full text of the software license.
78327 DECLARE
78328   pGrpid ALIAS FOR $1;
78329   pModuleName ALIAS FOR $2;
78330
78331 BEGIN
78332
78333   DELETE FROM grppriv
78334   WHERE (grppriv_id IN ( SELECT grppriv_id
78335                          FROM grppriv, priv
78336                          WHERE ( (grppriv_priv_id=priv_id)
78337                           AND (grppriv_grp_id=pGrpid)
78338                           AND (priv_module=pModuleName) ) ) );
78339
78340   RETURN 1;
78341
78342 END;
78343 $_$;
78344
78345
78346 ALTER FUNCTION public.revokeallmoduleprivgroup(integer, text) OWNER TO admin;
78347
78348 --
78349 -- TOC entry 2144 (class 1255 OID 146566992)
78350 -- Dependencies: 4536 8
78351 -- Name: revokecmnttypesource(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
78352 --
78353
78354 CREATE FUNCTION revokecmnttypesource(integer, integer) RETURNS boolean
78355     LANGUAGE plpgsql
78356     AS $_$
78357 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78358 -- See www.xtuple.com/CPAL for the full text of the software license.
78359 DECLARE
78360   pCmnttypeid ALIAS FOR $1;
78361   pSourceid ALIAS FOR $2;
78362
78363 BEGIN
78364
78365   DELETE FROM cmnttypesource
78366   WHERE ( (cmnttypesource_cmnttype_id=pCmnttypeid)
78367     AND (cmnttypesource_source_id=pSourceid) );
78368
78369   RETURN TRUE;
78370
78371 END;
78372 $_$;
78373
78374
78375 ALTER FUNCTION public.revokecmnttypesource(integer, integer) OWNER TO admin;
78376
78377 --
78378 -- TOC entry 2145 (class 1255 OID 146566993)
78379 -- Dependencies: 4536 8
78380 -- Name: revokegroup(text, integer); Type: FUNCTION; Schema: public; Owner: admin
78381 --
78382
78383 CREATE FUNCTION revokegroup(text, integer) RETURNS boolean
78384     LANGUAGE plpgsql
78385     AS $_$
78386 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78387 -- See www.xtuple.com/CPAL for the full text of the software license.
78388 DECLARE
78389   pUsername ALIAS FOR $1;
78390   pGrpid ALIAS FOR $2;
78391
78392 BEGIN
78393
78394   DELETE FROM usrgrp
78395   WHERE ( (usrgrp_username=pUsername)
78396    AND (usrgrp_grp_id=pGrpid) );
78397
78398   RETURN TRUE;
78399
78400 END;
78401 $_$;
78402
78403
78404 ALTER FUNCTION public.revokegroup(text, integer) OWNER TO admin;
78405
78406 --
78407 -- TOC entry 2146 (class 1255 OID 146566994)
78408 -- Dependencies: 4536 8
78409 -- Name: revokepriv(text, integer); Type: FUNCTION; Schema: public; Owner: admin
78410 --
78411
78412 CREATE FUNCTION revokepriv(text, integer) RETURNS boolean
78413     LANGUAGE plpgsql
78414     AS $_$
78415 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78416 -- See www.xtuple.com/CPAL for the full text of the software license.
78417 DECLARE
78418   pUsername ALIAS FOR $1;
78419   pPrivid ALIAS FOR $2;
78420
78421 BEGIN
78422
78423   DELETE FROM usrpriv
78424   WHERE ( (usrpriv_username=pUsername)
78425    AND (usrpriv_priv_id=pPrivid) );
78426
78427   NOTIFY "usrprivUpdated";
78428
78429   RETURN TRUE;
78430
78431 END;
78432 $_$;
78433
78434
78435 ALTER FUNCTION public.revokepriv(text, integer) OWNER TO admin;
78436
78437 --
78438 -- TOC entry 2147 (class 1255 OID 146566995)
78439 -- Dependencies: 4536 8
78440 -- Name: revokepriv(text, text); Type: FUNCTION; Schema: public; Owner: admin
78441 --
78442
78443 CREATE FUNCTION revokepriv(text, text) RETURNS boolean
78444     LANGUAGE plpgsql
78445     AS $_$
78446 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78447 -- See www.xtuple.com/CPAL for the full text of the software license.
78448 DECLARE
78449   pUsername ALIAS FOR $1;
78450   pPrivname ALIAS FOR $2;
78451
78452 BEGIN
78453
78454   DELETE FROM usrpriv
78455   WHERE ( (usrpriv_username=pUsername)
78456    AND (usrpriv_priv_id IN (SELECT priv_id
78457                               FROM priv
78458                              WHERE priv_name=pPrivname) ));
78459
78460   NOTIFY "usrprivUpdated";
78461
78462   RETURN TRUE;
78463
78464 END;
78465 $_$;
78466
78467
78468 ALTER FUNCTION public.revokepriv(text, text) OWNER TO admin;
78469
78470 --
78471 -- TOC entry 2148 (class 1255 OID 146566996)
78472 -- Dependencies: 4536 8
78473 -- Name: revokeprivgroup(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
78474 --
78475
78476 CREATE FUNCTION revokeprivgroup(integer, integer) RETURNS boolean
78477     LANGUAGE plpgsql
78478     AS $_$
78479 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78480 -- See www.xtuple.com/CPAL for the full text of the software license.
78481 DECLARE
78482   pGrpid ALIAS FOR $1;
78483   pPrivid ALIAS FOR $2;
78484
78485 BEGIN
78486
78487   DELETE FROM grppriv
78488   WHERE ( (grppriv_grp_id=pGrpid)
78489    AND (grppriv_priv_id=pPrivid) );
78490
78491   NOTIFY "usrprivUpdated";
78492
78493   RETURN TRUE;
78494
78495 END;
78496 $_$;
78497
78498
78499 ALTER FUNCTION public.revokeprivgroup(integer, integer) OWNER TO admin;
78500
78501 --
78502 -- TOC entry 2149 (class 1255 OID 146566997)
78503 -- Dependencies: 4536 8
78504 -- Name: rollupactualcost(integer); Type: FUNCTION; Schema: public; Owner: admin
78505 --
78506
78507 CREATE FUNCTION rollupactualcost(integer) RETURNS integer
78508     LANGUAGE plpgsql
78509     AS $_$
78510 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78511 -- See www.xtuple.com/CPAL for the full text of the software license.
78512 DECLARE
78513     pItemid ALIAS FOR $1;
78514
78515 BEGIN
78516     RETURN rollUpSorACost(pitemid, TRUE);
78517 END;
78518 $_$;
78519
78520
78521 ALTER FUNCTION public.rollupactualcost(integer) OWNER TO admin;
78522
78523 --
78524 -- TOC entry 2150 (class 1255 OID 146566998)
78525 -- Dependencies: 4536 8
78526 -- Name: rollupsoracost(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
78527 --
78528
78529 CREATE FUNCTION rollupsoracost(integer, boolean) RETURNS integer
78530     LANGUAGE plpgsql
78531     AS $_$
78532 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78533 -- See www.xtuple.com/CPAL for the full text of the software license.
78534 DECLARE
78535   pItemid       ALIAS FOR $1;
78536   pActual       ALIAS FOR $2;
78537   _counter INTEGER;
78538   _setid INTEGER;
78539   _consumers RECORD;
78540
78541 BEGIN
78542
78543   _counter := 0;
78544
78545   SELECT indentedWhereUsed(pItemid) INTO _setid;
78546
78547   FOR _consumers IN SELECT bomwork_item_id
78548                     FROM bomwork
78549                     WHERE (bomwork_set_id=_setid)
78550                     ORDER BY bomwork_level LOOP
78551     PERFORM updateSorACost( _consumers.bomwork_item_id, costelem_type, TRUE,
78552                             lowerCost(_consumers.bomwork_item_id,
78553                                       costelem_type, pActual),
78554                             pActual )
78555     FROM costelem
78556     WHERE (costelem_sys);
78557
78558     PERFORM updateLowerUserCosts(_consumers.bomwork_item_id, pActual);
78559
78560     _counter := _counter + 1;
78561
78562   END LOOP;
78563
78564   PERFORM deleteBOMWorkset(_setid);
78565
78566   RETURN _counter;
78567
78568 END;
78569 $_$;
78570
78571
78572 ALTER FUNCTION public.rollupsoracost(integer, boolean) OWNER TO admin;
78573
78574 --
78575 -- TOC entry 2151 (class 1255 OID 146566999)
78576 -- Dependencies: 4536 8
78577 -- Name: rollupstandardcost(integer); Type: FUNCTION; Schema: public; Owner: admin
78578 --
78579
78580 CREATE FUNCTION rollupstandardcost(integer) RETURNS integer
78581     LANGUAGE plpgsql
78582     AS $_$
78583 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78584 -- See www.xtuple.com/CPAL for the full text of the software license.
78585 DECLARE
78586     pItemid ALIAS FOR $1;
78587
78588 BEGIN
78589     RETURN rollUpSorACost(pItemid, FALSE);
78590 END;
78591 $_$;
78592
78593
78594 ALTER FUNCTION public.rollupstandardcost(integer) OWNER TO admin;
78595
78596 --
78597 -- TOC entry 2152 (class 1255 OID 146567000)
78598 -- Dependencies: 4536 8
78599 -- Name: roundcost(numeric); Type: FUNCTION; Schema: public; Owner: admin
78600 --
78601
78602 CREATE FUNCTION roundcost(pcost numeric) RETURNS numeric
78603     LANGUAGE plpgsql IMMUTABLE
78604     AS $$
78605 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78606 -- See www.xtuple.com/CPAL for the full text of the software license.
78607 DECLARE
78608   _scale INTEGER;
78609
78610 BEGIN
78611   IF (pCost IS NULL) THEN
78612     RETURN NULL;
78613   END IF;
78614
78615   SELECT locale_cost_scale INTO _scale
78616   FROM locale
78617   WHERE (locale_id=getUsrLocaleId());
78618
78619   RETURN ROUND(pCost, _scale);
78620
78621 END;
78622 $$;
78623
78624
78625 ALTER FUNCTION public.roundcost(pcost numeric) OWNER TO admin;
78626
78627 --
78628 -- TOC entry 2153 (class 1255 OID 146567001)
78629 -- Dependencies: 4536 8
78630 -- Name: roundlocale(boolean, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
78631 --
78632
78633 CREATE FUNCTION roundlocale(pfractional boolean, pqty numeric, plocale text) RETURNS numeric
78634     LANGUAGE plpgsql IMMUTABLE
78635     AS $$
78636 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78637 -- See www.xtuple.com/CPAL for the full text of the software license.
78638 DECLARE
78639   _r RECORD;
78640   _scale INTEGER;
78641
78642 BEGIN
78643   IF (pFractional) THEN
78644     SELECT * INTO _r
78645     FROM locale
78646     WHERE (locale_id=getUsrLocaleId());
78647
78648     _scale := CASE pLocale WHEN 'qtyper' THEN _r.locale_qtyper_scale
78649                            WHEN 'cost' THEN _r.locale_cost_scale
78650                            ELSE _r.locale_qty_scale
78651               END;
78652
78653     RETURN ROUND(pQty, _scale);
78654   ELSE
78655     IF (TRUNC(pQty) < pQty) THEN
78656       RETURN (TRUNC(pQty) + 1);
78657     ELSE
78658       RETURN TRUNC(pQty);
78659     END IF;
78660   END IF;
78661 END;
78662 $$;
78663
78664
78665 ALTER FUNCTION public.roundlocale(pfractional boolean, pqty numeric, plocale text) OWNER TO admin;
78666
78667 --
78668 -- TOC entry 2154 (class 1255 OID 146567002)
78669 -- Dependencies: 4536 8
78670 -- Name: roundqty(boolean, numeric); Type: FUNCTION; Schema: public; Owner: admin
78671 --
78672
78673 CREATE FUNCTION roundqty(pfractional boolean, pqty numeric) RETURNS numeric
78674     LANGUAGE plpgsql IMMUTABLE
78675     AS $$
78676 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78677 -- See www.xtuple.com/CPAL for the full text of the software license.
78678 DECLARE
78679   _scale INTEGER;
78680
78681 BEGIN
78682   SELECT locale_qty_scale INTO _scale
78683   FROM locale
78684   WHERE (locale_id=getUsrLocaleId());
78685
78686   IF (pFractional) THEN
78687     RETURN ROUND(pQty, _scale);
78688   ELSE
78689     IF (TRUNC(pQty) < ROUND(pQty, _scale)) THEN
78690       RETURN (TRUNC(pQty) + 1);
78691     ELSE
78692       RETURN TRUNC(pQty);
78693     END IF;
78694   END IF;
78695 END;
78696 $$;
78697
78698
78699 ALTER FUNCTION public.roundqty(pfractional boolean, pqty numeric) OWNER TO admin;
78700
78701 --
78702 -- TOC entry 2155 (class 1255 OID 146567003)
78703 -- Dependencies: 4536 8
78704 -- Name: roundsale(numeric); Type: FUNCTION; Schema: public; Owner: admin
78705 --
78706
78707 CREATE FUNCTION roundsale(psale numeric) RETURNS numeric
78708     LANGUAGE plpgsql IMMUTABLE
78709     AS $$
78710 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78711 -- See www.xtuple.com/CPAL for the full text of the software license.
78712 DECLARE
78713   _scale INTEGER;
78714
78715 BEGIN
78716   IF (pSale IS NULL) THEN
78717     RETURN NULL;
78718   END IF;
78719
78720   SELECT locale_salesprice_scale INTO _scale
78721   FROM locale
78722   WHERE (locale_id=getUsrLocaleId());
78723
78724   RETURN ROUND(pSale, _scale);
78725
78726 END;
78727 $$;
78728
78729
78730 ALTER FUNCTION public.roundsale(psale numeric) OWNER TO admin;
78731
78732 --
78733 -- TOC entry 2156 (class 1255 OID 146567004)
78734 -- Dependencies: 4536 8
78735 -- Name: roundup(numeric); Type: FUNCTION; Schema: public; Owner: admin
78736 --
78737
78738 CREATE FUNCTION roundup(numeric) RETURNS numeric
78739     LANGUAGE plpgsql IMMUTABLE
78740     AS $_$
78741 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78742 -- See www.xtuple.com/CPAL for the full text of the software license.
78743 DECLARE
78744
78745   pValue ALIAS FOR $1;
78746   _checkValue integer;
78747
78748 BEGIN
78749
78750   _checkValue := pValue::integer;
78751
78752   IF (_checkValue::numeric < pValue) THEN
78753     RETURN (_checkValue + 1)::numeric;
78754   ELSE
78755     RETURN _checkValue::numeric;
78756   END IF;
78757
78758 END;
78759 $_$;
78760
78761
78762 ALTER FUNCTION public.roundup(numeric) OWNER TO admin;
78763
78764 --
78765 -- TOC entry 2158 (class 1255 OID 146567006)
78766 -- Dependencies: 4536 8
78767 -- Name: saveaddr(integer, text, text, text, text, text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
78768 --
78769
78770 CREATE FUNCTION saveaddr(integer, text, text, text, text, text, text, text, text, text) RETURNS integer
78771     LANGUAGE plpgsql
78772     AS $_$
78773 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78774 -- See www.xtuple.com/CPAL for the full text of the software license.
78775 DECLARE
78776   pAddrId ALIAS FOR $1;
78777   pNumber ALIAS FOR $2;
78778   pAddr1 ALIAS FOR $3;
78779   pAddr2 ALIAS FOR $4;
78780   pAddr3 ALIAS FOR $5;
78781   pCity ALIAS FOR $6;
78782   pState ALIAS FOR $7;
78783   pPostalCode ALIAS FOR $8;
78784   pCountry ALIAS FOR $9;
78785   pFlag ALIAS FOR $10;
78786   _returnVal INTEGER;
78787
78788 BEGIN
78789  
78790   SELECT saveAddr(pAddrId,pNumber, pAddr1,pAddr2,pAddr3,pCity,pState,pPostalCode,pCountry,true,'',pFlag) INTO _returnVal;
78791   
78792   RETURN _returnVal;
78793
78794 END;
78795 $_$;
78796
78797
78798 ALTER FUNCTION public.saveaddr(integer, text, text, text, text, text, text, text, text, text) OWNER TO admin;
78799
78800 --
78801 -- TOC entry 2157 (class 1255 OID 146567005)
78802 -- Dependencies: 4536 8
78803 -- Name: saveaddr(integer, text, text, text, text, text, text, text, text, boolean, text, text); Type: FUNCTION; Schema: public; Owner: admin
78804 --
78805
78806 CREATE FUNCTION saveaddr(integer, text, text, text, text, text, text, text, text, boolean, text, text) RETURNS integer
78807     LANGUAGE plpgsql
78808     AS $_$
78809 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78810 -- See www.xtuple.com/CPAL for the full text of the software license.
78811 DECLARE
78812   pAddrId ALIAS FOR $1;
78813   pNumber ALIAS FOR $2;
78814   pAddr1 ALIAS FOR $3;
78815   pAddr2 ALIAS FOR $4;
78816   pAddr3 ALIAS FOR $5;
78817   pCity ALIAS FOR $6;
78818   pState ALIAS FOR $7;
78819   pPostalCode ALIAS FOR $8;
78820   pCountry ALIAS FOR $9;
78821   pActive ALIAS FOR $10;
78822   pNotes ALIAS FOR $11;
78823   pFlag ALIAS FOR $12;
78824   _addrId INTEGER;
78825   _addrNumber INTEGER;
78826   _flag TEXT;
78827   _p RECORD;
78828   _cnt INTEGER;
78829   _notes TEXT;
78830
78831 BEGIN
78832   --Validate
78833   IF ((pFlag IS NULL) OR (pFlag = '') OR (pFlag = 'CHECK') OR (pFlag = 'CHANGEONE') OR (pFlag = 'CHANGEALL')) THEN
78834     IF (pFlag='') THEN
78835       _flag := 'CHECK';
78836     ELSE
78837       _flag := COALESCE(pFlag,'CHECK');
78838     END IF;
78839   ELSE
78840         RAISE EXCEPTION 'Invalid Flag (%). Valid flags are CHECK, CHANGEONE or CHANGEALL', pFlag;
78841   END IF;
78842
78843   _notes := COALESCE(pNotes,'');
78844   
78845   --If there is nothing here, get out
78846   IF ( (pNumber = '' OR pNumber IS NULL)
78847     AND (pAddr1 = '' OR pAddr1 IS NULL)
78848     AND (pAddr2 = '' OR pAddr2 IS NULL)
78849     AND (pAddr3 = '' OR pAddr3 IS NULL)
78850     AND (pCity = '' OR pCity IS NULL)
78851     AND (pState = '' OR pState IS NULL)
78852     AND (pPostalCode = '' OR pPostalCode IS NULL)
78853     AND (pCountry = '' OR pCountry IS NULL) ) THEN
78854     RETURN NULL;
78855   
78856   END IF;
78857   
78858   _addrId := COALESCE(pAddrId,-1);
78859
78860   --If we have an ID see if anything has changed, if not get out
78861   IF (_addrId >= 0) THEN
78862     SELECT * FROM addr INTO _p
78863     WHERE ((pAddrId=addr_id)
78864     AND (COALESCE(pNumber,addr_number)=addr_number)
78865     AND (COALESCE(pAddr1, '')=COALESCE(addr_line1, ''))
78866     AND (COALESCE(pAddr2, '')=COALESCE(addr_line2, ''))
78867     AND (COALESCE(pAddr3, '')=COALESCE(addr_line3, ''))
78868     AND (COALESCE(pCity, '')=COALESCE(addr_city, ''))
78869     AND (COALESCE(pState, '')=COALESCE(addr_state, ''))
78870     AND (COALESCE(pPostalCode, '')=COALESCE(addr_postalcode, ''))
78871     AND (COALESCE(pCountry, '')=COALESCE(addr_country, ''))
78872     AND (pActive=addr_active)
78873     AND (_notes=COALESCE(addr_notes,'')));
78874     IF (FOUND) THEN
78875       RETURN _addrId;
78876     END IF;
78877   END IF;
78878  
78879   --Check to see if duplicate address exists
78880
78881     SELECT addr_id, addr_notes INTO _p
78882     FROM addr 
78883     WHERE ((_addrId <> addr_id)
78884     AND  (COALESCE(UPPER(addr_line1),'') = COALESCE(UPPER(pAddr1),''))
78885     AND  (COALESCE(UPPER(addr_line2),'') = COALESCE(UPPER(pAddr2),''))
78886     AND  (COALESCE(UPPER(addr_line3),'') = COALESCE(UPPER(pAddr3),''))
78887     AND  (COALESCE(UPPER(addr_city),'') = COALESCE(UPPER(pCity),''))
78888     AND  (COALESCE(UPPER(addr_state),'') = COALESCE(UPPER(pState),''))
78889     AND  (COALESCE(UPPER(addr_postalcode),'') = COALESCE(UPPER(pPostalcode),''))
78890     AND  (COALESCE(UPPER(addr_country),'') = COALESCE(UPPER(pCountry),'')));
78891     IF (FOUND) THEN
78892         --Note:  To prevent overwriting of existing notes, the application
78893         --needs to load any existing notes for a matching address before altering them.
78894         IF (_notes <> _p.addr_notes) THEN
78895                 UPDATE addr 
78896                 SET addr_notes=addr_notes || '
78897 ' || _notes
78898                 WHERE addr_id=_p.addr_id;
78899         END IF;
78900         RETURN _p.addr_id;  --A matching address exits
78901     END IF;
78902  
78903   IF (_addrId < 0) THEN
78904     _flag := 'CHANGEONE';
78905   END IF;
78906
78907   IF (_flag = 'CHECK') THEN
78908     IF addrUseCount(_addrId) > 1 THEN
78909       RETURN -2;
78910     ELSIF (SELECT COUNT(addr_id)=0 FROM addr WHERE (addr_id=_addrId)) THEN
78911       _flag := 'CHANGEONE';
78912     ELSE
78913       _flag := 'CHANGEALL';
78914     END IF;
78915   END IF;
78916
78917   IF (_flag = 'CHANGEALL') THEN
78918     _addrNumber := pNumber;
78919     IF (_addrNumber IS NULL) THEN
78920       SELECT addr_number INTO _addrNumber
78921         FROM addr
78922        WHERE(addr_id = _addrId);
78923       IF (_addrNumber IS NULL) THEN
78924         _addrNumber := fetchNextNumber('AddressNumber');
78925       END IF;
78926     END IF;
78927    
78928     UPDATE addr SET
78929       addr_line1 = pAddr1, addr_line2 = pAddr2, addr_line3 = pAddr3,
78930       addr_city = pCity, addr_state = pState,
78931       addr_postalcode = pPostalcode, addr_country = pCountry,
78932       addr_active = pActive, addr_notes = pNotes
78933     WHERE addr_id = _addrId;
78934     RETURN _addrId;
78935
78936   ELSE
78937     SELECT NEXTVAL('addr_addr_id_seq') INTO _addrId;
78938
78939     IF (_flag = 'CHANGEONE') THEN
78940       _addrNumber := fetchNextNumber('AddressNumber');
78941     ELSE
78942       _addrNumber := COALESCE(pNumber::text,fetchNextNumber('AddressNumber'));
78943     END IF;
78944
78945     INSERT INTO addr ( addr_id, addr_number,
78946     addr_line1, addr_line2, addr_line3, 
78947     addr_city, addr_state, addr_postalcode, addr_country, 
78948     addr_active, addr_notes  
78949     ) VALUES ( _addrId, _addrNumber,
78950     pAddr1, pAddr2, pAddr3, 
78951     pCity, pState, pPostalcode, pCountry,
78952     pActive, _notes);
78953     RETURN _addrId;
78954         
78955   END IF;
78956 END;
78957 $_$;
78958
78959
78960 ALTER FUNCTION public.saveaddr(integer, text, text, text, text, text, text, text, text, boolean, text, text) OWNER TO admin;
78961
78962 --
78963 -- TOC entry 2159 (class 1255 OID 146567007)
78964 -- Dependencies: 4536 8
78965 -- Name: savealarm(integer, text, date, time without time zone, integer, text, boolean, text, boolean, text, boolean, text, text, integer, text); Type: FUNCTION; Schema: public; Owner: admin
78966 --
78967
78968 CREATE FUNCTION savealarm(integer, text, date, time without time zone, integer, text, boolean, text, boolean, text, boolean, text, text, integer, text) RETURNS integer
78969     LANGUAGE plpgsql
78970     AS $_$
78971 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
78972 -- See www.xtuple.com/CPAL for the full text of the software license.
78973 DECLARE
78974   pAlarmId ALIAS FOR $1;
78975   pAlarmNumber ALIAS FOR $2;
78976   pDate ALIAS FOR $3;
78977   pTime ALIAS FOR $4;
78978   pOffset ALIAS FOR $5;
78979   pQualifier ALIAS FOR $6;
78980   pEvent ALIAS FOR $7;
78981   pEventRecipient ALIAS FOR $8;
78982   pEmail ALIAS FOR $9;
78983   pEmailRecipient ALIAS FOR $10;
78984   pSysmsg ALIAS FOR $11;
78985   pSysmsgRecipient ALIAS FOR $12;
78986   pSource ALIAS FOR $13;
78987   pSourceId ALIAS FOR $14;
78988   pFlag ALIAS FOR $15;
78989   _alarmId INTEGER;
78990   _alarmNumber TEXT;
78991   _alarmTime TIMESTAMP;
78992   _alarmInterval INTERVAL;
78993   _alarmTrigger TIMESTAMP;
78994   _isNew BOOLEAN;
78995   _flag TEXT;
78996   _alarmCount INTEGER := 0;
78997   _debug BOOLEAN := false;
78998
78999 BEGIN
79000   IF (_debug) THEN
79001     RAISE NOTICE 'pAlarmId = %', pAlarmId;
79002     RAISE NOTICE 'pAlarmNumber = %', pAlarmNumber;
79003     RAISE NOTICE 'pDate = %', pDate;
79004     RAISE NOTICE 'pTime = %', pTime;
79005     RAISE NOTICE 'pOffset = %', pOffset;
79006     RAISE NOTICE 'pQualifier = %', pQualifier;
79007     RAISE NOTICE 'pEvent = %', pEvent;
79008     RAISE NOTICE 'pEventRecipient = %', pEventRecipient;
79009     RAISE NOTICE 'pEmail = %', pEmail;
79010     RAISE NOTICE 'pEmailRecipient = %', pEmailRecipient;
79011     RAISE NOTICE 'pSysmsg = %', pSysmsg;
79012     RAISE NOTICE 'pSysmsgRecipient = %', pSysmsgRecipient;
79013     RAISE NOTICE 'pSource = %', pSource;
79014     RAISE NOTICE 'pSourceId = %', pSourceId;
79015     RAISE NOTICE 'pFlag = %', pFlag;
79016   END IF;
79017   --Validate
79018   IF ((pFlag IS NULL) OR (pFlag = '') OR (pFlag = 'CHECK') OR (pFlag = 'CHANGEONE') OR (pFlag = 'CHANGEALL')) THEN
79019     IF (pFlag='') THEN
79020       _flag := 'CHECK';
79021     ELSE
79022       _flag := COALESCE(pFlag,'CHECK');
79023     END IF;
79024   ELSE
79025         RAISE EXCEPTION 'Invalid Flag (%). Valid flags are CHECK, CHANGEONE or CHANGEALL', pFlag;
79026   END IF;
79027   
79028   --If there is nothing here get out
79029   IF ( (pAlarmId IS NULL OR pAlarmId = -1)
79030         AND (pOffset IS NULL)
79031         AND (pSourceId IS NULL)
79032         AND (COALESCE(pQualifier, '') = '')
79033         AND (COALESCE(pEventRecipient, '') = '')
79034         AND (COALESCE(pEmailRecipient, '') = '')
79035         AND (COALESCE(pSysmsgRecipient, '') = '')
79036         AND (COALESCE(pSource, '') = '') ) THEN
79037         
79038         RETURN NULL;
79039
79040   END IF;
79041   
79042   IF (pAlarmId IS NULL OR pAlarmId = -1) THEN 
79043     _isNew := true;
79044     _alarmId := nextval('alarm_alarm_id_seq');
79045     _alarmNumber := fetchNextNumber('AlarmNumber');
79046   ELSE
79047     SELECT COUNT(alarm_id) INTO _alarmCount
79048       FROM alarm
79049       WHERE ((alarm_id=pAlarmId)
79050       AND (alarm_source=pSource)
79051       AND (alarm_source_id=pSourceId));
79052
79053     -- ask whether new or update if name changes
79054     -- but only if this isn't a new record with a pre-allocated id
79055     IF (_alarmCount < 1 AND _flag = 'CHECK') THEN
79056       IF (EXISTS(SELECT alarm_id
79057                  FROM alarm
79058                  WHERE (alarm_id=pAlarmId))) THEN
79059         RETURN -10;
79060       ELSE
79061         _isNew := true;
79062         _alarmNumber := fetchNextNumber('AlarmNumber');
79063       END IF;
79064     ELSIF (_flag = 'CHANGEONE') THEN
79065       _isNew := true;
79066       _alarmId := nextval('alarm_alarm_id_seq');
79067       _alarmNumber := fetchNextNumber('AlarmNumber');
79068     END IF;
79069   END IF;
79070
79071   _alarmNumber := COALESCE(_alarmNumber,pAlarmNumber,fetchNextNumber('AlarmNumber'));
79072
79073   _alarmTime := COALESCE(pDate, CURRENT_DATE) + COALESCE(pTime, CURRENT_TIME);
79074   IF (COALESCE(pOffset, 0) > 0) THEN
79075     _alarmInterval := CASE WHEN (pQualifier IN ('MB', 'MA')) THEN CAST(pOffset AS TEXT) || ' minutes'
79076                            WHEN (pQualifier IN ('HB', 'HA')) THEN CAST(pOffset AS TEXT) || ' hours'
79077                            WHEN (pQualifier IN ('DB', 'DA')) THEN CAST(pOffset AS TEXT) || ' days'
79078                            ELSE ''
79079                      END;
79080     _alarmTrigger := CASE WHEN (pQualifier IN ('MB', 'HB', 'DB')) THEN _alarmTime - _alarmInterval 
79081                           WHEN (pQualifier IN ('MA', 'HA', 'DA')) THEN _alarmTime + _alarmInterval
79082                           ELSE _alarmTime
79083                      END; 
79084   ELSE
79085     _alarmTrigger := _alarmTime;
79086   END IF;
79087
79088   IF (_isNew) THEN
79089     _alarmId := COALESCE(_alarmId,pAlarmId,nextval('alarm_alarm_id_seq'));
79090  
79091     INSERT INTO alarm (
79092       alarm_id,alarm_number,
79093       alarm_event, alarm_email, alarm_sysmsg, alarm_trigger,
79094       alarm_time, alarm_time_offset, alarm_time_qualifier,
79095       alarm_creator, alarm_event_recipient, alarm_email_recipient, alarm_sysmsg_recipient,
79096       alarm_source, alarm_source_id )
79097     VALUES (
79098       _alarmId, _alarmNumber,
79099       pEvent, pEmail, pSysmsg, _alarmTrigger,
79100       _alarmTime, pOffset, pQualifier,
79101       getEffectiveXtUser(), pEventRecipient, pEmailRecipient, pSysmsgRecipient,
79102       pSource, pSourceId );
79103
79104     RETURN _alarmId;
79105
79106   ELSE
79107     UPDATE alarm SET
79108       alarm_number=_alarmNumber,
79109       alarm_event=COALESCE(pEvent, alarm_event),
79110       alarm_email=COALESCE(pEmail, alarm_event),
79111       alarm_sysmsg=COALESCE(pSysmsg, alarm_event),
79112       alarm_trigger=_alarmTrigger,
79113       alarm_time=_alarmTime,
79114       alarm_time_offset=COALESCE(pOffset, alarm_time_offset),
79115       alarm_time_qualifier=COALESCE(pQualifier, alarm_time_qualifier),
79116       alarm_event_recipient=COALESCE(pEventRecipient, alarm_event_recipient),
79117       alarm_email_recipient=COALESCE(pEmailRecipient, alarm_email_recipient),
79118       alarm_sysmsg_recipient=COALESCE(pSysmsgRecipient, alarm_sysmsg_recipient)
79119     WHERE (alarm_id=pAlarmId);
79120     
79121     RETURN pAlarmId;
79122
79123   END IF;
79124 END;
79125 $_$;
79126
79127
79128 ALTER FUNCTION public.savealarm(integer, text, date, time without time zone, integer, text, boolean, text, boolean, text, boolean, text, text, integer, text) OWNER TO admin;
79129
79130 --
79131 -- TOC entry 2160 (class 1255 OID 146567009)
79132 -- Dependencies: 4536 8
79133 -- Name: savebomhead(integer, text, date, text, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
79134 --
79135
79136 CREATE FUNCTION savebomhead(integer, text, date, text, numeric, numeric) RETURNS integer
79137     LANGUAGE plpgsql
79138     AS $_$
79139 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
79140 -- See www.xtuple.com/CPAL for the full text of the software license.
79141 DECLARE
79142   pItemid ALIAS FOR $1;
79143   pRevision ALIAS FOR $2;
79144   pRevisionDate ALIAS FOR $3;
79145   pDocumentNumber ALIAS FOR $4;
79146   pBatchSize ALIAS FOR $5;
79147   pRequiredQtyPer ALIAS FOR $6;
79148   _seq INTEGER;
79149   _p RECORD;
79150   _revid INTEGER;
79151   
79152 BEGIN
79153
79154   IF (NOT fetchMetricBool('RevControl')) THEN -- Deal with BOM if Rev Control Turned off
79155     SELECT bomhead_id INTO _seq
79156     FROM bomhead 
79157     WHERE (bomhead_item_id=pItemid);
79158
79159     IF (NOT FOUND) THEN  -- No bomhead exists
79160       _seq := NEXTVAL('bomhead_bomhead_id_seq');
79161       
79162       INSERT INTO bomhead 
79163         (bomhead_id,bomhead_item_id,bomhead_docnum,bomhead_revision,
79164         bomhead_revisiondate,bomhead_batchsize,bomhead_requiredqtyper,bomhead_rev_id)
79165         VALUES 
79166         (_seq,pItemid, pDocumentNumber, pRevision, pRevisionDate, pBatchSize, pRequiredQtyPer,-1);   
79167     ELSE
79168       UPDATE bomhead SET
79169         bomhead_revision        = pRevision,
79170         bomhead_revisiondate    = pRevisionDate,
79171         bomhead_docnum          = pDocumentNumber,
79172         bomhead_batchsize       = pBatchSize,
79173         bomhead_requiredqtyper = pRequiredQtyPer
79174       WHERE (bomhead_id=_seq);
79175     END IF;
79176     
79177     RETURN _seq;
79178   ELSE  -- Deal with Revision Control
79179     IF (COALESCE(pRevision,'') = '' AND getActiveRevId('BOM',pItemid) != -1) THEN 
79180         RAISE EXCEPTION 'Revision Control records exist for item.  You must provide a new or existing revision number.';
79181     END IF;
79182     
79183     SELECT * INTO _p
79184     FROM bomhead
79185       LEFT OUTER JOIN rev ON (bomhead_rev_id=rev_id),
79186       item
79187     WHERE ((bomhead_item_id=pItemid)
79188     AND (COALESCE(bomhead_revision,'')=COALESCE(pRevision,''))
79189     AND (bomhead_item_id=item_id));
79190
79191     IF (NOT FOUND) THEN  -- This is a new bomhead record
79192       IF LENGTH(pRevision) > 0 THEN  -- We need to create a revision record   
79193         SELECT createbomrev(pItemid, pRevision) INTO _revid;
79194         
79195         UPDATE bomhead SET
79196           bomhead_revisiondate          = pRevisiondate,
79197           bomhead_docnum                = pDocumentNumber,
79198           bomhead_batchsize             = pBatchsize,
79199           bomhead_requiredqtyper        = pRequiredqtyper
79200         WHERE (bomhead_rev_id=_revid);
79201         
79202         SELECT bomhead_id INTO _seq
79203         FROM bomhead
79204         WHERE (bomhead_rev_id=_revid);
79205         
79206         RETURN _seq;      
79207       ELSE  -- Just create a regular bom header record
79208        _seq := NEXTVAL('bomhead_bomhead_id_seq');
79209        
79210        INSERT INTO bomhead 
79211         (bomhead_id,bomhead_item_id,bomhead_docnum,bomhead_revision,
79212         bomhead_revisiondate,bomhead_batchsize,bomhead_requiredqtyper,bomhead_rev_id)
79213         VALUES 
79214         (_seq,pItemid, pDocumentNumber, pRevision, pRevisionDate, pBatchSize, pRequiredQtyPer,-1);
79215         
79216         RETURN _seq;      
79217         
79218       END IF;
79219     ELSE  -- We need to update a record
79220       IF (_p.rev_status = 'I') THEN
79221         RAISE EXCEPTION 'Revision % for % is inactive.  Update not allowed.', _p.rev_number, _p.item_number;
79222
79223       ELSIF (COALESCE(pRevision,'') = COALESCE(_p.bomhead_revision,'')) THEN  -- No change, just update
79224         UPDATE bomhead SET
79225           bomhead_revisiondate          = pRevisiondate,
79226           bomhead_docnum                = pDocumentNumber,
79227           bomhead_batchsize             = pBatchSize,
79228           bomhead_requiredqtyper        = pRequiredqtyper
79229         WHERE (bomhead_id=_p.bomhead_id);
79230
79231         RETURN _p.bomhead_id;
79232         
79233       ELSE -- Need a new revision
79234         SELECT createbomrev(pItemid, pRevision) INTO _revid;
79235         
79236         UPDATE bomhead SET
79237           bomhead_revisiondate          = pRevisiondate,
79238           bomhead_docnum                = pDocumentNumber,
79239           bomhead_batchsize             = pBatchSize,
79240           bomhead_requiredqtyper        = pRequiredqtyper
79241         WHERE (bomhead_rev_id=_revid);
79242
79243         SELECT bomhead_id INTO _seq
79244         FROM bomhead
79245         WHERE (bomhead_rev_id=_revid);
79246         
79247         RETURN _seq;
79248       END IF;
79249     END IF;
79250   END IF;
79251
79252   RETURN _seq;
79253
79254 END;
79255 $_$;
79256
79257
79258 ALTER FUNCTION public.savebomhead(integer, text, date, text, numeric, numeric) OWNER TO admin;
79259
79260 --
79261 -- TOC entry 2162 (class 1255 OID 146567011)
79262 -- Dependencies: 4536 8
79263 -- Name: savecntct(integer, text, integer, text, text, text, text, text, text, text, text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
79264 --
79265
79266 CREATE FUNCTION savecntct(pcntctid integer, pcontactnumber text, paddrid integer, phonorific text, pfirstname text, pmiddlename text, plastname text, psuffix text, pphone text, pphone2 text, pfax text, pemail text, pwebaddr text, ptitle text, pflag text) RETURNS integer
79267     LANGUAGE plpgsql
79268     AS $$
79269 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
79270 -- See www.xtuple.com/CPAL for the full text of the software license.
79271 DECLARE
79272   _returnVal INTEGER;
79273
79274 BEGIN
79275   
79276   SELECT saveCntct(pCntctId,pContactNumber,NULL,pAddrId,pHonorific,pFirstName,pMiddleName,pLastName,pSuffix,NULL,
79277         NULL,pPhone,pPhone2,pFax,pEmail,pWebAddr,NULL,pTitle,pFlag, NULL) INTO _returnVal;
79278   
79279   RETURN _returnVal;
79280
79281 END;
79282 $$;
79283
79284
79285 ALTER FUNCTION public.savecntct(pcntctid integer, pcontactnumber text, paddrid integer, phonorific text, pfirstname text, pmiddlename text, plastname text, psuffix text, pphone text, pphone2 text, pfax text, pemail text, pwebaddr text, ptitle text, pflag text) OWNER TO admin;
79286
79287 --
79288 -- TOC entry 2161 (class 1255 OID 146567010)
79289 -- Dependencies: 4536 8
79290 -- Name: savecntct(integer, text, integer, integer, text, text, text, text, text, text, boolean, text, text, text, text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
79291 --
79292
79293 CREATE FUNCTION savecntct(pcntctid integer, pcontactnumber text, pcrmacctid integer, paddrid integer, phonorific text, pfirstname text, pmiddlename text, plastname text, psuffix text, pinitials text, pactive boolean, pphone text, pphone2 text, pfax text, pemail text, pwebaddr text, pnotes text, ptitle text, pflag text) RETURNS integer
79294     LANGUAGE plpgsql
79295     AS $$
79296 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
79297 -- See www.xtuple.com/CPAL for the full text of the software license.
79298 DECLARE
79299   _returnVal INTEGER;
79300
79301 BEGIN
79302   
79303   SELECT saveCntct( pCntctId, pContactNumber, pCrmAcctId, pAddrId, pHonorific, pFirstName, pMiddleName, pLastName, pSuffix, pInitials, 
79304         pActive, pPhone, pPhone2, pFax, pEmail, pWebAddr, pNotes, pTitle, pFlag, NULL) INTO _returnVal;
79305   RETURN _returnVal;
79306
79307 END;
79308 $$;
79309
79310
79311 ALTER FUNCTION public.savecntct(pcntctid integer, pcontactnumber text, pcrmacctid integer, paddrid integer, phonorific text, pfirstname text, pmiddlename text, plastname text, psuffix text, pinitials text, pactive boolean, pphone text, pphone2 text, pfax text, pemail text, pwebaddr text, pnotes text, ptitle text, pflag text) OWNER TO admin;
79312
79313 --
79314 -- TOC entry 2163 (class 1255 OID 146567012)
79315 -- Dependencies: 4536 8
79316 -- Name: savecntct(integer, text, integer, integer, text, text, text, text, text, text, boolean, text, text, text, text, text, text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
79317 --
79318
79319 CREATE FUNCTION savecntct(pcntctid integer, pcontactnumber text, pcrmacctid integer, paddrid integer, phonorific text, pfirstname text, pmiddlename text, plastname text, psuffix text, pinitials text, pactive boolean, pphone text, pphone2 text, pfax text, pemail text, pwebaddr text, pnotes text, ptitle text, pflag text, pownerusername text) RETURNS integer
79320     LANGUAGE plpgsql
79321     AS $$
79322 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
79323 -- See www.xtuple.com/CPAL for the full text of the software license.
79324 DECLARE
79325   _cntctId INTEGER;
79326   _cntctNumber TEXT;
79327   _isNew BOOLEAN;
79328   _flag TEXT;
79329   _contactCount INTEGER := 0;
79330
79331 BEGIN
79332   --Validate
79333   IF ((pFlag IS NULL) OR (pFlag = '') OR (pFlag = 'CHECK') OR (pFlag = 'CHANGEONE') OR (pFlag = 'CHANGEALL')) THEN
79334     IF (pFlag='') THEN
79335       _flag := 'CHECK';
79336     ELSE
79337       _flag := COALESCE(pFlag,'CHECK');
79338     END IF;
79339   ELSE
79340         RAISE EXCEPTION 'Invalid Flag (%). Valid flags are CHECK, CHANGEONE or CHANGEALL', pFlag;
79341   END IF;
79342   
79343   --If there is nothing here get out
79344   IF ( (pCntctId IS NULL OR pCntctId = -1)
79345         AND (pAddrId IS NULL)
79346         AND (COALESCE(pFirstName, '') = '')
79347         AND (COALESCE(pMiddleName, '') = '')
79348         AND (COALESCE(pLastName, '') = '')
79349         AND (COALESCE(pSuffix, '') = '')
79350         AND (COALESCE(pHonorific, '') = '')
79351         AND (COALESCE(pInitials, '') = '')
79352         AND (COALESCE(pPhone, '') = '')
79353         AND (COALESCE(pPhone2, '') = '')
79354         AND (COALESCE(pFax, '') = '')
79355         AND (COALESCE(pEmail, '') = '')
79356         AND (COALESCE(pWebAddr, '') = '')
79357         AND (COALESCE(pNotes, '') = '')
79358         AND (COALESCE(pTitle, '') = '') ) THEN
79359         
79360         RETURN NULL;
79361
79362   END IF;
79363   
79364   IF (pCntctId IS NULL OR pCntctId = -1) THEN 
79365     _isNew := true;
79366     _cntctId := nextval('cntct_cntct_id_seq');
79367     _cntctNumber := COALESCE(pContactNumber,fetchNextNumber('ContactNumber'));
79368   ELSE
79369     SELECT COUNT(cntct_id) INTO _contactCount
79370       FROM cntct
79371       WHERE ((cntct_id=pCntctId)
79372       AND (cntct_first_name=pFirstName)
79373       AND (cntct_last_name=pLastName));
79374
79375     -- ask whether new or update if name changes
79376     -- but only if this isn't a new record with a pre-allocated id
79377     IF (_contactCount < 1 AND _flag = 'CHECK') THEN
79378       IF (EXISTS(SELECT cntct_id
79379                  FROM cntct
79380                  WHERE (cntct_id=pCntctId))) THEN
79381         RETURN -10;
79382       ELSE
79383         _isNew := true;
79384         _cntctNumber := fetchNextNumber('ContactNumber');
79385       END IF;
79386     ELSIF (_flag = 'CHANGEONE') THEN
79387       _isNew := true;
79388       _cntctId := nextval('cntct_cntct_id_seq');
79389       _cntctNumber := fetchNextNumber('ContactNumber');
79390     ELSIF (_flag = 'CHANGEALL') THEN
79391       _isNew := false;
79392     END IF;
79393   END IF;
79394
79395   IF (pContactNumber = '') THEN
79396     _cntctNumber := fetchNextNumber('ContactNumber');
79397   ELSE
79398     _cntctNumber := COALESCE(_cntctNumber,pContactNumber,fetchNextNumber('ContactNumber'));
79399   END IF;
79400
79401   IF (_isNew) THEN
79402     _cntctId := COALESCE(_cntctId,pCntctId,nextval('cntct_cntct_id_seq'));
79403  
79404     INSERT INTO cntct (
79405       cntct_id,cntct_number,
79406       cntct_crmacct_id,cntct_addr_id,cntct_first_name,
79407       cntct_last_name,cntct_honorific,cntct_initials,
79408       cntct_active,cntct_phone,cntct_phone2,
79409       cntct_fax,cntct_email,cntct_webaddr,
79410       cntct_notes,cntct_title,cntct_middle,cntct_suffix, cntct_owner_username ) 
79411     VALUES (
79412       _cntctId, COALESCE(_cntctNumber,fetchNextNumber('ContactNumber')) ,pCrmAcctId,pAddrId,
79413       pFirstName,pLastName,pHonorific,
79414       pInitials,COALESCE(pActive,true),pPhone,pPhone2,pFax,
79415       pEmail,pWebAddr,pNotes,pTitle,pMiddleName,pSuffix,pOwnerUsername );
79416
79417     RETURN _cntctId;
79418
79419   ELSE
79420     UPDATE cntct SET
79421       cntct_number=COALESCE(_cntctNumber,fetchNextNumber('ContactNumber')),
79422       cntct_crmacct_id=COALESCE(pCrmAcctId,cntct_crmacct_id),
79423       cntct_addr_id=COALESCE(pAddrId,cntct_addr_id),
79424       cntct_first_name=COALESCE(pFirstName,cntct_first_name),
79425       cntct_last_name=COALESCE(pLastName,cntct_last_name),
79426       cntct_honorific=COALESCE(pHonorific,cntct_honorific),
79427       cntct_initials=COALESCE(pInitials,cntct_initials),
79428       cntct_active=COALESCE(pActive,cntct_active),
79429       cntct_phone=COALESCE(pPhone,cntct_phone),
79430       cntct_phone2=COALESCE(pPhone2,cntct_phone2),
79431       cntct_fax=COALESCE(pFax,cntct_fax),
79432       cntct_email=COALESCE(pEmail,cntct_email),
79433       cntct_webaddr=COALESCE(pWebAddr,cntct_webaddr),
79434       cntct_notes=COALESCE(pNotes,cntct_notes),
79435       cntct_title=COALESCE(pTitle,cntct_title),
79436       cntct_middle=COALESCE(pMiddleName,cntct_middle),
79437       cntct_suffix=COALESCE(pSuffix,cntct_suffix),
79438       cntct_owner_username=COALESCE(pOwnerUsername, cntct_owner_username) 
79439     WHERE (cntct_id=pCntctId);
79440     
79441     RETURN pCntctId;
79442
79443   END IF;
79444 END;
79445 $$;
79446
79447
79448 ALTER FUNCTION public.savecntct(pcntctid integer, pcontactnumber text, pcrmacctid integer, paddrid integer, phonorific text, pfirstname text, pmiddlename text, plastname text, psuffix text, pinitials text, pactive boolean, pphone text, pphone2 text, pfax text, pemail text, pwebaddr text, pnotes text, ptitle text, pflag text, pownerusername text) OWNER TO admin;
79449
79450 --
79451 -- TOC entry 2165 (class 1255 OID 146567014)
79452 -- Dependencies: 4536 8
79453 -- Name: saveimageass(text, integer, character, integer); Type: FUNCTION; Schema: public; Owner: admin
79454 --
79455
79456 CREATE FUNCTION saveimageass(text, integer, character, integer) RETURNS integer
79457     LANGUAGE plpgsql
79458     AS $_$
79459 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
79460 -- See www.xtuple.com/CPAL for the full text of the software license.
79461 DECLARE
79462   pSource       ALIAS FOR $1;
79463   pSourceId     ALIAS FOR $2;
79464   pPurpose      ALIAS FOR $3;
79465   pImageid      ALIAS FOR $4;
79466   _imageassId INTEGER = 0;
79467
79468 BEGIN
79469
79470 --  See if this link already exists
79471   SELECT imageass_id INTO _imageassId
79472   FROM imageass
79473   WHERE ((imageass_source_id=pSourceId)
79474   AND (imageass_source=pSource)
79475   AND (imageass_image_id=pImageId)
79476   AND (imageass_purpose=pPurpose));
79477
79478   IF (FOUND) THEN
79479     RETURN _imageassId;
79480   END IF;
79481   
79482 -- See if a record with this purpose already exists (item only)
79483   IF (pSource = 'I' AND pPurpose != 'M') THEN
79484     SELECT imageass_id INTO _imageassId
79485     FROM imageass
79486     WHERE ((imageass_source_id=pSourceId)
79487     AND (imageass_source=pSource)
79488     AND (imageass_purpose=pPurpose));
79489   END IF;
79490
79491   IF (_imageassId > 0) THEN
79492     UPDATE imageass SET
79493       imageass_image_id=pImageId
79494     WHERE (imageass_id=_imageassId);
79495   ELSE
79496     _imageassId := NEXTVAL('imageass_imageass_id_seq');
79497     INSERT INTO imageass VALUES (_imageassId,pSourceId,pSource,pImageid,CASE WHEN pSource='I' THEN pPurpose ELSE 'M' END);
79498   END IF;
79499   
79500   RETURN _imageassId;
79501 END;
79502 $_$;
79503
79504
79505 ALTER FUNCTION public.saveimageass(text, integer, character, integer) OWNER TO admin;
79506
79507 --
79508 -- TOC entry 2166 (class 1255 OID 146567015)
79509 -- Dependencies: 4536 8
79510 -- Name: saveipsitem(integer, integer, integer, numeric, numeric, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
79511 --
79512
79513 CREATE FUNCTION saveipsitem(integer, integer, integer, numeric, numeric, integer, integer) RETURNS integer
79514     LANGUAGE plpgsql
79515     AS $_$
79516 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
79517 -- See www.xtuple.com/CPAL for the full text of the software license.
79518 DECLARE
79519   pIpsItemId    ALIAS FOR $1;
79520   pIpsHeadId    ALIAS FOR $2;
79521   pItemId       ALIAS FOR $3;
79522   pQtyBreak     ALIAS FOR $4;
79523   pPrice        ALIAS FOR $5;
79524   pQtyUomId     ALIAS FOR $6;
79525   pPriceUomId   ALIAS FOR $7;
79526   _ipsitemid    INTEGER;
79527   _new          BOOLEAN;
79528 BEGIN
79529
79530   -- Validation
79531   IF (SELECT COUNT(item_id)=0 FROM item WHERE (item_id=pItemId)) THEN
79532     RAISE EXCEPTION 'You must provide a valid Item';
79533   ELSIF (COALESCE(pQtyBreak,0) < 0) THEN
79534     RAISE EXCEPTION 'Quantity can not be a negative value';
79535   ELSIF (COALESCE(pPrice,0) < 0) THEN
79536     RAISE EXCEPTION 'Price must be a negative value';
79537   ELSIF ((pQtyUomId IS NOT NULL) AND (SELECT COUNT(item_id)=0 FROM
79538         (SELECT item_id
79539          FROM item
79540          WHERE ((item_id=pItemId)
79541            AND (item_inv_uom_id=pQtyUomId))
79542          UNION
79543          SELECT item_id
79544          FROM item,itemuomconv,itemuom,uomtype
79545          WHERE ((item_id=pItemId)
79546            AND (itemuomconv_item_id=item_id)
79547            AND (itemuomconv_from_uom_id=pQtyUomId)
79548            AND (itemuom_itemuomconv_id=itemuomconv_id)
79549            AND (itemuom_uomtype_id=uomtype_id)
79550            AND (uomtype_name='Selling'))
79551          UNION
79552          SELECT item_id
79553          FROM item,itemuomconv,itemuom,uomtype
79554          WHERE ((item_id=pItemId)
79555            AND (itemuomconv_item_id=item_id)
79556            AND (itemuomconv_to_uom_id=pQtyUomId)
79557            AND (itemuom_itemuomconv_id=itemuomconv_id)
79558            AND (itemuom_uomtype_id=uomtype_id)
79559            AND (uomtype_name='Selling'))) AS data)) THEN
79560     RAISE EXCEPTION 'Qty UOM Must be a valid Selling UOM for the Item';
79561   ELSIF ((pPriceUomId IS NOT NULL) AND (SELECT COUNT(item_id)=0 FROM
79562         (SELECT item_id
79563          FROM item
79564          WHERE ((item_id=pItemId)
79565            AND (item_inv_uom_id=pPriceUomId))
79566          UNION
79567          SELECT item_id
79568          FROM item,itemuomconv,itemuom,uomtype
79569          WHERE ((item_id=pItemId)
79570            AND (itemuomconv_item_id=item_id)
79571            AND (itemuomconv_from_uom_id=pPriceUomId)
79572            AND (itemuom_itemuomconv_id=itemuomconv_id)
79573            AND (itemuom_uomtype_id=uomtype_id)
79574            AND (uomtype_name='Selling'))
79575          UNION
79576          SELECT item_id
79577          FROM item,itemuomconv,itemuom,uomtype
79578          WHERE ((item_id=pItemId)
79579            AND (itemuomconv_item_id=item_id)
79580            AND (itemuomconv_to_uom_id=pPriceUomId)
79581            AND (itemuom_itemuomconv_id=itemuomconv_id)
79582            AND (itemuom_uomtype_id=uomtype_id)
79583            AND (uomtype_name='Selling'))) AS data)) THEN
79584     RAISE EXCEPTION 'Price UOM Must be a valid Selling UOM for the Item';
79585   END IF;
79586
79587   _new := TRUE;
79588
79589   IF (pIpsItemId IS NOT NULL) THEN
79590     SELECT ipsitem_id INTO _ipsitemid
79591     FROM ipsitem
79592     WHERE (ipsitem_id=pIpsItemId);
79593
79594     IF (FOUND) THEN
79595       _new := FALSE;
79596     ELSE
79597       RAISE EXCEPTION 'Pricing Schedule Item not found.';
79598     END IF;
79599   ELSE
79600     SELECT ipsitem_id INTO _ipsitemid
79601     FROM ipsitem
79602     WHERE ((ipsitem_ipshead_id  = pIpsheadId)
79603       AND (ipsitem_item_id      = pItemId)
79604       AND (ipsitem_qtybreak     = pQtyBreak)
79605       AND (ipsitem_qty_uom_id = COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))) 
79606       AND (ipsitem_price_uom_id =
79607            CASE
79608              WHEN (pQtyUomId = (SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)) THEN
79609                COALESCE(pPriceUomId,pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79610              ELSE
79611                COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79612            END));
79613   END IF;
79614   
79615   IF (FOUND) THEN
79616     _new := false;
79617   ELSE
79618     _ipsitemid := nextval('ipsitem_ipsitem_id_seq');
79619   END IF;
79620   
79621   IF (_new) THEN
79622     INSERT INTO ipsitem (
79623       ipsitem_id,
79624       ipsitem_ipshead_id, 
79625       ipsitem_item_id, 
79626       ipsitem_qtybreak, 
79627       ipsitem_price, 
79628       ipsitem_qty_uom_id, 
79629       ipsitem_price_uom_id,
79630       ipsitem_discntprcnt,
79631       ipsitem_fixedamtdiscount) 
79632     VALUES (
79633       _ipsitemid,
79634       pIpsheadId,
79635       pItemId,
79636       pQtyBreak, 
79637       pPrice,
79638       COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)), 
79639       CASE
79640         WHEN (pQtyUomId = (SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)) THEN
79641           COALESCE(pPriceUomId,pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79642         ELSE
79643           COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79644       END,
79645       0.0,
79646       0.0);
79647   ELSE 
79648     UPDATE ipsitem SET 
79649       ipsitem_qtybreak = pQtyBreak, 
79650       ipsitem_price = pPrice, 
79651       ipsitem_qty_uom_id = COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)), 
79652       ipsitem_price_uom_id =
79653       CASE
79654         WHEN (pQtyUomId = (SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)) THEN
79655           COALESCE(pPriceUomId,pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79656         ELSE
79657           COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79658       END
79659     WHERE (ipsitem_id=_ipsitemid);
79660    END IF;
79661
79662    RETURN _ipsitemid;
79663
79664 END;
79665 $_$;
79666
79667
79668 ALTER FUNCTION public.saveipsitem(integer, integer, integer, numeric, numeric, integer, integer) OWNER TO admin;
79669
79670 --
79671 -- TOC entry 2167 (class 1255 OID 146567016)
79672 -- Dependencies: 4536 8
79673 -- Name: saveipsitem(integer, integer, integer, numeric, numeric, integer, integer, numeric, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
79674 --
79675
79676 CREATE FUNCTION saveipsitem(pipsitemid integer, pipsheadid integer, pitemid integer, pqtybreak numeric, pprice numeric, pqtyuomid integer, ppriceuomid integer, ppercent numeric, pfixedamt numeric, ptype text) RETURNS integer
79677     LANGUAGE plpgsql
79678     AS $$
79679 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
79680 -- See www.xtuple.com/CPAL for the full text of the software license.
79681 DECLARE
79682   _ipsitemid    INTEGER;
79683   _new          BOOLEAN;
79684 BEGIN
79685
79686   -- Validation
79687   IF (SELECT COUNT(item_id)=0 FROM item WHERE (item_id=pItemId)) THEN
79688     RAISE EXCEPTION 'You must provide a valid Item';
79689   ELSIF (COALESCE(pQtyBreak,0) < 0) THEN
79690     RAISE EXCEPTION 'Quantity can not be a negative value';
79691   ELSIF (COALESCE(pPrice,0) < 0) THEN
79692     RAISE EXCEPTION 'Price must be a negative value';
79693   ELSIF ((pQtyUomId IS NOT NULL) AND (SELECT COUNT(item_id)=0 FROM
79694         (SELECT item_id
79695          FROM item
79696          WHERE ((item_id=pItemId)
79697            AND (item_inv_uom_id=pQtyUomId))
79698          UNION
79699          SELECT item_id
79700          FROM item,itemuomconv,itemuom,uomtype
79701          WHERE ((item_id=pItemId)
79702            AND (itemuomconv_item_id=item_id)
79703            AND (itemuomconv_from_uom_id=pQtyUomId)
79704            AND (itemuom_itemuomconv_id=itemuomconv_id)
79705            AND (itemuom_uomtype_id=uomtype_id)
79706            AND (uomtype_name='Selling'))
79707          UNION
79708          SELECT item_id
79709          FROM item,itemuomconv,itemuom,uomtype
79710          WHERE ((item_id=pItemId)
79711            AND (itemuomconv_item_id=item_id)
79712            AND (itemuomconv_to_uom_id=pQtyUomId)
79713            AND (itemuom_itemuomconv_id=itemuomconv_id)
79714            AND (itemuom_uomtype_id=uomtype_id)
79715            AND (uomtype_name='Selling'))) AS data)) THEN
79716     RAISE EXCEPTION 'Qty UOM Must be a valid Selling UOM for the Item';
79717   ELSIF ((pPriceUomId IS NOT NULL) AND (SELECT COUNT(item_id)=0 FROM
79718         (SELECT item_id
79719          FROM item
79720          WHERE ((item_id=pItemId)
79721            AND (item_inv_uom_id=pPriceUomId))
79722          UNION
79723          SELECT item_id
79724          FROM item,itemuomconv,itemuom,uomtype
79725          WHERE ((item_id=pItemId)
79726            AND (itemuomconv_item_id=item_id)
79727            AND (itemuomconv_from_uom_id=pPriceUomId)
79728            AND (itemuom_itemuomconv_id=itemuomconv_id)
79729            AND (itemuom_uomtype_id=uomtype_id)
79730            AND (uomtype_name='Selling'))
79731          UNION
79732          SELECT item_id
79733          FROM item,itemuomconv,itemuom,uomtype
79734          WHERE ((item_id=pItemId)
79735            AND (itemuomconv_item_id=item_id)
79736            AND (itemuomconv_to_uom_id=pPriceUomId)
79737            AND (itemuom_itemuomconv_id=itemuomconv_id)
79738            AND (itemuom_uomtype_id=uomtype_id)
79739            AND (uomtype_name='Selling'))) AS data)) THEN
79740     RAISE EXCEPTION 'Price UOM Must be a valid Selling UOM for the Item';
79741   END IF;
79742
79743   _new := TRUE;
79744
79745   IF (pIpsItemId IS NOT NULL) THEN
79746     SELECT ipsitem_id INTO _ipsitemid
79747     FROM ipsiteminfo
79748     WHERE (ipsitem_id=pIpsItemId);
79749
79750     IF (FOUND) THEN
79751       _new := FALSE;
79752     ELSE
79753       RAISE EXCEPTION 'Pricing Schedule Item not found.';
79754     END IF;
79755   ELSE
79756     SELECT ipsitem_id INTO _ipsitemid
79757     FROM ipsiteminfo
79758     WHERE ((ipsitem_ipshead_id  = pIpsheadId)
79759       AND (ipsitem_item_id      = pItemId)
79760       AND (ipsitem_qtybreak     = pQtyBreak)
79761       AND (ipsitem_qty_uom_id = COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))) 
79762       AND (ipsitem_price_uom_id =
79763            CASE
79764              WHEN (pQtyUomId = (SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)) THEN
79765                COALESCE(pPriceUomId,pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79766              ELSE
79767                COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79768            END));
79769   END IF;
79770   
79771   IF (FOUND) THEN
79772     _new := false;
79773   END IF;
79774   
79775   IF (_new) THEN
79776     INSERT INTO ipsiteminfo (
79777       ipsitem_ipshead_id, 
79778       ipsitem_item_id, 
79779       ipsitem_qtybreak, 
79780       ipsitem_price, 
79781       ipsitem_qty_uom_id, 
79782       ipsitem_price_uom_id,
79783       ipsitem_discntprcnt,
79784       ipsitem_fixedamtdiscount,
79785       ipsitem_type) 
79786     VALUES (
79787       pIpsheadId,
79788       pItemId,
79789       pQtyBreak, 
79790       pPrice,
79791       COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)), 
79792       CASE
79793         WHEN (pQtyUomId = (SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)) THEN
79794           COALESCE(pPriceUomId,pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79795         ELSE
79796           COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79797       END,
79798       pPercent,
79799       pFixedAmt,
79800       pType)
79801     RETURNING ipsitem_id INTO _ipsitemid;
79802   ELSE 
79803     UPDATE ipsiteminfo SET 
79804       ipsitem_qtybreak = pQtyBreak, 
79805       ipsitem_price = pPrice, 
79806       ipsitem_qty_uom_id = COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)), 
79807       ipsitem_price_uom_id =
79808       CASE
79809         WHEN (pQtyUomId = (SELECT item_inv_uom_id FROM item WHERE item_id = pItemId)) THEN
79810           COALESCE(pPriceUomId,pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79811         ELSE
79812           COALESCE(pQtyUomId,(SELECT item_inv_uom_id FROM item WHERE item_id = pItemId))
79813       END,
79814       ipsitem_discntprcnt=pPercent,
79815       ipsitem_fixedamtdiscount=pFixedAmt,
79816       ipsitem_type=pType
79817     WHERE (ipsitem_id=_ipsitemid);
79818    END IF;
79819
79820    RETURN _ipsitemid;
79821
79822 END;
79823 $$;
79824
79825
79826 ALTER FUNCTION public.saveipsitem(pipsitemid integer, pipsheadid integer, pitemid integer, pqtybreak numeric, pprice numeric, pqtyuomid integer, ppriceuomid integer, ppercent numeric, pfixedamt numeric, ptype text) OWNER TO admin;
79827
79828 --
79829 -- TOC entry 2168 (class 1255 OID 146567017)
79830 -- Dependencies: 4536 8
79831 -- Name: saveipsprodcat(integer, integer, integer, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
79832 --
79833
79834 CREATE FUNCTION saveipsprodcat(integer, integer, integer, numeric, numeric) RETURNS integer
79835     LANGUAGE plpgsql
79836     AS $_$
79837 DECLARE
79838   pIpsProdcatId ALIAS FOR $1;
79839   pIpsHeadId    ALIAS FOR $2;
79840   pProdCatId    ALIAS FOR $3;
79841   pQtyBreak     ALIAS FOR $4;
79842   pDiscount     ALIAS FOR $5;
79843   _ipsprodcatid INTEGER;
79844   _new          BOOLEAN;
79845   
79846 BEGIN
79847
79848   -- Validation
79849   IF (SELECT COUNT(*)=0 FROM prodcat WHERE (prodcat_id=pProdcatId)) THEN
79850     RAISE EXCEPTION 'You must provide a valid Product Category';
79851   ELSIF (COALESCE(pQtyBreak,0) < 0) THEN
79852     RAISE EXCEPTION 'Quantity can not be a negative value';
79853   ELSIF (COALESCE(pDiscount,0) < 0) THEN
79854     RAISE EXCEPTION 'Discount must be a negative value';
79855   END IF;
79856     
79857   _new := TRUE;
79858
79859   IF (pIpsProdcatId IS NOT NULL) THEN
79860     SELECT ipsprodcat_id INTO _ipsprodcatid
79861     FROM ipsprodcat
79862     WHERE (ipsprodcat_id=pIpsprodcatId);
79863
79864     IF (FOUND) THEN
79865       _new := FALSE;
79866     ELSE
79867       RAISE EXCEPTION 'Pricing Schedule Product Category not found';
79868     END IF;
79869   ELSE
79870     SELECT ipsprodcat_id INTO _ipsprodcatid
79871     FROM ipsprodcat
79872     WHERE ((ipsprodcat_ipshead_id=pIpsheadId)
79873       AND (ipsprodcat_prodcat_id=pProdcatId)
79874       AND (ipsprodcat_qtybreak=pQtyBreak));
79875
79876     IF (FOUND) THEN
79877       _new := false;
79878     ELSE
79879       _ipsprodcatid := nextval('ipsprodcat_ipsprodcat_id_seq');
79880     END IF;
79881   END IF;
79882   
79883   IF (_new) THEN
79884     INSERT INTO ipsprodcat (
79885       ipsprodcat_id,
79886       ipsprodcat_ipshead_id, 
79887       ipsprodcat_prodcat_id, 
79888       ipsprodcat_qtybreak, 
79889       ipsprodcat_discntprcnt) 
79890     VALUES (
79891       _ipsprodcatid,
79892       pIpsheadId,
79893       pProdcatId,
79894       pQtyBreak, 
79895       pDiscount * .01);
79896   ELSE 
79897     UPDATE ipsprodcat SET 
79898       ipsprodcat_qtybreak = pQtyBreak, 
79899       ipsprodcat_discntprcnt = pDiscount * .01
79900     WHERE (ipsprodcat_id=_ipsprodcatid);
79901   END IF;
79902
79903   RETURN _ipsprodcatid;
79904 END;
79905 $_$;
79906
79907
79908 ALTER FUNCTION public.saveipsprodcat(integer, integer, integer, numeric, numeric) OWNER TO admin;
79909
79910 --
79911 -- TOC entry 2169 (class 1255 OID 146567018)
79912 -- Dependencies: 4536 8
79913 -- Name: saveipsprodcat(integer, integer, integer, numeric, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
79914 --
79915
79916 CREATE FUNCTION saveipsprodcat(integer, integer, integer, numeric, numeric, numeric) RETURNS integer
79917     LANGUAGE plpgsql
79918     AS $_$
79919 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
79920 -- See www.xtuple.com/CPAL for the full text of the software license.
79921 DECLARE
79922   pIpsProdcatId     ALIAS FOR $1;
79923   pIpsHeadId        ALIAS FOR $2;
79924   pProdCatId        ALIAS FOR $3;
79925   pQtyBreak         ALIAS FOR $4;
79926   pDiscount         ALIAS FOR $5;
79927   pFixedAmtDiscount ALIAS FOR $6;
79928   _ipsprodcatid INTEGER;
79929   _new          BOOLEAN;
79930   
79931 BEGIN
79932
79933   -- Validation
79934   IF (SELECT COUNT(*)=0 FROM prodcat WHERE (prodcat_id=pProdcatId)) THEN
79935     RAISE EXCEPTION 'You must provide a valid Product Category';
79936   ELSIF (COALESCE(pQtyBreak,0) < 0) THEN
79937     RAISE EXCEPTION 'Quantity can not be a negative value';
79938   ELSIF (COALESCE(pDiscount,0) < 0) THEN
79939     RAISE EXCEPTION 'Discount must be a negative value';
79940   END IF;
79941     
79942   _new := TRUE;
79943
79944   IF (pIpsProdcatId IS NOT NULL) THEN
79945     SELECT ipsprodcat_id INTO _ipsprodcatid
79946     FROM ipsprodcat
79947     WHERE (ipsprodcat_id=pIpsprodcatId);
79948
79949     IF (FOUND) THEN
79950       _new := FALSE;
79951     ELSE
79952       RAISE EXCEPTION 'Pricing Schedule Product Category not found';
79953     END IF;
79954   ELSE
79955     SELECT ipsprodcat_id INTO _ipsprodcatid
79956     FROM ipsprodcat
79957     WHERE ((ipsprodcat_ipshead_id=pIpsheadId)
79958       AND (ipsprodcat_prodcat_id=pProdcatId)
79959       AND (ipsprodcat_qtybreak=pQtyBreak));
79960
79961     IF (FOUND) THEN
79962       _new := false;
79963     ELSE
79964       _ipsprodcatid := nextval('ipsprodcat_ipsprodcat_id_seq');
79965     END IF;
79966   END IF;
79967   
79968   IF (_new) THEN
79969     INSERT INTO ipsprodcat (
79970       ipsprodcat_id,
79971       ipsprodcat_ipshead_id, 
79972       ipsprodcat_prodcat_id, 
79973       ipsprodcat_qtybreak, 
79974       ipsprodcat_discntprcnt,
79975       ipsprodcat_fixedamtdiscount)  
79976     VALUES (
79977       _ipsprodcatid,
79978       pIpsheadId,
79979       pProdcatId,
79980       pQtyBreak, 
79981       pDiscount * .01,
79982       pFixedAmtDiscount);
79983   ELSE 
79984     UPDATE ipsprodcat SET 
79985       ipsprodcat_qtybreak = pQtyBreak, 
79986       ipsprodcat_discntprcnt = pDiscount * .01,
79987       ipsprodcat_fixedamtdiscount = pFixedAmtDiscount 
79988     WHERE (ipsprodcat_id=_ipsprodcatid);
79989   END IF;
79990
79991   RETURN _ipsprodcatid;
79992 END;
79993 $_$;
79994
79995
79996 ALTER FUNCTION public.saveipsprodcat(integer, integer, integer, numeric, numeric, numeric) OWNER TO admin;
79997
79998 --
79999 -- TOC entry 2164 (class 1255 OID 146567019)
80000 -- Dependencies: 4536 8
80001 -- Name: saveipsprodcat(integer, integer, integer, numeric, numeric, numeric, text); Type: FUNCTION; Schema: public; Owner: admin
80002 --
80003
80004 CREATE FUNCTION saveipsprodcat(pipsprodcatid integer, pipsheadid integer, pprodcatid integer, pqtybreak numeric, pdiscount numeric, pfixedamtdiscount numeric, ptype text) RETURNS integer
80005     LANGUAGE plpgsql
80006     AS $$
80007 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80008 -- See www.xtuple.com/CPAL for the full text of the software license.
80009 DECLARE
80010   _ipsitemid    INTEGER;
80011   _new          BOOLEAN;
80012   
80013 BEGIN
80014
80015   -- Validation
80016   IF (SELECT COUNT(*)=0 FROM prodcat WHERE (prodcat_id=pProdcatId)) THEN
80017     RAISE EXCEPTION 'You must provide a valid Product Category';
80018   ELSIF (COALESCE(pQtyBreak,0) < 0) THEN
80019     RAISE EXCEPTION 'Quantity can not be a negative value';
80020   ELSIF (COALESCE(pDiscount,0) < 0) THEN
80021     RAISE EXCEPTION 'Discount must be a negative value';
80022   END IF;
80023     
80024   _new := TRUE;
80025
80026   IF (pIpsProdcatId IS NOT NULL) THEN
80027     SELECT ipsitem_id INTO _ipsitemid
80028     FROM ipsiteminfo
80029     WHERE (ipsprodcat_id=pIpsprodcatId);
80030
80031     IF (FOUND) THEN
80032       _new := FALSE;
80033     ELSE
80034       RAISE EXCEPTION 'Pricing Schedule Product Category not found';
80035     END IF;
80036   ELSE
80037     SELECT ipsitem_id INTO _ipsitemid
80038     FROM ipsiteminfo
80039     WHERE ((ipsitem_ipshead_id=pIpsheadId)
80040       AND (ipsitem_prodcat_id=pProdcatId)
80041       AND (ipsitem_qtybreak=pQtyBreak));
80042
80043     IF (FOUND) THEN
80044       _new := false;
80045     ELSE
80046       _ipsitemid := nextval('ipsitem_ipsitem_id_seq');
80047     END IF;
80048   END IF;
80049   
80050   IF (_new) THEN
80051     INSERT INTO ipsiteminfo (
80052       ipsitem_id,
80053       ipsitem_ipshead_id, 
80054       ipsitem_prodcat_id, 
80055       ipsitem_qtybreak,
80056       ipsitem_price, 
80057       ipsitem_discntprcnt,
80058       ipsitem_fixedamtdiscount,
80059       ipsitem_type)  
80060     VALUES (
80061       _ipsitemid,
80062       pIpsheadId,
80063       pProdcatId,
80064       pQtyBreak, 
80065       0.0,
80066       pDiscount * .01,
80067       pFixedAmtDiscount,
80068       pType);
80069   ELSE 
80070     UPDATE ipsiteminfo SET 
80071       ipsitem_qtybreak = pQtyBreak, 
80072       ipsitem_discntprcnt = pDiscount * .01,
80073       ipsitem_fixedamtdiscount = pFixedAmtDiscount,
80074       ipsitem_type = pType 
80075     WHERE (ipsitem_id=_ipsitemid);
80076   END IF;
80077
80078   RETURN _ipsitemid;
80079 END;
80080 $$;
80081
80082
80083 ALTER FUNCTION public.saveipsprodcat(pipsprodcatid integer, pipsheadid integer, pprodcatid integer, pqtybreak numeric, pdiscount numeric, pfixedamtdiscount numeric, ptype text) OWNER TO admin;
80084
80085 --
80086 -- TOC entry 2171 (class 1255 OID 146567020)
80087 -- Dependencies: 4536 8
80088 -- Name: saveitemimage(integer, character, integer); Type: FUNCTION; Schema: public; Owner: admin
80089 --
80090
80091 CREATE FUNCTION saveitemimage(integer, character, integer) RETURNS integer
80092     LANGUAGE plpgsql
80093     AS $_$
80094 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80095 -- See www.xtuple.com/CPAL for the full text of the software license.
80096 DECLARE
80097   pItemid ALIAS FOR $1;
80098   pPurpose ALIAS FOR $2;
80099   pImageid ALIAS FOR $3;
80100   _itemimageId INTEGER;
80101
80102 BEGIN
80103 -- See if a record with this purpose already exists
80104   SELECT imageass_id INTO _itemimageId
80105   FROM imageass
80106   WHERE ( (imageass_source='I')
80107     AND   (imageass_source_id=pItemid)
80108     AND   (imageass_purpose=pPurpose) );
80109
80110   IF (FOUND) THEN
80111     UPDATE imageass SET imageass_image_id=pImageId
80112     WHERE (imageass_id=_itemimageId);
80113   ELSE
80114     _itemimageId := NEXTVAL('imageass_imageass_id_seq');
80115     INSERT INTO imageass VALUES (_itemimageId,pItemid,'I',pImageid,pPurpose);
80116   END IF;
80117   
80118   RETURN _itemimageId;
80119 END;
80120 $_$;
80121
80122
80123 ALTER FUNCTION public.saveitemimage(integer, character, integer) OWNER TO admin;
80124
80125 --
80126 -- TOC entry 2172 (class 1255 OID 146567021)
80127 -- Dependencies: 4536 8
80128 -- Name: saveitemuomconv(integer, integer, numeric, integer, numeric, boolean, integer[]); Type: FUNCTION; Schema: public; Owner: admin
80129 --
80130
80131 CREATE FUNCTION saveitemuomconv(integer, integer, numeric, integer, numeric, boolean, integer[]) RETURNS integer
80132     LANGUAGE plpgsql
80133     AS $_$
80134 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80135 -- See www.xtuple.com/CPAL for the full text of the software license.
80136 DECLARE
80137   pItemId ALIAS FOR $1;
80138   pFromUomId ALIAS FOR $2;
80139   pFromValue ALIAS FOR $3;
80140   pToUomId ALIAS FOR $4;
80141   pToValue ALIAS FOR $5;
80142   pFractional ALIAS FOR $6;
80143   pUomTypes ALIAS FOR $7;
80144   _p RECORD;
80145   _fromUomId INTEGER;
80146   _fromValue NUMERIC;
80147   _toUomId INTEGER;
80148   _toValue NUMERIC;
80149   _fractional BOOLEAN;
80150   _seq INTEGER;
80151   _i INTEGER;
80152   _uomtype TEXT;
80153
80154 BEGIN
80155 -- Make sure we have some itemtypes
80156   IF (pUomTypes IS NULL) OR (ARRAY_UPPER(pUomTypes,1) = 0) THEN
80157         RAISE EXCEPTION 'You must include at least one item type.';
80158   END IF;
80159
80160 -- If this is a global UOM, over-ride with global data.
80161   SELECT * INTO _p
80162   FROM uomconv
80163   WHERE ((((uomconv_from_uom_id=pFromUomId)
80164   AND (uomconv_to_uom_id=pToUomId))
80165   OR ((uomconv_from_uom_id=pToUomId)
80166   AND (uomconv_to_uom_id=pFromUomId))));
80167
80168   IF (FOUND) THEN
80169     _fromUomId := _p.uomconv_from_uom_id;
80170     _toUomId := _p.uomconv_to_uom_id;
80171     _fromValue := _p.uomconv_from_value;
80172     _toValue := _p.uomconv_to_value;
80173     _fractional := _p.uomconv_fractional;
80174     RAISE NOTICE 'Defaulted to global Unit of Measure conversion ratios.';
80175   ELSE
80176     _fromUomId := pFromUomId;
80177     _fromValue := pFromValue;
80178     _toUomId := pToUomId;
80179     _toValue := pToValue;
80180     _fractional := pFractional;
80181   END IF;
80182
80183 -- See if an item conversion exists going the other way
80184   SELECT f.uom_name AS f_uom, t.uom_name as t_uom INTO _p
80185   FROM itemuomconv,uom f, uom t
80186   WHERE ((itemuomconv_item_id=pItemId)
80187   AND (itemuomconv_from_uom_id=_toUomId)
80188   AND (itemuomconv_to_uom_id=_fromUomId)
80189   AND (f.uom_id=itemuomconv_from_uom_id)
80190   AND (t.uom_id=itemuomconv_to_uom_id));
80191   IF (FOUND) THEN
80192     RAISE EXCEPTION 'Unit of measure conversion already exists going from % to %.',_p.f_uom,_p.t_uom;
80193   END IF;
80194
80195 -- See if an item conversion record exists
80196   SELECT * INTO _p
80197   FROM itemuomconv
80198   WHERE ((itemuomconv_item_id=pItemId)
80199   AND (itemuomconv_from_uom_id=_fromUomId)
80200   AND (itemuomconv_to_uom_id=_toUomId));
80201
80202 -- Update if found
80203   IF (FOUND) THEN
80204     UPDATE itemuomconv SET
80205       itemuomconv_from_value=_fromValue,
80206       itemuomconv_to_value=_toValue,
80207       itemuomconv_fractional=_fractional
80208     WHERE (itemuomconv_id=_p.itemuomconv_id);
80209     _seq := _p.itemuomconv_id;
80210     
80211     --Delete old type list
80212     DELETE FROM itemuom WHERE itemuom_itemuomconv_id=_p.itemuomconv_id;
80213   ELSE
80214   
80215 -- Otherwise create a new one
80216     SELECT NEXTVAL('itemuomconv_itemuomconv_id_seq') INTO _seq;
80217     INSERT INTO itemuomconv VALUES
80218       (_seq, pItemId,_fromUomId,_fromValue,_toUomId,_toValue,_fractional);
80219   END IF;
80220   
80221 -- Build new type list
80222   FOR _i IN 1..ARRAY_UPPER(pUomTypes,1)
80223   LOOP
80224     SELECT uomtype_name INTO _uomtype
80225     FROM itemuomconv, itemuom, uomtype
80226     WHERE ((itemuom_uomtype_id=uomtype_id)
80227     AND (itemuomconv_id=itemuom_itemuomconv_id)
80228     AND (itemuomconv_item_id=pItemId)
80229     AND (uomtype_name != 'Selling')
80230     AND (itemuom_uomtype_id=pUomTypes[_i]));
80231     IF (FOUND) THEN
80232       RAISE EXCEPTION 'Unit of Measure Type % is already used on this item',_uomtype;
80233     ELSE
80234       INSERT INTO itemuom (itemuom_itemuomconv_id,itemuom_uomtype_id)
80235       VALUES (_seq,pUomTypes[_i]);
80236     END IF;
80237   END LOOP;
80238   
80239   RETURN _seq;
80240 END;
80241 $_$;
80242
80243
80244 ALTER FUNCTION public.saveitemuomconv(integer, integer, numeric, integer, numeric, boolean, integer[]) OWNER TO admin;
80245
80246 --
80247 -- TOC entry 2173 (class 1255 OID 146567022)
80248 -- Dependencies: 4536 8
80249 -- Name: savemetasql(text, text, text, text); Type: FUNCTION; Schema: public; Owner: admin
80250 --
80251
80252 CREATE FUNCTION savemetasql(text, text, text, text) RETURNS integer
80253     LANGUAGE plpgsql
80254     AS $_$
80255 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80256 -- See www.xtuple.com/CPAL for the full text of the software license.
80257 BEGIN
80258   RETURN saveMetasql($1, $2, $3, $4, true, NULL, 0);
80259 END;
80260 $_$;
80261
80262
80263 ALTER FUNCTION public.savemetasql(text, text, text, text) OWNER TO admin;
80264
80265 --
80266 -- TOC entry 2174 (class 1255 OID 146567023)
80267 -- Dependencies: 4536 8
80268 -- Name: savemetasql(text, text, text, text, boolean); Type: FUNCTION; Schema: public; Owner: admin
80269 --
80270
80271 CREATE FUNCTION savemetasql(text, text, text, text, boolean) RETURNS integer
80272     LANGUAGE plpgsql
80273     AS $_$
80274 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80275 -- See www.xtuple.com/CPAL for the full text of the software license.
80276 BEGIN
80277   RETURN saveMetasql($1, $2, $3, $4, $5, NULL, 0);
80278 END;
80279 $_$;
80280
80281
80282 ALTER FUNCTION public.savemetasql(text, text, text, text, boolean) OWNER TO admin;
80283
80284 --
80285 -- TOC entry 2175 (class 1255 OID 146567024)
80286 -- Dependencies: 4536 8
80287 -- Name: savemetasql(text, text, text, text, boolean, text); Type: FUNCTION; Schema: public; Owner: admin
80288 --
80289
80290 CREATE FUNCTION savemetasql(text, text, text, text, boolean, text) RETURNS integer
80291     LANGUAGE plpgsql
80292     AS $_$
80293 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80294 -- See www.xtuple.com/CPAL for the full text of the software license.
80295 BEGIN
80296   RETURN saveMetasql($1, $2, $3, $4, $5, $6, 0);
80297 END;
80298 $_$;
80299
80300
80301 ALTER FUNCTION public.savemetasql(text, text, text, text, boolean, text) OWNER TO admin;
80302
80303 --
80304 -- TOC entry 2176 (class 1255 OID 146567025)
80305 -- Dependencies: 4536 8
80306 -- Name: savemetasql(text, text, text, text, boolean, text, integer); Type: FUNCTION; Schema: public; Owner: admin
80307 --
80308
80309 CREATE FUNCTION savemetasql(text, text, text, text, boolean, text, integer) RETURNS integer
80310     LANGUAGE plpgsql
80311     AS $_$
80312 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80313 -- See www.xtuple.com/CPAL for the full text of the software license.
80314 DECLARE
80315   pGroup        ALIAS FOR $1;
80316   pName         ALIAS FOR $2;
80317   pNotes        ALIAS FOR $3;
80318   pQuery        ALIAS FOR $4;
80319   pSystem       ALIAS FOR $5;
80320   pSchema       ALIAS FOR $6;
80321   pGrade        ALIAS FOR $7;
80322   _metasqlid    INTEGER;
80323   _debug        BOOL    := false;
80324   _grade        INTEGER;
80325   _insertstr    TEXT;
80326   _table        TEXT;
80327   
80328 BEGIN
80329
80330   --See if Query already exists
80331   SELECT metasql_id INTO _metasqlid
80332   FROM metasql
80333   WHERE ((metasql_group=pGroup)
80334      AND (metasql_name=pName)
80335      AND (metasql_grade=pGrade));
80336
80337   IF (FOUND) THEN
80338     IF (_debug) THEN RAISE NOTICE 'update metasql'; END IF;
80339     UPDATE metasql SET
80340       metasql_group=pGroup,
80341       metasql_name=pName,
80342       metasql_notes=pNotes,
80343       metasql_query=pQuery
80344     WHERE (metasql_id=_metasqlid);
80345   ELSE
80346     IF (COALESCE(pSchema, 'public') = 'public' OR
80347         TRIM(pSchema) = '') THEN
80348       _table := 'metasql';
80349     ELSE
80350       _table := pSchema || '.pkgmetasql';
80351     END IF;
80352
80353     IF (pGrade IS NULL) THEN
80354       SELECT MAX(metasql_grade) + 1 INTO _grade
80355       FROM metasql
80356       WHERE ((metasql_group=pGroup)
80357          AND (metasql_name=pName));
80358     ELSE
80359       _grade := pGrade;
80360     END IF;
80361
80362     _insertstr := 'INSERT INTO ' || _table ||
80363                   ' (metasql_group, metasql_name, metasql_notes, ' ||
80364                   '  metasql_query, metasql_grade) VALUES (' ||
80365                   COALESCE(quote_literal(pGroup),'NULL') || ',' || COALESCE(quote_literal(pName), 'NULL') || ',' ||
80366                   COALESCE(quote_literal(pNotes), 'NULL') || ',' || COALESCE(quote_literal(pQuery), 'NULL') ||',' ||
80367                   COALESCE(quote_literal(_grade), 'NULL') || ') RETURNING metasql_id;' ;
80368
80369     IF (_debug) THEN RAISE NOTICE '%', _insertstr; END IF;
80370     EXECUTE _insertstr INTO _metasqlid;
80371   END IF;
80372  
80373   RETURN _metasqlid;
80374 END;
80375 $_$;
80376
80377
80378 ALTER FUNCTION public.savemetasql(text, text, text, text, boolean, text, integer) OWNER TO admin;
80379
80380 --
80381 -- TOC entry 2177 (class 1255 OID 146567026)
80382 -- Dependencies: 4536 8
80383 -- Name: scraps(text); Type: FUNCTION; Schema: public; Owner: admin
80384 --
80385
80386 CREATE FUNCTION scraps(text) RETURNS boolean
80387     LANGUAGE plpgsql
80388     AS $_$
80389 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80390 -- See www.xtuple.com/CPAL for the full text of the software license.
80391 DECLARE
80392   pTransType ALIAS FOR $1;
80393
80394 BEGIN
80395   IF (pTransType IN ('SI', 'SM', 'EX')) THEN
80396     RETURN TRUE;
80397   ELSE
80398     RETURN FALSE;
80399   END IF;
80400
80401 END;
80402 $_$;
80403
80404
80405 ALTER FUNCTION public.scraps(text) OWNER TO admin;
80406
80407 --
80408 -- TOC entry 2178 (class 1255 OID 146567027)
80409 -- Dependencies: 4536 8
80410 -- Name: scrapwomaterial(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
80411 --
80412
80413 CREATE FUNCTION scrapwomaterial(integer, numeric) RETURNS integer
80414     LANGUAGE plpgsql
80415     AS $_$
80416 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80417 -- See www.xtuple.com/CPAL for the full text of the software license.
80418 BEGIN
80419   RETURN scrapWoMaterial($1, $2, CURRENT_TIMESTAMP);
80420 END;
80421 $_$;
80422
80423
80424 ALTER FUNCTION public.scrapwomaterial(integer, numeric) OWNER TO admin;
80425
80426 --
80427 -- TOC entry 2179 (class 1255 OID 146567028)
80428 -- Dependencies: 4536 8
80429 -- Name: scrapwomaterial(integer, numeric, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
80430 --
80431
80432 CREATE FUNCTION scrapwomaterial(integer, numeric, timestamp with time zone) RETURNS integer
80433     LANGUAGE plpgsql
80434     AS $_$
80435 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80436 -- See www.xtuple.com/CPAL for the full text of the software license.
80437 DECLARE
80438   pWomatlid     ALIAS FOR $1;
80439   pQty          ALIAS FOR $2;
80440   pGlDistTS     ALIAS FOR $3;
80441   _costmethod           CHAR(1);
80442   _scrapValue           NUMERIC;
80443   _r                    RECORD;
80444
80445 BEGIN
80446   -- Validate
80447   IF (pQty <= 0) THEN
80448     RAISE EXCEPTION 'Scrap quantity must be a positive number';
80449   ELSIF ( ( SELECT (womatl_qtyiss < pQty)
80450              FROM womatl
80451              WHERE (womatl_id=pWomatlid) ) ) THEN
80452     RAISE EXCEPTION 'You may not scrap more material than has been issued';
80453   END IF;
80454
80455   -- Get the wip G/L account
80456   SELECT costcat_wip_accnt_id
80457     INTO _r
80458     FROM womatl, wo, itemsite, costcat
80459    WHERE((womatl_wo_id=wo_id)
80460      AND (wo_itemsite_id=itemsite_id)
80461      AND (itemsite_costcat_id=costcat_id)
80462      AND (womatl_id=pWomatlid));
80463
80464   -- Calculate scrap value
80465   SELECT itemsite_costmethod INTO _costmethod
80466   FROM womatl
80467     JOIN itemsite ON (womatl_itemsite_id=itemsite_id)
80468   WHERE (womatl_id=pWomatlid);
80469
80470   IF (_costmethod = 'S') THEN
80471     SELECT ROUND((stdCost(itemsite_item_id) * itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, pQty)),2)
80472     INTO _scrapValue
80473     FROM womatl
80474       JOIN itemsite ON (womatl_itemsite_id=itemsite_id)
80475     WHERE (womatl_id=pWomatlid);
80476      
80477   ELSIF (_costmethod = 'A') THEN
80478     SELECT ROUND((SUM(invhist_invqty * invhist_unitcost)-womatl_scrapvalue)/
80479             (CASE WHEN (SUM(invhist_invqty)-itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtywipscrap) = 0) THEN
80480               1
80481             ELSE
80482               SUM(invhist_invqty)-itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtywipscrap)
80483             END),2) * itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, pQty)
80484       INTO _scrapValue
80485     FROM womatl
80486         JOIN womatlpost ON (womatl_id=womatlpost_womatl_id)
80487         JOIN invhist ON (womatlpost_invhist_id=invhist_id)
80488         JOIN itemsite ON (womatl_itemsite_id=itemsite_id)
80489     WHERE (womatl_id=pWomatlid)
80490     GROUP BY itemsite_item_id,womatl_uom_id,womatl_qtywipscrap,womatl_scrapvalue;
80491   ELSE
80492     RAISE EXCEPTION 'Cost method not supported to scrap this item';
80493   END IF;
80494
80495   --  Distribute to G/L
80496   PERFORM insertGLTransaction( 'W/O', 'WO', formatWoNumber(womatl_wo_id),
80497                  ('Scrap ' || item_number || ' from Work Order'),
80498                  getPrjAccntId(wo_prj_id, _r.costcat_wip_accnt_id), getPrjAccntId(wo_prj_id, costcat_mfgscrap_accnt_id), -1,
80499                  _scrapValue, date(pGlDistTS) )
80500   FROM wo, womatl, itemsite, item, costcat
80501   WHERE ( (wo_id=womatl_wo_id)
80502    AND (womatl_itemsite_id=itemsite_id)
80503    AND (itemsite_item_id=item_id)
80504    AND (itemsite_costcat_id=costcat_id)
80505    AND (womatl_id=pWomatlid) );
80506
80507   UPDATE womatl
80508   SET womatl_qtywipscrap=(womatl_qtywipscrap + pQty),
80509     womatl_scrapvalue = womatl_scrapvalue + _scrapValue,
80510     womatl_qtyiss=(womatl_qtyiss - pQty)
80511   WHERE (womatl_id=pWomatlid);
80512
80513   UPDATE wo
80514   SET wo_wipvalue = wo_wipvalue-_scrapValue,
80515     wo_postedvalue = wo_postedvalue-_scrapValue
80516   FROM womatl
80517   WHERE ((womatl_id=pWomatlid)
80518    AND (wo_id=womatl_wo_id));
80519
80520   RETURN pWomatlid;
80521
80522 END;
80523 $_$;
80524
80525
80526 ALTER FUNCTION public.scrapwomaterial(integer, numeric, timestamp with time zone) OWNER TO admin;
80527
80528 --
80529 -- TOC entry 2181 (class 1255 OID 146567029)
80530 -- Dependencies: 4536 8
80531 -- Name: selectbalanceforbilling(integer); Type: FUNCTION; Schema: public; Owner: admin
80532 --
80533
80534 CREATE FUNCTION selectbalanceforbilling(integer) RETURNS boolean
80535     LANGUAGE plpgsql
80536     AS $_$
80537 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80538 -- See www.xtuple.com/CPAL for the full text of the software license.
80539 DECLARE
80540   pSoheadid ALIAS FOR $1;
80541   _returnval    BOOLEAN := TRUE;
80542   _doSelect BOOLEAN;
80543   _result INTEGER;
80544   _soitem RECORD;
80545
80546 BEGIN
80547
80548   FOR _soitem IN
80549     -- Get the shipments for this SO.  Kits are not shipped
80550     SELECT cust_partialship, coitem_id,
80551            coitem_linenumber, 'NOTK' AS item_type,
80552            SUM(shipitem_qty) AS qty,
80553            ( (SUM(shipitem_qty) >= (coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned + SUM(shipitem_qty))) OR
80554              (NOT cust_partialship) ) AS toclose
80555     FROM cohead JOIN custinfo ON (cust_id=cohead_cust_id)
80556                 JOIN coitem ON (coitem_cohead_id=cohead_id)
80557                 JOIN shipitem ON ( (shipitem_orderitem_id=coitem_id) AND (NOT shipitem_invoiced) )
80558                 JOIN shiphead ON ( (shiphead_id=shipitem_shiphead_id) AND (shiphead_order_type='SO') AND (shiphead_shipped) )
80559     WHERE (cohead_id=pSoheadid)
80560     GROUP BY cust_partialship, coitem_id, item_type,
80561              coitem_linenumber, coitem_qtyord,
80562              coitem_qtyshipped, coitem_qtyreturned
80563     UNION
80564     -- Get the Kits for this SO
80565     SELECT cust_partialship, coitem_id,
80566            coitem_linenumber, 'K' AS item_type,
80567            coitem_qtyord AS qty,
80568            TRUE AS toclose
80569     FROM cohead JOIN custinfo ON (cust_id=cohead_cust_id)
80570                 JOIN coitem ON (coitem_cohead_id=cohead_id AND coitem_status='O')
80571                 JOIN itemsite ON (itemsite_id=coitem_itemsite_id)
80572                 JOIN item ON ( (item_id=itemsite_item_id) AND (item_type='K') )
80573     WHERE (cohead_id=pSoheadid)
80574   LOOP
80575
80576     _doSelect := true;
80577     IF(_soitem.item_type = 'K') THEN
80578       -- see if all the sub items are shipped
80579       SELECT coitem_id
80580         INTO _result
80581         FROM coitem
80582        WHERE((coitem_cohead_id=pSoheadid)
80583          AND (coitem_linenumber=_soitem.coitem_linenumber)
80584          AND (coitem_subnumber > 0)
80585          AND ((coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) > 0))
80586        LIMIT 1;
80587       IF( FOUND ) THEN
80588         _doSelect := false;
80589       END IF;
80590     END IF;
80591
80592     IF (_doSelect) THEN
80593       -- do as much as we can but still report errors if they occur
80594       IF (selectForBilling(_soitem.coitem_id, _soitem.qty, _soitem.toclose) < 0) THEN
80595         _returnval := FALSE;
80596       END IF;
80597     END IF;
80598
80599   END LOOP;
80600
80601   RETURN _returnval;
80602
80603 END;
80604 $_$;
80605
80606
80607 ALTER FUNCTION public.selectbalanceforbilling(integer) OWNER TO admin;
80608
80609 --
80610 -- TOC entry 2182 (class 1255 OID 146567030)
80611 -- Dependencies: 4536 8
80612 -- Name: selectdiscountitemsforpayment(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
80613 --
80614
80615 CREATE FUNCTION selectdiscountitemsforpayment(integer, integer) RETURNS integer
80616     LANGUAGE plpgsql
80617     AS $_$
80618 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80619 -- See www.xtuple.com/CPAL for the full text of the software license.
80620 DECLARE
80621   pVendid ALIAS FOR $1;
80622   pBankaccntid ALIAS FOR $2;
80623   _currid INTEGER;
80624   _r RECORD;
80625
80626 BEGIN
80627
80628   SELECT bankaccnt_curr_id INTO _currid
80629   FROM bankaccnt
80630   WHERE (bankaccnt_id=pBankaccntid);
80631
80632   FOR _r IN SELECT apopen_id
80633               FROM apopen, terms
80634              WHERE((CURRENT_DATE <= determineDiscountDate(apopen_terms_id, apopen_docdate))
80635                AND (terms_discprcnt > 0.0)
80636                AND (apopen_terms_id=terms_id)
80637                AND (apopen_open)
80638                AND (apopen_status = 'O')
80639                AND (apopen_doctype IN ('V', 'D'))
80640                AND (apopen_vend_id=pVendid)
80641                AND (apopen_curr_id=_currid) ) LOOP
80642     PERFORM selectPayment(_r.apopen_id, pBankaccntid);
80643   END LOOP;
80644
80645   RETURN 1;
80646
80647 END;
80648 $_$;
80649
80650
80651 ALTER FUNCTION public.selectdiscountitemsforpayment(integer, integer) OWNER TO admin;
80652
80653 --
80654 -- TOC entry 2183 (class 1255 OID 146567031)
80655 -- Dependencies: 4536 8
80656 -- Name: selectdueitemsforpayment(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
80657 --
80658
80659 CREATE FUNCTION selectdueitemsforpayment(integer, integer) RETURNS integer
80660     LANGUAGE plpgsql
80661     AS $_$
80662 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80663 -- See www.xtuple.com/CPAL for the full text of the software license.
80664 DECLARE
80665   pVendid ALIAS FOR $1;
80666   pBankaccntid ALIAS FOR $2;
80667   _currid INTEGER;
80668
80669 BEGIN
80670
80671   SELECT bankaccnt_curr_id INTO _currid
80672   FROM bankaccnt
80673   WHERE (bankaccnt_id=pBankaccntid);
80674
80675   PERFORM selectPayment(apopen_id, pBankaccntid)
80676      FROM apopen
80677     WHERE((apopen_open)
80678       AND (apopen_vend_id=pVendid)
80679       AND (apopen_duedate <= CURRENT_DATE)
80680       AND (apopen_status = 'O')
80681       AND (apopen_doctype IN ('V', 'D'))
80682       AND (apopen_curr_id=_currid) );
80683
80684   RETURN 1;
80685
80686 END;
80687 $_$;
80688
80689
80690 ALTER FUNCTION public.selectdueitemsforpayment(integer, integer) OWNER TO admin;
80691
80692 --
80693 -- TOC entry 2184 (class 1255 OID 146567032)
80694 -- Dependencies: 4536 8
80695 -- Name: selectforbilling(integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
80696 --
80697
80698 CREATE FUNCTION selectforbilling(integer, numeric, boolean) RETURNS integer
80699     LANGUAGE plpgsql
80700     AS $_$
80701 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80702 -- See www.xtuple.com/CPAL for the full text of the software license.
80703 DECLARE
80704   pSoitemid     ALIAS FOR $1;
80705   pQty  ALIAS FOR $2;
80706   pClose        ALIAS FOR $3;
80707   _itemid       INTEGER := NULL;
80708   _taxzoneid    INTEGER := NULL;
80709   _taxid        INTEGER := NULL;
80710   _taxtypeid    INTEGER := NULL;
80711
80712 BEGIN
80713   SELECT cobmisc_taxzone_id,  item_id, coitem_taxtype_id
80714   INTO _taxzoneid,  _itemid, _taxtypeid
80715   FROM cobmisc, coitem, itemsite, item
80716   WHERE ((cobmisc_cohead_id = coitem_cohead_id)
80717   AND   (NOT cobmisc_posted)
80718   AND   (coitem_itemsite_id = itemsite_id)
80719   AND   (itemsite_item_id = item_id)
80720   AND   (coitem_id = pSoitemid) )
80721   LIMIT 1;
80722
80723    RETURN selectforbilling(pSoitemid, pQty, pClose, _taxtypeid);
80724 END;
80725 $_$;
80726
80727
80728 ALTER FUNCTION public.selectforbilling(integer, numeric, boolean) OWNER TO admin;
80729
80730 --
80731 -- TOC entry 2185 (class 1255 OID 146567033)
80732 -- Dependencies: 4536 8
80733 -- Name: selectforbilling(integer, numeric, boolean, integer); Type: FUNCTION; Schema: public; Owner: admin
80734 --
80735
80736 CREATE FUNCTION selectforbilling(integer, numeric, boolean, integer) RETURNS integer
80737     LANGUAGE plpgsql
80738     AS $_$
80739 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80740 -- See www.xtuple.com/CPAL for the full text of the software license.
80741 DECLARE
80742   pSoitemid     ALIAS FOR $1;
80743   pQty          ALIAS FOR $2;
80744   pClose        ALIAS FOR $3;
80745   ptaxtypeid    ALIAS FOR $4;
80746   _cobillid INTEGER;
80747   _r RECORD;
80748
80749 BEGIN
80750
80751 -- Get some information
80752   SELECT cobmisc_id, cobmisc_taxzone_id, coitem_id, coitem_price,
80753     coitem_price_invuomratio AS invpricerat, coitem_qty_invuomratio, item_id
80754   INTO _r
80755   FROM cobmisc, coitem, itemsite, item, site()
80756   WHERE ((cobmisc_cohead_id = coitem_cohead_id)
80757   AND   (NOT cobmisc_posted)
80758   AND   (coitem_itemsite_id = itemsite_id)
80759   AND   (itemsite_item_id = item_id)
80760   AND   (coitem_id = pSoitemid)
80761   AND   (itemsite_warehous_id = warehous_id) )
80762   LIMIT 1;
80763
80764 -- check to make sure the qty to bill for is not less than
80765 -- the total un-invoiced shipped amount
80766   IF ((SELECT (pQty < SUM(shipitem_qty))
80767        FROM shipitem, shiphead, coitem
80768        WHERE ( (shipitem_shiphead_id=shiphead_id)
80769        AND (shiphead_order_type='SO')
80770        AND (shiphead_order_id=coitem_cohead_id)
80771        AND (shipitem_orderitem_id=coitem_id)
80772        AND (shiphead_shipped)
80773        AND (NOT shipitem_invoiced)
80774        AND (coitem_id=pSoitemid) ) ) ) THEN
80775     RETURN -1;
80776   END IF;
80777
80778   SELECT cobill_id INTO _cobillid
80779   FROM cobill, cobmisc, coitem
80780   WHERE ((cobill_cobmisc_id = cobmisc_id)
80781   AND (cobmisc_cohead_id = coitem_cohead_id)
80782   AND (cobill_coitem_id = coitem_id)
80783   AND (NOT cobmisc_posted)
80784   AND (coitem_id = pSoitemid));
80785
80786   IF (FOUND) THEN
80787     UPDATE cobill
80788     SET cobill_selectdate = CURRENT_DATE,
80789         cobill_select_username = getEffectiveXtUser(),
80790         cobill_qty = pQty,
80791         cobill_toclose = pClose,
80792         cobill_taxtype_id = ptaxtypeid
80793     WHERE (cobill_id=_cobillid);
80794
80795   ELSE
80796     SELECT NEXTVAL('cobill_cobill_id_seq') INTO _cobillid;
80797     INSERT INTO cobill
80798     (cobill_id, cobill_coitem_id, cobill_cobmisc_id,
80799      cobill_selectdate, cobill_select_username,
80800      cobill_qty, cobill_toclose,
80801      cobill_taxtype_id)
80802     VALUES
80803     (_cobillid, _r.coitem_id, _r.cobmisc_id,
80804       CURRENT_DATE, getEffectiveXtUser(),
80805       pQty, pClose,
80806       ptaxtypeid);
80807   END IF;
80808
80809   RETURN _cobillid;
80810
80811 END;
80812 $_$;
80813
80814
80815 ALTER FUNCTION public.selectforbilling(integer, numeric, boolean, integer) OWNER TO admin;
80816
80817 --
80818 -- TOC entry 2186 (class 1255 OID 146567034)
80819 -- Dependencies: 4536 8
80820 -- Name: selectpayment(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
80821 --
80822
80823 CREATE FUNCTION selectpayment(integer, integer) RETURNS integer
80824     LANGUAGE plpgsql
80825     AS $_$
80826 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
80827 -- See www.xtuple.com/CPAL for the full text of the software license.
80828 DECLARE
80829   pApopenid ALIAS FOR $1;
80830   pBankaccntid ALIAS FOR $2;
80831   _p RECORD;
80832   _apselectid INTEGER;
80833   _amount NUMERIC;
80834   _discount NUMERIC;
80835 BEGIN
80836
80837   SELECT apopen_amount, apopen_paid,
80838          apopen_doctype, apopen_docdate,
80839          apopen_curr_id,
80840          apopen_amount - apopen_paid - apCheckPending(apopen_id) AS balance,
80841          noNeg(COALESCE(apopen_discountable_amount, 0) *
80842                CASE WHEN (CURRENT_DATE <= determineDiscountDate(apopen_terms_id, apopen_docdate)) THEN terms_discprcnt
80843                     ELSE 0.0 END - discount_applied) AS discount_available
80844     INTO _p
80845     FROM apopen LEFT OUTER JOIN terms ON (apopen_terms_id=terms_id),
80846          (SELECT COALESCE(SUM(apapply_amount),0) AS discount_applied
80847             FROM apapply, apopen
80848            WHERE((apapply_target_apopen_id=pApopenid)
80849              AND (apapply_source_apopen_id=apopen_id)
80850              AND (apopen_discount)) ) AS data
80851    WHERE(apopen_id=pApopenid);
80852   IF(NOT FOUND OR (NOT _p.apopen_doctype IN ('V','D','C'))) THEN
80853     RETURN -1;
80854   END IF;
80855
80856   _discount := round(_p.discount_available, 2);
80857   _amount := noNeg(round(_p.balance, 2) - _discount);
80858
80859   IF (round(_p.balance,2) < (_discount + _amount)) THEN
80860     RETURN -2;
80861   END IF;
80862
80863   IF (_amount > 0) THEN
80864     SELECT apselect_id INTO _apselectid
80865     FROM apselect
80866     WHERE (apselect_apopen_id=pApopenid);
80867
80868     IF (FOUND) THEN
80869       UPDATE apselect
80870          SET apselect_amount=_amount,
80871              apselect_discount=_discount,
80872              apselect_curr_id = _p.apopen_curr_id
80873        WHERE(apselect_id=_apselectid);
80874     ELSE
80875       SELECT NEXTVAL('apselect_apselect_id_seq') INTO _apselectid;
80876
80877       INSERT INTO apselect
80878       ( apselect_id, apselect_apopen_id,
80879         apselect_amount, apselect_discount,
80880         apselect_bankaccnt_id,
80881         apselect_curr_id, apselect_date )
80882       VALUES
80883       ( _apselectid, pApopenid,
80884         _amount, _discount,
80885         pBankaccntid,
80886         _p.apopen_curr_id, _p.apopen_docdate );
80887     END IF;
80888   ELSE
80889     _apselectid := 0;
80890   END IF;
80891   
80892   RETURN _apselectid;
80893
80894 END;
80895 $_$;
80896
80897
80898 ALTER FUNCTION public.selectpayment(integer, integer) OWNER TO admin;
80899
80900 --
80901 -- TOC entry 2187 (class 1255 OID 146567035)
80902 -- Dependencies: 4536 8
80903 -- Name: selectuninvoicedshipment(integer); Type: FUNCTION; Schema: public; Owner: admin
80904 --
80905
80906 CREATE FUNCTION selectuninvoicedshipment(integer) RETURNS integer
80907     LANGUAGE plpgsql
80908     AS $_$
80909 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
80910 -- See www.xtuple.com/CPAL for the full text of the software license.
80911 DECLARE
80912   pShipheadid ALIAS FOR $1;
80913   _cobmiscid INTEGER;
80914   _coheadid  INTEGER;
80915   _r RECORD;
80916   _cobillid INTEGER;
80917
80918 BEGIN
80919
80920   -- make a cobmisc head if it doesn't already exist for this cohead
80921   SELECT shiphead_order_id, createBillingHeader(shiphead_order_id)
80922     INTO _coheadid, _cobmiscid
80923     FROM shiphead
80924     JOIN shipitem ON (shipitem_shiphead_id=shiphead_id)
80925    WHERE (shiphead_shipped
80926       AND NOT shipitem_invoiced
80927       AND (shiphead_id=pShipheadid));
80928
80929   --  Grab all of the uninvoiced shipitem records
80930   FOR _r IN SELECT cohead_id, coitem_id, SUM(shipitem_qty) AS qty,
80931                    coitem_price, coitem_price_invuomratio AS invpricerat, coitem_qty_invuomratio, item_id,
80932                    ( ((coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) <= 0)
80933                     OR (NOT cust_partialship) ) AS toclose, coitem_taxtype_id
80934             FROM shiphead, shipitem, coitem, cohead, custinfo, itemsite, item
80935             WHERE ( (shipitem_shiphead_id=shiphead_id)
80936              AND (shipitem_orderitem_id=coitem_id)
80937              AND (coitem_cohead_id=cohead_id)
80938              AND (shiphead_shipped)
80939              AND (NOT shipitem_invoiced)
80940              AND (coitem_itemsite_id=itemsite_id)
80941              AND (itemsite_item_id=item_id)
80942              AND (cohead_cust_id=cust_id)
80943              AND (item_type != 'K')
80944              AND (cohead_id=_coheadid)
80945              AND (shiphead_id=pShipheadid) )
80946             GROUP BY cohead_id, coitem_id, cust_partialship, coitem_taxtype_id,
80947                      coitem_qtyord, coitem_qtyshipped, coitem_qtyreturned,
80948                      coitem_price, invpricerat, coitem_qty_invuomratio, item_id
80949             UNION
80950             SELECT cohead_id, coitem_id, coitem_qtyord AS qty,
80951                    coitem_price, coitem_price_invuomratio AS invpricerat, coitem_qty_invuomratio, item_id,
80952                    true AS toclose, coitem_taxtype_id
80953               FROM shiphead, cohead, custinfo, itemsite, item, coitem AS kit
80954              WHERE((shiphead_order_id=cohead_id)
80955                AND (coitem_cohead_id=cohead_id)
80956                AND (coitem_status='O')
80957                AND (shiphead_shipped)
80958                AND (coitem_itemsite_id=itemsite_id)
80959                AND (itemsite_item_id=item_id)
80960                AND (cohead_cust_id=cust_id)
80961                AND (item_type = 'K')
80962                AND (cohead_id=_coheadid)
80963                AND (shiphead_id=pShipheadid)
80964                AND (coitem_linenumber NOT IN
80965                       (SELECT sub.coitem_linenumber
80966                        FROM coitem AS sub
80967                        WHERE sub.coitem_cohead_id=cohead_id     -- cohead for kit
80968                         AND sub.coitem_linenumber=kit.coitem_linenumber
80969                         AND sub.coitem_subnumber > 0
80970                         AND ((sub.coitem_qtyord - sub.coitem_qtyshipped + sub.coitem_qtyreturned) > 0)
80971                         LIMIT 1)
80972                ))
80973              GROUP BY cohead_id, coitem_id, cust_partialship, coitem_taxtype_id,
80974                       coitem_qtyord, coitem_qtyshipped, coitem_qtyreturned,
80975                       coitem_price, invpricerat, coitem_qty_invuomratio, item_id, coitem_linenumber
80976   LOOP
80977
80978     SELECT cobill_id INTO _cobillid
80979       FROM cobill, cobmisc, coitem
80980      WHERE ((cobill_cobmisc_id=cobmisc_id)
80981        AND  (cobmisc_cohead_id=coitem_cohead_id)
80982        AND  (cobill_coitem_id=coitem_id)
80983        AND  (NOT cobmisc_posted)
80984        AND  (cobill_cobmisc_id=_cobmiscid)
80985        AND  (coitem_id=_r.coitem_id))
80986      LIMIT 1;
80987
80988     IF (FOUND) THEN
80989       UPDATE cobill
80990          SET cobill_selectdate = CURRENT_DATE,
80991              cobill_select_username = getEffectiveXtUser(),
80992              cobill_qty = cobill_qty + _r.qty,
80993              cobill_toclose = _r.toclose,
80994              cobill_taxtype_id = _r.coitem_taxtype_id
80995       WHERE (cobill_id=_cobillid);
80996     ELSE
80997 --  Now insert the cobill line
80998       INSERT INTO cobill
80999       ( cobill_cobmisc_id, cobill_coitem_id,
81000         cobill_selectdate, cobill_select_username,
81001         cobill_qty, cobill_toclose,
81002         cobill_taxtype_id )
81003       VALUES
81004       ( _cobmiscid, _r.coitem_id,
81005         CURRENT_DATE, getEffectiveXtUser(),
81006         _r.qty, _r.toclose,
81007          _r.coitem_taxtype_id );
81008      END IF;
81009
81010   END LOOP;
81011
81012   RETURN _cobmiscid;
81013
81014 END;
81015 $_$;
81016
81017
81018 ALTER FUNCTION public.selectuninvoicedshipment(integer) OWNER TO admin;
81019
81020 --
81021 -- TOC entry 2189 (class 1255 OID 146567037)
81022 -- Dependencies: 4536 8
81023 -- Name: selectuninvoicedshipments(integer); Type: FUNCTION; Schema: public; Owner: admin
81024 --
81025
81026 CREATE FUNCTION selectuninvoicedshipments(integer) RETURNS integer
81027     LANGUAGE plpgsql
81028     AS $_$
81029 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81030 -- See www.xtuple.com/CPAL for the full text of the software license.
81031 DECLARE
81032   pWarehousid ALIAS FOR $1;
81033   _r RECORD;
81034   _recordCounter INTEGER := 0;
81035
81036 BEGIN
81037
81038 --  Grab all of the uninvoiced shipitem records
81039   FOR _r IN SELECT DISTINCT shiphead_id
81040             FROM shiphead, shipitem, coitem, itemsite
81041             WHERE ( (shiphead_order_type='SO')
81042              AND (shipitem_shiphead_id=shiphead_id)
81043              AND (shipitem_orderitem_id=coitem_id)
81044              AND (coitem_itemsite_id=itemsite_id)
81045              AND (coitem_status <> 'C')
81046              AND ( (pWarehousid = -1) OR (itemsite_warehous_id=pWarehousid) )
81047              AND (shiphead_shipped)
81048              AND (NOT shipitem_invoiced)
81049              AND (coitem_id NOT IN ( SELECT cobill_coitem_id
81050                                      FROM cobmisc, cobill
81051                                      WHERE ((cobill_cobmisc_id=cobmisc_id)
81052                                       AND (NOT cobmisc_posted) ) ) ) ) LOOP
81053
81054       PERFORM selectUninvoicedShipment(_r.shiphead_id);
81055
81056     _recordCounter := _recordCounter + 1;
81057
81058   END LOOP;
81059
81060   RETURN _recordCounter;
81061
81062 END;
81063 $_$;
81064
81065
81066 ALTER FUNCTION public.selectuninvoicedshipments(integer) OWNER TO admin;
81067
81068 --
81069 -- TOC entry 2188 (class 1255 OID 146567036)
81070 -- Dependencies: 4536 8
81071 -- Name: selectuninvoicedshipments(integer, text); Type: FUNCTION; Schema: public; Owner: admin
81072 --
81073
81074 CREATE FUNCTION selectuninvoicedshipments(integer, text) RETURNS integer
81075     LANGUAGE plpgsql
81076     AS $_$
81077 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81078 -- See www.xtuple.com/CPAL for the full text of the software license.
81079 DECLARE
81080   pWarehousid ALIAS FOR $1;
81081   pCusttype ALIAS FOR $2;
81082   _r RECORD;
81083   _recordCounter INTEGER := 0;
81084
81085 BEGIN
81086
81087 --  Grab all of the uninvoiced shipitem records
81088   FOR _r IN SELECT DISTINCT shiphead_id
81089             FROM shiphead, shipitem, coitem, itemsite, cohead, custinfo, custtype
81090             WHERE ( (shiphead_order_type='SO')
81091              AND (shipitem_shiphead_id=shiphead_id)
81092              AND (shipitem_orderitem_id=coitem_id)
81093              AND (coitem_itemsite_id=itemsite_id)
81094              AND (coitem_status <> 'C')
81095              AND (coitem_cohead_id=cohead_id)
81096              AND (cohead_cust_id=cust_id)
81097              AND (cust_custtype_id=custtype_id)
81098              AND ( (pWarehousid = -1) OR (itemsite_warehous_id=pWarehousid) )
81099              AND (custtype_code ~ pCusttype)
81100              AND (shiphead_shipped)
81101              AND (NOT shipitem_invoiced)
81102              AND (coitem_id NOT IN ( SELECT cobill_coitem_id
81103                                      FROM cobmisc, cobill
81104                                      WHERE ((cobill_cobmisc_id=cobmisc_id)
81105                                       AND (NOT cobmisc_posted) ) ) ) ) LOOP
81106
81107       PERFORM selectUninvoicedShipment(_r.shiphead_id);
81108
81109     _recordCounter := _recordCounter + 1;
81110
81111   END LOOP;
81112
81113   RETURN _recordCounter;
81114
81115 END;
81116 $_$;
81117
81118
81119 ALTER FUNCTION public.selectuninvoicedshipments(integer, text) OWNER TO admin;
81120
81121 --
81122 -- TOC entry 2190 (class 1255 OID 146567038)
81123 -- Dependencies: 4536 8
81124 -- Name: selectuninvoicedshipments(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
81125 --
81126
81127 CREATE FUNCTION selectuninvoicedshipments(integer, integer) RETURNS integer
81128     LANGUAGE plpgsql
81129     AS $_$
81130 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81131 -- See www.xtuple.com/CPAL for the full text of the software license.
81132 DECLARE
81133   pWarehousid ALIAS FOR $1;
81134   pCusttypeid ALIAS FOR $2;
81135   _r RECORD;
81136   _recordCounter INTEGER := 0;
81137
81138 BEGIN
81139
81140 --  Grab all of the uninvoiced shipitem records
81141   FOR _r IN SELECT DISTINCT shiphead_id
81142             FROM shiphead, shipitem, coitem, itemsite, cohead, custinfo
81143             WHERE ( (shiphead_order_type='SO')
81144              AND (shipitem_shiphead_id=shiphead_id)
81145              AND (shipitem_orderitem_id=coitem_id)
81146              AND (coitem_itemsite_id=itemsite_id)
81147              AND (coitem_status <> 'C')
81148              AND (coitem_cohead_id=cohead_id)
81149              AND (cohead_cust_id=cust_id)
81150              AND (cust_custtype_id=pCusttypeid)
81151              AND ( (pWarehousid = -1) OR (itemsite_warehous_id=pWarehousid) )
81152              AND (shiphead_shipped)
81153              AND (NOT shipitem_invoiced)
81154              AND (coitem_id NOT IN ( SELECT cobill_coitem_id
81155                                      FROM cobmisc, cobill
81156                                      WHERE ((cobill_cobmisc_id=cobmisc_id)
81157                                       AND (NOT cobmisc_posted) ) ) ) ) LOOP
81158
81159       PERFORM selectUninvoicedShipment(_r.shiphead_id);
81160
81161     _recordCounter := _recordCounter + 1;
81162
81163   END LOOP;
81164
81165   RETURN _recordCounter;
81166
81167 END;
81168 $_$;
81169
81170
81171 ALTER FUNCTION public.selectuninvoicedshipments(integer, integer) OWNER TO admin;
81172
81173 --
81174 -- TOC entry 2191 (class 1255 OID 146567039)
81175 -- Dependencies: 4536 8
81176 -- Name: setapjournalnumber(); Type: FUNCTION; Schema: public; Owner: admin
81177 --
81178
81179 CREATE FUNCTION setapjournalnumber() RETURNS integer
81180     LANGUAGE plpgsql
81181     AS $$
81182 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81183 -- See www.xtuple.com/CPAL for the full text of the software license.
81184 DECLARE
81185   _journalNumber INTEGER;
81186   _r RECORD;
81187
81188 BEGIN
81189
81190 --  Fetch the next Journal Number
81191   SELECT fetchJournalNumber('A/P') INTO _journalNumber;
81192
81193 --  Walk through all of the A/P Open Items
81194   FOR _r IN SELECT apopen_id, apopen_docnumber
81195             FROM apopen
81196             WHERE (NOT apopen_posted) LOOP
81197
81198 --  Set the Journal Number for all of the G/L Transactions
81199 --  for the A/P Open Item
81200     UPDATE gltrans
81201     SET gltrans_journalnumber=_journalNumber
81202     WHERE ( (gltrans_source='P/O')
81203      AND (gltrans_doctype IN ('VO'))
81204      AND (gltrans_docnumber=_r.apopen_docnumber)
81205      AND (NOT gltrans_exported) );
81206
81207 --  Set the Journal Number for the A/P Open Item
81208     UPDATE apopen
81209     SET apopen_journalnumber=_journalNumber
81210     WHERE (apopen_id=_r.apopen_id);
81211
81212   END LOOP;
81213
81214   RETURN _journalNumber;
81215
81216 END;
81217 $$;
81218
81219
81220 ALTER FUNCTION public.setapjournalnumber() OWNER TO admin;
81221
81222 --
81223 -- TOC entry 2192 (class 1255 OID 146567040)
81224 -- Dependencies: 4536 8
81225 -- Name: setarjournalnumber(); Type: FUNCTION; Schema: public; Owner: admin
81226 --
81227
81228 CREATE FUNCTION setarjournalnumber() RETURNS integer
81229     LANGUAGE plpgsql
81230     AS $$
81231 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81232 -- See www.xtuple.com/CPAL for the full text of the software license.
81233 DECLARE
81234   _journalNumber INTEGER;
81235   _r RECORD;
81236
81237 BEGIN
81238
81239 --  Fetch the next Journal Number
81240   SELECT fetchJournalNumber('A/R') INTO _journalNumber;
81241
81242 --  Walk through all of the A/R Open Items
81243   FOR _r IN SELECT aropen_id, aropen_docnumber
81244             FROM aropen
81245             WHERE (NOT aropen_posted) LOOP
81246
81247 --  Set the Journal Number for all of the G/L Transactions
81248 --  for the A/R Open Item
81249     UPDATE gltrans
81250     SET gltrans_journalnumber=_journalNumber
81251     WHERE ( (gltrans_source='S/O')
81252      AND (gltrans_doctype IN ('CM', 'IN'))
81253      AND (gltrans_docnumber=_r.aropen_docnumber)
81254      AND (NOT gltrans_exported) );
81255
81256 --  Set the Journal Number for the A/R Open Item
81257     UPDATE aropen
81258     SET aropen_journalnumber=_journalNumber
81259     WHERE (aropen_id=_r.aropen_id);
81260
81261   END LOOP;
81262
81263   RETURN _journalNumber;
81264
81265 END;
81266 $$;
81267
81268
81269 ALTER FUNCTION public.setarjournalnumber() OWNER TO admin;
81270
81271 --
81272 -- TOC entry 2193 (class 1255 OID 146567041)
81273 -- Dependencies: 4536 8
81274 -- Name: setbudget(integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
81275 --
81276
81277 CREATE FUNCTION setbudget(integer, integer, numeric) RETURNS integer
81278     LANGUAGE plpgsql
81279     AS $_$
81280 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81281 -- See www.xtuple.com/CPAL for the full text of the software license.
81282 DECLARE
81283   pPeriodid ALIAS FOR $1;
81284   pAccntid ALIAS FOR $2;
81285   pAmount ALIAS FOR $3;
81286
81287 BEGIN
81288   RETURN setBudget(1, pPeriodid, pAccntid, pAmount);
81289 END;
81290 $_$;
81291
81292
81293 ALTER FUNCTION public.setbudget(integer, integer, numeric) OWNER TO admin;
81294
81295 --
81296 -- TOC entry 2195 (class 1255 OID 146567042)
81297 -- Dependencies: 4536 8
81298 -- Name: setbudget(integer, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
81299 --
81300
81301 CREATE FUNCTION setbudget(integer, integer, integer, numeric) RETURNS integer
81302     LANGUAGE plpgsql
81303     AS $_$
81304 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81305 -- See www.xtuple.com/CPAL for the full text of the software license.
81306 DECLARE
81307   pBudgheadid ALIAS FOR $1;
81308   pPeriodid ALIAS FOR $2;
81309   pAccntid ALIAS FOR $3;
81310   pAmount ALIAS FOR $4;
81311   _budgetid INTEGER;
81312
81313 BEGIN
81314
81315   SELECT budgitem_id INTO _budgetid
81316     FROM budgitem
81317    WHERE ((budgitem_period_id=pPeriodid)
81318      AND  (budgitem_budghead_id=pBudgheadid)
81319      AND  (budgitem_accnt_id=pAccntid));
81320   IF (FOUND) THEN
81321     UPDATE budgitem
81322        SET budgitem_amount = pAmount
81323      WHERE (budgitem_id=_budgetid);
81324   ELSE
81325     SELECT nextval('budgitem_budgitem_id_seq') INTO _budgetid;
81326
81327     INSERT INTO budgitem
81328           (budgitem_id, budgitem_budghead_id, budgitem_period_id, budgitem_accnt_id, budgitem_amount)
81329     VALUES(_budgetid, pBudgheadid, pPeriodid, pAccntid, pAmount);
81330   END IF;
81331
81332   RETURN _budgetid;
81333
81334 END;
81335 $_$;
81336
81337
81338 ALTER FUNCTION public.setbudget(integer, integer, integer, numeric) OWNER TO admin;
81339
81340 --
81341 -- TOC entry 2196 (class 1255 OID 146567043)
81342 -- Dependencies: 4536 8
81343 -- Name: setbytea(text); Type: FUNCTION; Schema: public; Owner: admin
81344 --
81345
81346 CREATE FUNCTION setbytea(text) RETURNS bytea
81347     LANGUAGE plpgsql
81348     AS $_$
81349 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81350 -- See www.xtuple.com/CPAL for the full text of the software license.
81351 DECLARE
81352   pMetricName ALIAS FOR $1;
81353   _value bytea;
81354
81355 BEGIN
81356
81357   _value := decode(pMetricName, 'escape');
81358
81359   RETURN _value;
81360
81361 END;
81362 $_$;
81363
81364
81365 ALTER FUNCTION public.setbytea(text) OWNER TO admin;
81366
81367 --
81368 -- TOC entry 2197 (class 1255 OID 146567044)
81369 -- Dependencies: 4536 8
81370 -- Name: setbytea(bytea); Type: FUNCTION; Schema: public; Owner: admin
81371 --
81372
81373 CREATE FUNCTION setbytea(bytea) RETURNS bytea
81374     LANGUAGE plpgsql
81375     AS $_$
81376 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81377 -- See www.xtuple.com/CPAL for the full text of the software license.
81378 DECLARE
81379   pMetricName ALIAS FOR $1;
81380   _value bytea;
81381
81382 BEGIN
81383
81384   _value := pMetricName;
81385
81386   RETURN _value;
81387
81388 END;
81389 $_$;
81390
81391
81392 ALTER FUNCTION public.setbytea(bytea) OWNER TO admin;
81393
81394 --
81395 -- TOC entry 2198 (class 1255 OID 146567045)
81396 -- Dependencies: 4536 8
81397 -- Name: setccbankaccnt(text, integer); Type: FUNCTION; Schema: public; Owner: admin
81398 --
81399
81400 CREATE FUNCTION setccbankaccnt(text, integer) RETURNS integer
81401     LANGUAGE plpgsql
81402     AS $_$
81403 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81404 -- See www.xtuple.com/CPAL for the full text of the software license.
81405 DECLARE
81406   pccardtype   ALIAS FOR $1;
81407   pbankaccntid ALIAS FOR $2;
81408
81409   _ccbankid    INTEGER;
81410   _numfound    INTEGER;
81411
81412 BEGIN
81413   RAISE DEBUG 'setCCBankAccount(%, %) entered', pccardtype, pbankaccntid;
81414   UPDATE ccbank SET ccbank_bankaccnt_id=pbankaccntid
81415   WHERE ccbank_ccard_type=pccardtype
81416   RETURNING ccbank_id INTO _ccbankid;
81417
81418   GET DIAGNOSTICS _numfound = ROW_COUNT;
81419
81420   IF (_numfound <= 0) THEN
81421     INSERT INTO ccbank (ccbank_ccard_type, ccbank_bankaccnt_id)
81422                 VALUES (pccardtype,        pbankaccntid)
81423     RETURNING _ccbankid;
81424   END IF;
81425
81426   RETURN _ccbankid;
81427 END;
81428 $_$;
81429
81430
81431 ALTER FUNCTION public.setccbankaccnt(text, integer) OWNER TO admin;
81432
81433 --
81434 -- TOC entry 2199 (class 1255 OID 146567046)
81435 -- Dependencies: 4536 8
81436 -- Name: seteffectivextuser(text); Type: FUNCTION; Schema: public; Owner: admin
81437 --
81438
81439 CREATE FUNCTION seteffectivextuser(text) RETURNS boolean
81440     LANGUAGE plpgsql
81441     AS $_$
81442 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81443 -- See www.xtuple.com/CPAL for the full text of the software license.
81444 DECLARE
81445   pUsername ALIAS FOR $1;
81446 BEGIN
81447   PERFORM initEffectiveXtUser();
81448
81449   PERFORM *
81450      FROM effective_user
81451     WHERE effective_key = 'username';
81452
81453   IF FOUND THEN
81454     UPDATE effective_user
81455        SET effective_value = pUsername
81456      WHERE effective_key = 'username';
81457   ELSE
81458     INSERT INTO effective_user (effective_key, effective_value)
81459          VALUES('username', pUsername);
81460   END IF;
81461
81462   RETURN true;
81463 END;
81464 $_$;
81465
81466
81467 ALTER FUNCTION public.seteffectivextuser(text) OWNER TO admin;
81468
81469 --
81470 -- TOC entry 2200 (class 1255 OID 146567047)
81471 -- Dependencies: 4536 8
81472 -- Name: setgljournalnumber(date, date); Type: FUNCTION; Schema: public; Owner: admin
81473 --
81474
81475 CREATE FUNCTION setgljournalnumber(date, date) RETURNS integer
81476     LANGUAGE plpgsql
81477     AS $_$
81478 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81479 -- See www.xtuple.com/CPAL for the full text of the software license.
81480 DECLARE
81481   pStartDate ALIAS FOR $1;
81482   pEndDate ALIAS FOR $2;
81483   _journalNumber INTEGER;
81484
81485 BEGIN
81486
81487 --  Fetch the next Journal Number
81488   SELECT fetchJournalNumber('G/L') INTO _journalNumber;
81489
81490 --  Set the Journal Number for all of the unposted G/L Transactions
81491 --  in the passed date range.
81492   UPDATE gltrans
81493   SET gltrans_journalnumber=_journalNumber
81494   WHERE ( (NOT gltrans_exported)
81495     AND (gltrans_date BETWEEN pStartDate and pEndDate) );
81496
81497   RETURN _journalNumber;
81498
81499 END;
81500 $_$;
81501
81502
81503 ALTER FUNCTION public.setgljournalnumber(date, date) OWNER TO admin;
81504
81505 --
81506 -- TOC entry 2201 (class 1255 OID 146567048)
81507 -- Dependencies: 4536 8
81508 -- Name: setmetric(text, text); Type: FUNCTION; Schema: public; Owner: admin
81509 --
81510
81511 CREATE FUNCTION setmetric(text, text) RETURNS boolean
81512     LANGUAGE plpgsql
81513     AS $_$
81514 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81515 -- See www.xtuple.com/CPAL for the full text of the software license.
81516 DECLARE
81517   pMetricName ALIAS FOR $1;
81518   pMetricValue ALIAS FOR $2;
81519   _metricid INTEGER;
81520
81521 BEGIN
81522
81523   SELECT metric_id INTO _metricid
81524   FROM metric
81525   WHERE (metric_name=pMetricName);
81526
81527   IF (FOUND) THEN
81528     UPDATE metric
81529     SET metric_value=pMetricValue
81530     WHERE (metric_id=_metricid);
81531
81532   ELSE
81533     INSERT INTO metric
81534     (metric_name, metric_value)
81535     VALUES (pMetricName, pMetricValue);
81536   END IF;
81537
81538   RETURN TRUE;
81539
81540 END;
81541 $_$;
81542
81543
81544 ALTER FUNCTION public.setmetric(text, text) OWNER TO admin;
81545
81546 --
81547 -- TOC entry 2202 (class 1255 OID 146567049)
81548 -- Dependencies: 4536 8
81549 -- Name: setmetricenc(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
81550 --
81551
81552 CREATE FUNCTION setmetricenc(text, text, text) RETURNS boolean
81553     LANGUAGE plpgsql
81554     AS $_$
81555 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81556 -- See www.xtuple.com/CPAL for the full text of the software license.
81557 DECLARE
81558   pMetricName ALIAS FOR $1;
81559   pMetricValue ALIAS FOR $2;
81560   pMetricEnc ALIAS FOR $3;
81561   _metricid INTEGER;
81562   _value bytea;
81563   _key bytea;
81564
81565 BEGIN
81566
81567   _value = decode(pMetricValue, 'escape');
81568   _key = decode(pMetricEnc, 'escape');
81569
81570   SELECT metricenc_id INTO _metricid
81571   FROM metricenc
81572   WHERE (metricenc_name=pMetricName);
81573
81574   IF (FOUND) THEN
81575     UPDATE metricenc
81576     SET metricenc_value=encrypt(_value, _key, 'bf')
81577     WHERE (metricenc_id=_metricid);
81578
81579   ELSE
81580     INSERT INTO metricenc
81581     (metricenc_name, metricenc_value)
81582     VALUES (pMetricName, encrypt(_value, _key, 'bf'));
81583   END IF;
81584
81585   RETURN TRUE;
81586
81587 END;
81588 $_$;
81589
81590
81591 ALTER FUNCTION public.setmetricenc(text, text, text) OWNER TO admin;
81592
81593 --
81594 -- TOC entry 2203 (class 1255 OID 146567050)
81595 -- Dependencies: 4536 8
81596 -- Name: setnextapmemonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81597 --
81598
81599 CREATE FUNCTION setnextapmemonumber(integer) RETURNS integer
81600     LANGUAGE plpgsql
81601     AS $_$
81602 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81603 -- See www.xtuple.com/CPAL for the full text of the software license.
81604 DECLARE
81605   pNumber ALIAS FOR $1;
81606   _orderseqid INTEGER;
81607
81608 BEGIN
81609
81610   SELECT orderseq_id INTO _orderseqid
81611   FROM orderseq
81612   WHERE (orderseq_name='APMemoNumber');
81613   IF (FOUND) THEN
81614     UPDATE orderseq
81615     SET orderseq_number=pNumber
81616     WHERE (orderseq_id=_orderseqid);
81617
81618   ELSE
81619     INSERT INTO orderseq
81620     (orderseq_name, orderseq_number)
81621     VALUES
81622     ('APMemoNumber', pNumber);
81623   END IF;
81624
81625   RETURN 1;
81626
81627 END;
81628 $_$;
81629
81630
81631 ALTER FUNCTION public.setnextapmemonumber(integer) OWNER TO admin;
81632
81633 --
81634 -- TOC entry 2204 (class 1255 OID 146567051)
81635 -- Dependencies: 4536 8
81636 -- Name: setnextarmemonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81637 --
81638
81639 CREATE FUNCTION setnextarmemonumber(integer) RETURNS integer
81640     LANGUAGE plpgsql
81641     AS $_$
81642 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81643 -- See www.xtuple.com/CPAL for the full text of the software license.
81644 DECLARE
81645   pNumber ALIAS FOR $1;
81646   _orderseqid INTEGER;
81647
81648 BEGIN
81649
81650   SELECT orderseq_id INTO _orderseqid
81651   FROM orderseq
81652   WHERE (orderseq_name='ARMemoNumber');
81653   IF (FOUND) THEN
81654     UPDATE orderseq
81655     SET orderseq_number=pNumber
81656     WHERE (orderseq_id=_orderseqid);
81657
81658   ELSE
81659     INSERT INTO orderseq
81660     (orderseq_name, orderseq_number)
81661     VALUES
81662     ('ARMemoNumber', pNumber);
81663   END IF;
81664
81665   RETURN 1;
81666
81667 END;
81668 $_$;
81669
81670
81671 ALTER FUNCTION public.setnextarmemonumber(integer) OWNER TO admin;
81672
81673 --
81674 -- TOC entry 2205 (class 1255 OID 146567052)
81675 -- Dependencies: 4536 8
81676 -- Name: setnextcashrcptnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81677 --
81678
81679 CREATE FUNCTION setnextcashrcptnumber(integer) RETURNS integer
81680     LANGUAGE plpgsql
81681     AS $_$
81682 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81683 -- See www.xtuple.com/CPAL for the full text of the software license.
81684 DECLARE
81685   pNumber ALIAS FOR $1;
81686   _orderseqid INTEGER;
81687
81688 BEGIN
81689
81690   SELECT orderseq_id INTO _orderseqid
81691   FROM orderseq
81692   WHERE (orderseq_name='CashRcptNumber');
81693   IF (FOUND) THEN
81694     UPDATE orderseq
81695     SET orderseq_number=pNumber
81696     WHERE (orderseq_id=_orderseqid);
81697
81698   ELSE
81699     INSERT INTO orderseq
81700     (orderseq_name, orderseq_number)
81701     VALUES
81702     ('CashRcptNumber', pNumber);
81703   END IF;
81704
81705   RETURN 1;
81706
81707 END;
81708 $_$;
81709
81710
81711 ALTER FUNCTION public.setnextcashrcptnumber(integer) OWNER TO admin;
81712
81713 --
81714 -- TOC entry 2170 (class 1255 OID 146567053)
81715 -- Dependencies: 4536 8
81716 -- Name: setnextchecknumber(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
81717 --
81718
81719 CREATE FUNCTION setnextchecknumber(integer, integer) RETURNS boolean
81720     LANGUAGE plpgsql
81721     AS $_$
81722 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81723 -- See www.xtuple.com/CPAL for the full text of the software license.
81724 DECLARE
81725   pBankaccntid ALIAS FOR $1;
81726   pNextCheckNumber ALIAS FOR $2;
81727
81728 BEGIN
81729
81730   UPDATE bankaccnt
81731   SET bankaccnt_nextchknum=pNextCheckNumber
81732   WHERE (bankaccnt_id=pBankaccntid);
81733
81734   RETURN TRUE;
81735
81736 END;
81737 $_$;
81738
81739
81740 ALTER FUNCTION public.setnextchecknumber(integer, integer) OWNER TO admin;
81741
81742 --
81743 -- TOC entry 2180 (class 1255 OID 146567054)
81744 -- Dependencies: 4536 8
81745 -- Name: setnextcmnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81746 --
81747
81748 CREATE FUNCTION setnextcmnumber(integer) RETURNS integer
81749     LANGUAGE plpgsql
81750     AS $_$
81751 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81752 -- See www.xtuple.com/CPAL for the full text of the software license.
81753 DECLARE
81754   pNumber ALIAS FOR $1;
81755   _orderseqid INTEGER;
81756
81757 BEGIN
81758
81759   SELECT orderseq_id INTO _orderseqid
81760   FROM orderseq
81761   WHERE (orderseq_name='CmNumber');
81762
81763   IF (NOT FOUND) THEN
81764     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
81765
81766     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
81767     VALUES (_orderseqid, 'CmNumber', pNumber);
81768
81769   ELSE
81770     UPDATE orderseq
81771     SET orderseq_number=pNumber
81772     WHERE (orderseq_name='CmNumber');
81773   END IF;
81774
81775   RETURN _orderseqid;
81776
81777 END;
81778 $_$;
81779
81780
81781 ALTER FUNCTION public.setnextcmnumber(integer) OWNER TO admin;
81782
81783 --
81784 -- TOC entry 2194 (class 1255 OID 146567055)
81785 -- Dependencies: 4536 8
81786 -- Name: setnextcrmaccountnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81787 --
81788
81789 CREATE FUNCTION setnextcrmaccountnumber(integer) RETURNS integer
81790     LANGUAGE plpgsql
81791     AS $_$
81792 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81793 -- See www.xtuple.com/CPAL for the full text of the software license.
81794 DECLARE
81795   pNumber ALIAS FOR $1;
81796   _orderseqid INTEGER;
81797
81798 BEGIN
81799
81800   SELECT orderseq_id INTO _orderseqid
81801   FROM orderseq
81802   WHERE (orderseq_name='CRMAccountNumber');
81803
81804   IF (NOT FOUND) THEN
81805     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
81806
81807     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
81808     VALUES (_orderseqid, 'CRMAccountNumber', pNumber);
81809
81810   ELSE
81811     UPDATE orderseq
81812     SET orderseq_number=pNumber
81813     WHERE (orderseq_name='CRMAccountNumber');
81814   END IF;
81815
81816   RETURN _orderseqid;
81817
81818 END;
81819 $_$;
81820
81821
81822 ALTER FUNCTION public.setnextcrmaccountnumber(integer) OWNER TO admin;
81823
81824 --
81825 -- TOC entry 2206 (class 1255 OID 146567056)
81826 -- Dependencies: 4536 8
81827 -- Name: setnextincidentnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81828 --
81829
81830 CREATE FUNCTION setnextincidentnumber(integer) RETURNS integer
81831     LANGUAGE plpgsql
81832     AS $_$
81833 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81834 -- See www.xtuple.com/CPAL for the full text of the software license.
81835 DECLARE
81836   pNumber ALIAS FOR $1;
81837   _orderseqid INTEGER;
81838
81839 BEGIN
81840
81841   SELECT orderseq_id INTO _orderseqid
81842   FROM orderseq
81843   WHERE (orderseq_name='IncidentNumber');
81844
81845   IF (NOT FOUND) THEN
81846     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
81847
81848     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
81849     VALUES (_orderseqid, 'IncidentNumber', pNumber);
81850
81851   ELSE
81852     UPDATE orderseq
81853     SET orderseq_number=pNumber
81854     WHERE (orderseq_name='IncidentNumber');
81855   END IF;
81856
81857   RETURN _orderseqid;
81858
81859 END;
81860 $_$;
81861
81862
81863 ALTER FUNCTION public.setnextincidentnumber(integer) OWNER TO admin;
81864
81865 --
81866 -- TOC entry 2207 (class 1255 OID 146567057)
81867 -- Dependencies: 4536 8
81868 -- Name: setnextinvcnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81869 --
81870
81871 CREATE FUNCTION setnextinvcnumber(integer) RETURNS integer
81872     LANGUAGE plpgsql
81873     AS $_$
81874 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81875 -- See www.xtuple.com/CPAL for the full text of the software license.
81876 DECLARE
81877   pNumber ALIAS FOR $1;
81878   _orderseqid INTEGER;
81879
81880 BEGIN
81881
81882   SELECT orderseq_id INTO _orderseqid
81883   FROM orderseq
81884   WHERE (orderseq_name='InvcNumber');
81885
81886   IF (NOT FOUND) THEN
81887     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
81888
81889     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
81890     VALUES (_orderseqid, 'InvcNumber', pNumber);
81891
81892   ELSE
81893     UPDATE orderseq
81894     SET orderseq_number=pNumber
81895     WHERE (orderseq_name='InvcNumber');
81896   END IF;
81897
81898   RETURN _orderseqid;
81899
81900 END;
81901 $_$;
81902
81903
81904 ALTER FUNCTION public.setnextinvcnumber(integer) OWNER TO admin;
81905
81906 --
81907 -- TOC entry 2208 (class 1255 OID 146567058)
81908 -- Dependencies: 4536 8
81909 -- Name: setnextnumber(text, integer); Type: FUNCTION; Schema: public; Owner: admin
81910 --
81911
81912 CREATE FUNCTION setnextnumber(text, integer) RETURNS integer
81913     LANGUAGE plpgsql
81914     AS $_$
81915 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81916 -- See www.xtuple.com/CPAL for the full text of the software license.
81917 DECLARE
81918   psequence     ALIAS FOR $1;
81919   pnumber       ALIAS FOR $2;
81920   _orderseqid   INTEGER;
81921
81922 BEGIN
81923   SELECT orderseq_id INTO _orderseqid
81924   FROM orderseq
81925   WHERE (orderseq_name=psequence);
81926
81927   IF (NOT FOUND) THEN
81928     INSERT INTO orderseq (orderseq_name, orderseq_number,
81929                           orderseq_table, orderseq_numcol)
81930                   VALUES (psequence,     pnumber,
81931                           CASE WHEN (psequence='APMemoNumber') THEN 'apopen'
81932                                WHEN (psequence='ARMemoNumber') THEN 'aropen'
81933                                WHEN (psequence='CmNumber') THEN 'cmhead'
81934                                WHEN (psequence='IncidentNumber') THEN 'incdt'
81935                                WHEN (psequence='InvcNumber') THEN 'invchead'
81936                                WHEN (psequence='JournalNumber') THEN 'gltrans'
81937                                WHEN (psequence='PlanNumber') THEN 'planord'
81938                                WHEN (psequence='PoNumber') THEN 'pohead'
81939                                WHEN (psequence='PrNumber') THEN 'pr'
81940                                WHEN (psequence='QuNumber') THEN 'quhead'
81941                                WHEN (psequence='ShipmentNumber') THEN 'shiphead'
81942                                WHEN (psequence='SoNumber') THEN 'cohead'
81943                                WHEN (psequence='ToNumber') THEN 'tohead'
81944                                WHEN (psequence='VcNumber') THEN 'vohead'
81945                                WHEN (psequence='WoNumber') THEN 'wo'
81946                                ELSE ''
81947                           END,
81948                           CASE WHEN (psequence='APMemoNumber') THEN 'apopen_docnumber'
81949                                WHEN (psequence='ARMemoNumber') THEN 'aropen_docnumber'
81950                                WHEN (psequence='CmNumber') THEN 'cmhead_number'
81951                                WHEN (psequence='IncidentNumber') THEN 'incdt_number'
81952                                WHEN (psequence='InvcNumber') THEN 'invchead_invcnumber'
81953                                WHEN (psequence='JournalNumber') THEN 'gltrans_journalnumber'
81954                                WHEN (psequence='PlanNumber') THEN 'planord_number'
81955                                WHEN (psequence='PoNumber') THEN 'pohead_number'
81956                                WHEN (psequence='PrNumber') THEN 'pr_number'
81957                                WHEN (psequence='QuNumber') THEN 'quhead_number'
81958                                WHEN (psequence='ShipmentNumber') THEN 'shiphead_number'
81959                                WHEN (psequence='SoNumber') THEN 'cohead_number'
81960                                WHEN (psequence='ToNumber') THEN 'tohead_number'
81961                                WHEN (psequence='VcNumber') THEN 'vohead_number'
81962                                WHEN (psequence='WoNumber') THEN 'wo_number'
81963                                ELSE ''
81964                           END
81965                           );
81966   ELSE
81967     UPDATE orderseq
81968     SET orderseq_number=pnumber
81969     WHERE (orderseq_name=psequence);
81970   END IF;
81971
81972   RETURN 0;
81973 END;
81974 $_$;
81975
81976
81977 ALTER FUNCTION public.setnextnumber(text, integer) OWNER TO admin;
81978
81979 --
81980 -- TOC entry 2209 (class 1255 OID 146567059)
81981 -- Dependencies: 4536 8
81982 -- Name: setnextponumber(integer); Type: FUNCTION; Schema: public; Owner: admin
81983 --
81984
81985 CREATE FUNCTION setnextponumber(integer) RETURNS integer
81986     LANGUAGE plpgsql
81987     AS $_$
81988 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
81989 -- See www.xtuple.com/CPAL for the full text of the software license.
81990 DECLARE
81991   pNumber ALIAS FOR $1;
81992   _orderseqid INTEGER;
81993
81994 BEGIN
81995
81996   SELECT orderseq_id INTO _orderseqid
81997   FROM orderseq
81998   WHERE (orderseq_name='PoNumber');
81999
82000   IF (NOT FOUND) THEN
82001     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82002     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82003     VALUES (_orderseqid, 'PoNumber', pNumber);
82004
82005   ELSE
82006     UPDATE orderseq
82007     SET orderseq_number=pNumber
82008     WHERE (orderseq_name='PoNumber');
82009   END IF;
82010
82011   RETURN _orderseqid;
82012
82013 END;
82014 $_$;
82015
82016
82017 ALTER FUNCTION public.setnextponumber(integer) OWNER TO admin;
82018
82019 --
82020 -- TOC entry 2210 (class 1255 OID 146567060)
82021 -- Dependencies: 4536 8
82022 -- Name: setnextprnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
82023 --
82024
82025 CREATE FUNCTION setnextprnumber(integer) RETURNS integer
82026     LANGUAGE plpgsql
82027     AS $_$
82028 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82029 -- See www.xtuple.com/CPAL for the full text of the software license.
82030 DECLARE
82031   pNumber ALIAS FOR $1;
82032   _orderseqid INTEGER;
82033
82034 BEGIN
82035
82036   SELECT orderseq_id INTO _orderseqid
82037   FROM orderseq
82038   WHERE (orderseq_name='PrNumber');
82039
82040   IF (NOT FOUND) THEN
82041     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82042     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82043     VALUES (_orderseqid, 'PrNumber', pNumber);
82044
82045   ELSE
82046     UPDATE orderseq
82047     SET orderseq_number=pNumber
82048     WHERE (orderseq_name='PrNumber');
82049   END IF;
82050
82051   RETURN _orderseqid;
82052
82053 END;
82054 $_$;
82055
82056
82057 ALTER FUNCTION public.setnextprnumber(integer) OWNER TO admin;
82058
82059 --
82060 -- TOC entry 2211 (class 1255 OID 146567061)
82061 -- Dependencies: 4536 8
82062 -- Name: setnextqunumber(integer); Type: FUNCTION; Schema: public; Owner: admin
82063 --
82064
82065 CREATE FUNCTION setnextqunumber(integer) RETURNS integer
82066     LANGUAGE plpgsql
82067     AS $_$
82068 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82069 -- See www.xtuple.com/CPAL for the full text of the software license.
82070 DECLARE
82071   pQuNumber ALIAS FOR $1;
82072   _orderseqid INTEGER;
82073
82074 BEGIN
82075
82076   SELECT orderseq_id INTO _orderseqid
82077   FROM orderseq
82078   WHERE (orderseq_name='QuNumber');
82079
82080   IF (NOT FOUND) THEN
82081     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82082
82083     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82084     VALUES (_orderseqid, 'QuNumber', pQuNumber);
82085
82086   ELSE
82087     UPDATE orderseq
82088     SET orderseq_number=pQuNumber
82089     WHERE (orderseq_name='QuNumber');
82090   END IF;
82091
82092   RETURN _orderseqid;
82093
82094 END;
82095 $_$;
82096
82097
82098 ALTER FUNCTION public.setnextqunumber(integer) OWNER TO admin;
82099
82100 --
82101 -- TOC entry 2212 (class 1255 OID 146567062)
82102 -- Dependencies: 4536 8
82103 -- Name: setnextshipmentnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
82104 --
82105
82106 CREATE FUNCTION setnextshipmentnumber(integer) RETURNS integer
82107     LANGUAGE plpgsql
82108     AS $_$
82109 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82110 -- See www.xtuple.com/CPAL for the full text of the software license.
82111 DECLARE
82112   pShipmentNumber ALIAS FOR $1;
82113   _orderseqid INTEGER;
82114
82115 BEGIN
82116
82117   SELECT orderseq_id INTO _orderseqid
82118   FROM orderseq
82119   WHERE (orderseq_name='ShipmentNumber');
82120
82121   IF (NOT FOUND) THEN
82122     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82123
82124     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82125     VALUES (_orderseqid, 'ShipmentNumber', pShipmentNumber);
82126
82127   ELSE
82128     UPDATE orderseq
82129     SET orderseq_number=pShipmentNumber
82130     WHERE (orderseq_name='ShipmentNumber');
82131   END IF;
82132
82133   RETURN _orderseqid;
82134
82135 END;
82136 $_$;
82137
82138
82139 ALTER FUNCTION public.setnextshipmentnumber(integer) OWNER TO admin;
82140
82141 --
82142 -- TOC entry 2213 (class 1255 OID 146567063)
82143 -- Dependencies: 4536 8
82144 -- Name: setnextsonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
82145 --
82146
82147 CREATE FUNCTION setnextsonumber(integer) RETURNS integer
82148     LANGUAGE plpgsql
82149     AS $_$
82150 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82151 -- See www.xtuple.com/CPAL for the full text of the software license.
82152 DECLARE
82153   pSoNumber ALIAS FOR $1;
82154   _orderseqid INTEGER;
82155
82156 BEGIN
82157
82158   SELECT orderseq_id INTO _orderseqid
82159   FROM orderseq
82160   WHERE (orderseq_name='SoNumber');
82161
82162   IF (NOT FOUND) THEN
82163     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82164
82165     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82166     VALUES (_orderseqid, 'SoNumber', pSoNumber);
82167
82168   ELSE
82169     UPDATE orderseq
82170     SET orderseq_number=pSoNumber
82171     WHERE (orderseq_name='SoNumber');
82172   END IF;
82173
82174   RETURN _orderseqid;
82175
82176 END;
82177 $_$;
82178
82179
82180 ALTER FUNCTION public.setnextsonumber(integer) OWNER TO admin;
82181
82182 --
82183 -- TOC entry 2214 (class 1255 OID 146567064)
82184 -- Dependencies: 4536 8
82185 -- Name: setnextvcnumber(integer); Type: FUNCTION; Schema: public; Owner: admin
82186 --
82187
82188 CREATE FUNCTION setnextvcnumber(integer) RETURNS integer
82189     LANGUAGE plpgsql
82190     AS $_$
82191 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82192 -- See www.xtuple.com/CPAL for the full text of the software license.
82193 DECLARE
82194   pNumber ALIAS FOR $1;
82195   _orderseqid INTEGER;
82196
82197 BEGIN
82198
82199   SELECT orderseq_id INTO _orderseqid
82200   FROM orderseq
82201   WHERE (orderseq_name='VcNumber');
82202
82203   IF (NOT FOUND) THEN
82204     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82205     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82206     VALUES (_orderseqid, 'VcNumber', pNumber);
82207
82208   ELSE
82209     UPDATE orderseq
82210     SET orderseq_number=pNumber
82211     WHERE (orderseq_name='VcNumber');
82212   END IF;
82213
82214   RETURN _orderseqid;
82215
82216 END;
82217 $_$;
82218
82219
82220 ALTER FUNCTION public.setnextvcnumber(integer) OWNER TO admin;
82221
82222 --
82223 -- TOC entry 2216 (class 1255 OID 146567065)
82224 -- Dependencies: 4536 8
82225 -- Name: setnextwonumber(integer); Type: FUNCTION; Schema: public; Owner: admin
82226 --
82227
82228 CREATE FUNCTION setnextwonumber(integer) RETURNS integer
82229     LANGUAGE plpgsql
82230     AS $_$
82231 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82232 -- See www.xtuple.com/CPAL for the full text of the software license.
82233 DECLARE
82234   pWoNumber ALIAS FOR $1;
82235   _orderseqid INTEGER;
82236
82237 BEGIN
82238
82239   SELECT orderseq_id INTO _orderseqid
82240   FROM orderseq
82241   WHERE (orderseq_name='WoNumber');
82242
82243   IF (NOT FOUND) THEN
82244     SELECT NEXTVAL('orderseq_orderseq_id_seq') INTO _orderseqid;
82245
82246     INSERT INTO orderseq (orderseq_id, orderseq_name, orderseq_number)
82247     VALUES (_orderseqid, 'WoNumber', pWoNumber);
82248
82249   ELSE
82250     UPDATE orderseq
82251     SET orderseq_number=pWoNumber
82252     WHERE (orderseq_name='WoNumber');
82253   END IF;
82254
82255   RETURN _orderseqid;
82256
82257 END;
82258 $_$;
82259
82260
82261 ALTER FUNCTION public.setnextwonumber(integer) OWNER TO admin;
82262
82263 --
82264 -- TOC entry 2217 (class 1255 OID 146567066)
82265 -- Dependencies: 4536 8
82266 -- Name: setusercancreateusers(text, boolean); Type: FUNCTION; Schema: public; Owner: admin
82267 --
82268
82269 CREATE FUNCTION setusercancreateusers(pusername text, pcreateuser boolean) RETURNS boolean
82270     LANGUAGE plpgsql
82271     AS $$
82272 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82273 -- See www.xtuple.com/CPAL for the full text of the software license.
82274 BEGIN
82275   IF (pCreateUser) THEN
82276     EXECUTE 'ALTER USER "' || pUsername || '" CREATEROLE;';
82277   ELSE
82278     EXECUTE 'ALTER USER "' || pUsername || '" NOCREATEROLE;';
82279   END IF;
82280   RETURN TRUE;
82281 END;
82282 $$;
82283
82284
82285 ALTER FUNCTION public.setusercancreateusers(pusername text, pcreateuser boolean) OWNER TO admin;
82286
82287 --
82288 -- TOC entry 2218 (class 1255 OID 146567067)
82289 -- Dependencies: 4536 8
82290 -- Name: setuserpreference(text, text); Type: FUNCTION; Schema: public; Owner: admin
82291 --
82292
82293 CREATE FUNCTION setuserpreference(text, text) RETURNS boolean
82294     LANGUAGE plpgsql
82295     AS $_$
82296 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82297 -- See www.xtuple.com/CPAL for the full text of the software license.
82298 DECLARE
82299   pPrefName ALIAS FOR $1;
82300   pPrefValue ALIAS FOR $2;
82301
82302 BEGIN
82303   RETURN setUserPreferences(getEffectiveXtUser(), pPrefName, pPrefValue);
82304 END;
82305 $_$;
82306
82307
82308 ALTER FUNCTION public.setuserpreference(text, text) OWNER TO admin;
82309
82310 --
82311 -- TOC entry 2219 (class 1255 OID 146567068)
82312 -- Dependencies: 4536 8
82313 -- Name: setuserpreference(text, text, text); Type: FUNCTION; Schema: public; Owner: admin
82314 --
82315
82316 CREATE FUNCTION setuserpreference(text, text, text) RETURNS boolean
82317     LANGUAGE plpgsql
82318     AS $_$
82319 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82320 -- See www.xtuple.com/CPAL for the full text of the software license.
82321 DECLARE
82322   pUsername ALIAS FOR $1;
82323   pPrefName ALIAS FOR $2;
82324   pPrefValue ALIAS FOR $3;
82325   _usrprefid INTEGER;
82326
82327 BEGIN
82328
82329   SELECT usrpref_id INTO _usrprefid
82330   FROM usrpref
82331   WHERE ( (usrpref_username=pUsername)
82332    AND (usrpref_name=pPrefName) );
82333
82334   IF (FOUND) THEN
82335     UPDATE usrpref
82336     SET usrpref_value=pPrefValue
82337     WHERE (usrpref_id=_usrprefid);
82338
82339   ELSE
82340     INSERT INTO usrpref
82341     (usrpref_username, usrpref_name, usrpref_value)
82342     VALUES
82343     (pUsername, pPrefName, pPrefValue);
82344   END IF;
82345
82346   RETURN TRUE;
82347
82348 END;
82349 $_$;
82350
82351
82352 ALTER FUNCTION public.setuserpreference(text, text, text) OWNER TO admin;
82353
82354 --
82355 -- TOC entry 2220 (class 1255 OID 146567069)
82356 -- Dependencies: 4536 8
82357 -- Name: shipments(text); Type: FUNCTION; Schema: public; Owner: admin
82358 --
82359
82360 CREATE FUNCTION shipments(text) RETURNS boolean
82361     LANGUAGE plpgsql
82362     AS $_$
82363 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82364 -- See www.xtuple.com/CPAL for the full text of the software license.
82365 DECLARE
82366   pTransType ALIAS FOR $1;
82367
82368 BEGIN
82369   IF (pTransType IN ('SC', 'SV', 'SH', 'RS', 'TS')) THEN
82370     RETURN TRUE;
82371   ELSE
82372     RETURN FALSE;
82373   END IF;
82374
82375 END;
82376 $_$;
82377
82378
82379 ALTER FUNCTION public.shipments(text) OWNER TO admin;
82380
82381 --
82382 -- TOC entry 2221 (class 1255 OID 146567070)
82383 -- Dependencies: 8
82384 -- Name: shipshipment(integer); Type: FUNCTION; Schema: public; Owner: admin
82385 --
82386
82387 CREATE FUNCTION shipshipment(integer) RETURNS integer
82388     LANGUAGE sql
82389     AS $_$
82390 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82391 -- See www.xtuple.com/CPAL for the full text of the software license.
82392   SELECT shipShipment($1, CURRENT_TIMESTAMP);
82393 $_$;
82394
82395
82396 ALTER FUNCTION public.shipshipment(integer) OWNER TO admin;
82397
82398 --
82399 -- TOC entry 2222 (class 1255 OID 146567071)
82400 -- Dependencies: 4536 8
82401 -- Name: shipshipment(integer, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
82402 --
82403
82404 CREATE FUNCTION shipshipment(integer, timestamp with time zone) RETURNS integer
82405     LANGUAGE plpgsql
82406     AS $_$
82407 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82408 -- See www.xtuple.com/CPAL for the full text of the software license.
82409 DECLARE
82410   pshipheadid           ALIAS FOR $1;
82411   _timestamp            TIMESTAMP WITH TIME ZONE := $2;
82412
82413   _billedQty            NUMERIC;
82414   _c                    RECORD;
82415   _coholdtype           TEXT;
82416   _gldate               DATE;
82417   _invhistid            INTEGER;
82418   _itemlocSeries        INTEGER;
82419   _lineitemsToClose     INTEGER[];
82420   _newQty               NUMERIC;
82421   _result               INTEGER;
82422   _s                    RECORD;
82423   _shipcomplete         BOOLEAN;
82424   _shiphead             RECORD;
82425   _ti                   RECORD;
82426   _to                   RECORD;
82427   _variance             NUMERIC;
82428   _k                    RECORD;
82429
82430 BEGIN
82431
82432   IF (_timestamp IS NULL) THEN
82433     _timestamp := CURRENT_TIMESTAMP;
82434   END IF;
82435   _gldate := _timestamp::DATE;
82436
82437   SELECT * INTO _shiphead
82438   FROM shiphead WHERE (shiphead_id=pshipheadid);
82439   IF (NOT FOUND) THEN
82440     RETURN -50;
82441   END IF;
82442
82443   IF (_shiphead.shiphead_order_type = 'SO') THEN
82444
82445     SELECT cohead_shipcomplete, cohead_holdtype INTO _shipcomplete, _coholdtype
82446       FROM cohead, shiphead
82447      WHERE ((shiphead_order_id=cohead_id)
82448        AND  (NOT shiphead_shipped)
82449        AND  (shiphead_order_type=_shiphead.shiphead_order_type)
82450        AND  (shiphead_id=pshipheadid));
82451
82452     IF (_coholdtype = 'C') THEN
82453       RETURN -12;
82454     ELSIF (_coholdtype = 'P') THEN
82455       RETURN -13;
82456     ELSIF (_coholdtype = 'R') THEN
82457       RETURN -14;
82458     ELSIF (_coholdtype = 'S') THEN
82459       RETURN -15;
82460     END IF;
82461
82462 ---Must Ship Kit components (coitem_subnumber <> 0 complete---------------
82463     IF ((
82464          --  Test to see if order's customer accepts backorders and partials 
82465          --  If not then test for shipping kit components complete 
82466         SELECT cohead_number
82467         FROM shiphead, cohead, custinfo
82468         WHERE 
82469           (shiphead_order_id = cohead_id) AND
82470           (cohead_cust_id = cust_id) AND
82471           (shiphead_order_type = 'SO') AND 
82472           (cust_partialship) AND
82473           (cust_backorder) AND
82474           (shiphead_id = pshipheadid)
82475          ) IS NULL) THEN
82476       FOR _k IN SELECT (coitem_qtyord -
82477                         (COALESCE(SUM(shipitem_qty),0) +
82478                          (coitem_qtyshipped - coitem_qtyreturned))) AS remain
82479                   FROM (coitem LEFT OUTER JOIN (itemsite JOIN item ON (itemsite_item_id=item_id)) ON (coitem_itemsite_id=itemsite_id)) LEFT OUTER JOIN
82480                        shipitem ON (shipitem_orderitem_id=coitem_id
82481                                 AND shipitem_shiphead_id=pshipheadid)
82482                  WHERE ((coitem_status NOT IN ('C','X'))
82483                    AND  (item_type != 'K')
82484                    AND  (coitem_cohead_id=_shiphead.shiphead_order_id)
82485                    AND  (coitem_subnumber <> 0)
82486                    )
82487               GROUP BY coitem_id, coitem_qtyshipped, coitem_qtyord,
82488                        coitem_qtyreturned LOOP
82489         IF (_k.remain > 0) THEN
82490           RAISE EXCEPTION 'Kit component item not shipped complete.  Kits must be shipped and shipped complete or closed on the order.';
82491         END IF;
82492       END LOOP;
82493     END IF;
82494 ---End--------------------------------------------------------------------
82495
82496     IF ( _shipcomplete ) THEN
82497       FOR _c IN SELECT (coitem_qtyord -
82498                         (COALESCE(SUM(shipitem_qty),0) +
82499                          (coitem_qtyshipped - coitem_qtyreturned))) AS remain
82500                   FROM (coitem LEFT OUTER JOIN (itemsite JOIN item ON (itemsite_item_id=item_id)) ON (coitem_itemsite_id=itemsite_id)) LEFT OUTER JOIN
82501                        shipitem ON (shipitem_orderitem_id=coitem_id
82502                                 AND shipitem_shiphead_id=pshipheadid)
82503                  WHERE ((coitem_status<>'X')
82504                    AND  (item_type != 'K')
82505                    AND  (coitem_cohead_id=_shiphead.shiphead_order_id))
82506               GROUP BY coitem_id, coitem_qtyshipped, coitem_qtyord,
82507                        coitem_qtyreturned LOOP
82508         IF (_c.remain > 0) THEN
82509           RETURN -99;
82510         END IF;
82511       END LOOP;
82512     END IF;
82513
82514     FOR _c IN SELECT coitem_id, cohead_number, cohead_cust_id, cohead_billtoname, cohead_prj_id,
82515                      cohead_saletype_id, cohead_shipzone_id,
82516                      itemsite_id, itemsite_item_id,
82517                      coitem_qty_invuomratio,
82518                      coitem_warranty, coitem_cos_accnt_id,
82519                      SUM(shipitem_qty) AS _qty,
82520                      SUM(shipitem_value) AS _value
82521               FROM coitem, cohead, shiphead, shipitem, itemsite
82522               WHERE ( (coitem_cohead_id=cohead_id)
82523                AND (coitem_itemsite_id=itemsite_id)
82524                AND (shiphead_order_id=cohead_id)
82525                AND (shipitem_shiphead_id=shiphead_id)
82526                AND (shipitem_orderitem_id=coitem_id)
82527                AND (NOT shiphead_shipped)
82528                AND (shiphead_id=pshipheadid) )
82529               GROUP BY coitem_id, coitem_qty_invuomratio, cohead_number, cohead_cust_id, cohead_billtoname,
82530            itemsite_id, itemsite_item_id, coitem_warranty, coitem_cos_accnt_id, cohead_prj_id, cohead_saletype_id, cohead_shipzone_id
82531     LOOP
82532
82533       IF _c._value > 0 THEN
82534   --    Distribute to G/L, credit Shipping Asset, debit COS
82535         SELECT MIN(insertGLTransaction( 'S/R', 'SH', _shiphead.shiphead_number,
82536                                         ('Ship Order ' || _c.cohead_number || ' for Customer ' || _c.cohead_billtoname),
82537                                         getPrjAccntId(_c.cohead_prj_id, costcat_shipasset_accnt_id),
82538                                         CASE WHEN (COALESCE(_c.coitem_cos_accnt_id, -1) != -1)
82539                                                THEN getPrjAccntId(_c.cohead_prj_id, _c.coitem_cos_accnt_id)
82540                                              WHEN (_c.coitem_warranty=TRUE)
82541                                                THEN getPrjAccntId(_c.cohead_prj_id, resolveCOWAccount(itemsite_id, _c.cohead_cust_id, _c.cohead_saletype_id, _c.cohead_shipzone_id))
82542                                              ELSE getPrjAccntId(_c.cohead_prj_id, resolveCOSAccount(itemsite_id, _c.cohead_cust_id, _c.cohead_saletype_id, _c.cohead_shipzone_id))
82543                                         END,
82544                                         -1, _c._value, _gldate )) INTO _result
82545         FROM itemsite, costcat
82546         WHERE ( (itemsite_costcat_id=costcat_id)
82547         AND (itemsite_id=_c.itemsite_id) );
82548
82549         IF (_result < 0 AND _result != -3) THEN -- ignore -3 as it just means it's not posting a 0 value
82550           RETURN _result;
82551         END IF;
82552
82553       END IF;
82554
82555       UPDATE coitem
82556       SET coitem_qtyshipped = (coitem_qtyshipped + _c._qty)
82557       WHERE (coitem_id=_c.coitem_id);
82558
82559       -- check to see if we have more invoiced than shipped items
82560       -- if we do we will need to mark some of these records as invoiced
82561       SELECT noNeg(( SELECT COALESCE(SUM(cobill_qty), 0.0)
82562                      FROM cobill, cobmisc, coitem
82563                      WHERE ( (cobill_cobmisc_id=cobmisc_id)
82564                       AND (cobmisc_cohead_id=coitem_cohead_id)
82565                       AND (cobill_coitem_id=coitem_id)
82566                       AND (cobmisc_posted)
82567                       AND (coitem_id=_c.coitem_id) )
82568                    ) - ( SELECT COALESCE(SUM(shipitem_qty), 0.0)
82569                          FROM shipitem, shiphead, coitem
82570                          WHERE ( (shipitem_shiphead_id=shiphead_id)
82571                           AND (shiphead_order_id=coitem_cohead_id)
82572                           AND (shipitem_orderitem_id=coitem_id)
82573                           AND (shiphead_order_type=_shiphead.shiphead_order_type)
82574                           AND (shiphead_shipped)
82575                           AND (coitem_id=_c.coitem_id) )
82576                        ) ) INTO _billedQty;
82577
82578       IF (_billedQty > 0.0) THEN
82579         FOR _s IN SELECT shipitem_id, shipitem_qty
82580                   FROM shipitem, shiphead
82581                   WHERE ( (shipitem_shiphead_id=shiphead_id)
82582                    AND (shipitem_orderitem_id=_c.coitem_id)
82583                    AND (shiphead_order_type=_shiphead.shiphead_order_type)
82584                    AND (NOT shiphead_shipped)
82585                    AND (shiphead_id=pshipheadid) )
82586                   ORDER BY shipitem_qty LOOP
82587
82588           IF (_billedQty > 0.0) THEN
82589
82590             IF (_billedQty >= _s.shipitem_qty) THEN
82591               UPDATE shipitem SET shipitem_invoiced=TRUE WHERE shipitem_id=_s.shipitem_id;
82592               -- must wait to close coitems until after shiphead_shipped -> true
82593               _lineitemsToClose := _lineitemsToClose || _c.coitem_id;
82594             ELSE
82595               _newQty := _s.shipitem_qty - _billedQty;
82596               UPDATE shipitem SET shipitem_invoiced=TRUE, shipitem_qty=_billedQty WHERE shipitem_id=_s.shipitem_id;
82597               INSERT INTO shipitem ( shipitem_orderitem_id, shipitem_shipdate,
82598                 shipitem_qty, shipitem_transdate, shipitem_invoiced,
82599                 shipitem_shiphead_id, shipitem_trans_username)
82600               SELECT shipitem_orderitem_id, shipitem_shipdate,
82601                 _newQty, shipitem_transdate, FALSE,
82602                 shipitem_shiphead_id, shipitem_trans_username
82603               FROM shipitem
82604               WHERE (shipitem_id=_s.shipitem_id);
82605             END IF;
82606
82607             _billedQty := _billedQty - _s.shipitem_qty;
82608           END IF;
82609         END LOOP;
82610
82611       END IF;
82612     END LOOP;
82613
82614   ELSEIF (_shiphead.shiphead_order_type = 'TO') THEN
82615     IF (_shiphead.shiphead_shipped) THEN
82616       RETURN -8;
82617     END IF;
82618
82619     SELECT tohead.* INTO _to
82620       FROM tohead
82621      WHERE (tohead_id=_shiphead.shiphead_order_id);
82622
82623     IF ( _to.tohead_shipcomplete ) THEN
82624       -- use sufficientInventory...()?
82625       FOR _ti IN SELECT (toitem_qty_ordered -
82626                          (COALESCE(SUM(shipitem_qty),0) + toitem_qty_shipped)) AS remain
82627                   FROM toitem LEFT OUTER JOIN
82628                        shipitem ON (shipitem_orderitem_id=toitem_id)
82629                  WHERE ((toitem_status<>'X')
82630                    AND  (toitem_tohead_id=_shiphead.shiphead_order_id))
82631               GROUP BY toitem_qty_shipped, toitem_qty_ordered LOOP
82632         IF (_ti.remain > 0) THEN
82633           RETURN -99;
82634         END IF;
82635       END LOOP;
82636     END IF;
82637
82638     FOR _ti IN SELECT toitem_id, toitem_item_id, SUM(shipitem_qty) AS qty, SUM(shipitem_value) AS value
82639                 FROM toitem, shipitem
82640                 WHERE ((toitem_tohead_id=_to.tohead_id)
82641                   AND  (shipitem_orderitem_id=toitem_id)
82642                   AND  (shipitem_shiphead_id=pshipheadid))
82643                 GROUP BY toitem_id, toitem_item_id LOOP
82644
82645       IF (NOT EXISTS(SELECT itemsite_id
82646                      FROM itemsite
82647                      WHERE ((itemsite_item_id=_ti.toitem_item_id)
82648                      AND  (itemsite_warehous_id = _to.tohead_trns_warehous_id))
82649                      )) THEN
82650         RETURN -6;
82651       END IF;
82652
82653       _itemlocSeries := NEXTVAL('itemloc_series_seq');
82654
82655       SELECT postInvTrans(si.itemsite_id, 'TS', _ti.qty,
82656                           'I/M', _shiphead.shiphead_order_type,
82657                           formatToNumber(_ti.toitem_id), _to.tohead_number,
82658                           'Ship from Src to Transit Warehouse',
82659                           tc.costcat_asset_accnt_id,
82660                           sc.costcat_shipasset_accnt_id,
82661                           _itemlocSeries, _timestamp, _ti.value) INTO _invhistid
82662       FROM itemsite AS ti, costcat AS tc,
82663            itemsite AS si, costcat AS sc
82664       WHERE ( (ti.itemsite_costcat_id=tc.costcat_id)
82665         AND  (si.itemsite_costcat_id=sc.costcat_id)
82666         AND  (ti.itemsite_item_id=_ti.toitem_item_id)
82667         AND  (si.itemsite_item_id=_ti.toitem_item_id)
82668         AND  (ti.itemsite_warehous_id=_to.tohead_trns_warehous_id)
82669         AND  (si.itemsite_warehous_id=_to.tohead_src_warehous_id) );
82670
82671       --We do not need to distribute lot/serial info for transit, post trans and discard dist detail
82672       PERFORM postIntoTrialBalance(itemlocpost_glseq) FROM itemlocpost WHERE (itemlocpost_itemlocseries=_itemlocSeries);
82673       IF (_invhistid > 0) THEN
82674         PERFORM postInvHist(_invhistid);
82675       END IF;
82676       DELETE FROM itemlocdist WHERE (itemlocdist_series=_itemlocSeries);
82677       DELETE FROM itemlocpost WHERE (itemlocpost_itemlocSeries=_itemlocSeries);
82678
82679       IF (_result < 0) THEN
82680         RETURN _result;
82681       END IF;
82682
82683       -- record inventory history and qoh changes at transit warehouse but
82684       -- there is only one g/l account to touch
82685       SELECT postInvTrans(ti.itemsite_id, 'TR', _ti.qty,
82686                           'I/M', _shiphead.shiphead_order_type,
82687                           formatToNumber(_ti.toitem_id), _to.tohead_number,
82688                           'Receive into Transit from Src Warehouse',
82689                           tc.costcat_asset_accnt_id,
82690                           tc.costcat_asset_accnt_id,
82691                           _itemlocSeries, _timestamp, 
82692                           _ti.value) INTO _invhistid
82693       FROM itemsite AS ti, costcat AS tc
82694       WHERE ((ti.itemsite_costcat_id=tc.costcat_id)
82695         AND  (ti.itemsite_item_id=_ti.toitem_item_id)
82696         AND  (ti.itemsite_warehous_id=_to.tohead_trns_warehous_id));
82697       --We do not need to distribute lot/serial info for transit, post trans and discard dist detail
82698       PERFORM postIntoTrialBalance(itemlocpost_glseq) FROM itemlocpost WHERE (itemlocpost_itemlocseries=_itemlocSeries);
82699       IF (_invhistid > 0) THEN
82700         PERFORM postInvHist(_invhistid);
82701       END IF;
82702       DELETE FROM itemlocdist WHERE (itemlocdist_series=_itemlocSeries);
82703       DELETE FROM itemlocpost WHERE (itemlocpost_itemlocSeries=_itemlocSeries);
82704
82705       --See if there was a change in values during the transfer, if so record the variance
82706       SELECT (invhist_invqty * invhist_unitcost - _ti.value) INTO _variance
82707       FROM invhist
82708       WHERE (invhist_id=_invhistid);
82709
82710       IF (_variance > 0) THEN
82711         PERFORM insertGLTransaction( 'S/R', _shiphead.shiphead_order_type, _to.tohead_number, 
82712                                      'Transfer Order - Transfer Variance',
82713                                      tc.costcat_invcost_accnt_id, tc.costcat_asset_accnt_id, _invhistid,
82714                                      _variance,
82715                                      CAST(_timestamp AS DATE) )
82716         FROM itemsite AS ti, costcat AS tc
82717         WHERE ( (ti.itemsite_costcat_id=tc.costcat_id)
82718         AND  (ti.itemsite_item_id=_ti.toitem_item_id)
82719         AND  (ti.itemsite_warehous_id=_to.tohead_trns_warehous_id) );
82720       END IF;
82721
82722       IF (_result < 0) THEN
82723         RETURN _result;
82724       END IF;
82725
82726       UPDATE shipitem SET shipitem_shipdate=_timestamp, shipitem_shipped=TRUE
82727       WHERE ((shipitem_orderitem_id=_ti.toitem_id)
82728         AND  (shipitem_shiphead_id=pshipheadid));
82729
82730       UPDATE toitem
82731       SET toitem_qty_shipped = (toitem_qty_shipped + _ti.qty)
82732       WHERE (toitem_id=_ti.toitem_id);
82733     END LOOP;
82734   END IF;
82735
82736   UPDATE shiphead
82737   SET shiphead_shipped=TRUE, shiphead_shipdate=_gldate
82738   WHERE (shiphead_id=pshipheadid);
82739
82740   -- now try to close line items that are fully shipped and invoiced
82741   IF (_shiphead.shiphead_order_type = 'SO') THEN
82742     UPDATE coitem SET coitem_status='C'
82743     WHERE ((coitem_id = ANY (_lineitemsToClose))
82744       AND  (coitem_qtyshipped >= coitem_qtyord));
82745   END IF;
82746
82747   RETURN _itemlocSeries;
82748
82749 END;
82750 $_$;
82751
82752
82753 ALTER FUNCTION public.shipshipment(integer, timestamp with time zone) OWNER TO admin;
82754
82755 --
82756 -- TOC entry 2223 (class 1255 OID 146567073)
82757 -- Dependencies: 4536 8
82758 -- Name: singlecharacteristicstostring(text, integer, text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
82759 --
82760
82761 CREATE FUNCTION singlecharacteristicstostring(text, integer, text, text, integer) RETURNS text
82762     LANGUAGE plpgsql
82763     AS $_$
82764 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82765 -- See www.xtuple.com/CPAL for the full text of the software license.
82766 DECLARE
82767   pTargetType ALIAS FOR $1;
82768   pTargetId ALIAS FOR $2;
82769   pValKeySep ALIAS FOR $3;
82770   pPairSep ALIAS FOR $4;
82771   pCharId ALIAS FOR $5;
82772   _string TEXT := '';
82773   _extra BOOLEAN := false;
82774   _r RECORD;
82775 BEGIN
82776   FOR _r IN SELECT char_name, charass_value
82777               FROM charass, char
82778              WHERE ((charass_char_id=char_id)
82779                AND  (charass_char_id=pCharId)
82780                AND  (charass_target_type=pTargetType)
82781                AND  (charass_target_id=pTargetId)) LOOP
82782     IF(_extra) THEN
82783       _string := _string || pPairSep;
82784     END IF;
82785     _extra := true;
82786
82787     _string := _string || _r.char_name || pValKeySep || _r.charass_value;
82788   END LOOP;
82789
82790   RETURN _string;
82791 END;
82792 $_$;
82793
82794
82795 ALTER FUNCTION public.singlecharacteristicstostring(text, integer, text, text, integer) OWNER TO admin;
82796
82797 --
82798 -- TOC entry 2224 (class 1255 OID 146567074)
82799 -- Dependencies: 2657 4536 8
82800 -- Name: singlelevelbom(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
82801 --
82802
82803 CREATE FUNCTION singlelevelbom(integer, integer, integer, integer) RETURNS SETOF bomdata
82804     LANGUAGE plpgsql
82805     AS $_$
82806 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
82807 -- See www.xtuple.com/CPAL for the full text of the software license.
82808 DECLARE
82809   pItemid ALIAS FOR $1;
82810   pRevisionid ALIAS FOR $2;
82811   pExpiredDays ALIAS FOR $3;
82812   pFutureDays ALIAS FOR $4;
82813   _row bomdata%ROWTYPE;
82814   _bomworksetid INTEGER;
82815   _x RECORD;
82816   _check CHAR(1);
82817   _inactive BOOLEAN;
82818   _batchsize NUMERIC;
82819
82820 BEGIN
82821
82822   _inactive := FALSE;
82823
82824   IF (pRevisionid != -1) THEN
82825     --Is this a deactivated revision?
82826     SELECT rev_status INTO _check
82827     FROM rev
82828     WHERE ((rev_id=pRevisionid)
82829     AND (rev_status='I'));
82830     IF (FOUND) THEN
82831       _inactive := TRUE;
82832     END IF;
82833   END IF;
82834  
82835   -- Get the batch quantity
82836   SELECT COALESCE( (
82837     SELECT bomhead_batchsize
82838     FROM bomhead
82839     WHERE ((bomhead_item_id=pItemId)
82840     AND (bomhead_rev_id=pRevisionid))),1) INTO _batchsize;
82841  
82842   IF NOT (_inactive) THEN
82843     FOR _x IN
82844         SELECT bomitem_id, bomitem_seqnumber, bomitem_seqnumber AS f_bomitem_seqnumber,
82845                item_id, item_number, uom_name,
82846                item_descrip1, item_descrip2,
82847                (item_descrip1 || ' ' || item_descrip2) AS itemdescription,
82848                (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyfxd) AS qtyfxd,
82849                (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyper) AS qtyper,
82850                bomitem_scrap, bomitem_createwo,
82851                CASE WHEN (bomitem_issuemethod='S') THEN 'Push'
82852                  WHEN (bomitem_issuemethod='L') THEN 'Pull'
82853                  WHEN (bomitem_issuemethod='M') THEN 'Mixed'
82854                  ELSE 'Special'
82855                END AS issuemethod,
82856                bomitem_effective, bomitem_expires,
82857                CASE WHEN (bomitem_expires <= CURRENT_DATE) THEN TRUE
82858                  ELSE FALSE
82859                END AS expired,
82860                CASE WHEN (bomitem_effective > CURRENT_DATE) THEN TRUE
82861                  ELSE FALSE
82862                END AS future,
82863                actcost(bomitem_item_id, bomitem_id) AS actunitcost,
82864                stdcost(bomitem_item_id, bomitem_id) AS stdunitcost,
82865                CASE WHEN item_type NOT IN ('R','T') THEN
82866                  itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL,
82867                               (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper') * actcost(bomitem_item_id, bomitem_id)
82868                ELSE 0.0 END AS actextendedcost,
82869                CASE WHEN item_type NOT IN ('R','T') THEN
82870                  itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL,
82871                               (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper') * stdcost(bomitem_item_id, bomitem_id)
82872                ELSE 0.0 END AS stdextendedcost,
82873                bomitem_char_id, bomitem_value, bomitem_notes, bomitem_ref 
82874        FROM bomitem(pItemid,pRevisionid), item, uom 
82875        WHERE ( (item_inv_uom_id=uom_id)
82876        AND (bomitem_item_id=item_id)
82877        AND (bomitem_expires > (CURRENT_DATE - pExpiredDays))
82878        AND (bomitem_effective <= (CURRENT_DATE + pFutureDays)) )
82879        UNION
82880        SELECT -1, -1, NULL, -1, costelem_type AS bomdata_item_number, '',
82881               '', '',
82882               '',
82883               NULL,
82884               NULL,
82885               NULL, NULL,
82886               NULL,
82887               NULL, NULL,
82888               false,false,
82889               currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE) AS actunitcost,
82890               itemcost_stdcost AS stdunitcost,
82891               currToBase(itemcost_curr_id, itemcost_actcost, CURRENT_DATE) AS actextendedcost,
82892               itemcost_stdcost AS stdextendedcost,
82893               NULL, NULL, NULL, NULL
82894        FROM itemcost, costelem 
82895        WHERE ( (itemcost_costelem_id=costelem_id)
82896        AND (NOT itemcost_lowlevel)
82897        AND (itemcost_item_id=pItemid) )
82898        ORDER BY bomitem_seqnumber, bomitem_effective, item_number
82899     LOOP
82900         _row.bomdata_bomitem_id := _x.bomitem_id;
82901         _row.bomdata_bomwork_seqnumber := _x.f_bomitem_seqnumber;
82902         _row.bomdata_item_id := _x.item_id;
82903         _row.bomdata_item_number := _x.item_number;
82904         _row.bomdata_uom_name := _x.uom_name;
82905         _row.bomdata_item_descrip1 := _x.item_descrip1;
82906         _row.bomdata_item_descrip2 := _x.item_descrip2;
82907         _row.bomdata_itemdescription := _x.itemdescription;
82908         _row.bomdata_batchsize := _batchsize;
82909         _row.bomdata_qtyfxd := _x.qtyfxd;
82910         _row.bomdata_qtyper := _x.qtyper;
82911         _row.bomdata_scrap := _x.bomitem_scrap;
82912         _row.bomdata_createchild := _x.bomitem_createwo;
82913         _row.bomdata_issuemethod := _x.issuemethod;
82914         _row.bomdata_effective := _x.bomitem_effective;
82915         _row.bomdata_expires := _x.bomitem_expires;
82916         _row.bomdata_expired := _x.expired;
82917         _row.bomdata_future := _x.future;
82918         _row.bomdata_actunitcost := _x.actunitcost;
82919         _row.bomdata_stdunitcost := _x.stdunitcost;
82920         _row.bomdata_actextendedcost := _x.actextendedcost;
82921         _row.bomdata_stdextendedcost := _x.stdextendedcost;
82922         _row.bomdata_char_id := _x.bomitem_char_id;
82923         _row.bomdata_value := _x.bomitem_value;
82924         _row.bomdata_notes := _x.bomitem_notes;
82925         _row.bomdata_ref := _x.bomitem_ref;
82926         RETURN NEXT _row;
82927     END LOOP;
82928
82929    ELSE
82930
82931 -- Use historical snapshot for inactive revisions
82932     FOR _x IN
82933         SELECT bomitem_id, bomitem_seqnumber, bomitem_seqnumber AS f_bomitem_seqnumber,
82934                item_id, item_number, uom_name,
82935                item_descrip1, item_descrip2,
82936                (item_descrip1 || ' ' || item_descrip2) AS itemdescription,
82937                (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyfxd) AS qtyfxd,
82938                (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL) * bomitem_qtyper) AS qtyper,
82939                bomitem_scrap, bomitem_createwo,
82940                CASE WHEN (bomitem_issuemethod='S') THEN 'Push'
82941                  WHEN (bomitem_issuemethod='L') THEN 'Pull'
82942                  WHEN (bomitem_issuemethod='M') THEN 'Mixed'
82943                  ELSE 'Special'
82944                END AS issuemethod,
82945                bomitem_effective, bomitem_expires,
82946                CASE WHEN (bomitem_expires <= CURRENT_DATE) THEN TRUE
82947                  ELSE FALSE
82948                END AS expired,
82949                CASE WHEN (bomitem_effective > CURRENT_DATE) THEN TRUE
82950                  ELSE FALSE
82951                END AS future,
82952                actcost(bomitem_item_id) AS actunitcost,
82953                stdcost(bomitem_item_id) AS stdunitcost,
82954                CASE WHEN item_type NOT IN ('R','T') THEN
82955                  itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL,
82956                               (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper') * actcost(bomitem_item_id)
82957                ELSE 0.0 END AS actextendedcost,
82958                CASE WHEN item_type NOT IN ('R','T') THEN
82959                  itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL,
82960                               (bomitem_qtyfxd/_batchsize + bomitem_qtyper) * (1 + bomitem_scrap), 'qtyper') * stdcost(bomitem_item_id)
82961                ELSE 0.0 END AS stdextendedcost,
82962                bomitem_char_id, bomitem_value, bomitem_notes, bomitem_ref 
82963        FROM bomitem(pItemid,pRevisionid), item, uom 
82964        WHERE ( (item_inv_uom_id=uom_id)
82965        AND (bomitem_item_id=item_id)
82966        AND (bomitem_expires > (CURRENT_DATE - pExpiredDays))
82967        AND (bomitem_effective <= (CURRENT_DATE + pFutureDays)) )
82968        UNION
82969        SELECT -1, -1, NULL, -1, costelem_type AS bomdata_item_number, '',
82970               '', '',
82971               '',
82972               NULL,
82973               NULL,
82974               NULL, NULL,
82975               NULL,
82976               NULL, NULL,
82977               false,false,
82978               bomhist_actunitcost AS actunitcost,
82979               bomhist_stdunitcost AS stdunitcost,
82980               bomhist_actunitcost AS actextendedcost,
82981               bomhist_stdunitcost AS stdextendedcost,
82982               NULL, NULL, NULL, NULL
82983        FROM bomhist, costelem 
82984        WHERE ( (bomhist_item_id=costelem_id)
82985        AND (bomhist_item_type='E')
82986        AND (bomhist_rev_id=pRevisionid) )
82987        ORDER BY bomitem_seqnumber, bomitem_effective, item_number
82988     LOOP
82989         _row.bomdata_bomitem_id := _x.bomitem_id;
82990         _row.bomdata_bomwork_seqnumber := _x.f_bomitem_seqnumber;
82991         _row.bomdata_item_id := _x.item_id;
82992         _row.bomdata_item_number := _x.item_number;
82993         _row.bomdata_uom_name := _x.uom_name;
82994         _row.bomdata_item_descrip1 := _x.item_descrip1;
82995         _row.bomdata_item_descrip2 := _x.item_descrip2;
82996         _row.bomdata_itemdescription := _x.itemdescription;
82997         _row.bomdata_batchsize := _batchsize;
82998         _row.bomdata_qtyfxd := _x.qtyfxd;
82999         _row.bomdata_qtyper := _x.qtyper;
83000         _row.bomdata_scrap := _x.bomitem_scrap;
83001         _row.bomdata_createchild := _x.bomitem_createwo;
83002         _row.bomdata_issuemethod := _x.issuemethod;
83003         _row.bomdata_effective := _x.bomitem_effective;
83004         _row.bomdata_expires := _x.bomitem_expires;
83005         _row.bomdata_expired := _x.expired;
83006         _row.bomdata_future := _x.future;
83007         _row.bomdata_actunitcost := _x.actunitcost;
83008         _row.bomdata_stdunitcost := _x.stdunitcost;
83009         _row.bomdata_actextendedcost := _x.actextendedcost;
83010         _row.bomdata_stdextendedcost := _x.stdextendedcost;
83011         _row.bomdata_char_id := _x.bomitem_char_id;
83012         _row.bomdata_value := _x.bomitem_value;
83013         _row.bomdata_notes := _x.bomitem_notes;
83014         _row.bomdata_ref := _x.bomitem_ref;
83015         RETURN NEXT _row;
83016     END LOOP;
83017   END IF;
83018
83019   RETURN;
83020 END;
83021 $_$;
83022
83023
83024 ALTER FUNCTION public.singlelevelbom(integer, integer, integer, integer) OWNER TO admin;
83025
83026 --
83027 -- TOC entry 2225 (class 1255 OID 146567076)
83028 -- Dependencies: 2736 4536 8
83029 -- Name: site(); Type: FUNCTION; Schema: public; Owner: admin
83030 --
83031
83032 CREATE FUNCTION site() RETURNS SETOF whsinfo
83033     LANGUAGE plpgsql
83034     AS $$
83035 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83036 -- See www.xtuple.com/CPAL for the full text of the software license.
83037 DECLARE
83038   _row whsinfo%ROWTYPE;
83039   _r RECORD;
83040
83041 BEGIN
83042
83043   IF ( (fetchMetricBool('MultiWhs')) AND
83044        (SELECT (COUNT(usrpref_id)=1)
83045         FROM usrpref
83046         WHERE ((usrpref_name='selectedSites')
83047         AND (usrpref_value='t')
83048         AND (usrpref_username=getEffectiveXtUser()))) ) THEN
83049
83050     FOR _r IN SELECT *
83051             FROM whsinfo,usrsite
83052             WHERE ((warehous_id=usrsite_warehous_id)
83053             AND (usrsite_username=getEffectiveXtUser()))
83054     LOOP
83055       _row.warehous_id:=_r.warehous_id;
83056       _row.warehous_code:=_r.warehous_code;
83057       _row.warehous_descrip:=_r.warehous_descrip;
83058       _row.warehous_fob:=_r.warehous_fob;
83059       _row.warehous_active:=_r.warehous_active;
83060       _row.warehous_counttag_prefix:=_r.warehous_counttag_prefix;
83061       _row.warehous_counttag_number:=_r.warehous_counttag_number;
83062       _row.warehous_bol_prefix:=_r.warehous_bol_prefix;
83063       _row.warehous_bol_number:=_r.warehous_bol_number;
83064       _row.warehous_shipping:=_r.warehous_shipping;
83065       _row.warehous_useslips:=_r.warehous_useslips;
83066       _row.warehous_usezones:=_r.warehous_usezones;
83067       _row.warehous_aislesize:=_r.warehous_aislesize;
83068       _row.warehous_racksize:=_r.warehous_racksize;
83069       _row.warehous_binsize:=_r.warehous_binsize;
83070       _row.warehous_binalpha:=_r.warehous_binalpha;
83071       _row.warehous_locationsize:=_r.warehous_locationsize;
83072       _row.warehous_locationalpha:=_r.warehous_locationalpha;
83073       _row.warehous_enforcearbl:=_r.warehous_enforcearbl;
83074       _row.warehous_default_accnt_id:=_r.warehous_default_accnt_id;
83075       _row.warehous_shipping_commission:=_r.warehous_shipping_commission;
83076       _row.warehous_cntct_id:=_r.warehous_cntct_id;
83077       _row.warehous_addr_id:=_r.warehous_addr_id;
83078       _row.warehous_taxzone_id:=_r.warehous_taxzone_id;
83079       _row.warehous_transit:=_r.warehous_transit;
83080       _row.warehous_shipform_id:=_r.warehous_shipform_id;
83081       _row.warehous_shipvia_id:=_r.warehous_shipvia_id;
83082       _row.warehous_shipcomments:=_r.warehous_shipcomments;
83083       _row.warehous_costcat_id:=_r.warehous_costcat_id;
83084       _row.warehous_sitetype_id:=_r.warehous_sitetype_id;
83085              
83086       RETURN NEXT _row;
83087     END LOOP;
83088   ELSE
83089     FOR _r IN SELECT *
83090             FROM whsinfo
83091     LOOP
83092       _row.warehous_id:=_r.warehous_id;
83093       _row.warehous_code:=_r.warehous_code;
83094       _row.warehous_descrip:=_r.warehous_descrip;
83095       _row.warehous_fob:=_r.warehous_fob;
83096       _row.warehous_active:=_r.warehous_active;
83097       _row.warehous_counttag_prefix:=_r.warehous_counttag_prefix;
83098       _row.warehous_counttag_number:=_r.warehous_counttag_number;
83099       _row.warehous_bol_prefix:=_r.warehous_bol_prefix;
83100       _row.warehous_bol_number:=_r.warehous_bol_number;
83101       _row.warehous_shipping:=_r.warehous_shipping;
83102       _row.warehous_useslips:=_r.warehous_useslips;
83103       _row.warehous_usezones:=_r.warehous_usezones;
83104       _row.warehous_aislesize:=_r.warehous_aislesize;
83105       _row.warehous_racksize:=_r.warehous_racksize;
83106       _row.warehous_binsize:=_r.warehous_binsize;
83107       _row.warehous_binalpha:=_r.warehous_binalpha;
83108       _row.warehous_locationsize:=_r.warehous_locationsize;
83109       _row.warehous_locationalpha:=_r.warehous_locationalpha;
83110       _row.warehous_enforcearbl:=_r.warehous_enforcearbl;
83111       _row.warehous_default_accnt_id:=_r.warehous_default_accnt_id;
83112       _row.warehous_shipping_commission:=_r.warehous_shipping_commission;
83113       _row.warehous_cntct_id:=_r.warehous_cntct_id;
83114       _row.warehous_addr_id:=_r.warehous_addr_id;
83115       _row.warehous_taxzone_id:=_r.warehous_taxzone_id;
83116       _row.warehous_transit:=_r.warehous_transit;
83117       _row.warehous_shipform_id:=_r.warehous_shipform_id;
83118       _row.warehous_shipvia_id:=_r.warehous_shipvia_id;
83119       _row.warehous_shipcomments:=_r.warehous_shipcomments;
83120       _row.warehous_costcat_id:=_r.warehous_costcat_id;
83121       _row.warehous_sitetype_id:=_r.warehous_sitetype_id;
83122              
83123       RETURN NEXT _row;
83124     END LOOP;
83125   END IF;
83126   
83127   RETURN;
83128 END;
83129 $$;
83130
83131
83132 ALTER FUNCTION public.site() OWNER TO admin;
83133
83134 --
83135 -- TOC entry 2226 (class 1255 OID 146567077)
83136 -- Dependencies: 4536 8
83137 -- Name: snoozemessage(integer); Type: FUNCTION; Schema: public; Owner: admin
83138 --
83139
83140 CREATE FUNCTION snoozemessage(integer) RETURNS boolean
83141     LANGUAGE plpgsql
83142     AS $_$
83143 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83144 -- See www.xtuple.com/CPAL for the full text of the software license.
83145 DECLARE
83146   pMsgid ALIAS FOR $1;
83147   snooze INTERVAL := '10 minutes';
83148
83149 BEGIN
83150
83151   UPDATE msg
83152   SET msg_scheduled=(msg_scheduled + snooze)
83153   WHERE (msg_id=pMsgid);
83154
83155   RETURN TRUE;
83156
83157 END;
83158 $_$;
83159
83160
83161 ALTER FUNCTION public.snoozemessage(integer) OWNER TO admin;
83162
83163 --
83164 -- TOC entry 2227 (class 1255 OID 146567078)
83165 -- Dependencies: 4536 8
83166 -- Name: spellamount(numeric); Type: FUNCTION; Schema: public; Owner: admin
83167 --
83168
83169 CREATE FUNCTION spellamount(numeric) RETURNS text
83170     LANGUAGE plpgsql
83171     AS $_$
83172 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83173 -- See www.xtuple.com/CPAL for the full text of the software license.
83174 BEGIN
83175   RETURN spellAmount($1, baseCurrId());
83176 END;
83177 $_$;
83178
83179
83180 ALTER FUNCTION public.spellamount(numeric) OWNER TO admin;
83181
83182 --
83183 -- TOC entry 2230 (class 1255 OID 146567079)
83184 -- Dependencies: 4536 8
83185 -- Name: spellamount(numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
83186 --
83187
83188 CREATE FUNCTION spellamount(numeric, integer) RETURNS text
83189     LANGUAGE plpgsql
83190     AS $_$
83191 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83192 -- See www.xtuple.com/CPAL for the full text of the software license.
83193 DECLARE
83194   pN ALIAS FOR $1;
83195   pCurrId ALIAS FOR $2;
83196   _t text;
83197   _dollars text;
83198   _cents text;
83199   _l integer;
83200   _p integer;
83201   _words text;
83202   _word text;
83203   _hundreds char;
83204   _tens char;
83205   _ones char;
83206   _fractionalPartName text;
83207   _curr curr_symbol%ROWTYPE;
83208 BEGIN
83209
83210   _t := ltrim(to_char(pN, '999999999990D99'),' ');
83211   IF strpos(_t, '.') > 0 THEN
83212     _dollars := split_part(_t, '.', 1);
83213     _cents := split_part(_t, '.', 2);
83214   ELSIF strpos(_t, ',') > 0 THEN
83215     _dollars := split_part(_t, ',', 1);
83216     _cents := split_part(_t, ',', 2);
83217   END IF;
83218
83219   _p := 0;
83220   _l := length(_dollars);
83221
83222   _words := '';
83223   WHILE (_p < _l) LOOP
83224     IF((_l - _p - 2) < 1) THEN
83225       _hundreds := '0';
83226     ELSE
83227       _hundreds := substr(_dollars, _l - _p - 2, 1);
83228     END IF;
83229     IF((_l - _p - 1) < 1) THEN
83230       _tens := '0';
83231     ELSE
83232       _tens := substr(_dollars, _l - _p - 1, 1);
83233     END IF;
83234     IF((_l - _p) < 1) THEN
83235       _ones := '0';
83236     ELSE
83237       _ones := substr(_dollars, _l - _p, 1);
83238     END IF;
83239
83240     IF(_hundreds != '0' OR _tens != '0' OR _ones != '0') THEN
83241       IF (_p = 3) THEN
83242         _words := 'thousand ' || _words;
83243       ELSIF (_p = 6) THEN
83244         _words := 'million ' || _words;
83245       ELSIF (_p = 9) THEN
83246         _words := 'billion ' || _words;
83247       END IF;
83248
83249       _word := '';
83250       IF(_tens = '1') THEN
83251         IF(_ones = '0') THEN
83252           _word := 'ten';
83253         ELSIF(_ones = '1') THEN
83254           _word := 'eleven';
83255         ELSIF(_ones = '2') THEN
83256           _word := 'twelve';
83257         ELSIF(_ones = '3') THEN
83258           _word := 'thirteen';
83259         ELSIF(_ones = '4') THEN
83260           _word := 'fourteen';
83261         ELSIF(_ones = '5') THEN
83262           _word := 'fifteen';
83263         ELSIF(_ones = '6') THEN
83264           _word := 'sixteen';
83265         ELSIF(_ones = '7') THEN
83266           _word := 'seventeen';
83267         ELSIF(_ones = '8') THEN
83268           _word := 'eighteen';
83269         ELSIF(_ones = '9') THEN
83270           _word := 'nineteen';
83271         ELSE
83272           _word := 'ERROR';
83273         END IF;
83274       ELSE
83275         IF(_ones = '1') THEN
83276           _word := 'one';
83277         ELSIF(_ones = '2') THEN
83278           _word := 'two';
83279         ELSIF(_ones = '3') THEN
83280           _word := 'three';
83281         ELSIF(_ones = '4') THEN
83282           _word := 'four';
83283         ELSIF(_ones = '5') THEN
83284           _word := 'five';
83285         ELSIF(_ones = '6') THEN
83286           _word := 'six';
83287         ELSIF(_ones = '7') THEN
83288           _word := 'seven';
83289         ELSIF(_ones = '8') THEN
83290           _word := 'eight';
83291         ELSIF(_ones = '9') THEN
83292           _word := 'nine';
83293         ELSIF(_ones != '0') THEN
83294           _word := 'ERROR';
83295         END IF;
83296
83297         if(_tens != '0') THEN
83298           _word := '-' || _word;
83299         END IF;
83300
83301         IF(_tens = '2') THEN
83302           _word := 'twenty' || _word;
83303         ELSIF(_tens = '3') THEN
83304           _word := 'thirty' || _word;
83305         ELSIF(_tens = '4') THEN
83306           _word := 'forty' || _word;
83307         ELSIF(_tens = '5') THEN
83308           _word := 'fifty' || _word;
83309         ELSIF(_tens = '6') THEN
83310           _word := 'sixty' || _word;
83311         ELSIF(_tens = '7') THEN
83312           _word := 'seventy' || _word;
83313         ELSIF(_tens = '8') THEN
83314           _word := 'eighty' || _word;
83315         ELSIF(_tens = '9') THEN
83316           _word := 'ninety' || _word;
83317         ELSIF(_tens != '0' AND _tens != '1') THEN
83318           _word := 'ERROR' || _word;
83319         END IF;
83320       END IF;
83321       if(_word != '') THEN
83322         _words := _word || ' ' || _words;
83323       END IF;
83324
83325       _word := '';
83326       IF(_hundreds = '1') THEN
83327         _word := 'one hundred';
83328       ELSIF(_hundreds = '2') THEN
83329         _word := 'two hundred';
83330       ELSIF(_hundreds = '3') THEN
83331         _word := 'three hundred';
83332       ELSIF(_hundreds = '4') THEN
83333         _word := 'four hundred';
83334       ELSIF(_hundreds = '5') THEN
83335         _word := 'five hundred';
83336       ELSIF(_hundreds = '6') THEN
83337         _word := 'six hundred';
83338       ELSIF(_hundreds = '7') THEN
83339         _word := 'seven hundred';
83340       ELSIF(_hundreds = '8') THEN
83341         _word := 'eight hundred';
83342       ELSIF(_hundreds = '9') THEN
83343         _word := 'nine hundred';
83344       ELSIF(_hundreds != '0') THEN
83345         _words := 'ERROR';
83346       END IF;
83347       if(_word != '') THEN
83348         _words := _word || ' ' || _words;
83349       END IF;
83350     END IF;
83351
83352     _p := _p + 3;
83353   END LOOP;
83354
83355   _words := rtrim(_words, ' ');
83356   IF(_words = '') THEN
83357     _words := 'zero';
83358   END IF;
83359
83360   SELECT * INTO _curr
83361     FROM curr_symbol
83362     WHERE curr_id = pCurrId;
83363
83364   IF(_words = 'one') AND TRIM(_curr.curr_name) ~ '.*s' THEN
83365     _word := rtrim(_curr.curr_name, ' s');
83366   ELSE
83367     _word := trim(_curr.curr_name);
83368   END IF;
83369
83370   IF _curr.curr_abbr = 'USD' OR _curr.curr_abbr = 'CAD' THEN
83371       IF (_cents = '1') THEN
83372         _fractionalPartName = ' cent';
83373       ELSE
83374         _fractionalPartName = ' cents';
83375       END IF;
83376   ELSE
83377     _fractionalPartName = ' / 100 ';
83378   END IF;
83379
83380   RETURN _words || ' ' || _word || ' and ' || _cents || _fractionalPartName;
83381 END;
83382 $_$;
83383
83384
83385 ALTER FUNCTION public.spellamount(numeric, integer) OWNER TO admin;
83386
83387 --
83388 -- TOC entry 2231 (class 1255 OID 146567080)
83389 -- Dependencies: 4536 8
83390 -- Name: splitreceipt(integer, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
83391 --
83392
83393 CREATE FUNCTION splitreceipt(integer, numeric, numeric) RETURNS integer
83394     LANGUAGE plpgsql
83395     AS $_$
83396 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83397 -- See www.xtuple.com/CPAL for the full text of the software license.
83398 DECLARE
83399   precvid       ALIAS FOR $1;
83400   pqty          ALIAS FOR $2;
83401   pfreight      ALIAS FOR $3;
83402   _check        RECORD;
83403   _seq          INTEGER;
83404
83405 BEGIN
83406   -- validate
83407   IF (COALESCE(pQty,0) <= 0) THEN
83408     RETURN -7;
83409   END IF;
83410   
83411   SELECT * INTO _check
83412   FROM recv
83413   WHERE (recv_id=precvid);
83414
83415   IF (FOUND) THEN
83416     IF (_check.recv_order_type != 'PO') THEN
83417       RETURN -1;
83418     ELSIF ( NOT _check.recv_posted) THEN
83419       RETURN -2;
83420     ELSIF ( (_check.recv_invoiced)
83421          OR (_check.recv_vohead_id IS NOT NULL)
83422          OR (_check.recv_voitem_id IS NOT NULL) ) THEN
83423       RETURN -3;
83424     ELSIF (pqty >= _check.recv_qty) THEN
83425       RETURN -4;
83426     ELSIF (COALESCE(pfreight,0) > _check.recv_freight) THEN
83427       RETURN -5;
83428     END IF;
83429   ELSE
83430     RETURN -6;
83431   END IF;
83432
83433   -- Create new receipt record
83434   _seq := nextval('recv_recv_id_seq');
83435   
83436   INSERT INTO recv
83437   SELECT _seq, recv_order_type,recv_order_number,
83438          recv_orderitem_id, recv_agent_username, recv_itemsite_id, recv_vend_id,
83439          recv_vend_item_number, recv_vend_item_descrip, recv_vend_uom,
83440          recv_purchcost, recv_purchcost_curr_id, recv_duedate, pqty, 
83441          recv_recvcost, recv_recvcost_curr_id, COALESCE(pfreight,0), recv_freight_curr_id, recv_date, 
83442          ROUND(recv_value/recv_qty * pqty, 2), TRUE, FALSE, NULL, NULL,
83443          recv_trans_usr_name, recv_notes, recv_gldistdate, precvid
83444   FROM recv
83445   WHERE (recv_id=precvid);
83446
83447   --  Update qty and value of old record
83448   UPDATE recv SET
83449     recv_qty = recv_qty-pqty,
83450     recv_value = recv_value - ROUND(recv_value/recv_qty * pqty, 2),
83451     recv_freight = recv_freight - COALESCE(pfreight,0)
83452   WHERE (recv_id=precvid);
83453
83454   RETURN _seq;
83455 END;
83456 $_$;
83457
83458
83459 ALTER FUNCTION public.splitreceipt(integer, numeric, numeric) OWNER TO admin;
83460
83461 --
83462 -- TOC entry 2232 (class 1255 OID 146567081)
83463 -- Dependencies: 4536 8
83464 -- Name: splitrecurrence(integer, text, timestamp with time zone); Type: FUNCTION; Schema: public; Owner: admin
83465 --
83466
83467 CREATE FUNCTION splitrecurrence(integer, text, timestamp with time zone) RETURNS integer
83468     LANGUAGE plpgsql
83469     AS $_$
83470 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83471 -- See www.xtuple.com/CPAL for the full text of the software license.
83472 DECLARE
83473   pParentid     ALIAS FOR $1;
83474   pType         TEXT := UPPER($2);
83475   pDatetime     TIMESTAMP WITH TIME ZONE := COALESCE($3, CURRENT_TIMESTAMP);
83476
83477   _count         INTEGER;
83478   _newrecurid    INTEGER;
83479   _newparentid   INTEGER;
83480   _newparentstmt TEXT;
83481   _rt            RECORD;
83482   _updchildstmt  TEXT;
83483
83484 BEGIN
83485   IF (pParentid IS NULL) THEN
83486     RETURN -11;
83487   END IF;
83488
83489   SELECT * INTO _rt FROM recurtype WHERE (UPPER(recurtype_type)=pType);
83490   GET DIAGNOSTICS _count = ROW_COUNT;
83491   IF (_count <= 0) THEN
83492     RETURN -10;
83493   END IF;
83494
83495   _newparentstmt := 'SELECT [table]_id FROM [fulltable]'
83496                  || ' WHERE (([table]_recurring_[table]_id=$1)'
83497                  || '    AND NOT ([done])'
83498                  || '    AND ([schedcol]>=''$2''))'
83499                  || ' ORDER BY [schedcol]'
83500                  || ' LIMIT 1;';
83501   _newparentstmt := REPLACE(_newparentstmt, '[fulltable]', _rt.recurtype_table);
83502   _newparentstmt := REPLACE(_newparentstmt, '[table]',
83503                             REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
83504   _newparentstmt := REPLACE(_newparentstmt, '[done]',  _rt.recurtype_donecheck);
83505   _newparentstmt := REPLACE(_newparentstmt, '[schedcol]', _rt.recurtype_schedcol);
83506   _updchildstmt := 'UPDATE [fulltable] SET [table]_recurring_[table]_id=$1'
83507                 || ' WHERE (([table]_recurring_[table]_id=$2)'
83508                 || '   AND NOT ([done])'
83509                 || '   AND ([schedcol] > ''$3''));';
83510   _updchildstmt := REPLACE(_updchildstmt, '[fulltable]', _rt.recurtype_table);
83511   _updchildstmt := REPLACE(_updchildstmt, '[table]',
83512                            REGEXP_REPLACE(_rt.recurtype_table, E'.*\\.', ''));
83513   _updchildstmt := REPLACE(_updchildstmt, '[done]',  _rt.recurtype_donecheck);
83514   _updchildstmt := REPLACE(_updchildstmt, '[schedcol]', _rt.recurtype_schedcol);
83515
83516   -- 8.4+: EXECUTE _newparentstmt INTO _newparentid USING pParentid, pDatetime;
83517   EXECUTE REPLACE(REPLACE(_newparentstmt, '$1', pParentid::TEXT),
83518                                           '$2', pDatetime::TEXT)
83519           INTO _newparentid;
83520
83521   -- if nothing to split
83522   IF (_newparentid = pParentid OR _newparentid IS NULL) THEN
83523     SELECT recur_id INTO _newrecurid
83524       FROM recur
83525      WHERE ((recur_parent_id=pParentid)
83526         AND (recur_parent_type=pType));
83527
83528   ELSE
83529     INSERT INTO recur (recur_parent_id, recur_parent_type, recur_period,
83530                        recur_freq,      recur_start,       recur_end,
83531                        recur_max,       recur_data
83532              ) SELECT _newparentid,     pType,             recur_period,
83533                       recur_freq,       pDatetime,         recur_end,
83534                       recur_max,        recur_data
83535                  FROM recur
83536                 WHERE ((recur_parent_id=pParentid)
83537                    AND (recur_parent_type=pType))
83538       RETURNING recur_id INTO _newrecurid;
83539
83540     UPDATE recur SET recur_end=pDatetime
83541     WHERE ((recur_parent_id=pParentid)
83542        AND (recur_parent_type=pType));
83543
83544     -- 8.4+: EXECUTE _updchildstmt USING _newparentid, pParentid, pDatetime;
83545     EXECUTE REPLACE(REPLACE(REPLACE(_updchildstmt, '$1', _newparentid::TEXT),
83546                                                    '$2', pParentid::TEXT),
83547                                                    '$3', pDatetime::TEXT);
83548   END IF;
83549
83550   RETURN _newrecurid;
83551 END;
83552 $_$;
83553
83554
83555 ALTER FUNCTION public.splitrecurrence(integer, text, timestamp with time zone) OWNER TO admin;
83556
83557 --
83558 -- TOC entry 2233 (class 1255 OID 146567082)
83559 -- Dependencies: 8
83560 -- Name: startoftime(); Type: FUNCTION; Schema: public; Owner: admin
83561 --
83562
83563 CREATE FUNCTION startoftime() RETURNS date
83564     LANGUAGE sql IMMUTABLE
83565     AS $$
83566 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83567 -- See www.xtuple.com/CPAL for the full text of the software license.
83568 SELECT DATE('1970-01-01') AS return;
83569 $$;
83570
83571
83572 ALTER FUNCTION public.startoftime() OWNER TO admin;
83573
83574 --
83575 -- TOC entry 2234 (class 1255 OID 146567083)
83576 -- Dependencies: 4536 8
83577 -- Name: stdcost(integer); Type: FUNCTION; Schema: public; Owner: admin
83578 --
83579
83580 CREATE FUNCTION stdcost(integer) RETURNS numeric
83581     LANGUAGE plpgsql STABLE
83582     AS $_$
83583 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83584 -- See www.xtuple.com/CPAL for the full text of the software license.
83585 BEGIN
83586   RETURN stdCost($1, NULL);
83587 END;
83588 $_$;
83589
83590
83591 ALTER FUNCTION public.stdcost(integer) OWNER TO admin;
83592
83593 --
83594 -- TOC entry 2235 (class 1255 OID 146567084)
83595 -- Dependencies: 4536 8
83596 -- Name: stdcost(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
83597 --
83598
83599 CREATE FUNCTION stdcost(integer, integer) RETURNS numeric
83600     LANGUAGE plpgsql STABLE
83601     AS $_$
83602 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83603 -- See www.xtuple.com/CPAL for the full text of the software license.
83604 DECLARE
83605   pItemid ALIAS FOR $1;
83606   pBomitemid ALIAS FOR $2;
83607   _cost NUMERIC;
83608
83609 BEGIN
83610
83611   SELECT SUM(COALESCE(bomitemcost_stdcost, itemcost_stdcost)) INTO _cost
83612   FROM itemcost
83613     LEFT OUTER JOIN bomitemcost ON (bomitemcost_bomitem_id=pBomitemid AND bomitemcost_costelem_id=itemcost_costelem_id)
83614   WHERE (itemcost_item_id=pItemid);
83615
83616   IF (_cost IS NULL) THEN
83617     RETURN 0;
83618   ELSE
83619     RETURN _cost;
83620   END IF;
83621
83622 END;
83623 $_$;
83624
83625
83626 ALTER FUNCTION public.stdcost(integer, integer) OWNER TO admin;
83627
83628 --
83629 -- TOC entry 2236 (class 1255 OID 146567085)
83630 -- Dependencies: 4536 8
83631 -- Name: sufficientinventorytoshipitem(text, integer); Type: FUNCTION; Schema: public; Owner: admin
83632 --
83633
83634 CREATE FUNCTION sufficientinventorytoshipitem(text, integer) RETURNS integer
83635     LANGUAGE plpgsql
83636     AS $_$
83637 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83638 -- See www.xtuple.com/CPAL for the full text of the software license.
83639 DECLARE
83640   pordertype    ALIAS FOR $1;
83641   porderitemid  ALIAS FOR $2;
83642
83643 BEGIN
83644   RETURN sufficientInventoryToShipItem(pordertype, porderitemid, NULL);
83645 END;
83646 $_$;
83647
83648
83649 ALTER FUNCTION public.sufficientinventorytoshipitem(text, integer) OWNER TO admin;
83650
83651 --
83652 -- TOC entry 2239 (class 1255 OID 146567086)
83653 -- Dependencies: 4536 8
83654 -- Name: sufficientinventorytoshipitem(text, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
83655 --
83656
83657 CREATE FUNCTION sufficientinventorytoshipitem(text, integer, numeric) RETURNS integer
83658     LANGUAGE plpgsql
83659     AS $_$
83660 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83661 -- See www.xtuple.com/CPAL for the full text of the software license.
83662 DECLARE
83663   pordertype           ALIAS FOR $1;
83664   porderitemid         ALIAS FOR $2;
83665   pqty                 ALIAS FOR $3;
83666   _returnVal           INTEGER;
83667   _isqtyavail          BOOLEAN;
83668
83669 BEGIN
83670   IF (porderitemid IS NULL) THEN
83671     RETURN -1;
83672   END IF;
83673
83674   IF (pordertype = 'SO') THEN
83675     IF ( SELECT fetchMetricBool('EnableSOReservations') ) THEN
83676       IF (SELECT (itemsite_costmethod = 'J')
83677           FROM coitem JOIN itemsite ON (coitem_itemsite_id=itemsite_id)
83678           WHERE (coitem_id=porderitemid)) THEN
83679         RETURN 0;
83680       END IF;
83681
83682       SELECT (((COALESCE(pqty, roundQty(item_fractional,
83683                       noNeg(coitem_qtyord - coitem_qtyshipped +
83684                             coitem_qtyreturned - qtyAtShipping(pordertype, coitem_id)
83685                            ))) - coitem_qtyreserved) * coitem_qty_invuomratio
83686                       ) <= itemsite_qtyonhand)
83687               AND 
83688              (((COALESCE(pqty, roundQty(item_fractional,
83689                       noNeg(coitem_qtyord - coitem_qtyshipped +
83690                             coitem_qtyreturned - qtyAtShipping(pordertype, coitem_id)
83691                            ))) - coitem_qtyreserved) * coitem_qty_invuomratio
83692                       ) <= qtyunreserved(itemsite_id))
83693         INTO _isqtyavail
83694         FROM coitem, itemsite, item
83695        WHERE ((coitem_itemsite_id=itemsite_id) 
83696          AND (coitem_status <> 'X')
83697          AND  (NOT ((item_type IN ('R','J')) OR (itemsite_controlmethod = 'N'))) 
83698          AND (itemsite_item_id=item_id) 
83699          AND (coitem_id=porderitemid));
83700     ELSE
83701       SELECT (COALESCE(pqty, roundQty(item_fractional,
83702                                       noNeg(coitem_qtyord - coitem_qtyshipped +
83703                                       coitem_qtyreturned - qtyAtShipping(pordertype, coitem_id) - coitem_qtyreserved
83704                                       ) * coitem_qty_invuomratio
83705                       )
83706               ) <= itemsite_qtyonhand)
83707         INTO _isqtyavail
83708         FROM coitem, itemsite, item
83709        WHERE ((coitem_itemsite_id=itemsite_id) 
83710          AND (coitem_status <> 'X')
83711          AND  (NOT ((item_type IN ('R','J')) OR (itemsite_controlmethod = 'N'))) 
83712          AND (itemsite_item_id=item_id) 
83713          AND (coitem_id=porderitemid));
83714     END IF;
83715   ELSEIF (pordertype = 'TO') THEN
83716     SELECT (COALESCE(pqty, roundQty(item_fractional,
83717                                     noNeg(toitem_qty_ordered - toitem_qty_shipped - 
83718                                     qtyAtShipping(pordertype, toitem_id)
83719                                     )
83720                     )
83721            ) <= itemsite_qtyonhand) INTO _isqtyavail  
83722       FROM toitem, tohead, itemsite, item
83723      WHERE ((toitem_tohead_id=tohead_id)
83724        AND  (tohead_src_warehous_id=itemsite_warehous_id) 
83725        AND  (toitem_item_id=itemsite_item_id) 
83726        AND  (itemsite_warehous_id=tohead_src_warehous_id) 
83727        AND  (itemsite_item_id=item_id) 
83728        AND  (toitem_status <> 'X')
83729          AND  (NOT ((item_type IN ('R','J')) OR (itemsite_controlmethod = 'N'))) 
83730        AND  (toitem_id=porderitemid));
83731   ELSE
83732     RETURN -11;
83733   END IF;
83734
83735   IF (NOT _isqtyavail) THEN
83736     RETURN -2;
83737   END IF;
83738
83739   IF (pordertype = 'SO') THEN
83740     SELECT (COALESCE((SELECT SUM(itemloc_qty) 
83741                         FROM itemloc 
83742                        WHERE (itemloc_itemsite_id=itemsite_id)), 0.0) >= roundQty(item_fractional, 
83743                               COALESCE(pQty, noNeg( coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned - 
83744                               qtyAtShipping(pordertype, coitem_id) )) * coitem_qty_invuomratio
83745                              )) INTO _isqtyavail 
83746       FROM coitem, itemsite, item
83747      WHERE ((coitem_itemsite_id=itemsite_id) 
83748        AND (itemsite_item_id=item_id) 
83749        AND (NOT ((item_type ='R') OR (itemsite_controlmethod = 'N'))) 
83750        AND ((itemsite_controlmethod IN ('L', 'S')) OR (itemsite_loccntrl)) 
83751        AND (coitem_id=porderitemid)); 
83752
83753   ELSEIF (pordertype = 'TO') THEN
83754     SELECT (COALESCE((SELECT SUM(itemloc_qty) 
83755                         FROM itemloc 
83756                        WHERE (itemloc_itemsite_id=itemsite_id)), 0.0) >= roundQty(item_fractional, 
83757                               noNeg( toitem_qty_ordered - toitem_qty_shipped - 
83758                               qtyAtShipping(pordertype, toitem_id) )
83759                              )) INTO _isqtyavail 
83760       FROM toitem, tohead, itemsite, item
83761      WHERE ((toitem_tohead_id=tohead_id)
83762        AND  (tohead_src_warehous_id=itemsite_warehous_id) 
83763        AND  (toitem_item_id=itemsite_item_id) 
83764        AND  (itemsite_item_id=item_id) 
83765        AND  (toitem_status <> 'X')
83766        AND  (NOT ((item_type ='R') OR (itemsite_costmethod = 'J') OR (itemsite_controlmethod = 'N'))) 
83767        AND  ((itemsite_controlmethod IN ('L', 'S')) OR (itemsite_loccntrl)) 
83768        AND  (toitem_id=porderitemid)); 
83769   END IF;
83770   
83771   IF (NOT _isqtyavail) THEN
83772     RETURN -3;
83773   END IF;
83774
83775   IF (pordertype = 'SO') THEN
83776     IF ( SELECT fetchMetricBool('RequireSOReservations') ) THEN
83777       SELECT (COALESCE(pqty, coitem_qtyreserved) <= coitem_qtyreserved)
83778         INTO _isqtyavail
83779         FROM coitem, itemsite, item
83780        WHERE ((coitem_itemsite_id=itemsite_id) 
83781          AND (coitem_status <> 'X')
83782          AND  (NOT ((item_type IN ('R','J')) OR (itemsite_controlmethod = 'N'))) 
83783          AND (itemsite_item_id=item_id) 
83784          AND (coitem_id=porderitemid));
83785     END IF;
83786   END IF;
83787
83788   IF (NOT _isqtyavail) THEN
83789     RETURN -4;
83790   END IF;
83791
83792   RETURN 0;
83793 END;
83794 $_$;
83795
83796
83797 ALTER FUNCTION public.sufficientinventorytoshipitem(text, integer, numeric) OWNER TO admin;
83798
83799 --
83800 -- TOC entry 2240 (class 1255 OID 146567087)
83801 -- Dependencies: 4536 8
83802 -- Name: sufficientinventorytoshiporder(text, integer); Type: FUNCTION; Schema: public; Owner: admin
83803 --
83804
83805 CREATE FUNCTION sufficientinventorytoshiporder(text, integer) RETURNS integer
83806     LANGUAGE plpgsql
83807     AS $_$
83808 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83809 -- See www.xtuple.com/CPAL for the full text of the software license.
83810 DECLARE
83811   pordertype    ALIAS FOR $1;
83812   porderid      ALIAS FOR $2;
83813   _s            RECORD;
83814   _returnVal    INTEGER := 0;
83815
83816 BEGIN
83817   IF (pordertype = 'SO') THEN
83818     FOR _s IN SELECT coitem_id
83819                 FROM coitem
83820                  JOIN itemsite ON (coitem_itemsite_id=itemsite_id)
83821                WHERE((coitem_cohead_id=porderid) 
83822                 AND (itemsite_costmethod != 'J')) LOOP
83823       _returnVal := sufficientInventoryToShipItem(pordertype, _s.coitem_id);
83824       EXIT WHEN (_returnVal < 0);
83825     END LOOP;
83826   ELSEIF (pordertype = 'TO') THEN
83827     FOR _s IN SELECT toitem_id
83828                 FROM toitem
83829                WHERE(toitem_tohead_id=porderid) LOOP
83830       _returnVal := sufficientInventoryToShipItem(pordertype, _s.toitem_id);
83831       EXIT WHEN (_returnVal < 0);
83832     END LOOP;
83833   END IF;
83834
83835   RETURN _returnVal;
83836 END;
83837 $_$;
83838
83839
83840 ALTER FUNCTION public.sufficientinventorytoshiporder(text, integer) OWNER TO admin;
83841
83842 --
83843 -- TOC entry 2241 (class 1255 OID 146567088)
83844 -- Dependencies: 4536 8
83845 -- Name: summarizedbom(integer); Type: FUNCTION; Schema: public; Owner: admin
83846 --
83847
83848 CREATE FUNCTION summarizedbom(integer) RETURNS integer
83849     LANGUAGE plpgsql
83850     AS $_$
83851 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83852 -- See www.xtuple.com/CPAL for the full text of the software license.
83853 DECLARE
83854   pItemid ALIAS FOR $1;
83855   _revid INTEGER;
83856
83857 BEGIN
83858
83859   SELECT getActiveRevId('BOM',pItemid) INTO _revid;
83860   
83861   RETURN summarizedBOM(pItemid, _revid);
83862
83863 END;
83864 $_$;
83865
83866
83867 ALTER FUNCTION public.summarizedbom(integer) OWNER TO admin;
83868
83869 --
83870 -- TOC entry 2243 (class 1255 OID 146567090)
83871 -- Dependencies: 4536 8
83872 -- Name: summarizedbom(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
83873 --
83874
83875 CREATE FUNCTION summarizedbom(integer, integer) RETURNS integer
83876     LANGUAGE plpgsql
83877     AS $_$
83878 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83879 -- See www.xtuple.com/CPAL for the full text of the software license.
83880 DECLARE
83881   pItemid ALIAS FOR $1;
83882   pRevisionid ALIAS FOR $2;
83883   _bomworkid INTEGER;
83884   _indexid INTEGER;
83885   _r RECORD;
83886
83887 BEGIN
83888
83889 --  Check on the temporary workspace
83890 --  PERFORM maintainBOMWorkspace();
83891
83892 --  Grab a new index for this bomwork set
83893   SELECT NEXTVAL('misc_index_seq') INTO _indexid;
83894
83895 --  Step through all of the components of the passed pItemid
83896   FOR _r IN SELECT bomitem.*,
83897                    item_id,
83898                    (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL)
83899                               * bomitem_qtyfxd) AS qtyfxd,
83900                    (itemuomtouomratio(bomitem_item_id, bomitem_uom_id, NULL)
83901                               * bomitem_qtyper) AS qtyper,
83902                    stdcost(item_id, bomitem_id) AS standardcost,
83903                    actcost(item_id, bomitem_id) AS actualcost
83904   FROM bomitem(pItemid, pRevisionid), item
83905   WHERE (bomitem_item_id=item_id) LOOP
83906
83907 --  Insert the component and bomitem parameters
83908     SELECT NEXTVAL('bomwork_bomwork_id_seq') INTO _bomworkid;
83909     INSERT INTO bomwork
83910     ( bomwork_id, bomwork_set_id, bomwork_parent_id, bomwork_level,
83911       bomwork_parent_seqnumber, bomwork_seqnumber,
83912       bomwork_item_id, bomwork_createwo, bomwork_qtyreq,
83913       bomwork_qtyfxd, bomwork_qtyper, bomwork_scrap, bomwork_issuemethod,
83914       bomwork_effective, bomwork_expires,
83915       bomwork_stdunitcost, bomwork_actunitcost )
83916     VALUES
83917     ( _bomworkid, _indexid, -1, 1,
83918       0, _r.bomitem_seqnumber,
83919       _r.item_id, _r.bomitem_createwo, (_r.qtyfxd + _r.qtyper),
83920       _r.qtyfxd, _r.qtyper, _r.bomitem_scrap, _r.bomitem_issuemethod,
83921       _r.bomitem_effective, _r.bomitem_expires,
83922       _r.standardcost, _r.actualcost,
83923       _r.bomitem_char_id, _r.bomitem_value, _r.bomitem_notes, _r.bomitem_ref,
83924       _r.bomitem_id, _r.bomitem_ecn );
83925
83926 --  Explode the components of the current component
83927     PERFORM explodeBOM(_r.item_id, _bomworkid, 1);
83928
83929   END LOOP;
83930
83931 --  Return a key to the result
83932   RETURN _indexid;
83933
83934 END;
83935 $_$;
83936
83937
83938 ALTER FUNCTION public.summarizedbom(integer, integer) OWNER TO admin;
83939
83940 --
83941 -- TOC entry 2242 (class 1255 OID 146567089)
83942 -- Dependencies: 4536 8
83943 -- Name: summarizedbom(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
83944 --
83945
83946 CREATE FUNCTION summarizedbom(integer, integer, integer) RETURNS integer
83947     LANGUAGE plpgsql
83948     AS $_$
83949 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83950 -- See www.xtuple.com/CPAL for the full text of the software license.
83951 DECLARE
83952   pItemid ALIAS FOR $1;
83953   pExpired ALIAS FOR $2;
83954   pFuture ALIAS FOR $3;
83955   _revid INTEGER;
83956
83957 BEGIN
83958
83959   SELECT getActiveRevId('BOM',pItemid) INTO _revid;
83960   
83961   RETURN summarizedBOM(pItemid, _revid, pExpired, pFuture);
83962
83963 END;
83964 $_$;
83965
83966
83967 ALTER FUNCTION public.summarizedbom(integer, integer, integer) OWNER TO admin;
83968
83969 --
83970 -- TOC entry 2244 (class 1255 OID 146567091)
83971 -- Dependencies: 2657 4536 8
83972 -- Name: summarizedbom(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: admin
83973 --
83974
83975 CREATE FUNCTION summarizedbom(integer, integer, integer, integer) RETURNS SETOF bomdata
83976     LANGUAGE plpgsql
83977     AS $_$
83978 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
83979 -- See www.xtuple.com/CPAL for the full text of the software license.
83980 DECLARE
83981   pItemid ALIAS FOR $1;
83982   pRevisionid ALIAS FOR $2;
83983   pExpiredDays  INTEGER := COALESCE($3, 0);
83984   pFutureDays   INTEGER := COALESCE($4, 0);
83985   _row bomdata%ROWTYPE;
83986   _bomworksetid INTEGER;
83987   _x RECORD;
83988   _check CHAR(1);
83989   _inactive BOOLEAN := FALSE;
83990   _batchsize NUMERIC;
83991
83992 BEGIN
83993
83994   IF (pRevisionid != -1) THEN
83995     --Is this a deactivated revision?
83996     SELECT rev_status INTO _check
83997     FROM rev
83998     WHERE ((rev_id=pRevisionid)
83999     AND (rev_status='I'));
84000     IF (FOUND) THEN
84001       _inactive := TRUE;
84002     END IF;
84003   END IF;
84004  
84005   -- Get the batch quantity
84006   SELECT COALESCE( (
84007     SELECT bomhead_batchsize
84008     FROM bomhead
84009     WHERE ((bomhead_item_id=pItemId)
84010     AND (bomhead_rev_id=pRevisionid))),1) INTO _batchsize;
84011  
84012   IF NOT (_inactive) THEN
84013
84014     --We can explode this out based on current data
84015     SELECT indentedBOM(pItemid, pRevisionid) INTO _bomworksetid;  
84016
84017     FOR _x IN
84018        SELECT item_number, uom_name,
84019                item_descrip1, item_descrip2,
84020                (item_descrip1 || ' ' || item_descrip2) AS itemdescription,
84021                SUM(bomwork_qtyreq) AS qtyreq,
84022                SUM(bomwork_qtyfxd * (1 + bomwork_scrap)) AS qtyfxd,
84023                SUM(bomwork_qtyper * (1 + bomwork_scrap)) AS qtyper,
84024        MAX(bomwork_actunitcost) AS actunitcost,
84025        MAX(bomwork_stdunitcost) AS stdunitcost,
84026        CASE WHEN item_type NOT IN ('R','T') THEN
84027          SUM(bomwork_actunitcost * bomwork_qtyreq)
84028        ELSE 0 END AS actextendedcost,
84029        CASE WHEN item_type NOT IN ('R','T') THEN
84030          SUM(bomwork_stdunitcost * bomwork_qtyreq)
84031        ELSE 0 END AS stdextendedcost,
84032        bomwork_effective,
84033        bomwork_expires,
84034        bomwork_effective > CURRENT_DATE AS future,
84035        bomwork_expires  <= CURRENT_DATE AS expired
84036        FROM ( SELECT item_number, item_type, uom_name,
84037                      item_descrip1, item_descrip2,
84038                      bomwork_qtyreq, bomwork_qtyfxd,
84039                      bomwork_qtyper, bomwork_scrap,
84040                      bomwork_actunitcost, bomwork_stdunitcost,
84041                      CASE WHEN (bomwork_effective > CURRENT_DATE) THEN (CURRENT_DATE + 1)
84042                           ELSE CURRENT_DATE END AS bomwork_effective,
84043                      CASE WHEN (bomwork_expires <= CURRENT_DATE) THEN (CURRENT_DATE - 1)
84044                           ELSE (CURRENT_DATE + 1) END AS bomwork_expires
84045                      FROM bomwork, item, uom 
84046                      WHERE ( (bomwork_item_id=item_id)
84047                        AND (item_inv_uom_id=uom_id)
84048                        AND (bomwork_set_id=_bomworksetid) )
84049                        AND (bomwork_expires > (CURRENT_DATE - pExpiredDays))
84050                        AND (bomwork_effective <= (CURRENT_DATE + pFutureDays)) ) AS data
84051        GROUP BY item_number, uom_name, item_type,
84052                 item_descrip1, item_descrip2,
84053                 bomwork_effective, bomwork_expires
84054        ORDER BY item_number
84055     LOOP
84056         _row.bomdata_item_number := _x.item_number;
84057         _row.bomdata_uom_name := _x.uom_name;
84058         _row.bomdata_item_descrip1 := _x.item_descrip1;
84059         _row.bomdata_item_descrip2 := _x.item_descrip2;
84060         _row.bomdata_itemdescription := _x.itemdescription;
84061         _row.bomdata_qtyreq := _x.qtyreq;
84062         _row.bomdata_qtyfxd := _x.qtyfxd;
84063         _row.bomdata_qtyper := _x.qtyper;
84064         _row.bomdata_actunitcost := _x.actunitcost;
84065         _row.bomdata_stdunitcost := _x.stdunitcost;
84066         _row.bomdata_actextendedcost := _x.actextendedcost;
84067         _row.bomdata_stdextendedcost := _x.stdextendedcost;
84068         _row.bomdata_effective := _x.bomwork_effective;
84069         _row.bomdata_expires := _x.bomwork_expires;
84070         _row.bomdata_future := _x.future;
84071         _row.bomdata_expired := _x.expired;
84072         RETURN NEXT _row;
84073     END LOOP;
84074     
84075     PERFORM deleteBOMWorkset(_bomworksetid);
84076
84077   ELSE
84078    
84079 -- Use historical snapshot for inactive revisions
84080     FOR _x IN
84081        SELECT item_number, uom_name,
84082                item_descrip1, item_descrip2,
84083                (item_descrip1 || ' ' || item_descrip2) AS itemdescription,
84084                SUM(bomhist_qtyreq * (1 + bomhist_scrap)) AS qtyreq,
84085                SUM(bomhist_qtyfxd * (1 + bomhist_scrap)) AS qtyfxd,
84086                SUM(bomhist_qtyper * (1 + bomhist_scrap)) AS qtyper,
84087        MAX(bomhist_actunitcost) AS actunitcost,
84088        MAX(bomhist_stdunitcost) AS stdunitcost,
84089        CASE WHEN item_type NOT IN ('R','T') THEN
84090          MAX(bomhist_actunitcost) * SUM((bomhist_qtyfxd/_batchsize + bomhist_qtyper) * (1 + bomhist_scrap))
84091        ELSE 0 END AS actextendedcost,
84092        CASE WHEN item_type NOT IN ('R','T') THEN
84093          MAX(bomhist_stdunitcost) * SUM((bomhist_qtyfxd/_batchsize + bomhist_qtyper) * (1 + bomhist_scrap)) 
84094        ELSE 0 END AS stdextendedcost
84095        FROM bomhist, item, uom 
84096        WHERE ( (bomhist_item_id=item_id)
84097        AND (item_inv_uom_id=uom_id)
84098        AND (bomhist_rev_id=pRevisionid) )
84099        AND (bomhist_expires > (CURRENT_DATE - pExpiredDays))
84100        AND (bomhist_effective <= (CURRENT_DATE + pFutureDays))
84101        GROUP BY item_number, uom_name, item_type,
84102                 item_descrip1, item_descrip2
84103        ORDER BY item_number
84104     LOOP
84105         _row.bomdata_item_number := _x.item_number;
84106         _row.bomdata_uom_name := _x.uom_name;
84107         _row.bomdata_item_descrip1 := _x.item_descrip1;
84108         _row.bomdata_item_descrip2 := _x.item_descrip2;
84109         _row.bomdata_itemdescription := _x.itemdescription;
84110         _row.bomdata_qtyreq := _x.qtyreq;
84111         _row.bomdata_qtyfxd := _x.qtyfxd;
84112         _row.bomdata_qtyper := _x.qtyper;
84113         _row.bomdata_actunitcost := _x.actunitcost;
84114         _row.bomdata_stdunitcost := _x.stdunitcost;
84115         _row.bomdata_actextendedcost := _x.actextendedcost;
84116         _row.bomdata_stdextendedcost := _x.stdextendedcost;
84117         RETURN NEXT _row;
84118     END LOOP;
84119
84120   END IF;
84121
84122   RETURN;
84123
84124 END;
84125 $_$;
84126
84127
84128 ALTER FUNCTION public.summarizedbom(integer, integer, integer, integer) OWNER TO admin;
84129
84130 --
84131 -- TOC entry 2245 (class 1255 OID 146567092)
84132 -- Dependencies: 4536 8
84133 -- Name: summarizetransactions(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84134 --
84135
84136 CREATE FUNCTION summarizetransactions(integer, date, date) RETURNS integer
84137     LANGUAGE plpgsql
84138     AS $_$
84139 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84140 -- See www.xtuple.com/CPAL for the full text of the software license.
84141 DECLARE
84142   pItemsiteid ALIAS FOR $1;
84143   pStartDate ALIAS FOR $2;
84144   pEndDate ALIAS FOR $3;
84145   _startDate DATE;
84146   _endDate DATE;
84147   _invhist RECORD;
84148   _itemuom TEXT;
84149   _transCounter INTEGER;
84150   _itemlocSeries INTEGER;
84151
84152 BEGIN
84153
84154 --  Cache the uom_name
84155   SELECT uom_name INTO _itemuom
84156   FROM itemsite, item, uom
84157   WHERE ((itemsite_item_id=item_id)
84158     AND (item_inv_uom_id=uom_id)
84159     AND (itemsite_id=pItemsiteid));
84160
84161 --  Can't summarize into the future...
84162   IF (pEndDate > CURRENT_DATE) THEN
84163     _endDate := CURRENT_DATE;
84164   ELSE
84165     _endDate := pEndDate;
84166   END IF;
84167
84168 --  Verify date bounds
84169   IF (pStartDate > pEndDate) THEN
84170     _startDate := pEndDate;
84171   ELSE
84172     _startDate := pStartDate;
84173   END IF;
84174
84175 --  Verify that history is not referenced elsewhere
84176   SELECT invhist_id INTO _transCounter
84177   FROM invhist JOIN womatlpost ON (womatlpost_invhist_id=invhist_id)
84178   WHERE ((invhist_itemsite_id=pItemsiteid)
84179     AND (invhist_transdate::DATE BETWEEN _startDate AND _endDate))
84180   LIMIT 1;
84181   IF (FOUND) THEN
84182     RETURN 0;
84183   END IF;
84184
84185   SELECT invhist_id INTO _transCounter
84186   FROM invhist JOIN shipitem ON (shipitem_invhist_id=invhist_id)
84187   WHERE ((invhist_itemsite_id=pItemsiteid)
84188     AND (invhist_transdate::DATE BETWEEN _startDate AND _endDate))
84189   LIMIT 1;
84190   IF (FOUND) THEN
84191     RETURN 0;
84192   END IF;
84193
84194   _transCounter := 0;
84195   _itemlocSeries := NEXTVAL('itemloc_series_seq');
84196
84197   FOR _invhist IN SELECT invhist_transtype, invhist_costmethod, SUM(invhist_invqty) AS qty
84198                   FROM invhist
84199                   WHERE ((invhist_itemsite_id=pItemsiteid)
84200                    AND (invhist_transdate::DATE BETWEEN _startDate AND _endDate))
84201                   GROUP BY invhist_transtype, invhist_costmethod LOOP
84202
84203     DELETE FROM invhist
84204     WHERE ((invhist_transdate::DATE BETWEEN _startDate AND _endDate)
84205      AND (invhist_transtype=_invhist.invhist_transtype)
84206      AND (invhist_itemsite_id=pItemsiteid));
84207
84208     INSERT INTO invhist
84209     ( invhist_itemsite_id, invhist_transdate, invhist_transtype,
84210       invhist_invqty, invhist_qoh_before, invhist_qoh_after,
84211       invhist_invuom, invhist_user, invhist_ordnumber,
84212       invhist_costmethod, invhist_value_before, invhist_value_after,
84213       invhist_series )
84214     VALUES
84215     ( pItemsiteid, _endDate, _invhist.invhist_transtype,
84216       _invhist.qty, 0, 0,
84217       _itemuom, getEffectiveXtUser(), 'Summary',
84218       _invhist.invhist_costmethod, 0, 0,
84219       _itemlocSeries );
84220
84221     _transCounter := (_transCounter + 1);
84222
84223   END LOOP;
84224
84225   RETURN _transCounter;
84226
84227 END;
84228 $_$;
84229
84230
84231 ALTER FUNCTION public.summarizetransactions(integer, date, date) OWNER TO admin;
84232
84233 --
84234 -- TOC entry 2228 (class 1255 OID 146567094)
84235 -- Dependencies: 4536 8
84236 -- Name: summdemand(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84237 --
84238
84239 CREATE FUNCTION summdemand(integer, integer) RETURNS numeric
84240     LANGUAGE plpgsql
84241     AS $_$
84242 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84243 -- See www.xtuple.com/CPAL for the full text of the software license.
84244 DECLARE
84245   pItemsiteid ALIAS FOR $1;
84246   pCalitemid ALIAS FOR $2;
84247   _value NUMERIC;
84248
84249 BEGIN
84250
84251   SELECT summDemand(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84252
84253   RETURN _value;
84254
84255 END;
84256 $_$;
84257
84258
84259 ALTER FUNCTION public.summdemand(integer, integer) OWNER TO admin;
84260
84261 --
84262 -- TOC entry 2215 (class 1255 OID 146567093)
84263 -- Dependencies: 4536 8
84264 -- Name: summdemand(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84265 --
84266
84267 CREATE FUNCTION summdemand(integer, date, date) RETURNS numeric
84268     LANGUAGE plpgsql
84269     AS $_$
84270 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84271 -- See www.xtuple.com/CPAL for the full text of the software license.
84272 DECLARE
84273   pItemsiteid ALIAS FOR $1;
84274   pStartDate ALIAS FOR $2;
84275   pEndDate ALIAS FOR $3;
84276   _value NUMERIC;
84277
84278 BEGIN
84279
84280   SELECT SUM(wo_qtyord - wo_qtyrcv) INTO _value
84281   FROM wo
84282   WHERE ( (wo_itemsite_id=pItemsiteid)
84283    AND (wo_status IN ('R', 'I'))
84284    AND (wo_startdate::DATE BETWEEN pStartDate AND pEndDate) );
84285
84286   IF (_value IS NULL) THEN
84287     _value := 0;
84288   END IF;
84289
84290   RETURN _value;
84291
84292 END;
84293 $_$;
84294
84295
84296 ALTER FUNCTION public.summdemand(integer, date, date) OWNER TO admin;
84297
84298 --
84299 -- TOC entry 2237 (class 1255 OID 146567096)
84300 -- Dependencies: 4536 8
84301 -- Name: summprod(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84302 --
84303
84304 CREATE FUNCTION summprod(integer, integer) RETURNS numeric
84305     LANGUAGE plpgsql
84306     AS $_$
84307 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84308 -- See www.xtuple.com/CPAL for the full text of the software license.
84309 DECLARE
84310   pItemsiteid ALIAS FOR $1;
84311   pCalitemid ALIAS FOR $2;
84312   _value NUMERIC;
84313
84314 BEGIN
84315
84316   SELECT summProd(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84317
84318   RETURN _value;
84319
84320 END;
84321 $_$;
84322
84323
84324 ALTER FUNCTION public.summprod(integer, integer) OWNER TO admin;
84325
84326 --
84327 -- TOC entry 2229 (class 1255 OID 146567095)
84328 -- Dependencies: 4536 8
84329 -- Name: summprod(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84330 --
84331
84332 CREATE FUNCTION summprod(integer, date, date) RETURNS numeric
84333     LANGUAGE plpgsql
84334     AS $_$
84335 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84336 -- See www.xtuple.com/CPAL for the full text of the software license.
84337 DECLARE
84338   pItemsiteid ALIAS FOR $1;
84339   pStartDate ALIAS FOR $2;
84340   pEndDate ALIAS FOR $3;
84341   _value NUMERIC;
84342
84343 BEGIN
84344
84345   SELECT SUM(invhist_invqty) INTO _value
84346   FROM invhist
84347   WHERE ( (invhist_itemsite_id=pItemsiteid)
84348    AND (invhist_transtype IN ('RM', 'RB'))
84349    AND (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate) );
84350
84351   IF (_value IS NULL) THEN
84352     _value := 0;
84353   END IF;
84354
84355   RETURN _value;
84356
84357 END;
84358 $_$;
84359
84360
84361 ALTER FUNCTION public.summprod(integer, date, date) OWNER TO admin;
84362
84363 --
84364 -- TOC entry 2246 (class 1255 OID 146567098)
84365 -- Dependencies: 4536 8
84366 -- Name: summtransa(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84367 --
84368
84369 CREATE FUNCTION summtransa(integer, integer) RETURNS numeric
84370     LANGUAGE plpgsql
84371     AS $_$
84372 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84373 -- See www.xtuple.com/CPAL for the full text of the software license.
84374 DECLARE
84375   pItemsiteid ALIAS FOR $1;
84376   pCalitemid ALIAS FOR $2;
84377   _value NUMERIC;
84378
84379 BEGIN
84380
84381   SELECT summTransA(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84382
84383   RETURN _value;
84384
84385 END;
84386 $_$;
84387
84388
84389 ALTER FUNCTION public.summtransa(integer, integer) OWNER TO admin;
84390
84391 --
84392 -- TOC entry 2238 (class 1255 OID 146567097)
84393 -- Dependencies: 4536 8
84394 -- Name: summtransa(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84395 --
84396
84397 CREATE FUNCTION summtransa(integer, date, date) RETURNS numeric
84398     LANGUAGE plpgsql
84399     AS $_$
84400 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84401 -- See www.xtuple.com/CPAL for the full text of the software license.
84402 DECLARE
84403   pItemsiteid ALIAS FOR $1;
84404   pStartDate ALIAS FOR $2;
84405   pEndDate ALIAS FOR $3;
84406   _value NUMERIC;
84407
84408 BEGIN
84409
84410   SELECT SUM(invhist_invqty) INTO _value
84411   FROM invhist
84412   WHERE ((invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
84413    AND (invhist_transtype IN ('AD', 'CC'))
84414    AND (invhist_itemsite_id=pItemsiteid));
84415
84416   IF (_value IS NULL) THEN
84417     _value := 0;
84418   END IF;
84419
84420   RETURN _value;
84421
84422 END;
84423 $_$;
84424
84425
84426 ALTER FUNCTION public.summtransa(integer, date, date) OWNER TO admin;
84427
84428 --
84429 -- TOC entry 2248 (class 1255 OID 146567100)
84430 -- Dependencies: 4536 8
84431 -- Name: summtransc(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84432 --
84433
84434 CREATE FUNCTION summtransc(integer, integer) RETURNS numeric
84435     LANGUAGE plpgsql
84436     AS $_$
84437 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84438 -- See www.xtuple.com/CPAL for the full text of the software license.
84439 DECLARE
84440   pItemsiteid ALIAS FOR $1;
84441   pCalitemid ALIAS FOR $2;
84442   _value NUMERIC;
84443
84444 BEGIN
84445
84446   SELECT summTransC(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84447
84448   RETURN _value;
84449
84450 END;
84451 $_$;
84452
84453
84454 ALTER FUNCTION public.summtransc(integer, integer) OWNER TO admin;
84455
84456 --
84457 -- TOC entry 2247 (class 1255 OID 146567099)
84458 -- Dependencies: 4536 8
84459 -- Name: summtransc(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84460 --
84461
84462 CREATE FUNCTION summtransc(integer, date, date) RETURNS numeric
84463     LANGUAGE plpgsql
84464     AS $_$
84465 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84466 -- See www.xtuple.com/CPAL for the full text of the software license.
84467 DECLARE
84468   pItemsiteid ALIAS FOR $1;
84469   pStartDate ALIAS FOR $2;
84470   pEndDAte ALIAS FOR $3;
84471   _value NUMERIC;
84472
84473 BEGIN
84474
84475   SELECT SUM(invhist_invqty) INTO _value
84476   FROM invhist
84477   WHERE ((invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
84478    AND (invhist_transtype IN ('SI'))
84479    AND (invhist_itemsite_id=pItemsiteid));
84480
84481   IF (_value IS NULL) THEN
84482     _value := 0;
84483   END IF;
84484
84485   RETURN _value;
84486
84487 END;
84488 $_$;
84489
84490
84491 ALTER FUNCTION public.summtransc(integer, date, date) OWNER TO admin;
84492
84493 --
84494 -- TOC entry 2250 (class 1255 OID 146567102)
84495 -- Dependencies: 4536 8
84496 -- Name: summtransi(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84497 --
84498
84499 CREATE FUNCTION summtransi(integer, integer) RETURNS numeric
84500     LANGUAGE plpgsql
84501     AS $_$
84502 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84503 -- See www.xtuple.com/CPAL for the full text of the software license.
84504 DECLARE
84505   pItemsiteid ALIAS FOR $1;
84506   pCalitemid ALIAS FOR $2;
84507   _value NUMERIC;
84508
84509 BEGIN
84510
84511   SELECT summTransI(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84512
84513   RETURN _value;
84514
84515 END;
84516 $_$;
84517
84518
84519 ALTER FUNCTION public.summtransi(integer, integer) OWNER TO admin;
84520
84521 --
84522 -- TOC entry 2249 (class 1255 OID 146567101)
84523 -- Dependencies: 4536 8
84524 -- Name: summtransi(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84525 --
84526
84527 CREATE FUNCTION summtransi(integer, date, date) RETURNS numeric
84528     LANGUAGE plpgsql
84529     AS $_$
84530 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84531 -- See www.xtuple.com/CPAL for the full text of the software license.
84532 DECLARE
84533   pItemsiteid ALIAS FOR $1;
84534   pStartDate ALIAS FOR $2;
84535   pEndDate ALIAS FOR $3;
84536   _value NUMERIC;
84537
84538 BEGIN
84539
84540   SELECT SUM(invhist_invqty) INTO _value
84541   FROM invhist
84542   WHERE ((invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
84543    AND (invhist_transtype IN ('IM', 'IC'))
84544    AND (invhist_itemsite_id=pItemsiteid));
84545
84546   IF (_value IS NULL) THEN
84547     _value := 0;
84548   END IF;
84549
84550   RETURN _value;
84551
84552 END;
84553 $_$;
84554
84555
84556 ALTER FUNCTION public.summtransi(integer, date, date) OWNER TO admin;
84557
84558 --
84559 -- TOC entry 2252 (class 1255 OID 146567104)
84560 -- Dependencies: 4536 8
84561 -- Name: summtransr(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84562 --
84563
84564 CREATE FUNCTION summtransr(integer, integer) RETURNS numeric
84565     LANGUAGE plpgsql
84566     AS $_$
84567 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84568 -- See www.xtuple.com/CPAL for the full text of the software license.
84569 DECLARE
84570   pItemsiteid ALIAS FOR $1;
84571   pCalitemid ALIAS FOR $2;
84572   _value NUMERIC;
84573
84574 BEGIN
84575
84576   SELECT summTransR(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84577
84578   RETURN _value;
84579
84580 END;
84581 $_$;
84582
84583
84584 ALTER FUNCTION public.summtransr(integer, integer) OWNER TO admin;
84585
84586 --
84587 -- TOC entry 2251 (class 1255 OID 146567103)
84588 -- Dependencies: 4536 8
84589 -- Name: summtransr(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84590 --
84591
84592 CREATE FUNCTION summtransr(integer, date, date) RETURNS numeric
84593     LANGUAGE plpgsql
84594     AS $_$
84595 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84596 -- See www.xtuple.com/CPAL for the full text of the software license.
84597 DECLARE
84598   pItemsiteid ALIAS FOR $1;
84599   pStartDate ALIAS FOR $2;
84600   pEndDate ALIAS FOR $3;
84601   _value NUMERIC;
84602
84603 BEGIN
84604
84605   SELECT SUM(invhist_invqty) INTO _value
84606   FROM invhist
84607   WHERE ((invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
84608    AND (invhist_transtype IN ('RM', 'RP', 'RX'))
84609    AND (invhist_itemsite_id=pItemsiteid) );
84610
84611   IF (_value IS NULL) THEN
84612     _value := 0;
84613   END IF;
84614
84615   RETURN _value;
84616
84617 END;
84618 $_$;
84619
84620
84621 ALTER FUNCTION public.summtransr(integer, date, date) OWNER TO admin;
84622
84623 --
84624 -- TOC entry 2254 (class 1255 OID 146567106)
84625 -- Dependencies: 4536 8
84626 -- Name: summtranss(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84627 --
84628
84629 CREATE FUNCTION summtranss(pitemsiteid integer, pcalitemid integer) RETURNS numeric
84630     LANGUAGE plpgsql
84631     AS $_$
84632 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84633 -- See www.xtuple.com/CPAL for the full text of the software license.
84634 DECLARE
84635   pItemsiteid ALIAS FOR $1;
84636   pCalitemid ALIAS FOR $2;
84637   _value NUMERIC;
84638
84639 BEGIN
84640
84641   SELECT summTransS(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84642
84643   RETURN _value;
84644
84645 END;
84646 $_$;
84647
84648
84649 ALTER FUNCTION public.summtranss(pitemsiteid integer, pcalitemid integer) OWNER TO admin;
84650
84651 --
84652 -- TOC entry 2253 (class 1255 OID 146567105)
84653 -- Dependencies: 4536 8
84654 -- Name: summtranss(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84655 --
84656
84657 CREATE FUNCTION summtranss(pitemsiteid integer, pstartdate date, penddate date) RETURNS numeric
84658     LANGUAGE plpgsql
84659     AS $$
84660 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84661 -- See www.xtuple.com/CPAL for the full text of the software license.
84662 DECLARE
84663   _value NUMERIC;
84664
84665 BEGIN
84666
84667   SELECT SUM( CASE WHEN (invhist_transtype = 'RS') THEN (invhist_invqty * -1)
84668                    ELSE (invhist_invqty)
84669               END ) INTO _value
84670   FROM invhist
84671   WHERE ( (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
84672    AND (invhist_transtype IN ('SC', 'SH', 'SV', 'RS'))
84673    AND (invhist_ordtype != 'TO')
84674    AND (invhist_itemsite_id=pItemsiteid) );
84675
84676   IF (_value IS NULL) THEN
84677     _value := 0;
84678   END IF;
84679
84680   RETURN _value;
84681
84682 END;
84683 $$;
84684
84685
84686 ALTER FUNCTION public.summtranss(pitemsiteid integer, pstartdate date, penddate date) OWNER TO admin;
84687
84688 --
84689 -- TOC entry 2256 (class 1255 OID 146567108)
84690 -- Dependencies: 4536 8
84691 -- Name: summtranst(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84692 --
84693
84694 CREATE FUNCTION summtranst(integer, integer) RETURNS numeric
84695     LANGUAGE plpgsql
84696     AS $_$
84697 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84698 -- See www.xtuple.com/CPAL for the full text of the software license.
84699 DECLARE
84700   pItemsiteid ALIAS FOR $1;
84701   pCalitemid ALIAS FOR $2;
84702   _value NUMERIC;
84703
84704 BEGIN
84705
84706   SELECT summTransT(pItemsiteid, findPeriodStart(pCalitemid), findPeriodEnd(pCalitemid)) INTO _value;
84707
84708   RETURN _value;
84709
84710 END;
84711 $_$;
84712
84713
84714 ALTER FUNCTION public.summtranst(integer, integer) OWNER TO admin;
84715
84716 --
84717 -- TOC entry 2255 (class 1255 OID 146567107)
84718 -- Dependencies: 4536 8
84719 -- Name: summtranst(integer, date, date); Type: FUNCTION; Schema: public; Owner: admin
84720 --
84721
84722 CREATE FUNCTION summtranst(integer, date, date) RETURNS numeric
84723     LANGUAGE plpgsql
84724     AS $_$
84725 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84726 -- See www.xtuple.com/CPAL for the full text of the software license.
84727 DECLARE
84728   pItemsiteid ALIAS FOR $1;
84729   pStartDate ALIAS FOR $2;
84730   pEndDate ALIAS FOR $3;
84731   _value NUMERIC;
84732
84733 BEGIN
84734
84735   SELECT SUM( CASE WHEN (invhist_transtype = 'TS') THEN (invhist_invqty * -1)
84736                    ELSE (invhist_invqty)
84737               END ) INTO _value
84738   FROM invhist
84739   WHERE ( (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
84740    AND (invhist_transtype IN ('TS', 'TR', 'TW'))
84741    AND (invhist_itemsite_id=pItemsiteid) );
84742
84743   IF (_value IS NULL) THEN
84744     _value := 0;
84745   END IF;
84746
84747   RETURN _value;
84748
84749 END;
84750 $_$;
84751
84752
84753 ALTER FUNCTION public.summtranst(integer, date, date) OWNER TO admin;
84754
84755 --
84756 -- TOC entry 2259 (class 1255 OID 146567109)
84757 -- Dependencies: 2705 4536 8
84758 -- Name: taxassignments(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
84759 --
84760
84761 CREATE FUNCTION taxassignments(integer, integer) RETURNS SETOF taxassign
84762     LANGUAGE plpgsql
84763     AS $_$
84764 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84765 -- See www.xtuple.com/CPAL for the full text of the software license.
84766 DECLARE
84767   pTaxZoneId ALIAS FOR $1;
84768   pTaxTypeId ALIAS FOR $2;
84769   _row taxassign%ROWTYPE;
84770   _qry text;
84771   _x RECORD;
84772   _y RECORD;
84773   _z RECORD;
84774
84775 BEGIN
84776   _qry = 'SELECT DISTINCT COALESCE(taxass_taxzone_id, -1) AS taxass_taxzone_id, COALESCE(taxass_taxtype_id, -1) AS taxass_taxtype_id, ';
84777   _qry = _qry || 'taxzone_code, taxtype_name FROM taxass LEFT OUTER JOIN taxzone ON (taxass_taxzone_id=taxzone_id) ';
84778   _qry = _qry || 'LEFT OUTER JOIN taxtype ON (taxass_taxtype_id=taxtype_id) ';
84779
84780   IF ((pTaxZoneId > 0) OR (pTaxTypeId > 0)) THEN
84781     _qry := _qry || ' WHERE ';
84782     IF (pTaxZoneId > 0) THEN
84783       _qry := _qry || ' (taxass_taxzone_id = ' || pTaxZoneId ||')';
84784       IF (pTaxTypeId > 0) THEN
84785         _qry := _qry || ' AND ';
84786       END IF;
84787     END IF;
84788     IF (pTaxTypeId > 0) THEN
84789       _qry := _qry || ' (taxass_taxtype_id = ' || pTaxTypeId || ')';
84790     END IF;
84791   END IF;
84792
84793   --This first query gets all the distinct tax zone and type groupings as if it were its own table.
84794   --This allows us to have a level 0 record as pictured in Tax Assignments window that code assignements will
84795   --Subordinate to.
84796   FOR _x IN  EXECUTE _qry
84797   LOOP
84798     --Map values to _row here
84799     _row.taxassign_taxzone_id = _x.taxass_taxzone_id;
84800     _row.taxassign_taxtype_id = _x.taxass_taxtype_id;
84801     _row.taxassign_level = 0;
84802     _row.taxassign_zone_code = _x.taxzone_code;
84803     _row.taxassign_type_descrip = _x.taxtype_name;
84804     _row.taxassign_taxclass_code = '';
84805     _row.taxassign_taxclass_sequence = NULL;
84806     RETURN NEXT _row; --so we get a level tax zone/type 0 record.
84807   
84808     -- Now get all the tax code assignments that belong to this Zone and Type pair
84809     FOR _y IN
84810       SELECT taxass_id, COALESCE(taxzone_id, -1) AS taxzone_id, tax_id,
84811       tax_code, tax_descrip, COALESCE(taxtype_id, -1) AS taxtype_id, taxzone_code, 
84812       taxtype_descrip, taxclass_code, 
84813       COALESCE(taxclass_sequence, 0) AS taxclass_sequence
84814       FROM taxass JOIN tax 
84815          LEFT OUTER JOIN taxclass ON (tax_taxclass_id = taxclass_id)
84816       ON (taxass_tax_id = tax_id)
84817       LEFT OUTER JOIN taxzone ON (taxass_taxzone_id = taxzone_id)
84818       LEFT OUTER JOIN taxtype ON (taxass_taxtype_id = taxtype_id)
84819       WHERE COALESCE(taxass_taxzone_id, -1) = _x.taxass_taxzone_id
84820       AND   COALESCE(taxass_taxtype_id, -1) = _x.taxass_taxtype_id
84821     LOOP
84822       --Map results to _row
84823       _row.taxassign_taxzone_id = _y.taxzone_id;
84824       _row.taxassign_taxtype_id = _y.taxtype_id;
84825       _row.taxassign_level = 1;
84826       _row.taxassign_zone_code = _y.tax_code;
84827       _row.taxassign_type_descrip = _y.tax_descrip;
84828       _row.taxassign_taxclass_code = _y.taxclass_code;
84829       _row.taxassign_taxclass_sequence = _y.taxclass_sequence;
84830       RETURN NEXT _row; --to get code detail record;
84831       
84832       FOR _z IN SELECT * FROM getsubtax(_y.tax_id, 1) --a new recursive function described above
84833       LOOP
84834         --Map results to _row
84835         _row.taxassign_taxzone_id = _y.taxzone_id;
84836         _row.taxassign_taxtype_id = _y.taxtype_id;
84837         _row.taxassign_level = _z.subtax_taxcode_level;
84838         _row.taxassign_zone_code = _z.subtax_taxcode_code;
84839         _row.taxassign_type_descrip = _z.subtax_taxcode_descrip;
84840         _row.taxassign_taxclass_code = _y.taxclass_code;
84841         _row.taxassign_taxclass_sequence = _y.taxclass_sequence;
84842         RETURN NEXT _row;
84843       END  LOOP;
84844
84845     END LOOP;
84846
84847   END LOOP;
84848
84849 END;
84850 $_$;
84851
84852
84853 ALTER FUNCTION public.taxassignments(integer, integer) OWNER TO admin;
84854
84855 --
84856 -- TOC entry 2260 (class 1255 OID 146567110)
84857 -- Dependencies: 4536 8
84858 -- Name: thawaccountingperiod(integer); Type: FUNCTION; Schema: public; Owner: admin
84859 --
84860
84861 CREATE FUNCTION thawaccountingperiod(integer) RETURNS integer
84862     LANGUAGE plpgsql
84863     AS $_$
84864 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84865 -- See www.xtuple.com/CPAL for the full text of the software license.
84866 DECLARE
84867   pPeriodid ALIAS FOR $1;
84868   _r RECORD;
84869
84870 BEGIN
84871
84872 --  Check to make sure that the period is frozen
84873   IF ( ( SELECT (NOT period_freeze)
84874          FROM period
84875          WHERE (period_id=pPeriodid) ) ) THEN
84876     RETURN -2;
84877   END IF;
84878
84879 --  Check to make sure that the period is not closed
84880   IF ( ( SELECT (period_closed)
84881          FROM period
84882          WHERE (period_id=pPeriodid) ) ) THEN
84883     RETURN -1;
84884   END IF;
84885
84886 --  Reset the period_freeze flag
84887   UPDATE period
84888   SET period_freeze=FALSE
84889   WHERE (period_id=pPeriodid);
84890
84891 --  Post any unposted G/L Transactions into the period
84892   FOR _r IN SELECT DISTINCT gltrans_sequence
84893             FROM gltrans, accnt, period
84894             WHERE ( (gltrans_accnt_id=accnt_id)
84895              AND (NOT gltrans_posted)
84896              AND (gltrans_date BETWEEN period_start AND period_end)
84897              AND (period_id=pPeriodid) ) LOOP
84898     PERFORM postIntoTrialBalance(_r.gltrans_sequence);
84899   END LOOP;
84900
84901   RETURN pPeriodid;
84902
84903 END;
84904 $_$;
84905
84906
84907 ALTER FUNCTION public.thawaccountingperiod(integer) OWNER TO admin;
84908
84909 --
84910 -- TOC entry 2261 (class 1255 OID 146567111)
84911 -- Dependencies: 4536 8
84912 -- Name: thawitemsite(integer); Type: FUNCTION; Schema: public; Owner: admin
84913 --
84914
84915 CREATE FUNCTION thawitemsite(integer) RETURNS integer
84916     LANGUAGE plpgsql
84917     AS $_$
84918 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
84919 -- See www.xtuple.com/CPAL for the full text of the software license.
84920 DECLARE
84921   pItemsiteid ALIAS FOR $1;
84922   _qoh            NUMERIC := 0;
84923   _netable_qoh    NUMERIC := 0;
84924   _nonnetable_qoh NUMERIC := 0;
84925   _value          NUMERIC := 0;
84926   _itemlocid INTEGER;
84927   _itemloc RECORD;
84928   _invhist RECORD;
84929   _coarse RECORD;
84930   _fine RECORD;
84931
84932 BEGIN
84933
84934   IF ( SELECT itemsite_freeze
84935        FROM itemsite
84936        WHERE (itemsite_id=pItemsiteid) ) THEN
84937
84938     SELECT invhist_id INTO _invhist
84939     FROM invhist
84940     WHERE ( (invhist_itemsite_id=pItemsiteid)
84941      AND (NOT invhist_posted) )
84942     LIMIT 1;
84943     IF (NOT FOUND) THEN
84944       UPDATE itemsite
84945       SET itemsite_freeze=FALSE
84946       WHERE (itemsite_id=pItemsiteid);
84947    END IF;
84948
84949 --  Run through any invdetail if this itemsite is still MLC and/or Lot/Serial
84950     IF ( SELECT ( (itemsite_loccntrl) OR
84951                   (itemsite_controlmethod IN ('L', 'S')) )
84952          FROM itemsite
84953          WHERE (itemsite_id=pItemsiteid) ) THEN
84954
84955 --  Grab all of the itemsite/location/lot/serial combinations
84956 --  that have unposted detail
84957       FOR _coarse IN SELECT DISTINCT invdetail_location_id, invdetail_ls_id,
84958                                      invdetail_expiration, invdetail_warrpurc
84959                      FROM invhist, invdetail
84960                      WHERE ( (invdetail_invhist_id=invhist_id)
84961                       AND (NOT invhist_posted)
84962                       AND (invhist_itemsite_id=pItemsiteid) )
84963                      ORDER BY invdetail_location_id, invdetail_ls_id LOOP
84964
84965 --  Cache the initial qty of the itemloc specified by the
84966 --  itemsite/location/lot/serial
84967         SELECT itemloc_id, itemloc_qty, COALESCE(location_netable, TRUE) AS location_netable
84968         INTO _itemloc
84969         FROM itemloc LEFT OUTER JOIN location ON (location_id=itemloc_location_id)
84970         WHERE ( (itemloc_itemsite_id=pItemsiteid)
84971          AND (itemloc_location_id=_coarse.invdetail_location_id)
84972          AND (COALESCE(itemloc_ls_id,-1)=COALESCE(_coarse.invdetail_ls_id,-1))
84973          AND (COALESCE(itemloc_expiration,endOfTime())=COALESCE(_coarse.invdetail_expiration,endOfTime()))
84974          AND (COALESCE(itemloc_warrpurc,endOfTime())=COALESCE(_coarse.invdetail_warrpurc,endOfTime())) );
84975
84976 --  If the itemloc in question cannot be found, create it
84977         IF (NOT FOUND) THEN
84978           SELECT NEXTVAL('itemloc_itemloc_id_seq') INTO _itemlocid;
84979           INSERT INTO itemloc
84980           ( itemloc_id, itemloc_itemsite_id,
84981             itemloc_location_id, itemloc_ls_id,
84982             itemloc_qty, itemloc_expiration )
84983           VALUES
84984           ( _itemlocid, pItemsiteid,
84985             _coarse.invdetail_location_id, _coarse.invdetail_ls_id,
84986             0, endOfTime() );
84987
84988         _qoh := 0.0;
84989         _netable_qoh := 0.0;
84990         _nonnetable_qoh := 0.0;
84991
84992         ELSE
84993           _itemlocid := _itemloc.itemloc_id;
84994           _qoh := _itemloc.itemloc_qty;
84995           IF (_itemloc.location_netable) THEN
84996             _netable_qoh := _itemloc.itemloc_qty;
84997           ELSE
84998             _nonnetable_qoh := _itemloc.itemloc_qty;
84999           END IF;
85000         END IF;
85001
85002 --  Now step through each unposted invdetail record for a given
85003 --  itemsite/location/lot/serial
85004         FOR _fine IN SELECT invdetail_id, invdetail_qty
85005                      FROM invhist, invdetail
85006                      WHERE ( (invdetail_invhist_id=invhist_id)
85007                       AND (NOT invhist_posted)
85008                       AND (invhist_itemsite_id=pItemsiteid)
85009                       AND (invdetail_location_id=_coarse.invdetail_location_id)
85010                       AND (COALESCE(invdetail_ls_id,-1)=COALESCE(_coarse.invdetail_ls_id,-1))
85011                       AND (COALESCE(invdetail_expiration,endOfTime())=COALESCE(_coarse.invdetail_expiration,endOfTime()))
85012                       AND (COALESCE(invdetail_warrpurc,endOfTime())=COALESCE(_coarse.invdetail_warrpurc,endOfTime())) )
85013                      ORDER BY invhist_transdate LOOP
85014
85015 --  Update the running qoh fields in the detail record
85016           UPDATE invdetail
85017           SET invdetail_qty_before = _qoh,
85018               invdetail_qty_after = (_qoh + invdetail_qty)
85019           WHERE (invdetail_id=_fine.invdetail_id);
85020
85021 --  Update the running qoh
85022           _qoh = (_qoh + _fine.invdetail_qty);
85023           IF (_itemloc.location_netable) THEN
85024             _netable_qoh := (_netable_qoh + _fine.invdetail_qty);
85025           ELSE
85026             _nonnetable_qoh := (_nonnetable_qoh + _fine.invdetail_qty);
85027           END IF;
85028
85029         END LOOP;
85030
85031 --  If the running qoh end up at 0, delete the itemloc in question
85032         IF (_qoh = 0) THEN
85033           DELETE FROM itemloc
85034           WHERE (itemloc_id=_itemlocid);
85035
85036 --  Otherwise, update the itemloc in question with the resultant qty
85037         ELSE
85038           UPDATE itemloc
85039           SET itemloc_qty=_qoh
85040           WHERE (itemloc_id=_itemlocid);
85041         END IF;
85042
85043       END LOOP;
85044
85045     END IF; 
85046
85047 --  Cache the inital qoh of the itemsite
85048     SELECT itemsite_qtyonhand, itemsite_value INTO _qoh, _value
85049     FROM itemsite
85050     WHERE (itemsite_id=pItemsiteid);
85051
85052 --  We have to un-freeze the itemsite before update-ing its QOH
85053 --  so that that itemsite trigger won't block the QOH update.
85054 --  Also so the invhist trigger won't block the posted update.
85055
85056     UPDATE itemsite
85057     SET itemsite_freeze=FALSE
85058     WHERE (itemsite_id=pItemsiteid);
85059
85060     FOR _invhist IN SELECT invhist_id,
85061                            invhist_qoh_before, invhist_qoh_after,
85062                            invhist_value_before, invhist_value_after
85063                       FROM invhist
85064                      WHERE((invhist_itemsite_id=pItemsiteid)
85065                        AND (NOT invhist_posted))
85066                      ORDER BY invhist_transdate LOOP
85067
85068       UPDATE invhist
85069       SET invhist_qoh_before = _qoh,
85070           invhist_qoh_after = ( _qoh +
85071                                 _invhist.invhist_qoh_after -
85072                                 _invhist.invhist_qoh_before ),
85073           invhist_value_before = _value,
85074           invhist_value_after = ( _value +
85075                                   _invhist.invhist_value_after -
85076                                   _invhist.invhist_value_before ),
85077           invhist_posted = TRUE
85078       WHERE (invhist_id=_invhist.invhist_id);
85079
85080       _qoh := (_qoh + (_invhist.invhist_qoh_after - _invhist.invhist_qoh_before));
85081       _value := (_value + (_invhist.invhist_value_after - _invhist.invhist_value_before));
85082
85083     END LOOP;
85084
85085 -- _qoh can be used for the netable qoh because of the negative NN transactions
85086     UPDATE itemsite
85087        SET itemsite_qtyonhand = _qoh,
85088            itemsite_nnqoh = _nonnetable_qoh,
85089            itemsite_value = CASE WHEN ((itemsite_costmethod='A') AND (_value < 0.0)) THEN 0.0
85090                                  ELSE _value END
85091      WHERE(itemsite_id=pItemsiteid);
85092
85093   END IF;
85094
85095   RETURN pItemsiteid;
85096
85097 END;
85098 $_$;
85099
85100
85101 ALTER FUNCTION public.thawitemsite(integer) OWNER TO admin;
85102
85103 --
85104 -- TOC entry 233 (class 1259 OID 146567113)
85105 -- Dependencies: 6042 6043 6044 8
85106 -- Name: todoitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
85107 --
85108
85109 CREATE TABLE todoitem (
85110     todoitem_id integer NOT NULL,
85111     todoitem_name text NOT NULL,
85112     todoitem_description text,
85113     todoitem_incdt_id integer,
85114     todoitem_creator_username text DEFAULT geteffectivextuser() NOT NULL,
85115     todoitem_status character(1),
85116     todoitem_active boolean DEFAULT true NOT NULL,
85117     todoitem_start_date date,
85118     todoitem_due_date date,
85119     todoitem_assigned_date date,
85120     todoitem_completed_date date,
85121     todoitem_seq integer DEFAULT 0 NOT NULL,
85122     todoitem_notes text,
85123     todoitem_crmacct_id integer,
85124     todoitem_ophead_id integer,
85125     todoitem_owner_username text,
85126     todoitem_priority_id integer,
85127     todoitem_username text,
85128     todoitem_recurring_todoitem_id integer,
85129     todoitem_cntct_id integer
85130 );
85131
85132
85133 ALTER TABLE public.todoitem OWNER TO admin;
85134
85135 --
85136 -- TOC entry 9076 (class 0 OID 0)
85137 -- Dependencies: 233
85138 -- Name: TABLE todoitem; Type: COMMENT; Schema: public; Owner: admin
85139 --
85140
85141 COMMENT ON TABLE todoitem IS 'To-Do List items.';
85142
85143
85144 --
85145 -- TOC entry 9077 (class 0 OID 0)
85146 -- Dependencies: 233
85147 -- Name: COLUMN todoitem.todoitem_recurring_todoitem_id; Type: COMMENT; Schema: public; Owner: admin
85148 --
85149
85150 COMMENT ON COLUMN todoitem.todoitem_recurring_todoitem_id IS 'The first todoitem record in the series if this is a recurring To-Do item. If the todoitem_recurring_todoitem_id is the same as the todoitem_id, this record is the first in the series.';
85151
85152
85153 --
85154 -- TOC entry 2262 (class 1255 OID 146567122)
85155 -- Dependencies: 2886 4536 8
85156 -- Name: todoitem(); Type: FUNCTION; Schema: public; Owner: admin
85157 --
85158
85159 CREATE FUNCTION todoitem() RETURNS SETOF todoitem
85160     LANGUAGE plpgsql
85161     AS $$
85162 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85163 -- See www.xtuple.com/CPAL for the full text of the software license.
85164 DECLARE
85165   _row todoitem%ROWTYPE;
85166   _priv TEXT;
85167   _grant BOOLEAN;
85168
85169 BEGIN
85170   -- This query will give us the most permissive privilege the user has been granted
85171   SELECT privilege, granted INTO _priv, _grant
85172   FROM privgranted 
85173   WHERE privilege IN ('MaintainAllToDoItems','ViewAllToDoItems','MaintainPersonalToDoItems','ViewPersonalToDoItems')
85174   ORDER BY granted DESC, sequence
85175   LIMIT 1;
85176
85177   -- If have an 'All' privilege return all results
85178   IF (_priv ~ 'All' AND _grant) THEN
85179     FOR _row IN 
85180       SELECT * FROM todoitem
85181     LOOP
85182       RETURN NEXT _row;
85183     END LOOP;
85184   -- Otherwise if have any other grant, must be personal privilege.
85185   ELSIF (_grant) THEN
85186     FOR _row IN 
85187       SELECT * FROM todoitem 
85188       WHERE getEffectiveXtUser() IN (todoitem_owner_username, todoitem_username)
85189     LOOP
85190       RETURN NEXT _row;
85191     END LOOP;
85192   END IF;
85193
85194   RETURN;
85195
85196 END;
85197 $$;
85198
85199
85200 ALTER FUNCTION public.todoitem() OWNER TO admin;
85201
85202 --
85203 -- TOC entry 9079 (class 0 OID 0)
85204 -- Dependencies: 2262
85205 -- Name: FUNCTION todoitem(); Type: COMMENT; Schema: public; Owner: admin
85206 --
85207
85208 COMMENT ON FUNCTION todoitem() IS 'A table function that returns To Do Items results according to privilege settings.';
85209
85210
85211 --
85212 -- TOC entry 2263 (class 1255 OID 146567123)
85213 -- Dependencies: 4536 8
85214 -- Name: todoitemmove(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
85215 --
85216
85217 CREATE FUNCTION todoitemmove(integer, integer) RETURNS integer
85218     LANGUAGE plpgsql
85219     AS $_$
85220 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85221 -- See www.xtuple.com/CPAL for the full text of the software license.
85222 DECLARE
85223   ptodoItemId ALIAS FOR $1;
85224   pHowFar     ALIAS FOR $2;   -- -1 moves toward front of list, +1 toward back
85225   _howFar     INTEGER := pHowFar;
85226   _username   TEXT;
85227   _currseq    INTEGER;
85228 BEGIN
85229   SELECT todoitem_username, todoitem_seq INTO _username, _currseq
85230   FROM todoitem
85231   WHERE todoitem_id = ptodoItemId;
85232
85233   IF NOT FOUND THEN
85234     RETURN -1;
85235   END IF;
85236
85237   IF (_currseq + pHowFar <= 0) THEN
85238     _howFar = 1 - _currseq;   -- move to beginning
85239   END IF;
85240
85241   UPDATE todoitem
85242   SET todoitem_seq=todoitem_seq - _howFar
85243   WHERE todoitem_seq >= _currseq + _howFar
85244     AND todoitem_id != ptodoItemId
85245     AND todoitem_username = _username
85246     AND todoitem_status != 'C';
85247
85248   UPDATE todoitem
85249   SET todoitem_seq=_currseq + _howFar
85250   WHERE todoitem_id = ptodoItemId;
85251
85252   RETURN 0;
85253 END;
85254 $_$;
85255
85256
85257 ALTER FUNCTION public.todoitemmove(integer, integer) OWNER TO admin;
85258
85259 --
85260 -- TOC entry 2264 (class 1255 OID 146567124)
85261 -- Dependencies: 4536 8
85262 -- Name: todoitemmovedown(integer); Type: FUNCTION; Schema: public; Owner: admin
85263 --
85264
85265 CREATE FUNCTION todoitemmovedown(integer) RETURNS integer
85266     LANGUAGE plpgsql
85267     AS $_$
85268 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85269 -- See www.xtuple.com/CPAL for the full text of the software license.
85270 DECLARE
85271   ptodoItemId ALIAS FOR $1;
85272 BEGIN
85273   RETURN todoItemMove(ptodoItemId, 1);        -- move toward end of list
85274 END;
85275 $_$;
85276
85277
85278 ALTER FUNCTION public.todoitemmovedown(integer) OWNER TO admin;
85279
85280 --
85281 -- TOC entry 2265 (class 1255 OID 146567125)
85282 -- Dependencies: 4536 8
85283 -- Name: todoitemmoveup(integer); Type: FUNCTION; Schema: public; Owner: admin
85284 --
85285
85286 CREATE FUNCTION todoitemmoveup(integer) RETURNS integer
85287     LANGUAGE plpgsql
85288     AS $_$
85289 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85290 -- See www.xtuple.com/CPAL for the full text of the software license.
85291 DECLARE
85292   ptodoItemId ALIAS FOR $1;
85293 BEGIN
85294   RETURN todoItemMove(ptodoItemId, -1);       -- move toward front of list
85295 END;
85296 $_$;
85297
85298
85299 ALTER FUNCTION public.todoitemmoveup(integer) OWNER TO admin;
85300
85301 --
85302 -- TOC entry 2266 (class 1255 OID 146567126)
85303 -- Dependencies: 4536 8
85304 -- Name: togglebankreccleared(integer, text, integer); Type: FUNCTION; Schema: public; Owner: admin
85305 --
85306
85307 CREATE FUNCTION togglebankreccleared(integer, text, integer) RETURNS boolean
85308     LANGUAGE plpgsql
85309     AS $_$
85310 DECLARE
85311   pBankrecid ALIAS FOR $1;
85312   pSource    ALIAS FOR $2;
85313   pSourceid  ALIAS FOR $3;
85314   _cleared BOOLEAN;
85315   _r RECORD;
85316
85317 BEGIN
85318
85319   SELECT bankrecitem_id, bankrecitem_cleared INTO _r
85320     FROM bankrecitem
85321    WHERE ( (bankrecitem_bankrec_id=pBankrecid)
85322      AND   (bankrecitem_source=pSource)
85323      AND   (bankrecitem_source_id=pSourceid) );
85324   IF ( NOT FOUND ) THEN
85325     _cleared := TRUE;
85326     INSERT INTO bankrecitem
85327     (bankrecitem_bankrec_id, bankrecitem_source,
85328      bankrecitem_source_id, bankrecitem_cleared)
85329     VALUES
85330     (pBankrecid, pSource, pSourceid, _cleared);
85331   ELSE
85332     _cleared := (NOT _r.bankrecitem_cleared);
85333     UPDATE bankrecitem
85334        SET bankrecitem_cleared=_cleared
85335      WHERE (bankrecitem_id=_r.bankrecitem_id);
85336   END IF;
85337
85338   RETURN _cleared;
85339 END;
85340 $_$;
85341
85342
85343 ALTER FUNCTION public.togglebankreccleared(integer, text, integer) OWNER TO admin;
85344
85345 --
85346 -- TOC entry 2267 (class 1255 OID 146567127)
85347 -- Dependencies: 4536 8
85348 -- Name: togglebankreccleared(integer, text, integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
85349 --
85350
85351 CREATE FUNCTION togglebankreccleared(integer, text, integer, numeric) RETURNS boolean
85352     LANGUAGE plpgsql
85353     AS $_$
85354 DECLARE
85355   pBankrecid ALIAS FOR $1;
85356   pSource    ALIAS FOR $2;
85357   pSourceid  ALIAS FOR $3;
85358   pCurrrate  ALIAS FOR $4;
85359   _cleared BOOLEAN;
85360   _r RECORD;
85361
85362 BEGIN
85363
85364   SELECT bankrecitem_id, bankrecitem_cleared INTO _r
85365     FROM bankrecitem
85366    WHERE ( (bankrecitem_bankrec_id=pBankrecid)
85367      AND   (bankrecitem_source=pSource)
85368      AND   (bankrecitem_source_id=pSourceid) );
85369   IF ( NOT FOUND ) THEN
85370     _cleared := TRUE;
85371     INSERT INTO bankrecitem
85372     (bankrecitem_bankrec_id, bankrecitem_source,
85373      bankrecitem_source_id, bankrecitem_cleared,
85374      bankrecitem_curr_rate)
85375     VALUES
85376     (pBankrecid, pSource,
85377      pSourceid, _cleared,
85378      pCurrrate);
85379   ELSE
85380     _cleared := (NOT _r.bankrecitem_cleared);
85381     UPDATE bankrecitem
85382        SET bankrecitem_cleared=_cleared,
85383            bankrecitem_curr_rate=pCurrrate
85384      WHERE (bankrecitem_id=_r.bankrecitem_id);
85385   END IF;
85386
85387   RETURN _cleared;
85388 END;
85389 $_$;
85390
85391
85392 ALTER FUNCTION public.togglebankreccleared(integer, text, integer, numeric) OWNER TO admin;
85393
85394 --
85395 -- TOC entry 2268 (class 1255 OID 146567128)
85396 -- Dependencies: 4536 8
85397 -- Name: togglebankreccleared(integer, text, integer, numeric, numeric); Type: FUNCTION; Schema: public; Owner: admin
85398 --
85399
85400 CREATE FUNCTION togglebankreccleared(integer, text, integer, numeric, numeric) RETURNS boolean
85401     LANGUAGE plpgsql
85402     AS $_$
85403 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85404 -- See www.xtuple.com/CPAL for the full text of the software license.
85405 DECLARE
85406   pBankrecid ALIAS FOR $1;
85407   pSource    ALIAS FOR $2;
85408   pSourceid  ALIAS FOR $3;
85409   pCurrrate  ALIAS FOR $4;
85410   pAmount    ALIAS FOR $5;
85411   _cleared BOOLEAN;
85412   _r RECORD;
85413
85414 BEGIN
85415
85416   SELECT bankrecitem_id, bankrecitem_cleared INTO _r
85417     FROM bankrecitem
85418    WHERE ( (bankrecitem_bankrec_id=pBankrecid)
85419      AND   (bankrecitem_source=pSource)
85420      AND   (bankrecitem_source_id=pSourceid) );
85421   IF ( NOT FOUND ) THEN
85422     _cleared := TRUE;
85423     INSERT INTO bankrecitem
85424     (bankrecitem_bankrec_id, bankrecitem_source,
85425      bankrecitem_source_id, bankrecitem_cleared,
85426      bankrecitem_curr_rate, bankrecitem_amount)
85427     VALUES
85428     (pBankrecid, pSource,
85429      pSourceid, _cleared,
85430      pCurrrate, pAmount);
85431   ELSE
85432     _cleared := FALSE;
85433     DELETE FROM bankrecitem 
85434     WHERE bankrecitem_id = _r.bankrecitem_id;
85435   END IF;
85436
85437   RETURN _cleared;
85438 END;
85439 $_$;
85440
85441
85442 ALTER FUNCTION public.togglebankreccleared(integer, text, integer, numeric, numeric) OWNER TO admin;
85443
85444 --
85445 -- TOC entry 2269 (class 1255 OID 146567129)
85446 -- Dependencies: 4536 8
85447 -- Name: togglebomitemcost(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
85448 --
85449
85450 CREATE FUNCTION togglebomitemcost(integer, boolean) RETURNS integer
85451     LANGUAGE plpgsql
85452     AS $_$
85453 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85454 -- See www.xtuple.com/CPAL for the full text of the software license.
85455 DECLARE
85456   pBomitemid ALIAS FOR $1;
85457   pEnabled   ALIAS FOR $2;
85458
85459 BEGIN
85460
85461   IF (pEnabled) THEN
85462     INSERT INTO bomitemcost
85463     (bomitemcost_bomitem_id, bomitemcost_costelem_id,
85464      bomitemcost_lowlevel, bomitemcost_stdcost,
85465      bomitemcost_posted, bomitemcost_actcost,
85466      bomitemcost_updated, bomitemcost_curr_id)
85467     SELECT
85468      bomitem_id, itemcost_costelem_id,
85469      itemcost_lowlevel, itemcost_stdcost,
85470      itemcost_posted, itemcost_actcost,
85471      itemcost_updated, itemcost_curr_id
85472     FROM bomitem JOIN itemcost ON (itemcost_item_id=bomitem_item_id)
85473     WHERE (bomitem_id=pBomitemid);
85474   ELSE
85475     DELETE FROM bomitemcost
85476     WHERE (bomitemcost_bomitem_id=pBomitemid);
85477   END IF;
85478
85479   RETURN 0;
85480 END;
85481 $_$;
85482
85483
85484 ALTER FUNCTION public.togglebomitemcost(integer, boolean) OWNER TO admin;
85485
85486 --
85487 -- TOC entry 2270 (class 1255 OID 146567130)
85488 -- Dependencies: 4536 8
85489 -- Name: tonumeric(text, numeric); Type: FUNCTION; Schema: public; Owner: admin
85490 --
85491
85492 CREATE FUNCTION tonumeric(text, numeric) RETURNS numeric
85493     LANGUAGE plpgsql IMMUTABLE
85494     AS $_$
85495 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85496 -- See www.xtuple.com/CPAL for the full text of the software license.
85497 DECLARE
85498   pText ALIAS FOR $1;
85499   pDefault ALIAS FOR $2;
85500
85501 BEGIN
85502
85503   IF (isNumeric(pText)) THEN
85504     RETURN TO_NUMBER(pText, '999999999999');
85505   ELSE
85506     RETURN pDefault;
85507   END IF;
85508
85509 END;
85510 $_$;
85511
85512
85513 ALTER FUNCTION public.tonumeric(text, numeric) OWNER TO admin;
85514
85515 --
85516 -- TOC entry 2271 (class 1255 OID 146567131)
85517 -- Dependencies: 4536 8
85518 -- Name: transitwhs(); Type: FUNCTION; Schema: public; Owner: admin
85519 --
85520
85521 CREATE FUNCTION transitwhs() RETURNS integer
85522     LANGUAGE plpgsql
85523     AS $$
85524 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85525 -- See www.xtuple.com/CPAL for the full text of the software license.
85526 DECLARE
85527   _id   INTEGER;
85528
85529 BEGIN
85530   _id = fetchMetricValue('TransitWarehouse');
85531
85532   IF (_id IS NOT NULL
85533       AND EXISTS(SELECT warehous_id FROM whsinfo WHERE (warehous_id=_id)) ) THEN
85534     RETURN _id;
85535   END IF;
85536
85537   SELECT warehous_id INTO _id FROM whsinfo WHERE warehous_transit;
85538
85539   IF (NOT FOUND) THEN
85540     _id := NEXTVAL('warehous_warehous_id_seq');
85541
85542     INSERT INTO whsinfo (
85543       warehous_id,
85544       warehous_code,
85545       warehous_descrip,
85546       --warehous_fob,
85547       warehous_active,
85548       --warehous_counttag_prefix,
85549       --warehous_counttag_number,
85550       --warehous_bol_prefix,
85551       --warehous_bol_number,
85552       warehous_shipping,
85553       warehous_useslips,
85554       warehous_usezones,
85555       --warehous_aislesize,
85556       --warehous_aislealpha,
85557       --warehous_racksize,
85558       --warehous_rackalpha,
85559       --warehous_binsize,
85560       --warehous_binalpha,
85561       --warehous_locationsize,
85562       --warehous_locationalpha,
85563       warehous_enforcearbl,
85564       warehous_default_accnt_id,
85565       --warehous_shipping_commission,
85566       --warehous_cntct_id,
85567       --warehous_addr_id,
85568       warehous_taxzone_id
85569      ) VALUES (
85570        _id,
85571       'TRANSIT',
85572       'Intermediate Warehouse for Inter-Warehouse Transfers',
85573       --text,
85574       TRUE,
85575       --text, 
85576       --integer, 
85577       --text, 
85578       --integer, 
85579       TRUE,
85580       FALSE,
85581       FALSE,
85582       --integer, 
85583       --boolean, 
85584       --integer, 
85585       --boolean, 
85586       --integer, 
85587       --boolean, 
85588       --integer, 
85589       --boolean, 
85590       FALSE,
85591       fetchMetricValue('UnassignedAccount'),
85592       --numeric(8,4) default 0.00,
85593       --integer, 
85594       --integer, 
85595       NULL
85596     );
85597   END IF;
85598
85599   PERFORM setMetric('TransitWarehouse', _id);
85600
85601   RETURN _id;
85602
85603 END;
85604 $$;
85605
85606
85607 ALTER FUNCTION public.transitwhs() OWNER TO admin;
85608
85609 --
85610 -- TOC entry 2272 (class 1255 OID 146567132)
85611 -- Dependencies: 4536 8
85612 -- Name: transtype(text, integer); Type: FUNCTION; Schema: public; Owner: admin
85613 --
85614
85615 CREATE FUNCTION transtype(text, integer) RETURNS boolean
85616     LANGUAGE plpgsql
85617     AS $_$
85618 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85619 -- See www.xtuple.com/CPAL for the full text of the software license.
85620 DECLARE
85621   pTransType ALIAS FOR $1;
85622   pTargetType ALIAS FOR $2;
85623
85624 BEGIN
85625
85626   IF (pTargetType = 255) THEN
85627     RETURN TRUE;
85628   ELSIF (pTargetType = 1) THEN
85629     RETURN receipts(pTransType);
85630   ELSIF (pTargetType = 2) THEN
85631     RETURN issues(pTransType);
85632   ELSIF (pTargetType = 4) THEN
85633     RETURN shipments(pTransType);
85634   ELSIF (pTargetType = 8) THEN
85635     RETURN adjustments(pTransType);
85636   ELSIF (pTargetType = 16) THEN
85637     RETURN transfers(pTransType);
85638   ELSIF (pTargetType = 32) THEN
85639     RETURN scraps(pTransType);
85640   ELSE
85641     RETURN TRUE;
85642   END IF;
85643
85644 END;
85645 $_$;
85646
85647
85648 ALTER FUNCTION public.transtype(text, integer) OWNER TO admin;
85649
85650 --
85651 -- TOC entry 2273 (class 1255 OID 146567133)
85652 -- Dependencies: 4536 8
85653 -- Name: trylock(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
85654 --
85655
85656 CREATE FUNCTION trylock(integer, integer) RETURNS boolean
85657     LANGUAGE plpgsql
85658     AS $_$
85659 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85660 -- See www.xtuple.com/CPAL for the full text of the software license.
85661 DECLARE
85662   pKey1 ALIAS FOR $1;
85663   pKey2 ALIAS FOR $2;
85664   _pid integer;
85665 BEGIN
85666
85667   /* The standard try lock ignores locks made by the current user in same
85668      session.  Check for ANY lock on this id, whether by this user or not */
85669   SELECT pid INTO _pid
85670   FROM pg_locks
85671   WHERE ((classid=pKey1)
85672    AND (objid=pKey2)
85673    AND (objsubid=2));
85674
85675   IF (FOUND) THEN
85676     RETURN false;
85677   ELSE
85678     RETURN pg_try_advisory_lock(pKey1,pKey2);
85679   END IF;
85680    
85681 END;
85682 $_$;
85683
85684
85685 ALTER FUNCTION public.trylock(integer, integer) OWNER TO admin;
85686
85687 --
85688 -- TOC entry 2274 (class 1255 OID 146567134)
85689 -- Dependencies: 4536 8
85690 -- Name: undomerge(text, text, integer); Type: FUNCTION; Schema: public; Owner: admin
85691 --
85692
85693 CREATE FUNCTION undomerge(text, text, integer) RETURNS integer
85694     LANGUAGE plpgsql
85695     AS $_$
85696 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85697 -- See www.xtuple.com/CPAL for the full text of the software license.
85698 DECLARE
85699   pSchema       ALIAS FOR $1;
85700   pTable        ALIAS FOR $2;
85701   pId           ALIAS FOR $3;
85702   _qry          TEXT;
85703   _r            RECORD;
85704   _result       INTEGER;
85705
85706 BEGIN
85707   FOR _r IN
85708     SELECT *
85709       FROM mrgundo
85710      WHERE mrgundo_base_schema = pSchema
85711        AND mrgundo_base_table  = pTable
85712        AND mrgundo_base_id     = pId
85713        AND mrgundo_col IS NOT NULL  -- NULL mrgundo_col signals a row to delete on purge
85714   LOOP
85715     IF (_r.mrgundo_value IS NULL) THEN
85716       _qry := 'UPDATE ' || quote_ident(_r.mrgundo_schema)  ||
85717                     '.' || quote_ident(_r.mrgundo_table)   ||
85718                 ' SET ' || quote_ident(_r.mrgundo_col)     || '= NULL
85719                WHERE (' || _r.mrgundo_pkey_col || '=' || _r.mrgundo_pkey_id || ');';
85720     ELSE
85721       _qry := 'UPDATE ' || quote_ident(_r.mrgundo_schema)  ||
85722                     '.' || quote_ident(_r.mrgundo_table)   ||
85723                 ' SET ' || quote_ident(_r.mrgundo_col)     ||
85724               '= CAST(' || quote_literal(_r.mrgundo_value) || ' AS '
85725                         || quote_ident(_r.mrgundo_type)    || ')
85726                WHERE (' || _r.mrgundo_pkey_col || '=' || _r.mrgundo_pkey_id || ');';
85727     END IF;
85728
85729     EXECUTE _qry;
85730   END LOOP;
85731
85732   DELETE FROM mrgundo
85733    WHERE mrgundo_base_schema = pSchema
85734      AND mrgundo_base_table  = pTable
85735      AND mrgundo_base_id     = pId;
85736
85737   GET DIAGNOSTICS _result = ROW_COUNT;
85738
85739   RETURN _result;
85740
85741 END;
85742 $_$;
85743
85744
85745 ALTER FUNCTION public.undomerge(text, text, integer) OWNER TO admin;
85746
85747 --
85748 -- TOC entry 2275 (class 1255 OID 146567135)
85749 -- Dependencies: 4536 8
85750 -- Name: unreleasepurchaseorder(integer); Type: FUNCTION; Schema: public; Owner: admin
85751 --
85752
85753 CREATE FUNCTION unreleasepurchaseorder(ppoheadid integer) RETURNS integer
85754     LANGUAGE plpgsql
85755     AS $$
85756 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85757 -- See www.xtuple.com/CPAL for the full text of the software license.
85758 BEGIN
85759
85760   IF ( ( SELECT (COUNT(*) > 0)
85761          FROM poitem
85762          WHERE ( (poitem_pohead_id=pPoheadid)
85763            AND   ( (poitem_status='C') OR
85764                    (poitem_qty_received > 0.0) OR
85765                    (poitem_qty_returned > 0.0) OR
85766                    (poitem_qty_vouchered > 0.0) ) ) ) ) THEN
85767     RETURN -1;
85768   END IF;
85769
85770   IF ( ( SELECT (pohead_status='O')
85771          FROM pohead
85772          WHERE (pohead_id=pPoheadid) ) ) THEN
85773
85774     --update status and erase the date that the order was released on
85775     UPDATE pohead
85776     SET pohead_status='U', pohead_released = NULL
85777     WHERE (pohead_id=pPoheadid);
85778
85779   END IF;
85780
85781   --update status and erase the duedates at release
85782   UPDATE poitem
85783   SET poitem_status='U', poitem_rlsd_duedate = NULL
85784   WHERE (poitem_pohead_id=pPoheadid);
85785
85786   RETURN 1;
85787
85788 END;
85789 $$;
85790
85791
85792 ALTER FUNCTION public.unreleasepurchaseorder(ppoheadid integer) OWNER TO admin;
85793
85794 --
85795 -- TOC entry 2276 (class 1255 OID 146567136)
85796 -- Dependencies: 2763 4536 8
85797 -- Name: uomusedforitem(integer); Type: FUNCTION; Schema: public; Owner: admin
85798 --
85799
85800 CREATE FUNCTION uomusedforitem(integer) RETURNS SETOF uom
85801     LANGUAGE plpgsql
85802     AS $_$
85803 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85804 -- See www.xtuple.com/CPAL for the full text of the software license.
85805 DECLARE
85806   pitemid       ALIAS FOR $1;
85807   _row          uom%ROWTYPE;
85808 BEGIN
85809   FOR _row IN SELECT DISTINCT *
85810               FROM uom
85811               WHERE uom_id IN (
85812                 SELECT bomitem_uom_id AS uom_id 
85813                 FROM bomitem 
85814                 WHERE (bomitem_item_id=pitemid)
85815                 UNION 
85816                 SELECT cmitem_qty_uom_id 
85817                 FROM cmitem, itemsite 
85818                 WHERE ((cmitem_itemsite_id=itemsite_id)
85819                    AND (itemsite_item_id=pitemid))
85820                 UNION 
85821                 SELECT cmitem_price_uom_id 
85822                 FROM cmitem, itemsite 
85823                 WHERE ((cmitem_itemsite_id=itemsite_id)
85824                    AND (itemsite_item_id=pitemid))
85825                 UNION 
85826                 SELECT coitem_qty_uom_id 
85827                 FROM coitem, itemsite 
85828                 WHERE ((coitem_itemsite_id=itemsite_id)
85829                    AND (itemsite_item_id=pitemid))
85830                 UNION 
85831                 SELECT coitem_price_uom_id 
85832                 FROM coitem, itemsite 
85833                 WHERE ((coitem_itemsite_id=itemsite_id)
85834                    AND (itemsite_item_id=pitemid))
85835                 UNION 
85836                 SELECT invcitem_qty_uom_id 
85837                 FROM invcitem 
85838                 WHERE ((invcitem_item_id=pitemid))
85839                 UNION 
85840                 SELECT invcitem_price_uom_id 
85841                 FROM invcitem 
85842                 WHERE ((invcitem_item_id=pitemid))
85843                 UNION 
85844                 SELECT ipsitem_qty_uom_id 
85845                 FROM ipsiteminfo 
85846                 WHERE (ipsitem_item_id=pitemid)
85847                 UNION 
85848                 SELECT ipsitem_price_uom_id 
85849                 FROM ipsiteminfo 
85850                 WHERE (ipsitem_item_id=pitemid)
85851                 UNION 
85852                 SELECT quitem_qty_uom_id 
85853                 FROM quitem, itemsite 
85854                 WHERE ((quitem_itemsite_id=itemsite_id)
85855                    AND (itemsite_item_id=pitemid))
85856                 UNION 
85857                 SELECT quitem_price_uom_id 
85858                 FROM quitem, itemsite 
85859                 WHERE ((quitem_itemsite_id=itemsite_id)
85860                    AND (itemsite_item_id=pitemid))
85861                 UNION 
85862                 SELECT womatl_uom_id 
85863                 FROM womatl, itemsite 
85864                 WHERE ((womatl_itemsite_id=itemsite_id)
85865                    AND (itemsite_item_id=pitemid))
85866   ) LOOP
85867     RETURN NEXT _row;
85868   END LOOP;
85869
85870   IF (fetchmetricbool('MultiWhs')) THEN
85871     FOR _row IN SELECT DISTINCT *
85872                 FROM uom
85873                 WHERE uom_id IN (
85874                   SELECT rahist_uom_id 
85875                   FROM rahist, itemsite 
85876                   WHERE ((rahist_itemsite_id=itemsite_id)
85877                      AND (itemsite_item_id=pitemid))
85878     ) LOOP
85879       RETURN NEXT _row;
85880     END LOOP;
85881   END IF;
85882
85883   RETURN;
85884 END;
85885 $_$;
85886
85887
85888 ALTER FUNCTION public.uomusedforitem(integer) OWNER TO admin;
85889
85890 --
85891 -- TOC entry 2277 (class 1255 OID 146567137)
85892 -- Dependencies: 4536 8
85893 -- Name: updateabcclass(text, numeric, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
85894 --
85895
85896 CREATE FUNCTION updateabcclass(text, numeric, numeric, date, date) RETURNS integer
85897     LANGUAGE plpgsql
85898     AS $_$
85899 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85900 -- See www.xtuple.com/CPAL for the full text of the software license.
85901 DECLARE
85902   pClassCodePattern ALIAS FOR $1;
85903   pACutoff ALIAS FOR $2;
85904   pBCutoff ALIAS FOR $3;
85905   pStartDate ALIAS FOR $4;
85906   pEndDate ALIAS FOR $5;
85907   _result INTEGER;
85908
85909 BEGIN
85910
85911   SELECT updateABCClass(pClassCodePattern, -1, pACutoff, pBCutoff, pStartDate, pEndDate) INTO _result;
85912   RETURN _result;
85913
85914 END;
85915 $_$;
85916
85917
85918 ALTER FUNCTION public.updateabcclass(text, numeric, numeric, date, date) OWNER TO admin;
85919
85920 --
85921 -- TOC entry 2279 (class 1255 OID 146567139)
85922 -- Dependencies: 4536 8
85923 -- Name: updateabcclass(integer, numeric, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
85924 --
85925
85926 CREATE FUNCTION updateabcclass(integer, numeric, numeric, date, date) RETURNS integer
85927     LANGUAGE plpgsql
85928     AS $_$
85929 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85930 -- See www.xtuple.com/CPAL for the full text of the software license.
85931 DECLARE
85932   pClasscodeid ALIAS FOR $1;
85933   pACutoff ALIAS FOR $2;
85934   pBCutoff ALIAS FOR $3;
85935   pStartDate ALIAS FOR $4;
85936   pEndDate ALIAS FOR $5;
85937   _result INTEGER;
85938
85939 BEGIN
85940
85941   SELECT updateABCClass(pClassCodeid, -1, pACutoff, pBCutoff, pStartDate, pEndDate) INTO _result;
85942   RETURN _result;
85943
85944 END;
85945 $_$;
85946
85947
85948 ALTER FUNCTION public.updateabcclass(integer, numeric, numeric, date, date) OWNER TO admin;
85949
85950 --
85951 -- TOC entry 2278 (class 1255 OID 146567138)
85952 -- Dependencies: 4536 8
85953 -- Name: updateabcclass(text, integer, numeric, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
85954 --
85955
85956 CREATE FUNCTION updateabcclass(text, integer, numeric, numeric, date, date) RETURNS integer
85957     LANGUAGE plpgsql
85958     AS $_$
85959 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
85960 -- See www.xtuple.com/CPAL for the full text of the software license.
85961 DECLARE
85962   pClassCodePattern ALIAS FOR $1;
85963   pWarehousid ALIAS FOR $2;
85964   pACutoff ALIAS FOR $3;
85965   pBCutoff ALIAS FOR $4;
85966   pStartDate ALIAS FOR $5;
85967   pEndDate ALIAS FOR $6;
85968   _updateCount INTEGER;
85969   _totalValue NUMERIC;
85970   _cumulativeValue NUMERIC;
85971   _itemsite RECORD;
85972
85973 BEGIN
85974
85975   SELECT COUNT(*) INTO _updateCount
85976   FROM itemsite, item, classcode
85977   WHERE ( (itemsite_item_id=item_id)
85978    AND (item_classcode_id=classcode_id)
85979    AND (itemsite_autoabcclass)
85980    AND (classcode_code ~ pClassCodePattern)
85981    AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) );
85982
85983   IF (_updateCount IS NULL) THEN
85984     RETURN 0;
85985   ELSE
85986
85987     UPDATE itemsite
85988     SET itemsite_abcclass='T'
85989     FROM item, classcode
85990     WHERE ( (itemsite_item_id=item_id)
85991      AND (item_classcode_id=classcode_id)
85992      AND (itemsite_autoabcclass)
85993      AND (classcode_code ~ pClassCodePattern)
85994      AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) );
85995
85996     SELECT SUM(ABS(invhist_qoh_before - invhist_qoh_after) * invhist_unitcost) INTO _totalValue
85997     FROM invhist, itemsite, item, classcode
85998     WHERE ( (invhist_itemsite_id=itemsite_id)
85999      AND (itemsite_item_id=item_id)
86000      AND (item_classcode_id=classcode_id)
86001      AND (invhist_analyze)
86002      AND (invhist_transtype ~ '^[IR]')
86003      AND (itemsite_autoabcclass)
86004      AND (classcode_code ~ pClassCodePattern)
86005      AND (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
86006      AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) );
86007
86008     IF ( (_totalValue IS NULL) OR (_totalValue = 0) ) THEN
86009       UPDATE itemsite
86010       SET itemsite_abcclass='A'
86011       WHERE (itemsite_abcclass='T');
86012     ELSE
86013
86014       _cumulativeValue := 0;
86015
86016       FOR _itemsite IN SELECT itemsite_id, item_number,
86017                               SUM(ABS(invhist_qoh_before - invhist_qoh_after) * invhist_unitcost) AS value
86018                        FROM invhist, itemsite, item, classcode
86019                        WHERE ( (invhist_itemsite_id=itemsite_id)
86020                         AND (itemsite_item_id=item_id)
86021                         AND (item_classcode_id=classcode_id)
86022                         AND (invhist_analyze)
86023                         AND (invhist_transtype ~ '^[IR]')
86024                         AND (itemsite_autoabcclass)
86025                         AND (classcode_code ~ pClassCodePattern)
86026                         AND (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
86027                         AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) )
86028                        GROUP BY itemsite_id, item_number
86029                        ORDER BY value DESC LOOP
86030
86031         IF (_itemsite.value IS NOT NULL) THEN
86032           _cumulativeValue := _cumulativeValue + _itemsite.value;
86033         END IF;
86034
86035         IF ((_cumulativeValue / _totalValue) <= pACutoff) THEN
86036           UPDATE itemsite
86037           SET itemsite_abcclass='A'
86038           WHERE (itemsite_id=_itemsite.itemsite_id);
86039         ELSE
86040           IF ((_cumulativeValue / _totalValue) <= pBCutoff) THEN
86041             UPDATE itemsite
86042             SET itemsite_abcclass='B'
86043             WHERE (itemsite_id=_itemsite.itemsite_id);
86044           ELSE
86045             UPDATE itemsite
86046             SET itemsite_abcclass='C'
86047             WHERE (itemsite_id=_itemsite.itemsite_id);
86048           END IF;
86049         END IF;
86050
86051       END LOOP;
86052
86053       UPDATE itemsite
86054       SET itemsite_abcclass='C'
86055       WHERE (itemsite_abcclass='T');
86056     END IF;
86057
86058   END IF;
86059
86060   RETURN _updateCount;
86061
86062 END;
86063 $_$;
86064
86065
86066 ALTER FUNCTION public.updateabcclass(text, integer, numeric, numeric, date, date) OWNER TO admin;
86067
86068 --
86069 -- TOC entry 2280 (class 1255 OID 146567140)
86070 -- Dependencies: 4536 8
86071 -- Name: updateabcclass(integer, integer, numeric, numeric, date, date); Type: FUNCTION; Schema: public; Owner: admin
86072 --
86073
86074 CREATE FUNCTION updateabcclass(integer, integer, numeric, numeric, date, date) RETURNS integer
86075     LANGUAGE plpgsql
86076     AS $_$
86077 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86078 -- See www.xtuple.com/CPAL for the full text of the software license.
86079 DECLARE
86080   pClasscodeid ALIAS FOR $1;
86081   pWarehousid ALIAS FOR $2;
86082   pACutoff ALIAS FOR $3;
86083   pBCutoff ALIAS FOR $4;
86084   pStartDate ALIAS FOR $5;
86085   pEndDate ALIAS FOR $6;
86086   _updateCount INTEGER;
86087   _totalValue NUMERIC;
86088   _cumulativeValue NUMERIC;
86089   _itemsite RECORD;
86090
86091 BEGIN
86092
86093   SELECT COUNT(*) INTO _updateCount
86094   FROM itemsite, item
86095   WHERE ( (itemsite_item_id=item_id)
86096    AND ((item_classcode_id=pClasscodeid) OR (pClasscodeid=-1))
86097    AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) );
86098
86099   IF (_updateCount IS NULL) THEN
86100     _updateCount := 0;
86101   ELSE
86102
86103     UPDATE itemsite
86104     SET itemsite_abcclass='T'
86105     FROM item
86106     WHERE ( (itemsite_item_id=item_id)
86107      AND ((item_classcode_id=pClasscodeid) OR (pClasscodeid=-1))
86108      AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) );
86109
86110     SELECT SUM(ABS(invhist_qoh_before - invhist_qoh_after) * invhist_unitcost) INTO _totalValue
86111     FROM invhist, itemsite, item
86112     WHERE ( (invhist_itemsite_id=itemsite_id)
86113      AND (itemsite_item_id=item_id)
86114      AND (invhist_analyze)
86115      AND (invhist_transtype ~ '^[IR]')
86116      AND ((item_classcode_id=pClasscodeid) OR (pClasscodeid=-1))
86117      AND (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
86118      AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) );
86119
86120     IF ( (_totalValue IS NULL) OR (_totalValue = 0) ) THEN
86121       UPDATE itemsite
86122       SET itemsite_abcclass='A'
86123       WHERE (itemsite_abcclass='T');
86124     ELSE
86125
86126       _cumulativeValue := 0;
86127
86128       FOR _itemsite IN SELECT itemsite_id, item_number,
86129                               SUM(ABS(invhist_qoh_before - invhist_qoh_after) * invhist_unitcost) AS value
86130                        FROM invhist, itemsite, item
86131                        WHERE ( (invhist_itemsite_id=itemsite_id)
86132                         AND (itemsite_item_id=item_id)
86133                         AND (invhist_analyze)
86134                         AND (invhist_transtype ~ '^[IR]')
86135                         AND ((item_classcode_id=pClasscodeid) OR (pClasscodeid=-1))
86136                         AND (invhist_transdate::DATE BETWEEN pStartDate AND pEndDate)
86137                         AND ((itemsite_warehous_id=pWarehousid) OR (pWarehousid=-1)) )
86138                        GROUP BY itemsite_id, item_number
86139                        ORDER BY value DESC LOOP
86140
86141         IF (_itemsite.value IS NOT NULL) THEN
86142           _cumulativeValue := _cumulativeValue + _itemsite.value;
86143         END IF;
86144
86145         IF ((_cumulativeValue / _totalValue) <= pACutoff) THEN
86146           UPDATE itemsite
86147           SET itemsite_abcclass='A'
86148           WHERE (itemsite_id=_itemsite.itemsite_id);
86149         ELSE
86150           IF ((_cumulativeValue / _totalValue) <= pBCutoff) THEN
86151             UPDATE itemsite
86152             SET itemsite_abcclass='B'
86153             WHERE (itemsite_id=_itemsite.itemsite_id);
86154           ELSE
86155             UPDATE itemsite
86156             SET itemsite_abcclass='C'
86157             WHERE (itemsite_id=_itemsite.itemsite_id);
86158           END IF;
86159         END IF;
86160
86161       END LOOP;
86162
86163       UPDATE itemsite
86164       SET itemsite_abcclass='C'
86165       WHERE (itemsite_abcclass='T');
86166     END IF;
86167
86168   END IF;
86169
86170   RETURN _updateCount;
86171
86172 END;
86173 $_$;
86174
86175
86176 ALTER FUNCTION public.updateabcclass(integer, integer, numeric, numeric, date, date) OWNER TO admin;
86177
86178 --
86179 -- TOC entry 2281 (class 1255 OID 146567141)
86180 -- Dependencies: 4536 8
86181 -- Name: updatecharassignment(text, integer, integer, text); Type: FUNCTION; Schema: public; Owner: admin
86182 --
86183
86184 CREATE FUNCTION updatecharassignment(text, integer, integer, text) RETURNS integer
86185     LANGUAGE plpgsql
86186     AS $_$
86187 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86188 -- See www.xtuple.com/CPAL for the full text of the software license.
86189 DECLARE
86190   pTargetType ALIAS FOR $1;
86191   pTargetId ALIAS FOR $2;
86192   pCharId ALIAS FOR $3;
86193   pValue ALIAS FOR $4;
86194   _charassid INTEGER;
86195
86196 BEGIN
86197
86198   SELECT updateCharAssignment(pTargetType, pTargetId, pCharId, pValue, 0) INTO _charassid;
86199
86200   RETURN _charassid;
86201
86202 END;
86203 $_$;
86204
86205
86206 ALTER FUNCTION public.updatecharassignment(text, integer, integer, text) OWNER TO admin;
86207
86208 --
86209 -- TOC entry 2282 (class 1255 OID 146567142)
86210 -- Dependencies: 4536 8
86211 -- Name: updatecharassignment(text, integer, integer, text, numeric); Type: FUNCTION; Schema: public; Owner: admin
86212 --
86213
86214 CREATE FUNCTION updatecharassignment(text, integer, integer, text, numeric) RETURNS integer
86215     LANGUAGE plpgsql
86216     AS $_$
86217 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86218 -- See www.xtuple.com/CPAL for the full text of the software license.
86219 DECLARE
86220   pTargetType ALIAS FOR $1;
86221   pTargetId ALIAS FOR $2;
86222   pCharId ALIAS FOR $3;
86223   pValue ALIAS FOR $4;
86224   pPrice ALIAS FOR $5;
86225   _charassid INTEGER;
86226   _charassprice NUMERIC;
86227   _explodedJob BOOLEAN = FALSE;
86228   _value TEXT;
86229
86230 BEGIN
86231
86232   -- Check for Valid Assignment
86233   IF (pTargetType='SI') THEN
86234     SELECT (item_config AND wo_status != 'O') INTO _explodedJob
86235         FROM coitem,itemsite,item,wo
86236         WHERE ((coitem_id=pTargetId)
86237         AND (itemsite_id=coitem_itemsite_id)
86238         AND (item_id=itemsite_item_id)
86239         AND (wo_ordtype='S')
86240         AND (wo_ordid=coitem_id));
86241   END IF;
86242   
86243   SELECT charass_id,charass_value INTO _charassid, _value
86244     FROM charass
86245    WHERE ((charass_target_type=pTargetType)
86246      AND  (charass_target_id=pTargetId)
86247      AND  (charass_char_id=pCharId) )
86248    LIMIT 1;
86249   IF (FOUND) THEN
86250     IF (_explodedJob AND pValue != _value) THEN
86251       RAISE EXCEPTION  'Characteristic may not be updated for Configured Item with exploded Work Order.';
86252     ELSIF(COALESCE(pValue, '')!='') THEN
86253         UPDATE charass
86254         SET charass_value = pValue,
86255             charass_price = pPrice
86256         WHERE (charass_id=_charassid);
86257     ELSE
86258       DELETE
86259         FROM charass
86260        WHERE (charass_id=_charassid);
86261       _charassid := 0;
86262     END IF;
86263   ELSE
86264     IF ( (_explodedJob) AND (COALESCE(pValue, '')!='') ) THEN
86265       RAISE EXCEPTION  'Characteristics may not be updated for Configured Item with exploded Work Order.';
86266     ELSIF(COALESCE(pValue, '')!='') THEN
86267       SELECT nextval('charass_charass_id_seq') INTO _charassid;
86268       INSERT INTO charass
86269             (charass_id, charass_target_type, charass_target_id,
86270              charass_char_id, charass_value, charass_price)
86271       VALUES(_charassid, pTargetType, pTargetId,
86272              pCharId, pValue, pPrice);
86273     ELSE
86274       _charassid := 0;
86275     END IF;
86276   END IF;
86277
86278   RETURN _charassid;
86279
86280 END;
86281 $_$;
86282
86283
86284 ALTER FUNCTION public.updatecharassignment(text, integer, integer, text, numeric) OWNER TO admin;
86285
86286 --
86287 -- TOC entry 2283 (class 1255 OID 146567143)
86288 -- Dependencies: 4536 8
86289 -- Name: updatecost(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
86290 --
86291
86292 CREATE FUNCTION updatecost(integer, numeric) RETURNS integer
86293     LANGUAGE plpgsql
86294     AS $_$
86295 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86296 -- See www.xtuple.com/CPAL for the full text of the software license.
86297 DECLARE
86298   pItemcostid ALIAS FOR $1;
86299   pCost ALIAS FOR $2;
86300
86301 BEGIN
86302   RETURN updateCost(pItemcostid, pCost, baseCurrId());
86303 END;
86304 $_$;
86305
86306
86307 ALTER FUNCTION public.updatecost(integer, numeric) OWNER TO admin;
86308
86309 --
86310 -- TOC entry 2284 (class 1255 OID 146567146)
86311 -- Dependencies: 4536 8
86312 -- Name: updatecost(integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
86313 --
86314
86315 CREATE FUNCTION updatecost(integer, numeric, integer) RETURNS integer
86316     LANGUAGE plpgsql
86317     AS $_$
86318 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86319 -- See www.xtuple.com/CPAL for the full text of the software license.
86320 DECLARE
86321     pItemcostid ALIAS FOR $1;
86322     pCost ALIAS FOR $2;
86323     pCurrId ALIAS FOR $3;
86324
86325 BEGIN
86326   IF ( ( SELECT (itemcost_stdcost > 0)
86327            FROM itemcost
86328           WHERE (itemcost_id=pItemcostid) )  OR
86329         (pCost > 0) ) THEN
86330     UPDATE itemcost
86331        SET itemcost_actcost=pCost, itemcost_updated=CURRENT_DATE,
86332            itemcost_curr_id=pCurrId
86333      WHERE (itemcost_id=pItemcostid);
86334
86335     RETURN pItemcostid;
86336
86337   ELSE
86338     DELETE FROM itemcost
86339      WHERE (itemcost_id=pItemcostid);
86340
86341     RETURN -1;
86342   END IF;
86343
86344 END;
86345 $_$;
86346
86347
86348 ALTER FUNCTION public.updatecost(integer, numeric, integer) OWNER TO admin;
86349
86350 --
86351 -- TOC entry 2257 (class 1255 OID 146567144)
86352 -- Dependencies: 4536 8
86353 -- Name: updatecost(integer, text, boolean, numeric); Type: FUNCTION; Schema: public; Owner: admin
86354 --
86355
86356 CREATE FUNCTION updatecost(integer, text, boolean, numeric) RETURNS integer
86357     LANGUAGE plpgsql
86358     AS $_$
86359 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86360 -- See www.xtuple.com/CPAL for the full text of the software license.
86361 DECLARE
86362   returnVal INTEGER;
86363
86364 BEGIN
86365   SELECT updateCost($1, $2, $3, $4, baseCurrId()) INTO returnVal;
86366   RETURN returnVal;
86367 END;
86368 $_$;
86369
86370
86371 ALTER FUNCTION public.updatecost(integer, text, boolean, numeric) OWNER TO admin;
86372
86373 --
86374 -- TOC entry 2258 (class 1255 OID 146567145)
86375 -- Dependencies: 4536 8
86376 -- Name: updatecost(integer, integer, boolean, numeric); Type: FUNCTION; Schema: public; Owner: admin
86377 --
86378
86379 CREATE FUNCTION updatecost(integer, integer, boolean, numeric) RETURNS integer
86380     LANGUAGE plpgsql
86381     AS $_$
86382 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86383 -- See www.xtuple.com/CPAL for the full text of the software license.
86384 DECLARE
86385   returnVal INTEGER;
86386
86387 BEGIN
86388   SELECT updateCost($1, $2, $3, $4, baseCurrId()) INTO returnVal;
86389   RETURN returnVal;
86390 END;
86391 $_$;
86392
86393
86394 ALTER FUNCTION public.updatecost(integer, integer, boolean, numeric) OWNER TO admin;
86395
86396 --
86397 -- TOC entry 2285 (class 1255 OID 146567147)
86398 -- Dependencies: 4536 8
86399 -- Name: updatecost(integer, text, boolean, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
86400 --
86401
86402 CREATE FUNCTION updatecost(integer, text, boolean, numeric, integer) RETURNS integer
86403     LANGUAGE plpgsql
86404     AS $_$
86405 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86406 -- See www.xtuple.com/CPAL for the full text of the software license.
86407 DECLARE
86408   pItemid ALIAS FOR $1;
86409   pCosttype ALIAS FOR $2;
86410   pLevel ALIAS FOR $3;
86411   pCost ALIAS FOR $4;
86412   pCurrid ALIAS FOR $5;
86413   _cost NUMERIC;
86414   _currId INTEGER;
86415   _p RECORD;
86416   _itemcostid INTEGER;
86417
86418 BEGIN
86419
86420   IF (pCost IS NULL) THEN
86421     _cost = 0;
86422   ELSE
86423     _cost = pCost;
86424   END IF;
86425
86426   IF (pCurrId IS NULL) THEN
86427     _currId := baseCurrID();
86428   ELSE
86429     _currId := pCurrId;
86430   END IF;
86431
86432   SELECT itemcost_id, itemcost_stdcost INTO _p
86433   FROM itemcost, costelem
86434   WHERE ( (itemcost_costelem_id=costelem_id)
86435    AND (itemcost_item_id=pItemid)
86436    AND (itemcost_lowlevel=pLevel)
86437    AND (costelem_type=pCosttype) );
86438
86439   IF (NOT FOUND) THEN
86440     IF (_cost > 0) THEN
86441       SELECT NEXTVAL('itemcost_itemcost_id_seq') INTO _itemcostid;
86442       INSERT INTO itemcost
86443       ( itemcost_id, itemcost_item_id, itemcost_costelem_id, itemcost_lowlevel,
86444         itemcost_stdcost, itemcost_posted, itemcost_actcost, itemcost_updated,
86445         itemcost_curr_id )
86446       SELECT _itemcostid, pItemid, costelem_id, pLevel,
86447              0, startOfTime(), _cost, CURRENT_DATE,
86448              _currId
86449       FROM costelem
86450       WHERE (costelem_type=pCosttype);
86451
86452       RETURN _itemcostid;
86453
86454     ELSE
86455       RETURN -1;
86456     END IF;
86457
86458   ELSIF ( (_p.itemcost_stdcost > 0) OR (_cost > 0) ) THEN
86459     UPDATE itemcost
86460     SET itemcost_actcost=_cost,
86461         itemcost_curr_id = _currId,
86462         itemcost_updated=CURRENT_DATE
86463     WHERE (itemcost_id=_p.itemcost_id);
86464
86465     RETURN _p.itemcost_id;
86466
86467   ELSE
86468     DELETE FROM itemcost
86469     WHERE (itemcost_id=_p.itemcost_id);
86470  
86471     RETURN -1;
86472   END IF;
86473
86474 END;
86475 $_$;
86476
86477
86478 ALTER FUNCTION public.updatecost(integer, text, boolean, numeric, integer) OWNER TO admin;
86479
86480 --
86481 -- TOC entry 2286 (class 1255 OID 146567148)
86482 -- Dependencies: 4536 8
86483 -- Name: updatecost(integer, integer, boolean, numeric, integer); Type: FUNCTION; Schema: public; Owner: admin
86484 --
86485
86486 CREATE FUNCTION updatecost(integer, integer, boolean, numeric, integer) RETURNS integer
86487     LANGUAGE plpgsql
86488     AS $_$
86489 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86490 -- See www.xtuple.com/CPAL for the full text of the software license.
86491 DECLARE
86492   pItemid ALIAS FOR $1;
86493   pCostelemid ALIAS FOR $2;
86494   pLevel ALIAS FOR $3;
86495   pCost ALIAS FOR $4;
86496   pCurrid ALIAS FOR $5;
86497   _cost NUMERIC;
86498   _currId INTEGER;
86499   _p RECORD;
86500   _itemcostid INTEGER;
86501
86502 BEGIN
86503
86504   IF (pCost IS NULL) THEN
86505     _cost = 0;
86506   ELSE
86507     _cost = pCost;
86508   END IF;
86509
86510   IF (pCurrId IS NULL) THEN
86511     _currId := baseCurrID();
86512   ELSE
86513     _currId := pCurrId;
86514   END IF;
86515
86516   SELECT itemcost_id, itemcost_stdcost INTO _p
86517   FROM itemcost
86518   WHERE ((itemcost_costelem_id=pCostelemid)
86519    AND (itemcost_item_id=pItemid)
86520    AND (itemcost_lowlevel=pLevel) );
86521
86522   IF (NOT FOUND) THEN
86523     IF (_cost > 0) THEN
86524       SELECT NEXTVAL('itemcost_itemcost_id_seq') INTO _itemcostid;
86525       INSERT INTO itemcost
86526       ( itemcost_id, itemcost_item_id, itemcost_costelem_id, itemcost_lowlevel,
86527         itemcost_stdcost, itemcost_posted, itemcost_actcost, itemcost_updated,
86528         itemcost_curr_id )
86529       SELECT _itemcostid, pItemid, costelem_id, pLevel,
86530              0, startOfTime(), _cost, CURRENT_DATE,
86531              _currId
86532       FROM costelem
86533       WHERE (costelem_id=pCostelemid);
86534
86535       RETURN _itemcostid;
86536
86537     ELSE
86538       RETURN -1;
86539     END IF;
86540
86541   ELSIF ( (_p.itemcost_stdcost > 0) OR (_cost > 0) ) THEN
86542     UPDATE itemcost
86543     SET itemcost_actcost=_cost,
86544         itemcost_curr_id = _currId,
86545         itemcost_updated=CURRENT_DATE
86546     WHERE (itemcost_id=_p.itemcost_id);
86547
86548     RETURN _p.itemcost_id;
86549
86550   ELSE
86551     DELETE FROM itemcost
86552     WHERE (itemcost_id=_p.itemcost_id);
86553  
86554     RETURN -1;
86555   END IF;
86556
86557 END;
86558 $_$;
86559
86560
86561 ALTER FUNCTION public.updatecost(integer, integer, boolean, numeric, integer) OWNER TO admin;
86562
86563 --
86564 -- TOC entry 2287 (class 1255 OID 146567149)
86565 -- Dependencies: 2849 2849 4536 8
86566 -- Name: updatecreditmemoline(api.creditmemoline, api.creditmemoline); Type: FUNCTION; Schema: public; Owner: admin
86567 --
86568
86569 CREATE FUNCTION updatecreditmemoline(api.creditmemoline, api.creditmemoline) RETURNS boolean
86570     LANGUAGE plpgsql
86571     AS $_$
86572 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86573 -- See www.xtuple.com/CPAL for the full text of the software license.
86574 DECLARE
86575   pNew ALIAS FOR $1;
86576   pOld ALIAS FOR $2;
86577   _check INTEGER;
86578   _r RECORD;
86579
86580 BEGIN
86581   SELECT cmitem_id INTO _check
86582   FROM cmitem
86583   WHERE ( (cmitem_cmhead_id=getCmheadId(pOld.memo_number, FALSE)) AND (cmitem_linenumber=pOld.line_number) );
86584   IF (NOT FOUND) THEN
86585     RAISE EXCEPTION 'Credit Memo # % Line Number # not found', pOld.memo_number, pOld.line_number;
86586   END IF;
86587
86588   UPDATE cmitem
86589     SET cmitem_itemsite_id=COALESCE(itemsite_id, -1),
86590         cmitem_qtycredit=pNew.qty_to_credit,
86591         cmitem_qtyreturned=pNew.qty_returned,
86592         cmitem_unitprice=pNew.net_unit_price,
86593         cmitem_comments=pNew.notes,
86594         cmitem_rsncode_id=getRsnId(pNew.reason_code),
86595         cmitem_taxtype_id=taxtype_id,
86596         cmitem_qty_uom_id=COALESCE(getUomId(pNew.qty_uom), item_inv_uom_id),
86597         cmitem_qty_invuomratio=CASE WHEN item_id IS NOT NULL THEN itemuomtouomratio(item_id, COALESCE(getUomId(pNew.qty_uom),item_inv_uom_id),item_inv_uom_id)
86598                                     ELSE 1
86599                                END,
86600         cmitem_price_uom_id=COALESCE(getUomId(pNew.price_uom),item_price_uom_id),
86601         cmitem_price_invuomratio=CASE WHEN item_id IS NOT NULL THEN itemuomtouomratio(item_id, COALESCE(getUomId(pNew.price_uom),item_price_uom_id),item_price_uom_id)
86602                                       ELSE 1
86603                                  END
86604   FROM cmhead LEFT OUTER JOIN item ON (item_id=getItemId(pNew.item_number))
86605               LEFT OUTER JOIN itemsite ON (itemsite_item_id=item_id AND
86606                                            itemsite_warehous_id=getWarehousId(pNew.recv_site, 'ALL'))
86607               LEFT OUTER JOIN taxtype ON (taxtype_id=CASE WHEN pNew.tax_type IS NULL THEN getItemTaxType(item_id,cmhead_taxzone_id)
86608                                                           WHEN pNew.tax_type = 'None' THEN NULL
86609                                                           ELSE getTaxTypeId(pNew.tax_type)
86610                                                      END)
86611   WHERE cmitem_cmhead_id=cmhead_id
86612     AND cmhead_number=pOld.memo_number
86613     AND cmitem_linenumber=pOld.line_number
86614     AND cmhead_posted=FALSE;
86615
86616   RETURN TRUE;
86617 END;
86618 $_$;
86619
86620
86621 ALTER FUNCTION public.updatecreditmemoline(api.creditmemoline, api.creditmemoline) OWNER TO admin;
86622
86623 --
86624 -- TOC entry 2288 (class 1255 OID 146567150)
86625 -- Dependencies: 4536 8
86626 -- Name: updatecustomprivs(); Type: FUNCTION; Schema: public; Owner: admin
86627 --
86628
86629 CREATE FUNCTION updatecustomprivs() RETURNS boolean
86630     LANGUAGE plpgsql
86631     AS $$
86632 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86633 -- See www.xtuple.com/CPAL for the full text of the software license.
86634 DECLARE
86635   _r RECORD;
86636 BEGIN
86637
86638   FOR _r IN SELECT priv_id
86639               FROM priv
86640              WHERE ((priv_name IN (SELECT priv_name
86641                                      FROM priv
86642                                     WHERE (priv_module='Custom')
86643                                    EXCEPT
86644                                    SELECT ('Custom'||cmd_privname)
86645                                      FROM cmd))
86646                AND  (priv_module='Custom')) LOOP
86647     -- TODO: something here
86648     DELETE FROM grppriv WHERE grppriv_priv_id=_r.priv_id;
86649     DELETE FROM usrpriv WHERE usrpriv_priv_id=_r.priv_id;
86650     DELETE FROM priv WHERE priv_id=_r.priv_id;
86651   END LOOP;
86652
86653   FOR _r IN SELECT ('Custom'||cmd_privname) AS privname
86654               FROM cmd
86655             EXCEPT
86656             SELECT priv_name
86657               FROM priv
86658              WHERE (priv_module='Custom') LOOP
86659     -- TODO: something here
86660     INSERT INTO priv (priv_module, priv_name, priv_descrip)
86661               VALUES ('Custom', _r.privname, 'Auto Generated Custom Priv.');
86662   END LOOP;
86663
86664   RETURN TRUE;
86665 END;
86666 $$;
86667
86668
86669 ALTER FUNCTION public.updatecustomprivs() OWNER TO admin;
86670
86671 --
86672 -- TOC entry 2291 (class 1255 OID 146567151)
86673 -- Dependencies: 2875 2875 4536 8
86674 -- Name: updateinvoicelineitem(api.invoiceline, api.invoiceline); Type: FUNCTION; Schema: public; Owner: admin
86675 --
86676
86677 CREATE FUNCTION updateinvoicelineitem(api.invoiceline, api.invoiceline) RETURNS boolean
86678     LANGUAGE plpgsql
86679     AS $_$
86680 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86681 -- See www.xtuple.com/CPAL for the full text of the software license.
86682 DECLARE
86683         pNew ALIAS FOR $1;
86684         pOld ALIAS FOR $2;
86685         _r RECORD;
86686 BEGIN
86687         UPDATE invcitem SET
86688                 invcitem_linenumber=pNew.line_number,
86689                 invcitem_item_id=COALESCE(item_id, -1),
86690                 invcitem_custpn=pNew.customer_part_number,
86691                 invcitem_number=(CASE WHEN item_id IS NULL THEN pNew.misc_item_number ELSE NULL END),
86692                 invcitem_warehous_id=(CASE WHEN invcitem_warehous_id IS NULL THEN COALESCE(getwarehousid(pNew.site,'ALL'),-1) ELSE NULL END),
86693                 invcitem_descrip=(CASE WHEN item_id IS NULL THEN pNew.misc_item_description ELSE NULL END),
86694                 invcitem_ordered=pNew.qty_ordered,
86695                 invcitem_billed=COALESCE(pNew.qty_billed, 0),
86696                 invcitem_updateinv=COALESCE(pNew.update_inventory,FALSE),
86697                 invcitem_price=COALESCE(pNew.net_unit_price,itemPrice(item_id,invchead_cust_id,
86698                         invchead_shipto_id,pNew.qty_ordered,invchead_curr_id,invchead_orderdate)),
86699                 invcitem_notes=COALESCE(pNew.notes,''),
86700                 invcitem_salescat_id=CASE
86701                         WHEN item_id IS NULL THEN
86702                                 (SELECT salescat_id FROM salescat WHERE salescat_name = pNew.sales_category)
86703                         ELSE NULL
86704                 END,
86705                 invcitem_taxtype_id=taxtype_id,
86706                 invcitem_qty_uom_id=CASE
86707                         WHEN item_id IS NOT NULL THEN
86708                                 COALESCE((SELECT uom_id FROM uom WHERE (uom_name=pNew.qty_uom)), item_price_uom_id)
86709                         ELSE NULL
86710                 END,
86711                 invcitem_qty_invuomratio=CASE
86712                         WHEN item_id IS NOT NULL THEN
86713                                 itemuomtouomratio(item_id,
86714                                         COALESCE((SELECT uom_id FROM uom WHERE uom_name=pNew.qty_uom),item_price_uom_id),
86715                                         item_price_uom_id
86716                                 )
86717                         ELSE 1
86718                 END,
86719                 invcitem_price_uom_id=CASE
86720                         WHEN item_id IS NOT NULL THEN
86721                                 COALESCE((SELECT uom_id FROM uom WHERE uom_name=pNew.price_uom),item_price_uom_id)
86722                         ELSE NULL
86723                 END,
86724                 invcitem_price_invuomratio=CASE
86725                         WHEN item_id IS NOT NULL THEN
86726                                 itemuomtouomratio(item_id,
86727                                         COALESCE((SELECT uom_id FROM uom WHERE uom_name=pNew.price_uom),item_price_uom_id),
86728                                         item_price_uom_id
86729                                 )
86730                         ELSE 1
86731                 END,
86732                 invcitem_rev_accnt_id=getGlAccntId(alternate_rev_account)
86733         FROM invchead
86734                 LEFT OUTER JOIN item ON (item_id=getItemId(pNew.item_number))
86735                 LEFT OUTER JOIN taxtype ON (taxtype_id=CASE
86736                         WHEN pNew.tax_type IS NULL THEN getItemTaxType(item_id,invchead_taxzone_id)
86737                         WHEN pNew.tax_type = 'None' THEN NULL
86738                         ELSE (SELECT taxtype_id FROM taxtype WHERE taxtype_name=pNew.tax_type)
86739                 END)
86740         WHERE invcitem_invchead_id=invchead_id
86741                 AND invcitem_linenumber=pOld.line_number
86742                 AND invchead_invcnumber=pOld.invoice_number
86743                 AND invchead_posted=FALSE;
86744         RETURN TRUE;
86745 END;
86746 $_$;
86747
86748
86749 ALTER FUNCTION public.updateinvoicelineitem(api.invoiceline, api.invoiceline) OWNER TO admin;
86750
86751 --
86752 -- TOC entry 2292 (class 1255 OID 146567152)
86753 -- Dependencies: 4536 8
86754 -- Name: updateitemcost(integer, integer, integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
86755 --
86756
86757 CREATE FUNCTION updateitemcost(integer, integer, integer, numeric, boolean) RETURNS integer
86758     LANGUAGE plpgsql
86759     AS $_$
86760 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86761 -- See www.xtuple.com/CPAL for the full text of the software license.
86762 DECLARE
86763 pItemId ALIAS FOR $1;
86764 pCostElemId ALIAS FOR $2;
86765 pCurrId ALIAS FOR $3;
86766 pCost ALIAS FOR $4;
86767 pPostToStandard ALIAS FOR $5;
86768 _itemcost_id INTEGER;
86769 _update_return INTEGER;
86770 _postcost_return BOOLEAN;
86771
86772 --This function is used with the api.itemcost View for updating
86773 --the itemcost table
86774
86775 BEGIN
86776   SELECT itemcost_id INTO _itemcost_id
86777   FROM itemcost
86778   WHERE ( (itemcost_item_id = pItemId) AND (itemcost_costelem_id = pCostElemId) );
86779
86780   IF (NOT FOUND) THEN
86781     RAISE EXCEPTION 'itemcost % not found for. ', pItemId || ' & ' || pCostElemId;
86782   END IF;
86783
86784   IF (pCost IS NULL OR pCost < 0) THEN
86785     RAISE EXCEPTION 'itemcost Actual Cost Invalid ', pCost;
86786   END IF;
86787   
86788   IF (pCost > 0) THEN
86789     UPDATE itemcost
86790     SET itemcost_actcost=pCost,
86791         itemcost_curr_id = pCurrId
86792     WHERE (itemcost_id=_itemcost_id);
86793
86794     --Only Post Cost to standard if the parameter is set to true
86795     IF (pPostToStandard) THEN
86796       IF (NOT checkPrivilege('PostStandardCosts')) THEN
86797         RAISE EXCEPTION 'You do not have privileges to poststandard itemcosts. Set api.itemcost post_to_standard to false';
86798       END IF;
86799       SELECT postcost(_itemcost_id) INTO _postcost_return;       
86800       IF (NOT _postcost_return) THEN
86801         RETURN -2;
86802       END IF;
86803     END IF;
86804   ELSE 
86805     RETURN -1;
86806   END IF;
86807
86808   RETURN _itemcost_id;
86809   
86810 END;
86811 $_$;
86812
86813
86814 ALTER FUNCTION public.updateitemcost(integer, integer, integer, numeric, boolean) OWNER TO admin;
86815
86816 --
86817 -- TOC entry 2293 (class 1255 OID 146567153)
86818 -- Dependencies: 4536 8
86819 -- Name: updateitemsiteleadtime(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
86820 --
86821
86822 CREATE FUNCTION updateitemsiteleadtime(integer, integer) RETURNS integer
86823     LANGUAGE plpgsql
86824     AS $_$
86825 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86826 -- See www.xtuple.com/CPAL for the full text of the software license.
86827 DECLARE
86828   pItemsiteid ALIAS FOR $1;
86829   pPad ALIAS FOR $2;
86830   _p RECORD;
86831   _materialLeadTime INTEGER;
86832   _productionLeadTime INTEGER;
86833   _leadTime INTEGER;
86834
86835 BEGIN
86836
86837   SELECT item_type, itemsite_wosupply INTO _p
86838   FROM item, itemsite
86839   WHERE ( (itemsite_item_id=item_id)
86840    AND (itemsite_id=pitemsiteid) );
86841   
86842   IF ( (_p.item_type IN ('M', 'P')) ) THEN
86843
86844     IF (_p.item_type = 'M') THEN
86845       SELECT COALESCE(MAX(component.itemsite_leadtime), 0) INTO _materialLeadTime
86846       FROM bomitem, itemsite AS parent, itemsite AS component
86847       WHERE ( (bomitem_parent_item_id=parent.itemsite_item_id)
86848        AND (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id))
86849        AND (bomitem_item_id=component.itemsite_item_id)
86850        AND (parent.itemsite_warehous_id=component.itemsite_warehous_id)
86851        AND (parent.itemsite_id=pItemsiteid) );
86852
86853       SELECT COALESCE(MAX(booitem_execday), 0) INTO _productionLeadTime
86854       FROM xtmfg.booitem, itemsite
86855       WHERE ( (booitem_item_id=itemsite_item_id)
86856        AND (booitem_rev_id=getActiveRevId('BOO',booitem_item_id))
86857        AND (itemsite_id=pItemsiteid) );
86858
86859       _leadTime := (_materialLeadTime + _productionLeadTime + pPad);
86860
86861     ELSIF (_p.item_type IN ('P')) THEN
86862       SELECT COALESCE(MAX(itemsrc_leadtime), 0) INTO _leadTime
86863       FROM itemsrc, itemsite
86864       WHERE ( (itemsite_item_id=itemsrc_item_id)
86865        AND (itemsite_id=pItemsiteid) );
86866
86867       _leadTime := (_leadTime + pPad);
86868     END IF;
86869
86870   ELSE
86871     _leadTime = pPad;
86872   END IF;
86873
86874   UPDATE itemsite
86875   SET itemsite_leadtime=_leadTime
86876   WHERE (itemsite_id=pItemsiteid);
86877
86878   RETURN _leadTime;
86879
86880 END;
86881 $_$;
86882
86883
86884 ALTER FUNCTION public.updateitemsiteleadtime(integer, integer) OWNER TO admin;
86885
86886 --
86887 -- TOC entry 2294 (class 1255 OID 146567154)
86888 -- Dependencies: 4536 8
86889 -- Name: updatelistprice(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
86890 --
86891
86892 CREATE FUNCTION updatelistprice(integer, numeric) RETURNS numeric
86893     LANGUAGE plpgsql
86894     AS $_$
86895 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86896 -- See www.xtuple.com/CPAL for the full text of the software license.
86897 DECLARE
86898   pItemid ALIAS FOR $1;
86899   pUpdateBy ALIAS FOR $2;
86900
86901 BEGIN
86902
86903   UPDATE item
86904   SET item_listprice = (item_listprice * pUpdateBy)
86905   WHERE (item_id=pItemid);
86906
86907   RETURN 1;
86908
86909 END;
86910 $_$;
86911
86912
86913 ALTER FUNCTION public.updatelistprice(integer, numeric) OWNER TO admin;
86914
86915 --
86916 -- TOC entry 2295 (class 1255 OID 146567155)
86917 -- Dependencies: 4536 8
86918 -- Name: updatelowerusercosts(integer); Type: FUNCTION; Schema: public; Owner: admin
86919 --
86920
86921 CREATE FUNCTION updatelowerusercosts(integer) RETURNS integer
86922     LANGUAGE plpgsql
86923     AS $_$
86924 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86925 -- See www.xtuple.com/CPAL for the full text of the software license.
86926 DECLARE
86927   pItemid ALIAS FOR $1;
86928
86929 BEGIN
86930     RETURN updateLowerUserCosts(pItemid, TRUE);
86931 END;
86932 $_$;
86933
86934
86935 ALTER FUNCTION public.updatelowerusercosts(integer) OWNER TO admin;
86936
86937 --
86938 -- TOC entry 2296 (class 1255 OID 146567156)
86939 -- Dependencies: 4536 8
86940 -- Name: updatelowerusercosts(integer, boolean); Type: FUNCTION; Schema: public; Owner: admin
86941 --
86942
86943 CREATE FUNCTION updatelowerusercosts(integer, boolean) RETURNS integer
86944     LANGUAGE plpgsql
86945     AS $_$
86946 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
86947 -- See www.xtuple.com/CPAL for the full text of the software license.
86948 DECLARE
86949   pItemid       ALIAS FOR $1;
86950   pUpdateActual ALIAS FOR $2;
86951   _bomitem RECORD;
86952   _type CHAR(1);
86953
86954 BEGIN
86955
86956   SELECT item_type INTO _type
86957   FROM item
86958   WHERE (item_id=pItemid);
86959
86960   IF (_type IN ('M', 'F', 'B', 'T')) THEN
86961     FOR _bomitem IN SELECT DISTINCT costelem_type
86962                     FROM ( SELECT COALESCE(bc.costelem_type, ic.costelem_type) AS costelem_type
86963                            FROM bomitem(pItemid)
86964                              JOIN item ON (item_id=bomitem_item_id AND item_type <> 'T')
86965                              JOIN itemcost ON (itemcost_item_id=bomitem_item_id)
86966                              JOIN costelem ic ON (ic.costelem_id=itemcost_costelem_id AND NOT ic.costelem_sys)
86967                              LEFT OUTER JOIN bomitemcost ON (bomitemcost_bomitem_id=bomitem_id)
86968                              LEFT OUTER JOIN costelem bc ON (bc.costelem_id=bomitemcost_costelem_id AND NOT bc.costelem_sys)
86969                            WHERE ( CURRENT_DATE BETWEEN bomitem_effective AND (bomitem_expires - 1) )
86970
86971                            UNION SELECT costelem_type
86972                            FROM itemcost, costelem
86973                            WHERE ( (itemcost_costelem_id=costelem_id)
86974                             AND (itemcost_item_id=pItemid) ) ) AS data LOOP
86975
86976       PERFORM updateSorACost( pItemid, _bomitem.costelem_type,
86977                               TRUE, lowerCost(pItemid, _bomitem.costelem_type, pUpdateActual),
86978                               pUpdateActual);
86979     END LOOP;
86980
86981   ELSIF (_type = 'C') THEN
86982     FOR _bomitem IN SELECT DISTINCT costelem_type
86983                     FROM ( SELECT costelem_type
86984                            FROM itemcost, costelem,
86985                                 xtmfg.bbomitem
86986                            WHERE ( (bbomitem_item_id=pItemid)
86987                             AND ( CURRENT_DATE BETWEEN bbomitem_effective
86988                                                AND (bbomitem_expires - 1) )
86989                             AND (NOT costelem_sys)
86990                             AND (bbomitem_item_id=itemcost_item_id)
86991                             AND (itemcost_costelem_id=costelem_id) ) 
86992
86993                            UNION SELECT costelem_type
86994                            FROM itemcost, costelem,
86995                                 xtmfg.bbomitem AS t,
86996                                 xtmfg.bbomitem AS s
86997                            WHERE ( (t.bbomitem_item_id=pItemid)
86998                             AND ( CURRENT_DATE BETWEEN s.bbomitem_effective
86999                                                AND (s.bbomitem_expires - 1) )
87000                             AND ( CURRENT_DATE BETWEEN t.bbomitem_effective
87001                                                AND (t.bbomitem_expires - 1) )
87002                             AND (s.bbomitem_parent_item_id=t.bbomitem_parent_item_id)
87003                             AND (NOT costelem_sys)
87004                             AND (s.bbomitem_item_id=itemcost_item_id)
87005                             AND (itemcost_costelem_id=costelem_id) ) ) AS data LOOP
87006
87007       PERFORM updateSorACost( pItemid, _bomitem.costelem_type,
87008                               TRUE, lowerCost(pItemid, _bomitem.costelem_type, pUpdateActual),
87009                               pUpdateActual);
87010     END LOOP;
87011   END IF;
87012
87013   RETURN 1;
87014
87015 END;
87016 $_$;
87017
87018
87019 ALTER FUNCTION public.updatelowerusercosts(integer, boolean) OWNER TO admin;
87020
87021 --
87022 -- TOC entry 2297 (class 1255 OID 146567157)
87023 -- Dependencies: 4536 8
87024 -- Name: updatelowlevel(integer); Type: FUNCTION; Schema: public; Owner: admin
87025 --
87026
87027 CREATE FUNCTION updatelowlevel(integer) RETURNS integer
87028     LANGUAGE plpgsql
87029     AS $_$
87030 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87031 -- See www.xtuple.com/CPAL for the full text of the software license.
87032 DECLARE
87033
87034   pLowlevel ALIAS FOR $1;
87035   _num_back INTEGER;
87036
87037 BEGIN
87038
87039   UPDATE costUpdate SET costUpdate_lowlevel_code = (pLowlevel + 1)
87040     WHERE costUpdate_item_id IN (
87041           SELECT bomitem_item_id
87042           FROM bomitem JOIN costUpdate ON (bomitem_parent_item_id = costUpdate_item_id)
87043           WHERE ((costUpdate_lowlevel_code = pLowlevel)
87044             AND  (bomitem_rev_id=getActiveRevId('BOM',bomitem_parent_item_id))
87045             AND  (CURRENT_DATE BETWEEN bomitem_effective
87046                                                AND (bomitem_expires - 1))))
87047       AND costUpdate_lowlevel_code >= pLowlevel;
87048
87049   GET DIAGNOSTICS _num_back = ROW_COUNT;
87050
87051   RETURN _num_back;
87052
87053 END;
87054 $_$;
87055
87056
87057 ALTER FUNCTION public.updatelowlevel(integer) OWNER TO admin;
87058
87059 --
87060 -- TOC entry 2298 (class 1255 OID 146567158)
87061 -- Dependencies: 4536 8
87062 -- Name: updateoutlevel(integer, integer, integer[]); Type: FUNCTION; Schema: public; Owner: admin
87063 --
87064
87065 CREATE FUNCTION updateoutlevel(integer, integer, integer[]) RETURNS boolean
87066     LANGUAGE plpgsql
87067     AS $_$
87068 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87069 -- See www.xtuple.com/CPAL for the full text of the software license.
87070 DECLARE
87071   pItemsiteid ALIAS FOR $1;
87072   pDays ALIAS FOR $2;
87073   pPeriods ALIAS FOR $3;
87074   _cursor INTEGER;
87075   _periodid INTEGER;
87076   _usage NUMERIC;
87077   _totalUsage NUMERIC;
87078   _totalDays INTEGER;
87079   _outLevel NUMERIC;
87080   _averageUsage NUMERIC;
87081
87082 BEGIN
87083
87084   _cursor := 1;
87085   _totalUsage := 0;
87086   _totalDays := 0;
87087
87088   _periodid = pPeriods[_cursor];
87089   WHILE (_periodid IS NOT NULL) LOOP
87090     SELECT COALESCE(SUM(invhist_invqty), 0) INTO _usage
87091     FROM invhist
87092     WHERE ( (invhist_itemsite_id=pItemsiteid)
87093      AND ( invhist_transdate::DATE BETWEEN findPeriodStart(_periodid)
87094                                    AND findPeriodEnd(_periodid) )
87095      AND (invhist_transtype IN ('SH', 'IM')) );
87096
87097     _totalUsage := (_totalUsage + _usage);
87098
87099     _totalDays := ( _totalDays + ( findPeriodEnd(_periodid) -
87100                                    findPeriodStart(_periodid) + 1 ) );
87101
87102     _cursor := (_cursor + 1);
87103     _periodid = pPeriods[_cursor];
87104   END LOOP;
87105
87106   IF (_totalDays > 0) THEN
87107     _outLevel := round(_totalUsage / _totalDays * pDays);
87108
87109     IF (_outLevel > 0) THEN
87110       UPDATE itemsite
87111       SET itemsite_ordertoqty = _outLevel
87112       WHERE (itemsite_id=pItemsiteid);
87113     ELSE
87114       UPDATE itemsite
87115       SET itemsite_ordertoqty = 0
87116       WHERE (itemsite_id=pItemsiteid);
87117     END IF;
87118
87119     RETURN TRUE;
87120   ELSE
87121     RETURN FALSE;
87122   END IF;
87123
87124 END;
87125 $_$;
87126
87127
87128 ALTER FUNCTION public.updateoutlevel(integer, integer, integer[]) OWNER TO admin;
87129
87130 --
87131 -- TOC entry 2299 (class 1255 OID 146567159)
87132 -- Dependencies: 4536 8
87133 -- Name: updateprice(integer, numeric); Type: FUNCTION; Schema: public; Owner: admin
87134 --
87135
87136 CREATE FUNCTION updateprice(integer, numeric) RETURNS numeric
87137     LANGUAGE plpgsql
87138     AS $_$
87139 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
87140 -- See www.xtuple.com/CPAL for the full text of the software license.
87141 DECLARE
87142   pIpsitemid ALIAS FOR $1;
87143   pUpdateBy ALIAS FOR $2;
87144
87145 BEGIN
87146
87147   RETURN updatePrice(pIpsitemid, 'P', pUpdateBy);
87148   
87149 END;
87150
87151 $_$;
87152
87153
87154 ALTER FUNCTION public.updateprice(integer, numeric) OWNER TO admin;
87155
87156 --
87157 -- TOC entry 2300 (class 1255 OID 146567160)
87158 -- Dependencies: 4536 8
87159 -- Name: updateprice(integer, character, numeric); Type: FUNCTION; Schema: public; Owner: admin
87160 --
87161
87162 CREATE FUNCTION updateprice(integer, character, numeric) RETURNS numeric
87163     LANGUAGE plpgsql
87164     AS $_$
87165 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
87166 -- See www.xtuple.com/CPAL for the full text of the software license.
87167 DECLARE
87168   pIpsitemid ALIAS FOR $1;
87169   pUpdateType ALIAS FOR $2;
87170   pUpdateBy ALIAS FOR $3;
87171
87172 BEGIN
87173
87174   IF (pUpdateType IN('V')) THEN
87175     UPDATE ipsitem
87176     SET ipsitem_price = (ipsitem_price + pUpdateBy)
87177     WHERE (ipsitem_id=pIpsitemid);
87178     RETURN 1;
87179   ELSE
87180     UPDATE ipsitem
87181     SET ipsitem_price = (ipsitem_price * pUpdateBy)
87182     WHERE (ipsitem_id=pIpsitemid);
87183     RETURN 1;
87184   END IF;
87185
87186 END;
87187 $_$;
87188
87189
87190 ALTER FUNCTION public.updateprice(integer, character, numeric) OWNER TO admin;
87191
87192 --
87193 -- TOC entry 2301 (class 1255 OID 146567161)
87194 -- Dependencies: 4536 8
87195 -- Name: updatepricesbypricingschedule(integer, character, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
87196 --
87197
87198 CREATE FUNCTION updatepricesbypricingschedule(pipsheadid integer, pupdatetype character, pupdateby numeric, pupdatecharprices boolean) RETURNS numeric
87199     LANGUAGE plpgsql
87200     AS $$
87201 DECLARE
87202   _percentMultiplier NUMERIC;
87203   _currencyDecimals INTEGER;
87204   _itemRows INTEGER :=0;
87205   _charRows INTEGER :=0;
87206
87207 BEGIN
87208
87209         IF NOT (checkPrivilege('MaintainPricingSchedules')) THEN
87210                 RAISE EXCEPTION 'You do not have privileges to maintain Price Schedules.';
87211         END IF;
87212
87213         -- Get the current user's currency precision
87214         SELECT COALESCE(locale_curr_scale, 2) INTO _currencyDecimals
87215         FROM locale, usr
87216         WHERE usr_locale_id = locale_id AND usr_username = CURRENT_USER;
87217
87218         IF (pUpdateType = 'V') THEN
87219                 UPDATE ipsitem
87220                 SET ipsitem_price = noNeg(ROUND( (ipsitem_price + pUpdateBy), _currencyDecimals))
87221                 WHERE (ipsitem_ipshead_id = pIpsHeadId);        
87222
87223                 GET DIAGNOSTICS _itemRows = ROW_COUNT;
87224                 
87225         ELSE
87226                 _percentMultiplier := (1.0 + (pUpdateBy / 100.0));
87227
87228                 UPDATE ipsitem
87229                 SET ipsitem_price = noNeg(ROUND( (ipsitem_price * _percentMultiplier), _currencyDecimals))
87230                 WHERE (ipsitem_ipshead_id = pIpsHeadId);
87231                 
87232                 GET DIAGNOSTICS _itemRows = ROW_COUNT;
87233                 
87234                 IF (pUpdateCharPrices) THEN
87235                         UPDATE ipsitemchar 
87236                         SET ipsitemchar_price = noNeg(ROUND( (ipsitemchar_price * _percentMultiplier), _currencyDecimals))
87237                         FROM ipsitem
87238                         WHERE ipsitemchar_ipsitem_id = ipsitem_id AND ipsitem_ipshead_id = pIpsHeadId;
87239                         
87240                         GET DIAGNOSTICS _charRows = ROW_COUNT;
87241                 END IF;
87242
87243         END IF;
87244         
87245         RETURN _itemRows + _charRows;
87246
87247 END;
87248 $$;
87249
87250
87251 ALTER FUNCTION public.updatepricesbypricingschedule(pipsheadid integer, pupdatetype character, pupdateby numeric, pupdatecharprices boolean) OWNER TO admin;
87252
87253 --
87254 -- TOC entry 2302 (class 1255 OID 146567162)
87255 -- Dependencies: 4536 8
87256 -- Name: updatepricesbyproductcategory(integer, text, character, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
87257 --
87258
87259 CREATE FUNCTION updatepricesbyproductcategory(pprodcatid integer, pprodcatpattern text, pupdatetype character, pupdateby numeric, pupdatecharprices boolean) RETURNS numeric
87260     LANGUAGE plpgsql
87261     AS $$
87262 DECLARE
87263   _percentMultiplier NUMERIC;
87264   _currencyDecimals INTEGER;
87265   _itemRows INTEGER :=0;
87266   _charRows INTEGER :=0;
87267
87268 BEGIN
87269
87270         IF NOT (checkPrivilege('MaintainPricingSchedules')) THEN
87271                 RAISE EXCEPTION 'You do not have privileges to maintain Price Schedules.';
87272         END IF;
87273
87274         -- Get the current user's currency precision
87275         SELECT COALESCE(locale_curr_scale, 2) INTO _currencyDecimals
87276         FROM locale, usr
87277         WHERE usr_locale_id = locale_id AND usr_username = CURRENT_USER;
87278         
87279         _percentMultiplier := (1.0 + (pUpdateBy / 100.0));
87280         
87281         IF (pUpdateType = 'V') THEN
87282         
87283                 IF (pProdCatId IS NOT NULL) THEN
87284                         -- Specified category id
87285                         UPDATE ipsitem 
87286                         SET ipsitem_price = noNeg(ROUND( (ipsitem_price + pUpdateBy), _currencyDecimals ))
87287                         FROM item
87288                         WHERE 
87289                                 ipsitem_item_id = item_id
87290                                 AND item_prodcat_id = pProdCatId;
87291                         
87292                 ELSIF (pProdCatPattern IS NOT NULL) THEN
87293                         -- Pattern match category
87294                         UPDATE ipsitem 
87295                         SET ipsitem_price = noNeg(ROUND( (ipsitem_price + pUpdateBy), _currencyDecimals ))
87296                         FROM item
87297                         WHERE 
87298                                 ipsitem_item_id = item_id
87299                                 AND item_prodcat_id IN (
87300                                         SELECT prodcat_id FROM prodcat 
87301                                         WHERE (prodcat_code ~ pProdCatPattern) 
87302                                 );              
87303                 ELSE
87304                         -- All categories
87305                         UPDATE ipsitem 
87306                         SET ipsitem_price = noNeg(ROUND( (ipsitem_price + pUpdateBy), _currencyDecimals ));
87307                 END IF;
87308                 
87309                 GET DIAGNOSTICS _itemRows = ROW_COUNT;
87310                 
87311         ELSE
87312                 
87313                 IF (pProdCatId IS NOT NULL) THEN
87314                         -- Specified category id
87315                         UPDATE ipsitem 
87316                         SET ipsitem_price = noNeg(ROUND( (ipsitem_price * _percentMultiplier), _currencyDecimals ))
87317                         FROM item
87318                         WHERE 
87319                                 ipsitem_item_id = item_id
87320                                 AND item_prodcat_id = pProdCatId;
87321                                 
87322                         GET DIAGNOSTICS _itemRows = ROW_COUNT;
87323
87324                         IF(pUpdateCharPrices) THEN
87325                                 UPDATE ipsitemchar
87326                                 SET ipsitemchar_price = noNeg(ROUND( (ipsitemchar_price * _percentMultiplier), _currencyDecimals ))
87327                                 FROM ipsitem, item
87328                                 WHERE
87329                                         item_prodcat_id = pProdCatId
87330                                         AND ipsitem_item_id = item_id
87331                                         AND ipsitemchar_ipsitem_id = ipsitem_id;
87332                                 
87333                                 GET DIAGNOSTICS _charRows = ROW_COUNT;
87334                         END IF;
87335                         
87336                 ELSIF (pProdCatPattern IS NOT NULL) THEN
87337                         -- Pattern match category
87338                         UPDATE ipsitem 
87339                         SET ipsitem_price = noNeg(ROUND( (ipsitem_price * _percentMultiplier), _currencyDecimals ))
87340                         FROM item
87341                         WHERE 
87342                                 item_prodcat_id IN (
87343                                         SELECT prodcat_id FROM prodcat 
87344                                         WHERE (prodcat_code ~ pProdCatPattern ) 
87345                                 )
87346                                 AND ipsitem_item_id = item_id;
87347                         
87348                         GET DIAGNOSTICS _itemRows = ROW_COUNT;
87349
87350                         IF(pUpdateCharPrices) THEN
87351                                 UPDATE ipsitemchar
87352                                 SET ipsitemchar_price = noNeg(ROUND( (ipsitemchar_price * _percentMultiplier), _currencyDecimals ))
87353                                 FROM ipsitem, item
87354                                 WHERE
87355                                         item_prodcat_id IN (
87356                                                 SELECT prodcat_id FROM prodcat 
87357                                                 WHERE (prodcat_code ~ pProdCatPattern ) 
87358                                         )
87359                                         AND ipsitem_item_id = item_id
87360                                         AND ipsitemchar_ipsitem_id = ipsitem_id;
87361                                 
87362                                 GET DIAGNOSTICS _charRows = ROW_COUNT;
87363                         END IF;
87364                         
87365                 ELSE
87366                         -- All categories
87367                         UPDATE ipsitem 
87368                         SET ipsitem_price = noNeg(ROUND( (ipsitem_price * _percentMultiplier), _currencyDecimals ));
87369                         
87370                         GET DIAGNOSTICS _itemRows = ROW_COUNT;
87371                         
87372                         IF(pUpdateCharPrices) THEN
87373                                 UPDATE ipsitemchar
87374                                 SET ipsitemchar_price = noNeg(ROUND( (ipsitemchar_price * _percentMultiplier), _currencyDecimals ));
87375                                 
87376                                 GET DIAGNOSTICS _charRows = ROW_COUNT;
87377                         END IF;
87378                         
87379                 END IF;
87380
87381         END IF;
87382
87383         RETURN _itemRows + _charRows;
87384
87385 END;
87386 $$;
87387
87388
87389 ALTER FUNCTION public.updatepricesbyproductcategory(pprodcatid integer, pprodcatpattern text, pupdatetype character, pupdateby numeric, pupdatecharprices boolean) OWNER TO admin;
87390
87391 --
87392 -- TOC entry 2303 (class 1255 OID 146567163)
87393 -- Dependencies: 4536 8
87394 -- Name: updatereorderlevel(integer, integer, integer[]); Type: FUNCTION; Schema: public; Owner: admin
87395 --
87396
87397 CREATE FUNCTION updatereorderlevel(integer, integer, integer[]) RETURNS boolean
87398     LANGUAGE plpgsql
87399     AS $_$
87400 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87401 -- See www.xtuple.com/CPAL for the full text of the software license.
87402 DECLARE
87403   pItemsiteid ALIAS FOR $1;
87404   pDays ALIAS FOR $2;
87405   pPeriods ALIAS FOR $3;
87406   _cursor INTEGER;
87407   _periodid INTEGER;
87408   _usage NUMERIC;
87409   _totalUsage NUMERIC;
87410   _totalDays INTEGER;
87411   _reorderLevel INTEGER;
87412   _averageUsage NUMERIC;
87413   _result       TEXT;
87414
87415 BEGIN
87416
87417   _cursor := 1;
87418   _totalUsage := 0;
87419   _totalDays := 0;
87420
87421   _periodid = pPeriods[_cursor];
87422   WHILE (_periodid IS NOT NULL) LOOP
87423     SELECT COALESCE(SUM(invhist_invqty), 0) INTO _usage
87424     FROM invhist
87425     WHERE ( (invhist_itemsite_id=pItemsiteid)
87426      AND ( invhist_transdate::DATE BETWEEN findPeriodStart(_periodid)
87427                                    AND findPeriodEnd(_periodid) )
87428      AND (invhist_transtype IN ('SH', 'IM')) );
87429
87430     _totalUsage := (_totalUsage + _usage);
87431
87432     _totalDays := ( _totalDays + ( findPeriodEnd(_periodid) -
87433                                    findPeriodStart(_periodid) + 1 ) );
87434
87435     _cursor := (_cursor + 1);
87436     _periodid = pPeriods[_cursor];
87437   END LOOP;
87438
87439   IF (_totalDays > 0) THEN
87440     _reorderLevel := round(_totalUsage / _totalDays * pDays);
87441
87442     SELECT itemsite_stocked INTO _result from itemsite WHERE (itemsite_id=pItemsiteid);
87443     IF (_reorderLevel = 0 AND _result='t') THEN
87444       _reorderLevel := 1;
87445     END IF;
87446     
87447     IF (_reorderLevel > 0) THEN
87448       UPDATE itemsite
87449       SET itemsite_reorderlevel = _reorderLevel
87450       WHERE (itemsite_id=pItemsiteid);
87451     ELSE
87452       UPDATE itemsite
87453       SET itemsite_reorderlevel = 0
87454       WHERE (itemsite_id=pItemsiteid);
87455     END IF;
87456
87457     RETURN TRUE;
87458   ELSE
87459     RETURN FALSE;
87460   END IF;
87461
87462 END;
87463 $_$;
87464
87465
87466 ALTER FUNCTION public.updatereorderlevel(integer, integer, integer[]) OWNER TO admin;
87467
87468 --
87469 -- TOC entry 2305 (class 1255 OID 146567164)
87470 -- Dependencies: 2696 4536 8
87471 -- Name: updatereorderlevel(integer[], integer, boolean, integer[]); Type: FUNCTION; Schema: public; Owner: admin
87472 --
87473
87474 CREATE FUNCTION updatereorderlevel(integer[], integer, boolean, integer[]) RETURNS SETOF reordlvl
87475     LANGUAGE plpgsql
87476     AS $_$
87477 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87478 -- See www.xtuple.com/CPAL for the full text of the software license.
87479 DECLARE
87480   pItemsiteids          ALIAS FOR $1;
87481   pDays                 ALIAS FOR $2;
87482   pAddLeadtime          ALIAS FOR $3;
87483   pPeriodIds            ALIAS FOR $4;
87484   _icursor              INTEGER := 1;
87485   _pcursor              INTEGER := 1;
87486   _totalUsage           NUMERIC := 0;
87487   _totalDays            INTEGER := 0;
87488   _reorderLevel         INTEGER := 0;
87489   _result               TEXT;
87490   _usage                NUMERIC;
87491   _averageUsage         NUMERIC;
87492   _row reordlvl         %ROWTYPE;
87493
87494 BEGIN
87495   -- Validate
87496   IF (pItemsiteIds[1] IS NULL OR pPeriodIds[1] IS NULL) THEN
87497     RETURN;
87498   END IF;
87499   
87500   -- Calculate total days
87501   FOR _pcursor IN 1..ARRAY_UPPER(pPeriodIds,1) 
87502   LOOP
87503     _totalDays := ( _totalDays + ( findPeriodEnd(pPeriodIds[_pcursor]) -
87504                                       findPeriodStart(pPeriodIds[_pcursor]) + 1 ) );
87505   END LOOP;
87506
87507   --  Loop through each itemsite id
87508   FOR _icursor IN 1..ARRAY_UPPER(pItemsiteIds,1)
87509   LOOP
87510       -- Get itemsite data
87511     SELECT itemsite_id,
87512       item_id,
87513       warehous_code,
87514       item_number,
87515       item_descrip1,
87516       itemsite_leadtime,
87517       0,
87518       itemsite_reorderlevel,
87519       0,
87520       0,
87521       0
87522       INTO _row
87523     FROM itemsite
87524       JOIN item ON (itemsite_item_id=item_id)
87525       JOIN whsinfo ON (itemsite_warehous_id=warehous_id)
87526     WHERE (itemsite_id=pItemsiteIds[_icursor]);
87527
87528     IF (FOUND) THEN
87529       IF (pAddLeadtime) THEN
87530         _row.reordlvl_daysofstock := pDays + _row.reordlvl_leadtime;
87531       ELSE
87532         _row.reordlvl_daysofstock := pDays;
87533       END IF;
87534       
87535       --  Loop through each period id
87536       FOR _pcursor IN 1..ARRAY_UPPER(pPeriodIds,1) 
87537       LOOP
87538         -- Sum days and usage shipping and inventory transactions
87539         SELECT COALESCE(SUM(invhist_invqty), 0) INTO _usage
87540         FROM invhist
87541         WHERE ( (invhist_itemsite_id=pItemsiteIds[_icursor])
87542          AND ( invhist_transdate::DATE BETWEEN findPeriodStart(pPeriodIds[_pcursor])
87543                                        AND findPeriodEnd(pPeriodIds[_pcursor]) )
87544          AND (invhist_transtype IN ('SH', 'IM')) );
87545
87546         _totalUsage := (_totalUsage + _usage);
87547
87548       END LOOP;
87549
87550       -- Calculate reorder level
87551       IF (_totalDays > 0) THEN
87552         _reorderLevel := round(_totalUsage / _totalDays * _row.reordlvl_daysofstock);
87553       END IF;
87554   
87555       IF (_reorderLevel <= 0) THEN
87556         _reorderLevel := 0;
87557       END IF;
87558
87559       SELECT itemsite_stocked INTO _result from itemsite WHERE (itemsite_id=pItemsiteIds[_icursor]);
87560       IF (_reorderLevel = 0 AND _result='t') THEN
87561         _reorderLevel := 1;
87562       END IF;
87563
87564       -- Set values
87565       _row.reordlvl_total_days          := _totalDays;
87566       _row.reordlvl_total_usage := _totalUsage;
87567       _row.reordlvl_calc_level          := _reorderLevel;
87568
87569       -- Return result
87570       RETURN NEXT _row;
87571     END IF;
87572
87573     _usage              := 0;
87574     _averageUsage       := 0;
87575     _totalUsage         := 0;
87576     _reorderLevel       := 0;
87577   END LOOP;
87578
87579   RETURN;
87580 END;
87581 $_$;
87582
87583
87584 ALTER FUNCTION public.updatereorderlevel(integer[], integer, boolean, integer[]) OWNER TO admin;
87585
87586 --
87587 -- TOC entry 2306 (class 1255 OID 146567165)
87588 -- Dependencies: 4536 8
87589 -- Name: updateretainedearnings(integer); Type: FUNCTION; Schema: public; Owner: admin
87590 --
87591
87592 CREATE FUNCTION updateretainedearnings(integer) RETURNS integer
87593     LANGUAGE plpgsql
87594     AS $_$
87595 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87596 -- See www.xtuple.com/CPAL for the full text of the software license.
87597 DECLARE
87598   pYearPeriodid ALIAS FOR $1;
87599   _r RECORD;
87600   _n RECORD;
87601   _c RECORD;
87602   _beginningPeriodid INTEGER;
87603   _trialbalid INTEGER;
87604   _accntid INTEGER;
87605   _totalProfitLoss      NUMERIC;
87606   _periodid INTEGER;
87607   _forwardupdate INTEGER;
87608 BEGIN
87609
87610 --  First thing we need to do is to get the yearperiod
87611
87612   SELECT * INTO _r FROM yearperiod where yearperiod_id = pYearPeriodid;
87613
87614   IF (NOT FOUND) THEN
87615     RETURN -6;
87616   END IF;
87617
87618 --  Now we need to find the next yearperiod
87619
87620   SELECT * INTO _n FROM yearperiod WHERE yearperiod_start = _r.yearperiod_end + interval '1 day';
87621
87622   IF (NOT FOUND) THEN
87623     RETURN -4;
87624   END IF;
87625
87626 --  Now we have to find where to stick the end of year data
87627
87628   SELECT period_id INTO _periodid FROM period WHERE period_start = _n.yearperiod_start;
87629
87630   IF (NOT FOUND) THEN
87631     RETURN -8;
87632   END IF;
87633
87634 --  Loop through companies and process each one
87635
87636   IF (coalesce(fetchMetricValue('GLCompanySize'),0) = 0) THEN
87637   --  Process for installs not using company segment
87638   --  Now we need to get the default account number for year end closing
87639
87640     SELECT CAST ( metric_value AS integer ) INTO _accntid FROM metric WHERE metric_name = 'YearEndEquityAccount';
87641
87642     IF (NOT FOUND) THEN
87643       RETURN -7;
87644     END IF;
87645
87646   --  So far so good.  Now we need to calculate the profit-loss for the year that we are closing
87647
87648     SELECT SUM(gltrans_amount) INTO _totalProfitLoss
87649      FROM gltrans, accnt
87650      WHERE ( (gltrans_accnt_id = accnt_id)
87651        AND   (accnt_type IN ( 'R', 'E' ) )
87652        AND   (gltrans_posted)
87653        AND   (NOT gltrans_deleted)
87654        AND   (gltrans_date between _r.yearperiod_start and _r.yearperiod_end ) );
87655     IF (_totalProfitLoss IS NULL) THEN
87656       _totalProfitLoss := 0;
87657     END IF;
87658
87659   -- Get the trailbal_id
87660
87661     SELECT trialbal_id INTO _trialbalid
87662       FROM trialbal
87663      WHERE ( (trialbal_period_id = _periodid )
87664        AND   (trialbal_accnt_id = _accntid) );
87665
87666     IF (NOT FOUND) THEN
87667       RETURN -9;
87668     END IF;
87669
87670   -- Lets do the update for the trialbal
87671
87672     UPDATE trialbal
87673        SET trialbal_beginning = trialbal_beginning - trialbal_yearend + _totalProfitLoss,
87674            trialbal_ending = trialbal_beginning - trialbal_yearend - trialbal_debits + trialbal_credits + _totalProfitLoss,
87675            trialbal_yearend = _totalProfitLoss
87676      WHERE trialbal_id = _trialbalid;
87677
87678   -- Now the forward update
87679
87680     SELECT forwardupdatetrialbalance(_trialbalid) INTO _forwardupdate;
87681     
87682   ELSE  -- Process for a multi-company set up
87683   
87684     FOR _c IN
87685       SELECT company_number, company_yearend_accnt_id
87686       FROM company
87687     LOOP
87688   --  Calculate the profit-loss for the year that we are closing
87689
87690       SELECT SUM(gltrans_amount) INTO _totalProfitLoss
87691        FROM gltrans, accnt
87692        WHERE ( (gltrans_accnt_id = accnt_id)
87693          AND   (accnt_type IN ( 'R', 'E' ) )
87694          AND   (gltrans_posted)
87695          AND   (NOT gltrans_deleted)
87696          AND   (accnt_company = _c.company_number)
87697          AND   (gltrans_date between _r.yearperiod_start and _r.yearperiod_end ) );
87698       IF(_totalProfitLoss IS NULL) THEN
87699         _totalProfitLoss := 0;
87700       END IF;
87701
87702     -- Get the trailbal_id
87703
87704       SELECT trialbal_id INTO _trialbalid
87705         FROM trialbal
87706           JOIN accnt ON (trialbal_accnt_id=accnt_id)
87707        WHERE ( (trialbal_period_id = _periodid )
87708          AND   (trialbal_accnt_id = _c.company_yearend_accnt_id) );
87709
87710       IF (NOT FOUND) THEN
87711         -- Create a trial balance record
87712         SELECT NEXTVAL('trialbal_trialbal_id_seq') INTO _trialbalid;
87713         INSERT INTO trialbal
87714           ( trialbal_id, trialbal_accnt_id, trialbal_period_id,
87715             trialbal_beginning, trialbal_dirty,
87716             trialbal_ending,
87717             trialbal_credits,
87718             trialbal_debits,
87719             trialbal_yearend )
87720         VALUES
87721           ( _trialbalid, _c.company_yearend_accnt_id, _periodid,
87722             _totalProfitLoss, TRUE,
87723             _totalProfitLoss,
87724             0,
87725             0,
87726             _totalProfitLoss );
87727       ELSE
87728         -- Lets do the update for the trialbal
87729         UPDATE trialbal
87730            SET trialbal_beginning = trialbal_beginning - trialbal_yearend + _totalProfitLoss,
87731                trialbal_ending = trialbal_beginning - trialbal_yearend - trialbal_debits + trialbal_credits + _totalProfitLoss,
87732                trialbal_yearend = _totalProfitLoss
87733          WHERE trialbal_id = _trialbalid;
87734       END IF;
87735
87736     -- Now the forward update
87737
87738       SELECT forwardupdatetrialbalance(_trialbalid) INTO _forwardupdate;
87739
87740     END LOOP;
87741   END IF;
87742
87743   RETURN 0;
87744
87745 END;
87746 $_$;
87747
87748
87749 ALTER FUNCTION public.updateretainedearnings(integer) OWNER TO admin;
87750
87751 --
87752 -- TOC entry 2307 (class 1255 OID 146567166)
87753 -- Dependencies: 4536 8
87754 -- Name: updatesoracost(integer, text, boolean, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
87755 --
87756
87757 CREATE FUNCTION updatesoracost(integer, text, boolean, numeric, boolean) RETURNS integer
87758     LANGUAGE plpgsql
87759     AS $_$
87760 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87761 -- See www.xtuple.com/CPAL for the full text of the software license.
87762 DECLARE
87763   pItemid       ALIAS FOR $1;
87764   pCosttype     ALIAS FOR $2;
87765   pLevel        ALIAS FOR $3;
87766   pCost         ALIAS FOR $4;
87767   pUpdateActual ALIAS FOR $5;
87768
87769 BEGIN
87770     IF (pUpdateActual) THEN
87771         RETURN updateCost(pItemid, pCosttype, pLevel, pCost);
87772     ELSE
87773         RETURN updateStdCost(pItemid, pCosttype, pLevel, pCost);
87774     END IF;
87775 END;
87776 $_$;
87777
87778
87779 ALTER FUNCTION public.updatesoracost(integer, text, boolean, numeric, boolean) OWNER TO admin;
87780
87781 --
87782 -- TOC entry 2309 (class 1255 OID 146567168)
87783 -- Dependencies: 4536 8
87784 -- Name: updatestdcost(integer, text, boolean, numeric); Type: FUNCTION; Schema: public; Owner: admin
87785 --
87786
87787 CREATE FUNCTION updatestdcost(integer, text, boolean, numeric) RETURNS integer
87788     LANGUAGE plpgsql
87789     AS $_$
87790 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87791 -- See www.xtuple.com/CPAL for the full text of the software license.
87792 DECLARE
87793     pItemid     ALIAS FOR $1;
87794     pCostType   ALIAS FOR $2;
87795     pLevel      ALIAS FOR $3;
87796     pCost       ALIAS FOR $4;
87797     _newCost    NUMERIC;
87798     _oldCost    NUMERIC := 0;
87799     _itemcostid INTEGER;
87800     _updateRet  BOOLEAN;
87801     _itemNumber TEXT;
87802
87803 BEGIN
87804     IF (pCost IS NULL) THEN
87805         _newCost = 0;
87806     ELSE
87807         _newCost = pCost;
87808     END IF;
87809
87810     SELECT itemcost_id, itemcost_stdCost, item_number
87811         INTO _itemcostid, _oldCost, _itemNumber
87812     FROM itemcost, costelem, item
87813     WHERE ((itemcost_costelem_id=costelem_id)
87814       AND  (itemcost_item_id=item_id)
87815       AND  (item_id=pItemid)
87816       AND  (itemcost_lowlevel=pLevel)
87817       AND  (costelem_type=pCosttype));
87818 --    RAISE NOTICE 'updateStdCost(%, %, %, %) has itemcost_id % and stdcost %',
87819 --                              pItemid, pCostType, plevel, _newCost, _itemcostid, _oldCost;
87820
87821     IF (NOT FOUND) AND (_newCost > 0) THEN
87822         SELECT NEXTVAL('itemcost_itemcost_id_seq') INTO _itemcostid;
87823         RAISE NOTICE 'updateStdCost() inserting itemcost_id %', _itemcostid;
87824         INSERT INTO itemcost
87825             (itemcost_id, itemcost_item_id, itemcost_costelem_id,
87826              itemcost_lowlevel, itemcost_stdcost, itemcost_posted,
87827              itemcost_actcost, itemcost_updated)
87828         SELECT
87829               _itemcostid, pItemid, costelem_id,
87830               pLevel, _newCost, CURRENT_DATE,
87831               0, CURRENT_DATE
87832         FROM costelem
87833         WHERE (costelem_type=pCosttype);
87834     END IF;
87835
87836     IF (_itemcostid IS NOT NULL) THEN
87837         SELECT updateStdCost(_itemcostid, _newCost, _oldCost, 'Post Cost',
87838                ('Set Standard Cost - ' || pCosttype || ' for item ' || _itemNumber)) INTO _updateRet;
87839         IF (_updateRet) THEN
87840             RETURN _itemcostid;
87841         END IF;
87842     END IF;
87843
87844     RETURN -1;
87845 END;
87846 $_$;
87847
87848
87849 ALTER FUNCTION public.updatestdcost(integer, text, boolean, numeric) OWNER TO admin;
87850
87851 --
87852 -- TOC entry 2308 (class 1255 OID 146567167)
87853 -- Dependencies: 4536 8
87854 -- Name: updatestdcost(integer, numeric, numeric, text, text); Type: FUNCTION; Schema: public; Owner: admin
87855 --
87856
87857 CREATE FUNCTION updatestdcost(integer, numeric, numeric, text, text) RETURNS boolean
87858     LANGUAGE plpgsql
87859     AS $_$
87860 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
87861 -- See www.xtuple.com/CPAL for the full text of the software license.
87862 DECLARE
87863     pItemcostid ALIAS FOR $1;
87864     pNewcost    ALIAS FOR $2;
87865     pOldcost    ALIAS FOR $3;
87866     pDocNumber  ALIAS FOR $4;
87867     pNotes      ALIAS FOR $5;
87868     _itemcostid INTEGER;
87869     _r          RECORD;
87870     _newcost    NUMERIC;
87871     _oldcost    NUMERIC;
87872
87873 BEGIN
87874   IF (pNewcost IS NULL) THEN
87875     _newcost := 0;
87876   ELSE
87877     _newcost := pNewcost;
87878   END IF;
87879   IF (pOldcost IS NULL) THEN
87880     _oldcost := 0;
87881   ELSE
87882     _oldcost := pOldcost;
87883   END IF;
87884
87885   IF (_newcost > 0) THEN
87886     UPDATE itemcost
87887     SET itemcost_stdcost=_newcost,
87888         itemcost_posted=CURRENT_DATE
87889     WHERE (itemcost_id=pItemcostid);
87890   END IF;
87891
87892 --  Distribute to G/L, debit Inventory Asset, credit Inventory Cost Variance
87893   FOR _r IN SELECT itemsite_id, (itemsite_qtyonhand + itemsite_nnqoh) AS totalQty,
87894                    costcat_invcost_accnt_id, costcat_asset_accnt_id,
87895                    itemsite_costmethod
87896             FROM itemcost, itemsite, costcat
87897             WHERE ( (itemsite_item_id=itemcost_item_id)
87898              AND (itemsite_costcat_id=costcat_id)
87899              AND (itemsite_costmethod != 'A')
87900              AND ((itemsite_qtyonhand + itemsite_nnqoh) <> 0)
87901              AND (itemcost_id=pItemcostid) ) LOOP
87902 --    IF (_newcost <> _oldcost) THEN
87903 --      RAISE NOTICE 'itemcost_id = %, Qty = %, Old Cost = %, New Cost = %', pItemcostid, _r.totalQty, _oldcost, _newcost;
87904 --    END IF;
87905     PERFORM insertGLTransaction( 'P/D', '', pDocNumber, pNotes,
87906                                  _r.costcat_invcost_accnt_id, _r.costcat_asset_accnt_id, _r.itemsite_id,
87907                                  ((_newcost - _oldcost) * _r.totalQty),
87908                                  CURRENT_DATE );
87909 --  Update Itemsite Value if not Average Cost
87910     IF (_r.itemsite_costmethod <> 'A') THEN
87911 --      RAISE NOTICE 'itemsite_id = %, Qty = %, New Cost = %', _r.itemsite_id, _r.totalQty, _newcost;
87912       UPDATE itemsite SET itemsite_value=(_r.totalQty * stdCost(itemsite_item_id))
87913       WHERE (itemsite_id=_r.itemsite_id);
87914     END IF;
87915   END LOOP;
87916
87917   IF (_newcost = 0) THEN
87918     DELETE FROM itemcost
87919     WHERE (itemcost_id=pItemcostid);
87920
87921     RETURN FALSE;
87922   END IF;
87923
87924   IF ( SELECT metric_value
87925         FROM metric
87926         WHERE ((metric_name = 'EnableAsOfQOH')
87927         AND (metric_value = 't'))) THEN
87928     IF (pNewcost IS NOT NULL) THEN
87929       _newcost := pNewcost;
87930     END IF;
87931     IF (pOldcost IS NULL) THEN
87932       _oldcost := 0;
87933     ELSE
87934       _oldcost := pOldcost;
87935     END IF;
87936   --  Distribute to G/L, debit Inventory Asset, credit Inventory Cost Variance
87937     PERFORM postValueIntoInvBalance(
87938                   itemsite_id,
87939                   current_date,
87940                   asofinvqty(itemsite_id,current_date),
87941                   asofinvnn(itemsite_id,current_date),
87942                   _oldcost,
87943                   _newcost)
87944        FROM itemsite
87945        JOIN item ON (itemsite_item_id=item_id)
87946        JOIN itemcost ON (itemcost_item_id=item_id)
87947       WHERE((itemsite_costmethod = 'S')
87948         AND (itemcost_id=pItemcostid));
87949   END IF;
87950
87951   RETURN TRUE;
87952
87953 END;
87954 $_$;
87955
87956
87957 ALTER FUNCTION public.updatestdcost(integer, numeric, numeric, text, text) OWNER TO admin;
87958
87959 --
87960 -- TOC entry 2310 (class 1255 OID 146567169)
87961 -- Dependencies: 4536 8
87962 -- Name: updatetodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, boolean, text); Type: FUNCTION; Schema: public; Owner: admin
87963 --
87964
87965 CREATE FUNCTION updatetodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, boolean, text) RETURNS integer
87966     LANGUAGE plpgsql
87967     AS $_$
87968 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
87969 -- See www.xtuple.com/CPAL for the full text of the software license.
87970 BEGIN
87971   RETURN updateTodoItem($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, NULL);
87972 END;
87973 $_$;
87974
87975
87976 ALTER FUNCTION public.updatetodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, boolean, text) OWNER TO admin;
87977
87978 --
87979 -- TOC entry 2313 (class 1255 OID 146567170)
87980 -- Dependencies: 4536 8
87981 -- Name: updatetodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, boolean, text, integer); Type: FUNCTION; Schema: public; Owner: admin
87982 --
87983
87984 CREATE FUNCTION updatetodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, boolean, text, integer) RETURNS integer
87985     LANGUAGE plpgsql
87986     AS $_$
87987 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
87988 -- See www.xtuple.com/CPAL for the full text of the software license.
87989 DECLARE
87990   ptodoitemid ALIAS FOR  $1;
87991   pusername   ALIAS FOR  $2;
87992   pname       ALIAS FOR  $3;
87993   pdesc       ALIAS FOR  $4;
87994   pincdtid    ALIAS FOR  $5;
87995   pcrmacctid  ALIAS FOR  $6;
87996   pOpheadid   ALIAS FOR  $7;
87997   pstarted    ALIAS FOR  $8;
87998   pdue        ALIAS FOR  $9;
87999   pstatus     ALIAS FOR $10;
88000   passigned   ALIAS FOR $11;
88001   pcompleted  ALIAS FOR $12;
88002   ppriority   ALIAS FOR $13;
88003   pnotes      ALIAS FOR $14;
88004   pactive     ALIAS FOR $15;
88005   powner        ALIAS FOR $16;
88006   pcntctid      ALIAS FOR $17;
88007
88008   _priority   INTEGER         := ppriority;
88009   _status     CHARACTER(1)    := pstatus;
88010   _incdtid    INTEGER         := pincdtid;
88011   _crmacctid  INTEGER         := pcrmacctid;
88012   _opheadid   INTEGER         := pOpheadid;
88013   _assigned   DATE            := passigned;
88014   _active     BOOL            := pactive;
88015   _result     INTEGER;
88016
88017 BEGIN
88018   IF (pusername IS NULL OR pusername = '') THEN
88019     RETURN -1;
88020   END IF;
88021
88022   IF (pname IS NULL OR pname = '') THEN
88023     RETURN -2;
88024   END IF;
88025
88026   IF (pdue IS NULL) THEN
88027     RETURN -3;
88028   END IF;
88029
88030   IF (ptodoitemid IS NULL OR ptodoitemid <= 0) THEN
88031     RETURN -10;
88032   END IF;
88033
88034   IF (pcompleted IS NOT NULL) THEN
88035     _status := 'C';
88036   ELSIF (pstatus IS NULL AND pstarted IS NOT NULL) THEN
88037     _status := 'I';
88038   ELSIF (pstatus IS NULL) THEN
88039     _status := 'N';
88040   END IF;
88041
88042   IF (_incdtid <= 0) THEN
88043     _incdtid := NULL;
88044   END IF;
88045
88046   IF (_crmacctid <= 0) THEN
88047     _crmacctid := NULL;
88048   END IF;
88049
88050   IF (_opheadid <= 0) THEN
88051     _opheadid := NULL;
88052   END IF;
88053
88054   IF (_priority <= 0) THEN
88055     _priority := NULL;
88056   END IF;
88057
88058   IF (_assigned IS NULL) THEN
88059     _assigned := CURRENT_DATE;
88060   END IF;
88061
88062   IF (_active IS NULL) THEN
88063     _active := TRUE;
88064   END IF;
88065
88066   UPDATE todoitem SET
88067       todoitem_username=pusername, todoitem_name=pname, todoitem_description=pdesc,
88068       todoitem_incdt_id=_incdtid, todoitem_status=_status,
88069       todoitem_active=_active, todoitem_start_date=pstarted,
88070       todoitem_due_date=pdue, todoitem_assigned_date=_assigned,
88071       todoitem_completed_date=pcompleted, todoitem_priority_id=_priority,
88072       todoitem_notes=pnotes, todoitem_crmacct_id=_crmacctid,
88073       todoitem_ophead_id=_opheadid, todoitem_owner_username=powner,
88074       todoitem_cntct_id=pcntctid
88075   WHERE (todoitem_id=ptodoitemid);
88076
88077   RETURN ptodoitemid;
88078 END;
88079 $_$;
88080
88081
88082 ALTER FUNCTION public.updatetodoitem(integer, text, text, text, integer, integer, integer, date, date, character, date, date, integer, text, boolean, text, integer) OWNER TO admin;
88083
88084 --
88085 -- TOC entry 2314 (class 1255 OID 146567171)
88086 -- Dependencies: 4536 8
88087 -- Name: usedefaultlocation(integer); Type: FUNCTION; Schema: public; Owner: admin
88088 --
88089
88090 CREATE FUNCTION usedefaultlocation(integer) RETURNS boolean
88091     LANGUAGE plpgsql
88092     AS $_$
88093 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88094 -- See www.xtuple.com/CPAL for the full text of the software license.
88095 DECLARE
88096   pItemsiteid ALIAS FOR $1;
88097   _p RECORD;
88098
88099 BEGIN
88100
88101   SELECT itemsite_location_id,
88102          LENGTH(itemsite_location) AS locationlength INTO _p
88103   FROM itemsite
88104   WHERE (itemsite_id=pItemsiteid);
88105
88106   IF (NOT FOUND) THEN
88107     RETURN FALSE;
88108
88109   ELSIF (_p.itemsite_location_id <> -1) THEN
88110     RETURN TRUE;
88111
88112   ELSIF (_p.locationlength > 0) THEN
88113     RETURN TRUE;
88114
88115   ELSE
88116     RETURN FALSE;
88117   END IF;
88118
88119 END;
88120 $_$;
88121
88122
88123 ALTER FUNCTION public.usedefaultlocation(integer) OWNER TO admin;
88124
88125 --
88126 -- TOC entry 2315 (class 1255 OID 146567172)
88127 -- Dependencies: 8
88128 -- Name: usercancreateusers(text); Type: FUNCTION; Schema: public; Owner: admin
88129 --
88130
88131 CREATE FUNCTION usercancreateusers(text) RETURNS boolean
88132     LANGUAGE sql
88133     AS $_$
88134 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88135 -- See www.xtuple.com/CPAL for the full text of the software license.
88136 SELECT rolcreaterole OR rolsuper
88137   FROM pg_roles
88138  WHERE rolname=($1);
88139 $_$;
88140
88141
88142 ALTER FUNCTION public.usercancreateusers(text) OWNER TO admin;
88143
88144 --
88145 -- TOC entry 2316 (class 1255 OID 146567173)
88146 -- Dependencies: 4536 8
88147 -- Name: usercanlogin(text); Type: FUNCTION; Schema: public; Owner: admin
88148 --
88149
88150 CREATE FUNCTION usercanlogin(pusername text) RETURNS boolean
88151     LANGUAGE plpgsql
88152     AS $$
88153 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88154 -- See www.xtuple.com/CPAL for the full text of the software license.
88155 DECLARE
88156   _isactive  BOOLEAN;
88157   _mode      TEXT;
88158 BEGIN
88159   IF (isDBA(pUsername) OR userCanCreateUsers(pUsername)) THEN
88160     RETURN TRUE;
88161
88162   ELSIF (pg_has_role(pUsername, 'xtrole', 'member')) THEN
88163     _mode := COALESCE(fetchMetricText('AllowedUserLogins'), '');
88164
88165     IF (_mode = 'AdminOnly') THEN
88166       RETURN FALSE; -- administrators were checked above
88167     END IF;
88168
88169     IF (_mode NOT IN ('AdminOnly','ActiveOnly','Any')) THEN
88170       _mode := 'ActiveOnly';
88171     END IF;
88172
88173     SELECT (usrpref_value = 't') INTO _isactive
88174       FROM usrpref
88175      WHERE usrpref_username = pUsername
88176        AND usrpref_name = 'active';
88177
88178     IF (_isactive OR _mode = 'Any') THEN
88179       RETURN TRUE;
88180     END IF;
88181   END IF;
88182
88183   RETURN FALSE;
88184 END;
88185 $$;
88186
88187
88188 ALTER FUNCTION public.usercanlogin(pusername text) OWNER TO admin;
88189
88190 --
88191 -- TOC entry 2317 (class 1255 OID 146567174)
88192 -- Dependencies: 4536 8
88193 -- Name: userid(text); Type: FUNCTION; Schema: public; Owner: admin
88194 --
88195
88196 CREATE FUNCTION userid(text) RETURNS integer
88197     LANGUAGE plpgsql
88198     AS $_$
88199 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88200 -- See www.xtuple.com/CPAL for the full text of the software license.
88201 DECLARE
88202   pUsername ALIAS FOR $1;
88203   _userId INTEGER;
88204
88205 BEGIN
88206
88207   SELECT usesysid INTO _userId
88208   FROM pg_user
88209   WHERE (usename=pUsername);
88210
88211   IF (FOUND) THEN
88212     RETURN _userId;
88213   ELSE
88214     RETURN -1;
88215   END IF;
88216
88217 END;
88218 $_$;
88219
88220
88221 ALTER FUNCTION public.userid(text) OWNER TO admin;
88222
88223 --
88224 -- TOC entry 2318 (class 1255 OID 146567175)
88225 -- Dependencies: 4536 8
88226 -- Name: validateorderqty(integer, numeric, boolean); Type: FUNCTION; Schema: public; Owner: admin
88227 --
88228
88229 CREATE FUNCTION validateorderqty(integer, numeric, boolean) RETURNS numeric
88230     LANGUAGE plpgsql
88231     AS $_$
88232 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88233 -- See www.xtuple.com/CPAL for the full text of the software license.
88234 DECLARE
88235   pItemsiteid ALIAS FOR $1;
88236   pQty ALIAS FOR $2;
88237   pManual ALIAS FOR $3;
88238   _p RECORD;
88239   _qty NUMERIC;
88240
88241 BEGIN
88242
88243   _qty := pQty;
88244
88245   SELECT itemsite_useparams,
88246          CASE WHEN (itemsite_useparams) THEN itemsite_useparamsmanual ELSE FALSE END AS itemsite_useparamsmanual,
88247          CASE WHEN (itemsite_useparams) THEN itemsite_minordqty ELSE 0.0 END AS itemsite_minordqty,
88248          CASE WHEN (itemsite_useparams) THEN itemsite_multordqty ELSE 0.0 END AS itemsite_multordqty,
88249          item_fractional, item_type INTO _p
88250   FROM itemsite, item
88251   WHERE ( (itemsite_item_id=item_id)
88252    AND (itemsite_id=pItemsiteid) );
88253
88254   IF ( (pManual AND (_p.itemsite_useparamsmanual)) OR
88255        ((NOT pManual) AND (_p.itemsite_useparams)) ) THEN
88256
88257     IF (_qty < _p.itemsite_minordqty) THEN
88258       _qty := _p.itemsite_minordqty;
88259     END IF;
88260
88261     IF ( (_p.itemsite_multordqty > 0) AND ((_qty % _p.itemsite_multordqty) > 0) ) THEN
88262       _qty := ((TRUNC(_qty / _p.itemsite_multordqty) * _p.itemsite_multordqty) + _p.itemsite_multordqty);
88263     END IF;
88264
88265   END IF;
88266
88267   _qty := roundQty(_p.item_fractional, _qty);
88268
88269   RETURN _qty;
88270
88271 END;
88272 $_$;
88273
88274
88275 ALTER FUNCTION public.validateorderqty(integer, numeric, boolean) OWNER TO admin;
88276
88277 --
88278 -- TOC entry 2319 (class 1255 OID 146567176)
88279 -- Dependencies: 4536 8
88280 -- Name: validlocation(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
88281 --
88282
88283 CREATE FUNCTION validlocation(integer, integer) RETURNS boolean
88284     LANGUAGE plpgsql
88285     AS $_$
88286 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88287 -- See www.xtuple.com/CPAL for the full text of the software license.
88288 DECLARE
88289   pLocationid ALIAS FOR $1;
88290   pItemsiteid ALIAS FOR $2;
88291   _p RECORD;
88292   
88293 BEGIN
88294
88295   SELECT location_restrict INTO _p
88296   FROM location, itemsite
88297   WHERE ( (location_warehous_id=itemsite_warehous_id)
88298     AND (itemsite_id=pItemsiteid)
88299     AND (location_id=pLocationid) );
88300
88301   IF (FOUND) THEN
88302     IF (_p.location_restrict) THEN
88303
88304       SELECT locitem_id INTO _p
88305       FROM locitem, itemsite
88306       WHERE ( (locitem_item_id=itemsite_item_id)
88307        AND (itemsite_id=pItemsiteid)
88308        AND (locitem_location_id=pLocationid) );
88309
88310       IF (FOUND) THEN
88311         RETURN TRUE;
88312       END IF;
88313
88314     ELSE
88315       RETURN TRUE;
88316     END IF;
88317
88318   ELSE
88319     RETURN FALSE;
88320   END IF;
88321
88322   RETURN FALSE;
88323
88324 END;
88325 $_$;
88326
88327
88328 ALTER FUNCTION public.validlocation(integer, integer) OWNER TO admin;
88329
88330 --
88331 -- TOC entry 2320 (class 1255 OID 146567177)
88332 -- Dependencies: 4536 8
88333 -- Name: valueatshipping(integer); Type: FUNCTION; Schema: public; Owner: admin
88334 --
88335
88336 CREATE FUNCTION valueatshipping(plineitemid integer) RETURNS numeric
88337     LANGUAGE plpgsql
88338     AS $$
88339 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88340 -- See www.xtuple.com/CPAL for the full text of the software license.
88341 BEGIN
88342   RETURN valueAtShipping('SO', plineitemid);
88343 END;
88344 $$;
88345
88346
88347 ALTER FUNCTION public.valueatshipping(plineitemid integer) OWNER TO admin;
88348
88349 --
88350 -- TOC entry 2321 (class 1255 OID 146567178)
88351 -- Dependencies: 4536 8
88352 -- Name: valueatshipping(text, integer); Type: FUNCTION; Schema: public; Owner: admin
88353 --
88354
88355 CREATE FUNCTION valueatshipping(pordertype text, plineitemid integer) RETURNS numeric
88356     LANGUAGE plpgsql
88357     AS $$
88358 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88359 -- See www.xtuple.com/CPAL for the full text of the software license.
88360 DECLARE
88361   _value NUMERIC := 0.0;
88362
88363 BEGIN
88364
88365   IF (pordertype NOT IN ('SO', 'TO')) THEN
88366     RAISE EXCEPTION '% is not a valid order type', pordertype;
88367   END IF;
88368
88369   SELECT COALESCE(SUM(shipitem_value), 0.0) INTO _value
88370   FROM shipitem JOIN shiphead ON (shipitem_shiphead_id=shiphead_id)
88371   WHERE ( (NOT shiphead_shipped)
88372     AND  (shiphead_order_type=pordertype)
88373     AND  (shipitem_orderitem_id=plineitemid) );
88374
88375   RETURN _value;
88376
88377 END;
88378 $$;
88379
88380
88381 ALTER FUNCTION public.valueatshipping(pordertype text, plineitemid integer) OWNER TO admin;
88382
88383 --
88384 -- TOC entry 2322 (class 1255 OID 146567179)
88385 -- Dependencies: 4536 8
88386 -- Name: voidapcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
88387 --
88388
88389 CREATE FUNCTION voidapcheck(integer) RETURNS integer
88390     LANGUAGE plpgsql
88391     AS $_$
88392 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88393 -- See www.xtuple.com/CPAL for the full text of the software license.
88394 BEGIN
88395   RAISE NOTICE 'voidAPCheck() is deprecated - use voidCheck() instead';
88396   RETURN voidCheck($1);
88397 END;
88398 $_$;
88399
88400
88401 ALTER FUNCTION public.voidapcheck(integer) OWNER TO admin;
88402
88403 --
88404 -- TOC entry 2289 (class 1255 OID 146567180)
88405 -- Dependencies: 4536 8
88406 -- Name: voidapopenvoucher(integer); Type: FUNCTION; Schema: public; Owner: admin
88407 --
88408
88409 CREATE FUNCTION voidapopenvoucher(integer) RETURNS integer
88410     LANGUAGE plpgsql
88411     AS $_$
88412 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88413 -- See www.xtuple.com/CPAL for the full text of the software license.
88414 DECLARE
88415   pApopenid ALIAS FOR $1;
88416 BEGIN
88417   RETURN voidApopenVoucher(pApopenid, fetchJournalNumber('AP-VO'));
88418 END;
88419 $_$;
88420
88421
88422 ALTER FUNCTION public.voidapopenvoucher(integer) OWNER TO admin;
88423
88424 --
88425 -- TOC entry 2290 (class 1255 OID 146567181)
88426 -- Dependencies: 4536 8
88427 -- Name: voidapopenvoucher(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
88428 --
88429
88430 CREATE FUNCTION voidapopenvoucher(integer, integer) RETURNS integer
88431     LANGUAGE plpgsql
88432     AS $_$
88433 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88434 -- See www.xtuple.com/CPAL for the full text of the software license.
88435 DECLARE
88436   pApopenid ALIAS FOR $1;
88437   pJournalNumber ALIAS FOR $2;
88438   _apopenid INTEGER;
88439   _apcreditapplyid INTEGER;
88440   _reference    TEXT;
88441   _result INTEGER;
88442   _sequence INTEGER;
88443   _totalAmount_base NUMERIC;
88444   _totalAmount NUMERIC;
88445   _itemAmount_base NUMERIC;
88446   _itemAmount NUMERIC;
88447   _test INTEGER;
88448   _a RECORD;
88449   _d RECORD;
88450   _g RECORD;
88451   _p RECORD;
88452   _n RECORD;
88453   _r RECORD;
88454   _costx RECORD;
88455   _pExplain BOOLEAN;
88456   _pLowLevel BOOLEAN;
88457   _exchGainFreight NUMERIC;
88458   _firstExchDateFreight DATE;
88459   _tmpTotal             NUMERIC;
88460   _glDate               DATE;
88461
88462 BEGIN
88463
88464   _totalAmount_base := 0;
88465   _totalAmount := 0;
88466   SELECT fetchGLSequence() INTO _sequence;
88467
88468 --  Cache APOpen Information
88469   SELECT apopen.* INTO _n
88470   FROM apopen
88471   WHERE ( (apopen_doctype='V')
88472     AND   (apopen_id=pApopenid) );
88473   IF (NOT FOUND) THEN
88474     RAISE EXCEPTION 'Cannot Void Voucher #% as apopen not found', pApopenid;
88475   END IF;
88476
88477 --  Cache Voucher Infomation
88478   SELECT vohead.*,
88479          vend_number || '-' || vend_name || ' ' || vohead_reference
88480                                                           AS glnotes,
88481          COALESCE(pohead_orderdate, vohead_docdate) AS pohead_orderdate,
88482          COALESCE(pohead_curr_id, vohead_curr_id) AS pohead_curr_id INTO _p
88483   FROM vohead JOIN vendinfo ON (vend_id=vohead_vend_id)
88484               LEFT OUTER JOIN pohead ON (vohead_pohead_id = pohead_id)
88485   WHERE (vohead_number=_n.apopen_docnumber);
88486   IF (NOT FOUND) THEN
88487     RAISE EXCEPTION 'Cannot Void Voucher #% as vohead not found', _n.apopen_docnumber;
88488   END IF;
88489
88490   _glDate := COALESCE(_p.vohead_gldistdate, _p.vohead_distdate);
88491
88492 -- there is no currency gain/loss on items, see issue 3892,
88493 -- but there might be on freight, which is first encountered at p/o receipt
88494   SELECT recv_date::DATE INTO _firstExchDateFreight
88495   FROM recv
88496   WHERE (recv_vohead_id = _p.vohead_id);
88497
88498 --  Start by handling taxes
88499   FOR _r IN SELECT tax_sales_accnt_id, 
88500               round(sum(taxdetail_tax),2) AS tax,
88501               currToBase(_p.vohead_curr_id, round(sum(taxdetail_tax),2), _p.vohead_docdate) AS taxbasevalue
88502             FROM tax 
88503              JOIN calculateTaxDetailSummary('VO', _p.vohead_id, 'T') ON (taxdetail_tax_id=tax_id)
88504             GROUP BY tax_id, tax_sales_accnt_id LOOP
88505
88506     PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', _p.vohead_number,
88507                                 _r.tax_sales_accnt_id, 
88508                                 (_r.taxbasevalue * -1),
88509                                 _glDate, _p.glnotes );
88510
88511     _totalAmount_base := (_totalAmount_base - _r.taxbasevalue);
88512     _totalAmount := (_totalAmount - _r.tax);
88513      
88514   END LOOP;
88515
88516 --  Loop through the vodist records for the passed vohead that
88517 --  are posted against a P/O Item
88518   FOR _g IN SELECT DISTINCT poitem_id, voitem_qty, poitem_expcat_id,
88519                             poitem_invvenduomratio,
88520                             COALESCE(itemsite_id, -1) AS itemsiteid,
88521                             COALESCE(itemsite_costcat_id, -1) AS costcatid,
88522                             COALESCE(itemsite_item_id, -1) AS itemsite_item_id,
88523                             (SELECT SUM(value) 
88524                              FROM (
88525                                 SELECT SUM(recv_value) AS value
88526                                 FROM recv
88527                                 WHERE (recv_voitem_id=voitem_id)
88528                              UNION
88529                                 SELECT SUM(poreject_value)*-1 AS value
88530                                 FROM poreject
88531                                 WHERE (poreject_voitem_id=voitem_id)) as data)
88532                             AS value_base,
88533                             (poitem_freight_vouchered / poitem_qty_vouchered) * voitem_qty AS vouchered_freight,
88534                             currToBase(_p.pohead_curr_id, (poitem_freight_vouchered / poitem_qty_vouchered) * voitem_qty, _firstExchDateFreight ) AS vouchered_freight_base,
88535                             voitem_freight,
88536                             currToBase(_p.vohead_curr_id, voitem_freight,
88537                                        _p.vohead_distdate) AS voitem_freight_base
88538             FROM vodist, voitem,
88539                  poitem LEFT OUTER JOIN itemsite ON (poitem_itemsite_id=itemsite_id)
88540             WHERE ( (vodist_poitem_id=poitem_id)
88541              AND (voitem_poitem_id=poitem_id)
88542              AND (voitem_vohead_id=vodist_vohead_id)
88543              AND (vodist_vohead_id=_p.vohead_id)) LOOP
88544
88545 --  Grab the G/L Accounts
88546     IF (_g.costcatid = -1) THEN
88547       SELECT pp.accnt_id AS pp_accnt_id,
88548              lb.accnt_id AS lb_accnt_id INTO _a
88549       FROM expcat, accnt AS pp, accnt AS lb
88550       WHERE ( (expcat_purchprice_accnt_id=pp.accnt_id)
88551        AND (expcat_liability_accnt_id=lb.accnt_id)
88552        AND (expcat_id=_g.poitem_expcat_id) );
88553       IF (NOT FOUND) THEN
88554         RAISE EXCEPTION 'Cannot Void Voucher #% due to unassigned G/L Accounts.', _p.vohead_number;
88555       END IF;
88556     ELSE
88557       SELECT pp.accnt_id AS pp_accnt_id,
88558              lb.accnt_id AS lb_accnt_id INTO _a
88559       FROM costcat, accnt AS pp, accnt AS lb
88560       WHERE ( (costcat_purchprice_accnt_id=pp.accnt_id)
88561        AND (costcat_liability_accnt_id=lb.accnt_id)
88562        AND (costcat_id=_g.costcatid) );
88563       IF (NOT FOUND) THEN
88564         RAISE EXCEPTION 'Cannot Void Voucher #% due to unassigned G/L Accounts.', _p.vohead_number;
88565       END IF;
88566     END IF;
88567
88568 --  Clear the Item Amount accumulator
88569     _itemAmount_base := 0;
88570     _itemAmount := 0;
88571
88572 --  Figure out the total posted value for this line item
88573     FOR _d IN SELECT vodist_id, vodist_amount,
88574                      _p.vohead_curr_id, vodist_costelem_id,
88575                      currToBase(_p.vohead_curr_id, vodist_amount,
88576                                 _p.vohead_distdate) AS vodist_amount_base
88577               FROM vodist
88578               WHERE ( (vodist_vohead_id=_p.vohead_id)
88579                AND (vodist_poitem_id=_g.poitem_id) ) LOOP
88580
88581        _pExplain := TRUE;
88582        SELECT * INTO _costx
88583          FROM itemcost
88584         WHERE ( (itemcost_item_id = _g.itemsite_item_id)
88585           AND   (itemcost_costelem_id = _d.vodist_costelem_id) );
88586
88587        IF (FOUND) THEN
88588          _pExplain := _costx.itemcost_lowlevel;
88589        END IF;
88590
88591 --  Add the Distribution Amount to the Item Amount
88592       _itemAmount_base := _itemAmount_base + ROUND(_d.vodist_amount_base, 2);
88593       _itemAmount := _itemAmount + _d.vodist_amount;
88594
88595     END LOOP;
88596
88597 --  Distribute from the clearing account
88598     PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
88599                                 _a.lb_accnt_id,
88600                                 round(_g.value_base + _g.vouchered_freight_base, 2),
88601                                 _glDate, _p.glnotes );
88602
88603 --  Attribute the correct portion to currency gain/loss
88604     _exchGainFreight := 0;
88605     SELECT currGain(_p.pohead_curr_id, _g.vouchered_freight,
88606                     _firstExchDateFreight, _p.vohead_distdate )
88607                     INTO _exchGainFreight;
88608     IF (round(_exchGainFreight, 2) <> 0) THEN
88609       PERFORM insertIntoGLSeries(_sequence, 'A/P', 'VO',
88610                                  text(_p.vohead_number),
88611                                  getGainLossAccntId(_a.lb_accnt_id), round(_exchGainFreight, 2) * -1,
88612                                  _glDate, _p.glnotes);
88613     END IF;
88614
88615 --  Distribute the remaining variance to the Purchase Price Variance account
88616     IF (round(_itemAmount_base, 2) <> round(_g.value_base, 2)) THEN
88617       _tmpTotal := round(_itemAmount_base, 2) - round(_g.value_base, 2);
88618       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
88619                                   _a.pp_accnt_id,
88620                                   _tmpTotal,
88621                                   _glDate, _p.glnotes );
88622     END IF;
88623
88624 --  Distribute the remaining freight variance to the Purchase Price Variance account
88625     IF (round(_g.voitem_freight_base + _exchGainFreight, 2) <> round(_g.vouchered_freight_base, 2)) THEN
88626       _tmpTotal := round(_g.voitem_freight_base + _exchGainFreight, 2) - round(_g.vouchered_freight_base, 2);
88627       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
88628                                   _a.pp_accnt_id,
88629                                   _tmpTotal,
88630                                   _glDate, _p.glnotes );
88631     END IF;
88632
88633 --  Add the distribution amount to the total amount to distribute
88634     _totalAmount_base := (_totalAmount_base + _itemAmount_base + _g.voitem_freight_base);
88635     _totalAmount := (_totalAmount + _itemAmount + _g.voitem_freight);
88636
88637 --  Reverse the posting for all the Tagged Receivings for this P/O Item
88638     UPDATE recv
88639     SET recv_invoiced=FALSE,
88640         recv_recvcost_curr_id=basecurrid(),
88641         recv_recvcost=0,
88642         recv_vohead_id=NULL,
88643         recv_voitem_id=NULL
88644     FROM poitem
88645     WHERE ( (recv_orderitem_id=poitem_id)
88646       AND   (recv_order_type='PO')
88647       AND   (recv_orderitem_id=_g.poitem_id)
88648       AND   (recv_vohead_id=_p.vohead_id) );
88649
88650 --  Reverse the posting for all the Tagged Rejections for this P/O Item
88651     UPDATE poreject
88652     SET poreject_invoiced=FALSE,
88653         poreject_vohead_id=NULL,
88654         poreject_voitem_id=NULL
88655     WHERE ( (poreject_poitem_id=_g.poitem_id)
88656       AND   (poreject_vohead_id=_p.vohead_id) );
88657
88658 --  Update the qty and freight vouchered fields
88659     UPDATE poitem
88660        SET poitem_qty_vouchered = (poitem_qty_vouchered - _g.voitem_qty),
88661            poitem_freight_vouchered = (poitem_freight_vouchered - _g.voitem_freight)
88662     WHERE (poitem_id=_g.poitem_id);
88663
88664   END LOOP;
88665
88666 --  Loop through the vodist records for the passed vohead that
88667 --  are not posted against a P/O Item
88668 --  Skip the tax distributions
88669   FOR _d IN SELECT vodist_id,
88670                    currToBase(_p.vohead_curr_id, vodist_amount,
88671                               _p.vohead_distdate) AS vodist_amount_base,
88672                    vodist_amount,
88673                    vodist_accnt_id, vodist_expcat_id
88674             FROM vodist
88675             WHERE ( (vodist_vohead_id=_p.vohead_id)
88676               AND   (vodist_poitem_id=-1)
88677               AND   (vodist_tax_id=-1) ) LOOP
88678
88679 --  Distribute from the misc. account
88680     IF (_d.vodist_accnt_id = -1) THEN
88681       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
88682                                   expcat_exp_accnt_id,
88683                                   round(_d.vodist_amount_base, 2),
88684                                   _glDate, _p.glnotes )
88685       FROM expcat
88686       WHERE (expcat_id=_d.vodist_expcat_id);
88687     ELSE
88688       PERFORM insertIntoGLSeries( _sequence, 'A/P', 'VO', text(_p.vohead_number),
88689                                   _d.vodist_accnt_id,
88690                                   round(_d.vodist_amount_base, 2),
88691                                   _glDate, _p.glnotes );
88692     END IF;
88693
88694 --  Add the Distribution Amount to the Total Amount
88695     _totalAmount_base := _totalAmount_base + ROUND(_d.vodist_amount_base, 2);
88696     _totalAmount := _totalAmount + _d.vodist_amount;
88697
88698   END LOOP;
88699
88700   SELECT insertIntoGLSeries( _sequence, 'A/P', 'VO', text(vohead_number),
88701                              accnt_id, round(_totalAmount_base, 2) * -1,
88702                              _glDate, _p.glnotes ) INTO _test
88703   FROM vohead LEFT OUTER JOIN accnt ON (accnt_id=findAPAccount(vohead_vend_id))
88704   WHERE ( (findAPAccount(vohead_vend_id)=0 OR accnt_id > 0) -- G/L interface might be disabled
88705     AND   (vohead_id=_p.vohead_id) );
88706   IF (NOT FOUND) THEN
88707     RAISE EXCEPTION 'Cannot Void Voucher #% due to an unassigned A/P Account.', _p.vohead_number;
88708   END IF;
88709
88710   PERFORM postGLSeries(_sequence, pJournalNumber);
88711
88712 --  Create the A/P Open Item
88713   SELECT NEXTVAL('apopen_apopen_id_seq') INTO _apopenid;
88714   _reference := ('Void Voucher #' || _n.apopen_docnumber);
88715   INSERT INTO apopen
88716   ( apopen_id, apopen_username, apopen_journalnumber,
88717     apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_ponumber,
88718     apopen_docdate, apopen_duedate, apopen_distdate, apopen_terms_id, apopen_curr_id,
88719     apopen_amount, apopen_paid, apopen_open, apopen_notes, apopen_discount, apopen_curr_rate )
88720   SELECT _apopenid, getEffectiveXtUser(), pJournalnumber,
88721          apopen_vend_id, apopen_docnumber, 'C', apopen_ponumber,
88722          _glDate, _glDate, _glDate, -1, apopen_curr_id,
88723          apopen_amount - apopen_paid, 0, TRUE, _reference, TRUE, apopen_curr_rate
88724     FROM apopen
88725    WHERE (apopen_id=_n.apopen_id);
88726
88727   SELECT apcreditapply_id INTO _apcreditapplyid
88728     FROM apcreditapply
88729    WHERE ( (apcreditapply_source_apopen_id=_apopenid)
88730      AND   (apcreditapply_target_apopen_id=_n.apopen_id) );
88731   IF (FOUND) THEN
88732     UPDATE apcreditapply
88733        SET apcreditapply_amount=_n.apopen_amount-_n.apopen_paid
88734      WHERE (apcreditapply_id=_apcreditapplyid);
88735   ELSE
88736     SELECT nextval('apcreditapply_apcreditapply_id_seq') INTO _apcreditapplyid;
88737     INSERT INTO apcreditapply
88738            ( apcreditapply_id, apcreditapply_source_apopen_id,
88739              apcreditapply_target_apopen_id, apcreditapply_amount,
88740              apcreditapply_curr_id )
88741     VALUES ( _apcreditapplyid, _apopenid, _n.apopen_id, _n.apopen_amount-_n.apopen_paid, _n.apopen_curr_id );
88742   END IF;
88743
88744   SELECT postAPCreditMemoApplication(_apopenid) INTO _result;
88745
88746   IF (_result < 0) THEN
88747     RAISE EXCEPTION 'Credit application failed with result %.', _result;
88748   END IF;
88749
88750 --  Reopen all of the P/O Items that were closed by this Voucher
88751   UPDATE poitem
88752   SET poitem_status='O'
88753   FROM voitem
88754   WHERE ( (voitem_poitem_id=poitem_id)
88755     AND   (voitem_close)
88756     AND   (voitem_vohead_id=_p.vohead_id) );
88757
88758 --  Reopen the P/O
88759   UPDATE pohead
88760   SET pohead_status='O'
88761   WHERE (pohead_id=_p.vohead_pohead_id);
88762
88763 --  Mark as voided
88764   UPDATE apopen
88765   SET apopen_void=TRUE
88766   WHERE (apopen_id=_n.apopen_id);
88767
88768   RETURN pJournalNumber;
88769
88770 END;
88771 $_$;
88772
88773
88774 ALTER FUNCTION public.voidapopenvoucher(integer, integer) OWNER TO admin;
88775
88776 --
88777 -- TOC entry 2304 (class 1255 OID 146567183)
88778 -- Dependencies: 4536 8
88779 -- Name: voidcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
88780 --
88781
88782 CREATE FUNCTION voidcheck(integer) RETURNS integer
88783     LANGUAGE plpgsql
88784     AS $_$
88785 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88786 -- See www.xtuple.com/CPAL for the full text of the software license.
88787 DECLARE
88788   pCheckid ALIAS FOR $1;
88789
88790 BEGIN
88791
88792   IF ( SELECT (checkhead_void OR checkhead_posted OR checkhead_replaced)
88793        FROM checkhead
88794        WHERE (checkhead_id=pCheckid) ) THEN
88795     RETURN -1;
88796   END IF;
88797
88798   UPDATE checkhead
88799   SET checkhead_void=TRUE
88800   WHERE (checkhead_id=pCheckid);
88801
88802   RETURN 1;
88803
88804 END;
88805 $_$;
88806
88807
88808 ALTER FUNCTION public.voidcheck(integer) OWNER TO admin;
88809
88810 --
88811 -- TOC entry 2311 (class 1255 OID 146567184)
88812 -- Dependencies: 4536 8
88813 -- Name: voidcreditmemo(integer); Type: FUNCTION; Schema: public; Owner: admin
88814 --
88815
88816 CREATE FUNCTION voidcreditmemo(integer) RETURNS integer
88817     LANGUAGE plpgsql
88818     AS $_$
88819 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
88820 -- See www.xtuple.com/CPAL for the full text of the software license.
88821 DECLARE
88822   pCmheadid ALIAS FOR $1;
88823   _r RECORD;
88824   _p RECORD;
88825   _n RECORD;
88826   _glSequence INTEGER := 0;
88827   _glJournal INTEGER := 0;
88828   _itemlocSeries INTEGER := 0;
88829   _invhistid INTEGER;
88830   _test INTEGER;
88831   _amount NUMERIC;
88832   _roundedBase NUMERIC;
88833   _totalAmount NUMERIC   := 0;
88834   _totalRoundedBase NUMERIC := 0;
88835   _commissionDue NUMERIC := 0;
88836   _toApply NUMERIC;
88837   _toClose BOOLEAN;
88838   _glDate       DATE;
88839   _taxBaseValue NUMERIC := 0;
88840
88841 BEGIN
88842
88843 --  Cache C/M information
88844   SELECT cmhead.*,
88845          findARAccount(cmhead_cust_id) AS ar_accnt_id,
88846          ( SELECT COALESCE(SUM(taxhist_tax), 0)
88847            FROM cmheadtax
88848            WHERE ( (taxhist_parent_id = cmhead_id)
88849              AND   (taxhist_taxtype_id = getAdjustmentTaxtypeId()) ) ) AS adjtax
88850          INTO _p
88851   FROM cmhead
88852   WHERE (cmhead_id=pCmheadid);
88853   IF (NOT FOUND) THEN
88854     RAISE EXCEPTION 'Cannot Void Credit Memo as cmhead not found';
88855   END IF;
88856   IF (NOT _p.cmhead_posted) THEN
88857     RETURN -10;
88858   END IF;
88859
88860 --  Cache AROpen Information
88861   SELECT aropen.* INTO _n
88862   FROM aropen
88863   WHERE ( (aropen_doctype='C')
88864     AND   (aropen_docnumber=_p.cmhead_number) );
88865   IF (NOT FOUND) THEN
88866     RAISE EXCEPTION 'Cannot Void Credit Memo as aropen not found';
88867   END IF;
88868
88869 --  Check for ARApplications
88870   SELECT arapply_id INTO _test
88871   FROM arapply
88872   WHERE (arapply_target_aropen_id=_n.aropen_id)
88873      OR (arapply_source_aropen_id=_n.aropen_id)
88874   LIMIT 1;
88875   IF (FOUND) THEN
88876     RETURN -20;
88877   END IF;
88878
88879   _glDate := COALESCE(_p.cmhead_gldistdate, _p.cmhead_docdate);
88880
88881   SELECT fetchGLSequence() INTO _glSequence;
88882   SELECT fetchJournalNumber('AR-IN') INTO _glJournal;
88883
88884 --  Start by handling taxes (reverse sense)
88885   FOR _r IN SELECT tax_sales_accnt_id, 
88886               round(sum(taxdetail_tax),2) AS tax,
88887               currToBase(_p.cmhead_curr_id, round(sum(taxdetail_tax),2), _p.cmhead_docdate) AS taxbasevalue
88888             FROM tax 
88889              JOIN calculateTaxDetailSummary('CM', _p.cmhead_id, 'T') ON (taxdetail_tax_id=tax_id)
88890             GROUP BY tax_id, tax_sales_accnt_id LOOP
88891
88892     PERFORM insertIntoGLSeries( _glSequence, 'A/R', 'CM', _p.cmhead_number,
88893                                 _r.tax_sales_accnt_id, 
88894                                 (_r.taxbasevalue * -1.0),
88895                                 _glDate, ('Void-' || _p.cmhead_billtoname) );
88896
88897     _totalAmount := _totalAmount + _r.tax * -1;
88898     _totalRoundedBase := _totalRoundedBase + _r.taxbasevalue * -1;  
88899   END LOOP;
88900
88901 -- Process line items
88902   FOR _r IN SELECT *
88903             FROM creditmemoitem
88904             WHERE ( (cmitem_cmhead_id=_p.cmhead_id)
88905               AND   (cmitem_qtycredit <> 0 ) ) LOOP
88906
88907     IF (_r.extprice <> 0) THEN
88908 --  Debit the Sales Account for the current cmitem (reverse sense)
88909       _roundedBase := round(currToBase(_p.cmhead_curr_id, _r.extprice, _p.cmhead_docdate), 2);
88910       SELECT insertIntoGLSeries( _glSequence, 'A/R', 'CM', _p.cmhead_number,
88911                                  CASE WHEN _p.cmhead_rahead_id IS NULL THEN
88912                                    getPrjAccntId(_p.cmhead_prj_id, salesaccnt_credit_accnt_id)
88913                                  ELSE
88914                                    getPrjAccntId(_p.cmhead_prj_id, salesaccnt_returns_accnt_id)
88915                                  END,
88916                                  _roundedBase,
88917                                  _glDate, ('Void-' || _p.cmhead_billtoname) ) INTO _test
88918       FROM salesaccnt
88919       WHERE (salesaccnt_id=findSalesAccnt(_r.cmitem_itemsite_id, 'IS', _p.cmhead_cust_id,
88920                                           _p.cmhead_saletype_id, _p.cmhead_shipzone_id));
88921       IF (NOT FOUND) THEN
88922         PERFORM deleteGLSeries(_glSequence);
88923         RETURN -11;
88924       END IF;
88925     END IF;
88926
88927     _totalAmount := _totalAmount + round(_r.extprice, 2);
88928     _totalRoundedBase := _totalRoundedBase + _roundedBase;
88929
88930   END LOOP;
88931
88932 --  Credit the Misc. Account for Miscellaneous Charges (reverse sense)
88933   IF (_p.cmhead_misc <> 0) THEN
88934     _roundedBase := round(currToBase(_p.cmhead_curr_id, _p.cmhead_misc, _p.cmhead_docdate), 2);
88935     SELECT insertIntoGLSeries( _glSequence, 'A/R', 'CM', _p.cmhead_number,
88936                                getPrjAccntId(_p.cmhead_prj_id, accnt_id),
88937                                _roundedBase,
88938                                _glDate, ('Void-' ||_p.cmhead_billtoname) ) INTO _test
88939     FROM accnt
88940     WHERE (accnt_id=_p.cmhead_misc_accnt_id);
88941
88942 --  If the Misc. Charges Account was not found then punt
88943     IF (NOT FOUND) THEN
88944       PERFORM deleteGLSeries(_glSequence);
88945       RETURN _test;
88946     END IF;
88947
88948 --  Cache the Misc. Amount distributed
88949     _totalAmount := _totalAmount + _p.cmhead_misc;
88950     _totalRoundedBase := _totalRoundedBase + _roundedBase;
88951   END IF;
88952
88953 --  Debit the Freight Account (reverse sense)
88954   IF (_p.cmhead_freight <> 0) THEN
88955     _roundedBase := round(currToBase(_p.cmhead_curr_id, _p.cmhead_freight, _p.cmhead_docdate), 2);
88956     SELECT insertIntoGLSeries( _glSequence, 'A/R', 'CM', _p.cmhead_number,
88957                                getPrjAccntId(_p.cmhead_prj_id, accnt_id),
88958                                _roundedBase,
88959                                _glDate, ('Void-' || _p.cmhead_billtoname) ) INTO _test
88960     FROM accnt
88961     WHERE (accnt_id=findFreightAccount(_p.cmhead_cust_id));
88962
88963 --  If the Freight Charges Account was not found then punt
88964     IF (NOT FOUND) THEN
88965       PERFORM deleteGLSeries(_glSequence);
88966       RETURN _test;
88967     END IF;
88968
88969 --  Cache the Amount Distributed to Freight
88970     _totalAmount := _totalAmount + _p.cmhead_freight;
88971     _totalRoundedBase := _totalRoundedBase + _roundedBase;
88972   END IF;
88973
88974   _totalAmount := _totalAmount;
88975
88976 --  Credit the A/R for the total Amount (reverse sense)
88977   IF (_totalAmount <> 0) THEN
88978     IF (_p.ar_accnt_id != -1) THEN
88979       SELECT insertIntoGLSeries( _glSequence, 'A/R', 'CM', _p.cmhead_number,
88980                                  _p.ar_accnt_id,
88981                                  (_totalRoundedBase * -1.0),
88982                                  _glDate, ('Void-' || _p.cmhead_billtoname) ) INTO _test;
88983     ELSE
88984       PERFORM deleteGLSeries(_glSequence);
88985       RETURN _test;
88986     END IF;
88987   END IF;
88988
88989 --  Commit the GLSeries;
88990   SELECT postGLSeries(_glSequence, _glJournal) INTO _test;
88991   IF (_test < 0) THEN
88992     PERFORM deleteGLSeries(_glSequence);
88993     RETURN _test;
88994   END IF;
88995
88996 --  Delete sales history
88997   DELETE FROM cohisttax
88998   WHERE (taxhist_parent_id IN (SELECT cohist_id
88999                                FROM cohist
89000                                WHERE (cohist_doctype='C' AND cohist_ordernumber=_p.cmhead_number)));
89001
89002   DELETE FROM cohist
89003   WHERE (cohist_doctype='C' AND cohist_ordernumber=_p.cmhead_number);
89004
89005 --  Delete the Invoice aropen item
89006   DELETE FROM aropen
89007   WHERE (aropen_doctype='C' AND aropen_docnumber=_p.cmhead_number);
89008
89009 -- Handle the Inventory and G/L Transactions for any returned Inventory where cmitem_updateinv is true (reverse sense)
89010   FOR _r IN SELECT cmitem_itemsite_id AS itemsite_id, cmitem_id,
89011                    (cmitem_qtyreturned * cmitem_qty_invuomratio) AS qty,
89012                    cmhead_number, cmhead_cust_id AS cust_id, item_number,
89013                    cmhead_prj_id AS prj_id, cmhead_saletype_id AS saletype_id,
89014                    cmhead_shipzone_id AS shipzone_id
89015             FROM cmhead, cmitem, itemsite, item
89016             WHERE ( (cmitem_cmhead_id=cmhead_id)
89017              AND (cmitem_itemsite_id=itemsite_id)
89018              AND (itemsite_item_id=item_id)
89019              AND (cmitem_qtyreturned <> 0)
89020              AND (cmitem_updateinv)
89021              AND (cmhead_id=_p.cmhead_id) ) LOOP
89022
89023 --  Return credited stock to inventory
89024     IF (_itemlocSeries = 0) THEN
89025       SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
89026     END IF;
89027     SELECT postInvTrans( itemsite_id, 'RS', (_r.qty * -1),
89028                          'S/O', 'CM', _r.cmhead_number, '',
89029                          ('Credit Voided ' || _r.item_number),
89030                          costcat_asset_accnt_id,
89031                          getPrjAccntId(_r.prj_id, resolveCOSAccount(itemsite_id, _r.cust_id, _r.saletype_id, _r.shipzone_id)),  
89032                          _itemlocSeries, _glDate) INTO _invhistid
89033     FROM itemsite, costcat
89034     WHERE ( (itemsite_costcat_id=costcat_id)
89035      AND (itemsite_id=_r.itemsite_id) );
89036
89037   END LOOP;
89038
89039 --  Update coitem to reflect the returned qty where cmitem_updateinv is true (reverse sense)
89040   FOR _r IN SELECT cmitem_qtyreturned, cmitem_itemsite_id, cohead_id
89041             FROM cmitem, cmhead, invchead, cohead
89042             WHERE ( (cmitem_cmhead_id=cmhead_id)
89043              AND (cmhead_invcnumber=invchead_invcnumber)
89044              AND (invchead_ordernumber=cohead_number)
89045              AND (cmitem_qtyreturned <> 0)
89046              AND (cmitem_updateinv)
89047              AND (cmhead_id=_p.cmhead_id) ) LOOP
89048     UPDATE coitem
89049     SET coitem_qtyreturned = (coitem_qtyreturned + (_r.cmitem_qtyreturned * -1.0))
89050     WHERE coitem_id IN ( SELECT coitem_id
89051                          FROM coitem
89052                          WHERE ( (coitem_cohead_id=_r.cohead_id)
89053                           AND (coitem_itemsite_id = _r.cmitem_itemsite_id) )
89054                          LIMIT 1 );
89055   END LOOP;
89056
89057 --  Mark the cmhead as voided
89058   UPDATE cmhead
89059   SET cmhead_void=TRUE
89060   WHERE (cmhead_id=_p.cmhead_id);
89061
89062   RETURN _itemlocSeries;
89063
89064 END;
89065 $_$;
89066
89067
89068 ALTER FUNCTION public.voidcreditmemo(integer) OWNER TO admin;
89069
89070 --
89071 -- TOC entry 2312 (class 1255 OID 146567186)
89072 -- Dependencies: 4536 8
89073 -- Name: voidinvoice(integer); Type: FUNCTION; Schema: public; Owner: admin
89074 --
89075
89076 CREATE FUNCTION voidinvoice(integer) RETURNS integer
89077     LANGUAGE plpgsql
89078     AS $_$
89079 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89080 -- See www.xtuple.com/CPAL for the full text of the software license.
89081 DECLARE
89082   pInvcheadid ALIAS FOR $1;
89083   _glSequence INTEGER := 0;
89084   _glJournal INTEGER := 0;
89085   _itemlocSeries INTEGER := 0;
89086   _aropenid INTEGER := 0;
89087   _invhistid INTEGER := 0;
89088   _amount NUMERIC;
89089   _roundedBase NUMERIC;
89090   _r RECORD;
89091   _p RECORD;
89092   _n RECORD;
89093   _test INTEGER;
89094   _totalAmount          NUMERIC := 0;
89095   _totalRoundedBase     NUMERIC := 0;
89096   _totalAmountBase      NUMERIC := 0;
89097   _appliedAmount        NUMERIC := 0;
89098   _commissionDue        NUMERIC := 0;
89099   _tmpAccntId INTEGER;
89100   _tmpCurrId  INTEGER;
89101   _firstExchDate        DATE;
89102   _glDate               DATE;
89103   _exchGain             NUMERIC := 0;
89104
89105 BEGIN
89106
89107 --  Cache Invoice information
89108   SELECT invchead.*,
89109          findFreightAccount(invchead_cust_id) AS freightaccntid,
89110          findARAccount(invchead_cust_id) AS araccntid,
89111          aropen_id, cohist_unitcost,
89112          ( SELECT COALESCE(SUM(taxhist_tax), 0)
89113            FROM invcheadtax
89114            WHERE ( (taxhist_parent_id = invchead_id)
89115              AND   (taxhist_taxtype_id = getFreightTaxtypeId()) ) ) AS freighttax,
89116          ( SELECT COALESCE(SUM(taxhist_tax), 0)
89117            FROM invcheadtax
89118            WHERE ( (taxhist_parent_id = invchead_id)
89119              AND   (taxhist_taxtype_id = getAdjustmentTaxtypeId()) ) ) AS adjtax
89120        INTO _p 
89121   FROM invchead JOIN aropen ON (aropen_doctype='I' AND aropen_docnumber=invchead_invcnumber)
89122                 JOIN cohist ON (cohist_doctype='I' AND cohist_invcnumber=invchead_invcnumber)
89123   WHERE (invchead_id=pInvcheadid);
89124   IF (NOT FOUND) THEN
89125     RAISE EXCEPTION 'Cannot Void Invoice as invchead not found';
89126   END IF;
89127   IF (NOT _p.invchead_posted) THEN
89128     RETURN -10;
89129   END IF;
89130
89131 --  Cache AROpen Information
89132   SELECT aropen.* INTO _n
89133   FROM aropen
89134   WHERE ( (aropen_doctype='I')
89135     AND   (aropen_docnumber=_p.invchead_invcnumber) );
89136   IF (NOT FOUND) THEN
89137     RAISE EXCEPTION 'Cannot Void Invoice as aropen not found';
89138   END IF;
89139
89140 --  Check for ARApplications
89141   SELECT arapply_id INTO _test
89142   FROM arapply
89143   WHERE (arapply_target_aropen_id=_n.aropen_id)
89144   LIMIT 1;
89145   IF (FOUND) THEN
89146     RETURN -20;
89147   END IF;
89148
89149   SELECT fetchGLSequence() INTO _glSequence;
89150   SELECT fetchJournalNumber('AR-IN') INTO _glJournal;
89151
89152   _glDate := COALESCE(_p.invchead_gldistdate, _p.invchead_invcdate);
89153
89154 -- the 1st MC iteration used the cohead_orderdate so we could get curr exch
89155 -- gain/loss between the sales and invoice dates, but see issue 3892.  leave
89156 -- this condition TRUE until we make this configurable or decide not to.
89157   IF TRUE THEN
89158       _firstExchDate := _p.invchead_invcdate;
89159   ELSE
89160 -- can we save a select by using: _firstExchDate := _p.invchead_orderdate;
89161       SELECT cohead_orderdate INTO _firstExchDate
89162       FROM cohead
89163       WHERE (cohead_number = _p.invchead_ordernumber);
89164   END IF;
89165
89166 --  Start by handling taxes (reverse sense)
89167   FOR _r IN SELECT tax_sales_accnt_id, 
89168               round(sum(taxdetail_tax),2) AS tax,
89169               currToBase(_p.invchead_curr_id, round(sum(taxdetail_tax),2), _firstExchDate) AS taxbasevalue
89170             FROM tax 
89171              JOIN calculateTaxDetailSummary('I', _p.invchead_id, 'T') ON (taxdetail_tax_id=tax_id)
89172             GROUP BY tax_id, tax_sales_accnt_id LOOP
89173
89174     PERFORM insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89175                                 _r.tax_sales_accnt_id, 
89176                                 (_r.taxbasevalue * -1.0),
89177                                 _glDate, ('Void-' || _p.invchead_billto_name) );
89178
89179     _totalAmount := _totalAmount + _r.tax;
89180     _totalRoundedBase := _totalRoundedBase + _r.taxbasevalue;  
89181   END LOOP;
89182
89183 --  March through the Non-Misc. Invcitems
89184   FOR _r IN SELECT *
89185             FROM invoiceitem
89186             WHERE ( (invcitem_invchead_id = _p.invchead_id)
89187               AND   (invcitem_item_id <> -1) ) LOOP
89188
89189 --  Cache the amount due for this line
89190     _amount := _r.extprice;
89191
89192     IF (_amount > 0) THEN
89193 --  Credit the Sales Account for the invcitem item (reverse sense)
89194       IF (_r.itemsite_id IS NULL) THEN
89195         SELECT getPrjAccntId(_p.invchead_prj_id, salesaccnt_sales_accnt_id) 
89196         INTO _tmpAccntId
89197         FROM salesaccnt
89198         WHERE (salesaccnt_id=findSalesAccnt(_r.invcitem_item_id, 'I', _p.invchead_cust_id,
89199                                             _p.invchead_saletype_id, _p.invchead_shipzone_id));
89200       ELSE
89201         SELECT getPrjAccntId(_p.invchead_prj_id, salesaccnt_sales_accnt_id) 
89202         INTO _tmpAccntId
89203         FROM salesaccnt
89204         WHERE (salesaccnt_id=findSalesAccnt(_r.itemsite_id, 'IS', _p.invchead_cust_id,
89205                                             _p.invchead_saletype_id, _p.invchead_shipzone_id));
89206       END IF;
89207
89208 --  If the Sales Account Assignment was not found then punt
89209       IF (NOT FOUND) THEN
89210         PERFORM deleteGLSeries(_glSequence);
89211         RETURN -11;
89212       END IF;
89213
89214       _roundedBase := round(currToBase(_p.invchead_curr_id, _amount, _firstExchDate), 2);
89215       SELECT insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89216                                  _tmpAccntId,
89217                                  (_roundedBase * -1.0),
89218                                  _glDate, ('Void-' || _p.invchead_billto_name) ) INTO _test;
89219
89220       _totalAmount := (_totalAmount + _amount);
89221       _totalRoundedBase := _totalRoundedBase + _roundedBase;
89222       _commissionDue := (_commissionDue + (_amount * _p.invchead_commission));
89223     END IF;
89224
89225     _totalAmount := _totalAmount;
89226     _totalRoundedBase := _totalRoundedBase;
89227
89228   END LOOP;
89229
89230 --  March through the Misc. Invcitems
89231   FOR _r IN SELECT *
89232             FROM invoiceitem JOIN salescat ON (salescat_id = invcitem_salescat_id)
89233             WHERE ( (invcitem_item_id = -1)
89234               AND   (invcitem_invchead_id=_p.invchead_id) ) LOOP
89235
89236 --  Cache the amount due for this line and the commission due for such
89237     _amount := _r.extprice;
89238
89239     IF (_amount > 0) THEN
89240 --  Credit the Sales Account for the invcitem item (reverse sense)
89241       _roundedBase = round(currToBase(_p.invchead_curr_id, _amount,
89242                                       _firstExchDate), 2);
89243       SELECT insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89244                                  getPrjAccntId(_p.invchead_prj_id, _r.salescat_sales_accnt_id), 
89245                                  (_roundedBase * -1.0),
89246                                  _glDate, ('Void-' || _p.invchead_billto_name) ) INTO _test;
89247
89248       IF (_test < 0) THEN
89249         PERFORM deleteGLSeries(_glSequence);
89250         RETURN _test;
89251       END IF;
89252
89253       _totalAmount := (_totalAmount + _amount);
89254       _totalRoundedBase :=  _totalRoundedBase + _roundedBase;
89255       _commissionDue := (_commissionDue + (_amount * _p.invchead_commission));
89256     END IF;
89257
89258   END LOOP;
89259
89260 --  Credit the Freight Account for Freight Charges (reverse sense)
89261   IF (_p.invchead_freight <> 0) THEN
89262     IF (_p.freightaccntid <> -1) THEN
89263       _roundedBase = round(currToBase(_p.invchead_curr_id, _p.invchead_freight,
89264                                       _firstExchDate), 2);
89265       SELECT insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89266                                  getPrjAccntId(_p.invchead_prj_id,_p.freightaccntid), 
89267                                  (_roundedBase * -1.0),
89268                                  _glDate, ('Void-' || _p.invchead_billto_name) ) INTO _test;
89269
89270 --  Cache the Freight Amount distributed
89271         _totalAmount := (_totalAmount + _p.invchead_freight);
89272         _totalRoundedBase := _totalRoundedBase + _roundedBase;
89273     ELSE
89274       _test := -14;
89275     END IF;
89276
89277 --  If the Freight Account was not found then punt
89278     IF (_test < 0) THEN
89279       PERFORM deleteGLSeries(_glSequence);
89280       RETURN _test;
89281     END IF;
89282
89283   END IF;
89284
89285 --  Credit the Misc. Account for Miscellaneous Charges (reverse sense)
89286   IF (_p.invchead_misc_amount <> 0) THEN
89287     _roundedBase := round(currToBase(_p.invchead_curr_id, _p.invchead_misc_amount,
89288                                      _firstExchDate), 2);
89289     SELECT insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89290                                getPrjAccntId(_p.invchead_prj_id, _p.invchead_misc_accnt_id), 
89291                                (_roundedBase * -1.0),
89292                                _glDate, ('Void-' || _p.invchead_billto_name) ) INTO _test;
89293
89294 --  If the Misc. Charges Account was not found then punt
89295     IF (_test < 0) THEN
89296       PERFORM deleteGLSeries(_glSequence);
89297       RETURN _test;
89298     END IF;
89299
89300 --  Cache the Misc. Amount distributed
89301     _totalAmount := (_totalAmount + _p.invchead_misc_amount);
89302     _totalRoundedBase := _totalRoundedBase + _roundedBase;
89303
89304   END IF;
89305
89306 -- ToDo: handle rounding errors (reverse sense)
89307     _exchGain := currGain(_p.invchead_curr_id, _totalAmount,
89308                           _firstExchDate, _glDate);
89309     IF (_exchGain <> 0) THEN
89310         SELECT insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89311                                    getGainLossAccntId(_p.araccntid),
89312                                    round(_exchGain, 2),
89313                                    _glDate, ('Void-' || _p.invchead_billto_name) ) INTO _test ;
89314         IF (_test < 0) THEN
89315           PERFORM deleteGLSeries(_glSequence);
89316           RETURN _test;
89317         END IF;
89318     END IF;
89319
89320 --  Debit A/R for the total Amount (reverse sense)
89321   IF (_totalRoundedBase <> 0) THEN
89322     IF (_p.araccntid != -1) THEN
89323       SELECT insertIntoGLSeries( _glSequence, 'A/R', 'IN', _p.invchead_invcnumber,
89324                                  _p.araccntid,
89325                                  round(_totalRoundedBase, 2),
89326                                  _glDate, ('Void-' || _p.invchead_billto_name) ) INTO _test;
89327     ELSE
89328       PERFORM deleteGLSeries(_glSequence);
89329       RETURN _test;
89330     END IF;
89331   END IF;
89332
89333 --  Commit the GLSeries;
89334   SELECT postGLSeries(_glSequence, _glJournal) INTO _test;
89335   IF (_test < 0) THEN
89336     PERFORM deleteGLSeries(_glSequence);
89337     RETURN _test;
89338   END IF;
89339
89340 --  Delete sales history
89341   DELETE FROM cohisttax
89342   WHERE (taxhist_parent_id IN (SELECT cohist_id
89343                                FROM cohist
89344                                WHERE (cohist_doctype='I' AND cohist_invcnumber=_p.invchead_invcnumber)));
89345
89346   DELETE FROM cohist
89347   WHERE (cohist_doctype='I' AND cohist_invcnumber=_p.invchead_invcnumber);
89348
89349 --  Create the Credit aropen item
89350   SELECT nextval('aropen_aropen_id_seq') INTO _aropenid;
89351   INSERT INTO aropen
89352   ( aropen_id, aropen_username, aropen_journalnumber,
89353     aropen_open, aropen_posted,
89354     aropen_cust_id, aropen_ponumber,
89355     aropen_docnumber, aropen_applyto, aropen_doctype,
89356     aropen_docdate, aropen_duedate, aropen_distdate, aropen_terms_id,
89357     aropen_amount, aropen_paid,
89358     aropen_salesrep_id, aropen_commission_due, aropen_commission_paid,
89359     aropen_ordernumber, aropen_notes, aropen_cobmisc_id,
89360     aropen_curr_id )
89361   VALUES
89362   ( _aropenid, getEffectiveXtUser(), _glJournal,
89363     TRUE, FALSE,
89364     _p.invchead_cust_id, _p.invchead_ponumber,
89365     _p.invchead_invcnumber, _p.invchead_invcnumber, 'C',
89366     _p.invchead_invcdate, determineDueDate(_p.invchead_terms_id, _p.invchead_invcdate), _glDate, _p.invchead_terms_id,
89367     round(_totalAmount, 2), round(_totalAmount, 2), 
89368     _p.invchead_salesrep_id, _commissionDue, FALSE,
89369     _p.invchead_ordernumber::text, _p.invchead_notes, pInvcheadid,
89370     _p.invchead_curr_id );
89371
89372 --  Alter the Invoice A/R Open Item to reflect the application
89373     UPDATE aropen
89374     SET aropen_paid = round(_totalAmount, 2)
89375     WHERE (aropen_id=_p.aropen_id);
89376
89377 --  Record the application
89378     INSERT INTO arapply
89379     ( arapply_cust_id,
89380       arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
89381       arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
89382       arapply_fundstype, arapply_refnumber,
89383       arapply_applied, arapply_closed,
89384       arapply_postdate, arapply_distdate, arapply_journalnumber, arapply_curr_id )
89385     VALUES
89386     ( _p.invchead_cust_id,
89387       _aropenid, 'C', _p.invchead_invcnumber,
89388       _p.aropen_id, 'I', _p.invchead_invcnumber,
89389       '', '',
89390       round(_totalAmount, 2), TRUE,
89391       CURRENT_DATE, _p.invchead_invcdate, 0, _p.invchead_curr_id );
89392
89393 -- Handle the Inventory and G/L Transactions for any billed Inventory where invcitem_updateinv is true (reverse sense)
89394   FOR _r IN SELECT itemsite_id AS itemsite_id, invcitem_id,
89395                    (invcitem_billed * invcitem_qty_invuomratio) AS qty,
89396                    invchead_invcnumber, invchead_cust_id AS cust_id, item_number,
89397                    invchead_prj_id AS prj_id, invchead_saletype_id AS saletype_id,
89398                    invchead_shipzone_id AS shipzone_id
89399             FROM invchead JOIN invcitem ON ( (invcitem_invchead_id=invchead_id) AND
89400                                              (invcitem_billed <> 0) AND
89401                                              (invcitem_updateinv) )
89402                           JOIN itemsite ON ( (itemsite_item_id=invcitem_item_id) AND
89403                                              (itemsite_warehous_id=invcitem_warehous_id) )
89404                           JOIN item ON (item_id=invcitem_item_id)
89405             WHERE (invchead_id=_p.invchead_id) LOOP
89406
89407 --  Return billed stock to inventory
89408     IF (_itemlocSeries = 0) THEN
89409       SELECT NEXTVAL('itemloc_series_seq') INTO _itemlocSeries;
89410     END IF;
89411     SELECT postInvTrans( itemsite_id, 'SH', (_r.qty * -1.0),
89412                          'S/O', 'IN', _r.invchead_invcnumber, '',
89413                          ('Invoice Voided ' || _r.item_number),
89414                          getPrjAccntId(_r.prj_id, resolveCOSAccount(itemsite_id, _r.cust_id, _r.saletype_id, _r.shipzone_id)),
89415                          costcat_asset_accnt_id, _itemlocSeries, _glDate,
89416                          (_p.cohist_unitcost * _r.qty)) INTO _invhistid
89417     FROM itemsite JOIN costcat ON (itemsite_costcat_id=costcat_id)
89418     WHERE (itemsite_id=_r.itemsite_id);
89419
89420   END LOOP;
89421
89422 --  Reopen Billing
89423   UPDATE shipitem
89424   SET shipitem_invoiced=FALSE,
89425       shipitem_invcitem_id=NULL
89426   WHERE (shipitem_invcitem_id IN (SELECT invcitem_id
89427                                   FROM invcitem
89428                                   WHERE (invcitem_invchead_id=_p.invchead_id)));
89429   UPDATE cobill
89430   SET cobill_invcnum=NULL,
89431       cobill_invcitem_id=NULL
89432   WHERE (cobill_invcitem_id IN (SELECT invcitem_id
89433                                 FROM invcitem
89434                                 WHERE (invcitem_invchead_id=_p.invchead_id)));
89435   UPDATE cobmisc
89436   SET cobmisc_posted=FALSE,
89437       cobmisc_invcnumber=NULL,
89438       cobmisc_invchead_id=NULL
89439   WHERE (cobmisc_invchead_id=_p.invchead_id);
89440
89441 --  Mark the invoice as voided
89442   UPDATE invchead
89443   SET invchead_void=TRUE,
89444       invchead_notes=(invchead_notes || 'Voided on ' || current_date || ' by ' || getEffectiveXtUser())
89445   WHERE (invchead_id=_p.invchead_id);
89446  
89447   RETURN _itemlocSeries;
89448
89449 END;
89450 $_$;
89451
89452
89453 ALTER FUNCTION public.voidinvoice(integer) OWNER TO admin;
89454
89455 --
89456 -- TOC entry 1115 (class 1255 OID 146567188)
89457 -- Dependencies: 4536 8
89458 -- Name: voidpostedapcheck(integer); Type: FUNCTION; Schema: public; Owner: admin
89459 --
89460
89461 CREATE FUNCTION voidpostedapcheck(integer) RETURNS integer
89462     LANGUAGE plpgsql
89463     AS $_$
89464 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89465 -- See www.xtuple.com/CPAL for the full text of the software license.
89466 BEGIN
89467   RAISE NOTICE 'voidPostedAPCheck() is deprecated - use voidPostedCheck() instead';
89468   RETURN voidPostedCheck($1, fetchJournalNumber('AP-CK'), CURRENT_DATE);
89469 END;
89470 $_$;
89471
89472
89473 ALTER FUNCTION public.voidpostedapcheck(integer) OWNER TO admin;
89474
89475 --
89476 -- TOC entry 1145 (class 1255 OID 146567189)
89477 -- Dependencies: 4536 8
89478 -- Name: voidpostedapcheck(integer, integer); Type: FUNCTION; Schema: public; Owner: admin
89479 --
89480
89481 CREATE FUNCTION voidpostedapcheck(integer, integer) RETURNS integer
89482     LANGUAGE plpgsql
89483     AS $_$
89484 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89485 -- See www.xtuple.com/CPAL for the full text of the software license.
89486 BEGIN
89487   RAISE NOTICE 'voidPostedAPCheck() is deprecated - use voidPostedCheck() instead';
89488   RETURN voidPostedCheck($1, $2, CURRENT_DATE);
89489 END;
89490 $_$;
89491
89492
89493 ALTER FUNCTION public.voidpostedapcheck(integer, integer) OWNER TO admin;
89494
89495 --
89496 -- TOC entry 1215 (class 1255 OID 146567190)
89497 -- Dependencies: 4536 8
89498 -- Name: voidpostedapcheck(integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
89499 --
89500
89501 CREATE FUNCTION voidpostedapcheck(integer, integer, date) RETURNS integer
89502     LANGUAGE plpgsql
89503     AS $_$
89504 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89505 -- See www.xtuple.com/CPAL for the full text of the software license.
89506 BEGIN
89507   RAISE NOTICE 'voidPostedAPCheck() is deprecated - use voidPostedCheck() instead';
89508   RETURN voidPostedCheck($1, $2, $3);
89509 END;
89510 $_$;
89511
89512
89513 ALTER FUNCTION public.voidpostedapcheck(integer, integer, date) OWNER TO admin;
89514
89515 --
89516 -- TOC entry 1222 (class 1255 OID 146567191)
89517 -- Dependencies: 4536 8
89518 -- Name: voidpostedcheck(integer, integer, date); Type: FUNCTION; Schema: public; Owner: admin
89519 --
89520
89521 CREATE FUNCTION voidpostedcheck(integer, integer, date) RETURNS integer
89522     LANGUAGE plpgsql
89523     AS $_$
89524 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89525 -- See www.xtuple.com/CPAL for the full text of the software license.
89526 DECLARE
89527   pCheckid              ALIAS FOR $1;
89528   pJournalNumber        ALIAS FOR $2;
89529   pVoidDate             ALIAS FOR $3;
89530   _amount_base          NUMERIC := 0;
89531   _result               INTEGER;
89532   _apopenid             INTEGER;
89533   _credit_glaccnt       INTEGER;
89534   _docnumber            TEXT;
89535   _exchGain             NUMERIC := 0;
89536   _exchGainTmp          NUMERIC := 0;
89537   _gltransNote          TEXT;
89538   _p                    RECORD;
89539   _r                    RECORD;
89540   _sequence             INTEGER;
89541   _amount_check         NUMERIC := 0;
89542
89543 BEGIN
89544
89545   SELECT fetchGLSequence() INTO _sequence;
89546
89547   SELECT checkhead.*,
89548          checkhead_amount / checkhead_curr_rate AS checkhead_amount_base,
89549          bankaccnt_accnt_id AS bankaccntid,
89550          findPrepaidAccount(checkhead_recip_id) AS prepaidaccntid,
89551          checkrecip.* INTO _p
89552   FROM bankaccnt, checkhead LEFT OUTER JOIN
89553        checkrecip ON ((checkrecip_type=checkhead_recip_type)
89554                   AND (checkrecip_id=checkhead_recip_id))
89555   WHERE ((checkhead_bankaccnt_id=bankaccnt_id)
89556     AND  (checkhead_id=pCheckid));
89557
89558   IF (NOT _p.checkhead_posted) THEN
89559     RETURN -10;
89560   END IF;
89561
89562   IF (_p.checkrecip_id IS NULL) THEN    -- outer join failed
89563     RETURN -11;
89564   END IF;
89565
89566   -- Cannot void if already reconciled
89567   SELECT trans_id INTO _result
89568   FROM ( SELECT gltrans_id AS trans_id
89569          FROM gltrans
89570               LEFT OUTER JOIN bankrecitem ON (bankrecitem_source='GL' AND bankrecitem_source_id=gltrans_id)
89571          WHERE ( (gltrans_doctype='CK')
89572            AND   (gltrans_misc_id=_p.checkhead_id)
89573            AND   ((gltrans_rec) OR (bankrecitem_id IS NOT NULL)) )
89574          UNION ALL
89575          SELECT sltrans_id AS trans_id
89576          FROM sltrans
89577               LEFT OUTER JOIN bankrecitem ON (bankrecitem_source='GL' AND bankrecitem_source_id=sltrans_id)
89578          WHERE ( (sltrans_doctype='CK')
89579            AND   (sltrans_misc_id=_p.checkhead_id)
89580            AND   ((sltrans_rec) OR (bankrecitem_id IS NOT NULL)) )
89581        ) AS data;
89582   IF (FOUND) THEN
89583     RETURN -14;
89584   END IF;
89585
89586   _gltransNote := 'Void Posted Check #' || _p.checkhead_number || ' ' ||
89587                   _p.checkrecip_number || '-' || _p.checkrecip_name;
89588
89589   IF (_p.checkhead_misc) THEN
89590     IF (COALESCE(_p.checkhead_expcat_id, -1) < 0) THEN
89591       IF (_p.checkhead_recip_type = 'V') THEN
89592         PERFORM createAPDebitMemo(_p.checkhead_recip_id, pJournalNumber,
89593                                   CAST(fetchAPMemoNumber() AS text), '',
89594                                   pVoidDate, _p.checkhead_amount,
89595                                   _gltransNote || ' '|| _p.checkhead_notes,
89596                                   -1, pVoidDate, -1, _p.checkhead_curr_id );
89597         _credit_glaccnt := findAPPrepaidAccount(_p.checkhead_recip_id);
89598
89599       ELSIF (_p.checkhead_recip_type = 'C') THEN
89600         PERFORM createARCreditMemo(NULL, _p.checkhead_recip_id,
89601                                   fetchARMemoNumber(), '', 
89602                                   pVoidDate, _p.checkhead_amount,
89603                                   _gltransNote || ' '|| _p.checkhead_notes,
89604                                   -1, -1, -1, pVoidDate, -1, NULL, 0.0,
89605                                   pJournalNumber, _p.checkhead_curr_id );
89606         _credit_glaccnt := _p.prepaidaccntid;
89607
89608       ELSIF (_p.checkhead_recip_type = 'T') THEN
89609         -- TODO: should we create a debit memo for the tax authority? how?
89610         _credit_glaccnt := _p.checkrecip_accnt_id;
89611
89612       END IF; -- recip type
89613
89614     ELSE
89615       SELECT expcat_exp_accnt_id INTO _credit_glaccnt
89616       FROM expcat
89617       WHERE (expcat_id=_p.checkhead_expcat_id);
89618       IF (NOT FOUND) THEN
89619         RETURN -12;
89620       END IF;
89621     END IF;
89622
89623     IF (COALESCE(_credit_glaccnt, -1) < 0) THEN
89624       RETURN -13;
89625     END IF;
89626
89627     PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source, 'CK',
89628                                 text(_p.checkhead_number),
89629                                 _credit_glaccnt,
89630                                 round(_p.checkhead_amount_base, 2),
89631                                 pVoidDate, _gltransNote, pCheckid);
89632
89633     _amount_base := _p.checkhead_amount_base;
89634
89635   ELSE
89636     FOR _r IN SELECT checkitem_amount, checkitem_discount,
89637                      CASE WHEN (checkitem_apopen_id IS NOT NULL AND apopen_doctype='C') THEN
89638                             checkitem_amount / apopen_curr_rate * -1.0
89639                           WHEN (checkitem_apopen_id IS NOT NULL) THEN
89640                             checkitem_amount / apopen_curr_rate
89641                           ELSE
89642                             currToBase(checkitem_curr_id,
89643                                        checkitem_amount,
89644                                        COALESCE(checkitem_docdate, _p.checkhead_checkdate)) 
89645                      END AS checkitem_amount_base,
89646                      currTocurr(checkitem_curr_id, _p.checkhead_curr_id,
89647                                 CASE WHEN (checkitem_apopen_id IS NOT NULL AND apopen_doctype='C') THEN
89648                                           checkitem_amount * -1.0
89649                                      ELSE checkitem_amount END,
89650                                   _p.checkhead_checkdate) AS amount_check,
89651                      apopen_id, apopen_doctype, apopen_docnumber, apopen_curr_rate, apopen_docdate,
89652                      aropen_id, aropen_doctype, aropen_docnumber,
89653                      checkitem_curr_id, checkitem_curr_rate,
89654                      COALESCE(checkitem_docdate, _p.checkhead_checkdate) AS docdate
89655               FROM (checkitem LEFT OUTER JOIN
89656                     apopen ON (checkitem_apopen_id=apopen_id)) LEFT OUTER JOIN
89657                     aropen ON (checkitem_aropen_id=aropen_id)
89658               WHERE (checkitem_checkhead_id=pcheckid) LOOP
89659
89660       _exchGainTmp := 0;
89661       IF (_r.apopen_id IS NOT NULL) THEN
89662         -- undo the APDiscount Credit Memo if a discount was taken
89663         IF(_r.checkitem_discount > 0) THEN
89664           SELECT NEXTVAL('apopen_apopen_id_seq') INTO _apopenid;
89665           SELECT fetchAPMemoNumber() INTO _docnumber;
89666           INSERT INTO apopen
89667           ( apopen_id, apopen_username, apopen_journalnumber,
89668             apopen_vend_id, apopen_docnumber, apopen_doctype, apopen_ponumber,
89669             apopen_docdate, apopen_duedate, apopen_distdate, apopen_terms_id,
89670             apopen_amount, apopen_paid, apopen_open,
89671             apopen_notes,
89672             apopen_accnt_id, apopen_curr_id, apopen_discount, apopen_curr_rate,
89673             apopen_closedate )
89674           VALUES
89675           ( _apopenid, getEffectiveXtUser(), pJournalNumber,
89676             _p.checkhead_recip_id, _docnumber, 'D', '',
89677             pVoidDate, pVoidDate, pVoidDate, -1,
89678             _r.checkitem_discount, _r.checkitem_discount, FALSE,
89679             ('Reverse Posted Discount ' || _r.apopen_doctype || ' ' ||
89680               _r.apopen_docnumber),
89681             -1, _p.checkhead_curr_id, TRUE, _r.apopen_curr_rate,
89682             current_date );
89683
89684
89685           PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source,
89686                                       'DS', _r.apopen_docnumber,
89687                                       findAPDiscountAccount(_p.checkhead_recip_id),
89688                                       round(_r.checkitem_discount / _r.apopen_curr_rate, 2) * -1,
89689                                       pVoidDate, _gltransNote, pCheckid);
89690
89691           PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source,
89692                                       'DS', _r.apopen_docnumber,
89693                                       findAPAccount(_p.checkhead_recip_id),
89694                                       round(_r.checkitem_discount / _r.apopen_curr_rate, 2),
89695                                       pVoidDate, _gltransNote, pCheckid);
89696
89697           --  Post the application
89698           INSERT INTO apapply
89699           ( apapply_vend_id, apapply_postdate, apapply_username,
89700             apapply_source_apopen_id, apapply_source_doctype, apapply_source_docnumber,
89701             apapply_target_apopen_id, apapply_target_doctype, apapply_target_docnumber,
89702             apapply_journalnumber, apapply_amount, apapply_curr_id )
89703           VALUES
89704           ( _p.checkhead_recip_id, pVoidDate, getEffectiveXtUser(),
89705             _apopenid, 'D', _docnumber,
89706             _r.apopen_id, _r.apopen_doctype, _r.apopen_docnumber,
89707             pJournalNumber, (_r.checkitem_discount * -1), _r.checkitem_curr_id );
89708         END IF; -- discount was taken
89709
89710         UPDATE apopen
89711        SET apopen_paid = round(apopen_paid -
89712                                 (_r.checkitem_amount + noNeg(_r.checkitem_discount)), 2),
89713             apopen_open = round(apopen_amount, 2) >
89714                           round(apopen_paid -
89715                                 (_r.checkitem_amount + noNeg(_r.checkitem_discount)), 2),
89716             apopen_closedate = CASE WHEN (round(apopen_amount, 2) >
89717                                           round(apopen_paid -
89718                                            (_r.checkitem_amount + noNeg(_r.checkitem_discount)))) THEN NULL ELSE apopen_closedate END
89719         WHERE (apopen_id=_r.apopen_id);
89720
89721         --  Post the application
89722         INSERT INTO apapply
89723         ( apapply_vend_id, apapply_postdate, apapply_username,
89724           apapply_source_apopen_id, apapply_source_doctype, apapply_source_docnumber,
89725           apapply_target_apopen_id, apapply_target_doctype, apapply_target_docnumber,
89726           apapply_journalnumber, apapply_amount, apapply_curr_id )
89727         VALUES
89728         ( _p.checkhead_recip_id, pVoidDate, getEffectiveXtUser(),
89729           -1, 'K', _p.checkhead_number,
89730           _r.apopen_id, _r.apopen_doctype, _r.apopen_docnumber,
89731           pJournalNumber, (_r.checkitem_amount * -1), _r.checkitem_curr_id );
89732       END IF; -- if check item's apopen_id is not null
89733
89734       IF (_r.aropen_id IS NOT NULL) THEN
89735         UPDATE aropen
89736         SET aropen_paid = round(aropen_paid -_r.checkitem_amount, 2),
89737             aropen_open = round(aropen_amount, 2) >
89738                           round(aropen_paid - _r.checkitem_amount, 2)
89739         WHERE (aropen_id=_r.aropen_id);
89740
89741         --  Post the application
89742         INSERT INTO arapply
89743         ( arapply_cust_id, arapply_postdate, arapply_distdate, arapply_username,
89744           arapply_source_aropen_id, arapply_source_doctype, arapply_source_docnumber,
89745           arapply_target_aropen_id, arapply_target_doctype, arapply_target_docnumber,
89746           arapply_journalnumber, arapply_applied, arapply_curr_id )
89747         VALUES
89748         ( _p.checkhead_recip_id, pVoidDate, pVoidDate, getEffectiveXtUser(),
89749           -1, 'K', _p.checkhead_number,
89750           _r.aropen_id, _r.aropen_doctype, _r.aropen_docnumber,
89751           pJournalNumber, (_r.checkitem_amount * -1), _r.checkitem_curr_id );
89752
89753       END IF; -- if check item's aropen_id is not null
89754
89755 --  calculate currency gain/loss
89756       IF (_r.apopen_id IS NOT NULL) THEN
89757         IF (_p.checkhead_curr_id = _r.checkitem_curr_id) THEN
89758           IF (_r.apopen_docdate > _p.checkhead_checkdate) THEN
89759             _exchGainTmp := ((_r.checkitem_amount/_p.checkhead_curr_rate) - (_r.checkitem_amount / _r.apopen_curr_rate)) * -1;
89760           ELSE
89761             _exchGainTmp := ((_r.checkitem_amount / _r.apopen_curr_rate) - (_r.checkitem_amount/_p.checkhead_curr_rate));
89762           END IF;
89763         ELSE
89764           -- unusual condition where bank overridden and different currency from voucher
89765           -- this does not work for all situations
89766           --IF (_r.apopen_docdate > _p.checkhead_checkdate) THEN
89767           --  _exchGainTmp := ((_r.checkitem_amount/_r.checkitem_curr_rate) - (_r.checkitem_amount / _r.apopen_curr_rate)) * -1;
89768           --ELSE
89769           --  _exchGainTmp := ((_r.checkitem_amount / _r.apopen_curr_rate) - (_r.checkitem_amount/_r.checkitem_curr_rate));
89770           --END IF;
89771           _exchGainTmp := 0.0;
89772         END IF;
89773       ELSE
89774         SELECT arCurrGain(_r.aropen_id,_r.checkitem_curr_id, _r.checkitem_amount,
89775                         _p.checkhead_checkdate)
89776               INTO _exchGainTmp;
89777       END IF;
89778       _exchGain := _exchGain + _exchGainTmp;
89779
89780       PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source,
89781                                   'CK', text(_p.checkhead_number),
89782                                   _p.checkrecip_accnt_id,
89783                                   round(_r.checkitem_amount_base, 2),
89784                                   pVoidDate, _gltransNote, pCheckid);
89785       IF (_exchGainTmp <> 0) THEN
89786           PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source,
89787                                       'CK', text(_p.checkhead_number),
89788                                       getGainLossAccntId(_p.checkrecip_accnt_id),
89789                                       round(_exchGainTmp, 2) * -1,
89790                                       pVoidDate, _gltransNote, pCheckid);
89791       END IF;
89792
89793       _amount_check := (_amount_check + _r.amount_check);
89794       _amount_base := (_amount_base + _r.checkitem_amount_base);
89795
89796     END LOOP;
89797
89798     IF( (_amount_check - _p.checkhead_amount) <> 0.0 ) THEN 
89799       _exchGainTmp :=  (_amount_check - _p.checkhead_amount) / _p.checkhead_curr_rate;
89800       _exchGain := _exchGain + _exchGainTmp;
89801     END IF;
89802
89803     --  ensure that the check balances, attribute rounding errors to gain/loss
89804     IF round(_amount_base, 2) - round(_exchGain, 2) <> round(_p.checkhead_amount_base, 2) THEN
89805       IF round(_amount_base - _exchGain, 2) = round(_p.checkhead_amount_base, 2) THEN
89806         PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source,
89807                                     'CK',
89808                                     text(_p.checkhead_number), getGainLossAccntId(_p.bankaccntid),
89809                                     (round(_amount_base, 2) -
89810                                      round(_exchGain, 2) -
89811                                      round(_p.checkhead_amount_base, 2)) * -1,
89812                                     pVoidDate, _gltransNote, pCheckid);
89813       ELSE
89814         RAISE EXCEPTION 'checkhead_id % does not balance (% - % <> %)', pCheckid,
89815               _amount_base, _exchGain, _p.checkhead_amount_base;
89816       END IF;
89817     END IF;
89818   END IF;
89819
89820   PERFORM insertIntoGLSeries( _sequence, _p.checkrecip_gltrans_source, 'CK',
89821                               text(_p.checkhead_number),
89822                               _p.bankaccntid,
89823                               round(_p.checkhead_amount_base, 2) * -1,
89824                               pVoidDate, _gltransNote, pCheckid);
89825
89826   PERFORM postGLSeries(_sequence, pJournalNumber);
89827
89828   UPDATE gltrans
89829      SET gltrans_misc_id=pCheckid
89830    WHERE gltrans_sequence=_sequence;
89831
89832   UPDATE checkhead
89833   SET checkhead_posted=false,
89834       checkhead_void=true,
89835       checkhead_journalnumber=pJournalNumber
89836   WHERE (checkhead_id=pCheckid);
89837
89838   RETURN pJournalNumber;
89839
89840 END;
89841 $_$;
89842
89843
89844 ALTER FUNCTION public.voidpostedcheck(integer, integer, date) OWNER TO admin;
89845
89846 --
89847 -- TOC entry 1254 (class 1255 OID 146567193)
89848 -- Dependencies: 4536 8
89849 -- Name: woeffectivedate(date); Type: FUNCTION; Schema: public; Owner: admin
89850 --
89851
89852 CREATE FUNCTION woeffectivedate(date) RETURNS date
89853     LANGUAGE plpgsql
89854     AS $_$
89855 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89856 -- See www.xtuple.com/CPAL for the full text of the software license.
89857 DECLARE
89858   pStartDate ALIAS FOR $1;
89859
89860 BEGIN
89861
89862   IF (explodeWoEffective() = 'E') THEN
89863     RETURN CURRENT_DATE;
89864   ELSE
89865     RETURN pStartDate;
89866   END IF;
89867
89868 END;
89869 $_$;
89870
89871
89872 ALTER FUNCTION public.woeffectivedate(date) OWNER TO admin;
89873
89874 --
89875 -- TOC entry 2324 (class 1255 OID 146567195)
89876 -- Dependencies: 2714 4536 8
89877 -- Name: woinvavail(integer, integer, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
89878 --
89879
89880 CREATE FUNCTION woinvavail(integer, integer, boolean, boolean) RETURNS SETOF woinvav
89881     LANGUAGE plpgsql
89882     AS $_$
89883 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89884 -- See www.xtuple.com/CPAL for the full text of the software license.
89885 DECLARE
89886    pwoid ALIAS FOR $1; 
89887    plevel ALIAS FOR $2;
89888    pshowshortage ALIAS FOR $3;
89889    pshowlowinventory ALIAS FOR $4;
89890   _row woinvav%ROWTYPE;
89891   _x RECORD;
89892   _subx RECORD;
89893   _index INTEGER;
89894   _level INTEGER;
89895   _qry TEXT;   
89896 BEGIN   
89897     FOR _x IN
89898           SELECT wo_id,
89899                 itemsite_id,
89900                 item_type,
89901                 wo_number,
89902                 wo_subnumber,                             
89903                 item_number,
89904                 item_descrip1, 
89905                 item_descrip2, 
89906                 uom_name,
89907                 qoh, 
89908                 wobalance, 
89909                 allocated, 
89910                 ordered,                        
89911                 reorderlevel,
89912                 (qoh + ordered - wobalance) AS woavail,
89913                 (qoh + ordered - allocated) AS totalavail 
89914          FROM(SELECT wo_id,
89915                 itemsite_id,
89916                 item_type,
89917                 wo_number,
89918                 wo_subnumber,                             
89919                 item_number,
89920                 item_descrip1, 
89921                 item_descrip2, 
89922                 uom_name,
89923                 noNeg(itemsite_qtyonhand) AS qoh, 
89924                 noNeg(wo_qtyord - wo_qtyrcv) AS wobalance, 
89925                 qtyAllocated(itemsite_id, wo_duedate) AS allocated, 
89926                 qtyOrdered(itemsite_id, wo_duedate) AS ordered,                        
89927                 CASE WHEN(itemsite_useparams) THEN itemsite_reorderlevel ELSE 0.0 END AS reorderlevel 
89928           FROM wo, itemsite, item, uom     
89929          WHERE ((wo_ordid = pwoid)
89930            AND NOT (wo_status = 'C')          
89931            AND (itemsite_id = wo_itemsite_id)
89932            AND (itemsite_item_id=item_id)
89933            AND (item_inv_uom_id=uom_id))               
89934          ORDER BY wo_number, wo_subnumber) AS data
89935        LOOP       
89936          _row.woinvav_itemsite_id := _x.itemsite_id;            
89937          _row.woinvav_womatl_id := -1;
89938          _row.woinvav_type := _x.item_type;          
89939          _row.woinvav_item_wo_number := _x.wo_number || '-' || _x.wo_subnumber;
89940          _row.woinvav_descrip := _x.item_descrip1 || ' ' || _x.item_descrip2;
89941          _row.woinvav_uomname := _x.uom_name;
89942          _row.woinvav_qoh := _x.qoh;
89943          _row.woinvav_balance := _x.wobalance;
89944          _row.woinvav_allocated := _x.allocated;     
89945          _row.woinvav_ordered := _x.ordered;         
89946          _row.woinvav_woavail := _x.woavail;
89947          _row.woinvav_totalavail := _x.totalavail;
89948          _row.woinvav_reorderlevel := _x.reorderlevel;               
89949          _row.woinvav_level := plevel;                       
89950          RETURN NEXT _row;         
89951         --get materials for this level
89952         FOR _subx IN
89953           SELECT * FROM woinvavailmatl(_x.wo_id, plevel + 1, pshowshortage, pshowlowinventory) 
89954         LOOP                                            
89955           RETURN NEXT _subx;
89956         END LOOP;
89957         --get next level wo
89958         FOR _subx IN
89959           SELECT * FROM woinvavail(_x.wo_id, plevel + 1, pshowshortage, pshowlowinventory) 
89960         LOOP                                            
89961           RETURN NEXT _subx;
89962         END LOOP;
89963       END LOOP;   
89964   RETURN;
89965 END;
89966 $_$;
89967
89968
89969 ALTER FUNCTION public.woinvavail(integer, integer, boolean, boolean) OWNER TO admin;
89970
89971 --
89972 -- TOC entry 2323 (class 1255 OID 146567194)
89973 -- Dependencies: 2714 4536 8
89974 -- Name: woinvavail(integer, boolean, boolean, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
89975 --
89976
89977 CREATE FUNCTION woinvavail(integer, boolean, boolean, boolean, boolean) RETURNS SETOF woinvav
89978     LANGUAGE plpgsql
89979     AS $_$
89980 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
89981 -- See www.xtuple.com/CPAL for the full text of the software license.
89982 DECLARE
89983    pwoid ALIAS FOR $1;   
89984    pshowchildindent ALIAS FOR $2;    
89985    pshowchildsum ALIAS FOR $3;
89986    pshowshortage ALIAS FOR $4;
89987    pshowlowinventory ALIAS FOR $5;
89988   _row woinvav%ROWTYPE;
89989   _subrow woinvav%ROWTYPE;
89990   _wonumber TEXT;
89991   _x RECORD;
89992   _subx RECORD;  
89993   _qry TEXT;
89994    
89995 BEGIN   
89996     
89997     IF(pshowchildindent) THEN 
89998       --get top level order   
89999       FOR _x IN
90000           SELECT wo_id,
90001                 itemsite_id,
90002                 item_type,
90003                 wo_number,
90004                 wo_subnumber,                             
90005                 item_number,
90006                 item_descrip1, 
90007                 item_descrip2, 
90008                 uom_name,
90009                 qoh, 
90010                 wobalance, 
90011                 allocated, 
90012                 ordered,                        
90013                 reorderlevel,
90014                 (qoh + ordered - wobalance) AS woavail,
90015                 (qoh + ordered - allocated) AS totalavail 
90016          FROM(SELECT wo_id,
90017                 itemsite_id,
90018                 item_type,
90019                 wo_number,
90020                 wo_subnumber,                             
90021                 item_number,
90022                 item_descrip1, 
90023                 item_descrip2, 
90024                 uom_name,
90025                 noNeg(itemsite_qtyonhand) AS qoh, 
90026                 noNeg(wo_qtyord - wo_qtyrcv) AS wobalance, 
90027                 qtyAllocated(itemsite_id, wo_duedate) AS allocated, 
90028                 qtyOrdered(itemsite_id, wo_duedate) AS ordered,                        
90029                 CASE WHEN(itemsite_useparams) THEN itemsite_reorderlevel ELSE 0.0 END AS reorderlevel 
90030           FROM wo, itemsite, item, uom     
90031          WHERE ((wo_id = pwoid)          
90032            AND (itemsite_id = wo_itemsite_id)
90033            AND (itemsite_item_id=item_id)
90034            AND (item_inv_uom_id=uom_id))               
90035          ORDER BY wo_number, wo_subnumber) AS data
90036        LOOP       
90037          _row.woinvav_itemsite_id := _x.itemsite_id;            
90038          _row.woinvav_womatl_id := -1;
90039          _row.woinvav_type := _x.item_type;          
90040          _row.woinvav_item_wo_number := _x.wo_number || '-' || _x.wo_subnumber;
90041          _row.woinvav_descrip := _x.item_descrip1 || ' ' || _x.item_descrip2;
90042          _row.woinvav_uomname := _x.uom_name;
90043          _row.woinvav_qoh := _x.qoh;
90044          _row.woinvav_balance := _x.wobalance;
90045          _row.woinvav_allocated := _x.allocated;     
90046          _row.woinvav_ordered := _x.ordered;         
90047          _row.woinvav_woavail := _x.woavail;
90048          _row.woinvav_totalavail := _x.totalavail;
90049          _row.woinvav_reorderlevel := _x.reorderlevel;
90050          _row.woinvav_level := 0;                       
90051          RETURN NEXT _row;                
90052         --get materials for this level        
90053         FOR _subx IN
90054           SELECT * FROM woinvavailmatl(_x.wo_id, 1, pshowshortage, pshowlowinventory) 
90055         LOOP                                            
90056           RETURN NEXT _subx;
90057         END LOOP;  
90058         FOR _subx IN
90059           SELECT * FROM woinvavail(_x.wo_id, 1, pshowshortage, pshowlowinventory)
90060         LOOP                                            
90061           RETURN NEXT _subx;
90062         END LOOP;  
90063      END LOOP;             
90064     ELSE
90065        SELECT wo_number FROM wo WHERE wo_id=pwoid LIMIT 1 INTO _wonumber;   
90066        --display a single level sum of work order requirements
90067        _qry := 'SELECT  wo_id,
90068                         itemsite_id, 
90069                         womatl_id,
90070                         item_type,
90071                         wo_number,                         
90072                         item_number, 
90073                         item_descrip1, 
90074                         item_descrip2, 
90075                         uom_name,                         
90076                         qoh, 
90077                         wobalance, 
90078                         allocated, 
90079                         ordered,                        
90080                         reorderlevel,
90081                         (qoh + ordered - wobalance) AS woavail,
90082                         (qoh + ordered - allocated) AS totalavail
90083                   FROM (SELECT wo_id,
90084                         itemsite_id, 
90085                         womatl_id,
90086                         item_type,                      
90087                         wo_number,                         
90088                         item_number, 
90089                         item_descrip1, 
90090                         item_descrip2, 
90091                         uom_name,                         
90092                         noNeg(itemsite_qtyonhand) AS qoh, 
90093                         noNeg(itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq - womatl_qtyiss)) AS wobalance, 
90094                         qtyAllocated(itemsite_id, womatl_duedate) AS allocated, 
90095                         qtyOrdered(itemsite_id, womatl_duedate) AS ordered,                        
90096                         CASE WHEN(itemsite_useparams) THEN itemsite_reorderlevel ELSE 0.0 END AS reorderlevel 
90097                    FROM wo, womatl, itemsite, item, uom  
90098                  WHERE (womatl_wo_id=wo_id) 
90099                    AND (womatl_itemsite_id=itemsite_id) 
90100                    AND (itemsite_item_id=item_id) 
90101                    AND (item_inv_uom_id=uom_id) ';
90102                 IF(pshowchildsum) THEN
90103                   _qry := _qry || ' AND (wo_number=' || _wonumber || ')';
90104                 ELSE  
90105                   _qry := _qry || ' AND (womatl_wo_id=' || pwoid || ')';                  
90106                 END IF; 
90107                  _qry := _qry || ' ORDER BY item_number) AS data ';  
90108                 IF(pshowshortage) THEN
90109                   _qry := _qry || ' WHERE (((qoh + ordered - allocated) < 0) OR ((qoh + ordered - wobalance) < 0)) '; 
90110                 END IF;
90111                 IF(pshowlowinventory AND NOT pshowshortage) THEN                 
90112                   _qry := _qry || ' WHERE (((qoh - allocated) < 0) OR ((qoh - wobalance) < 0)) '; 
90113                 END IF;                 
90114                 
90115       FOR _x IN   
90116          EXECUTE _qry
90117       LOOP        
90118         _row.woinvav_itemsite_id := _x.itemsite_id;            
90119         _row.woinvav_womatl_id := _x.womatl_id;  
90120         _row.woinvav_type := _x.item_type;      
90121         _row.woinvav_item_wo_number := _x.item_number;
90122         _row.woinvav_descrip := _x.item_descrip1 || ' ' || _x.item_descrip2;
90123         _row.woinvav_uomname := _x.uom_name;
90124         _row.woinvav_qoh := _x.qoh;
90125         _row.woinvav_balance := _x.wobalance;
90126         _row.woinvav_allocated := _x.allocated;     
90127         _row.woinvav_ordered := _x.ordered;         
90128         _row.woinvav_woavail := _x.woavail;
90129         _row.woinvav_totalavail := _x.totalavail;
90130         _row.woinvav_reorderlevel := _x.reorderlevel;
90131         _row.woinvav_level := 0;                
90132         RETURN NEXT _row;  
90133   END LOOP;
90134   END IF;                     
90135   RETURN;
90136 END;
90137 $_$;
90138
90139
90140 ALTER FUNCTION public.woinvavail(integer, boolean, boolean, boolean, boolean) OWNER TO admin;
90141
90142 --
90143 -- TOC entry 2325 (class 1255 OID 146567196)
90144 -- Dependencies: 2714 4536 8
90145 -- Name: woinvavailmatl(integer, integer, boolean, boolean); Type: FUNCTION; Schema: public; Owner: admin
90146 --
90147
90148 CREATE FUNCTION woinvavailmatl(integer, integer, boolean, boolean) RETURNS SETOF woinvav
90149     LANGUAGE plpgsql
90150     AS $_$
90151 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
90152 -- See www.xtuple.com/CPAL for the full text of the software license.
90153 DECLARE
90154    pwoid ALIAS FOR $1;    
90155    plevel ALIAS FOR $2;
90156    pshowshortage ALIAS FOR $3;
90157    pshowlowinventory ALIAS FOR $4;
90158   _subrow woinvav%ROWTYPE;  
90159   _subx RECORD;
90160   _qry TEXT;
90161 BEGIN
90162   
90163    _qry := 'SELECT itemsite_id, 
90164            womatl_id,
90165            item_type, 
90166            wo_number, 
90167            wo_subnumber, 
90168            womatl_ref, 
90169            womatl_notes, 
90170            item_number,
90171            item_descrip1, 
90172            item_descrip2, 
90173            uom_name,
90174            qoh, 
90175            wobalance, 
90176            allocated, 
90177            ordered,
90178            (qoh + ordered - wobalance) AS woavail,
90179            (qoh + ordered - allocated) AS totalavail,
90180            reorderlevel 
90181     FROM(SELECT itemsite_id, 
90182                 womatl_id,
90183                 item_type,                 
90184                 wo_number, 
90185                 wo_subnumber, 
90186                 womatl_ref, 
90187                 womatl_notes, 
90188                 item_number,
90189                 item_descrip1, 
90190                 item_descrip2, 
90191                 uom_name,
90192                 noNeg(itemsite_qtyonhand) AS qoh, 
90193                 noNeg(itemuomtouom(itemsite_item_id, womatl_uom_id, NULL, womatl_qtyreq - womatl_qtyiss)) AS wobalance, 
90194                 qtyAllocated(itemsite_id, womatl_duedate) AS allocated, 
90195                 qtyOrdered(itemsite_id, womatl_duedate) AS ordered,
90196                 CASE WHEN(itemsite_useparams) THEN itemsite_reorderlevel ELSE 0.0 END AS reorderlevel
90197     FROM womatl, wo, itemsite, item, uom
90198     WHERE ((wo_id = womatl_wo_id)     
90199      AND (womatl_itemsite_id = itemsite_id)
90200      AND (itemsite_item_id=item_id)
90201      AND (womatl_uom_id=uom_id)
90202      AND (NOT womatl_createwo OR womatl_createwo IS NULL))';
90203      _qry := _qry || ' AND (wo_id=' || pwoid || ') ORDER BY item_number) AS data';
90204      IF(pshowshortage) THEN
90205      _qry := _qry || ' WHERE (((qoh + ordered - allocated) < 0) OR ((qoh + ordered - wobalance) < 0)) '; 
90206      END IF;
90207      IF(pshowlowinventory AND NOT pshowshortage) THEN                 
90208      _qry := _qry || ' WHERE (((qoh - allocated) < 0) OR ((qoh - wobalance) < 0)) '; 
90209      END IF;
90210         
90211      
90212      
90213   FOR _subx IN
90214       EXECUTE _qry
90215   LOOP
90216      _subrow.woinvav_itemsite_id := _subx.itemsite_id;            
90217      _subrow.woinvav_womatl_id := _subx.womatl_id;
90218      _subrow.woinvav_type := _subx.item_type;            
90219      _subrow.woinvav_item_wo_number := _subx.item_number;
90220      _subrow.woinvav_descrip := _subx.item_descrip1 || ' ' || _subx.item_descrip2;
90221      _subrow.woinvav_uomname := _subx.uom_name;
90222      _subrow.woinvav_qoh := _subx.qoh;
90223      _subrow.woinvav_balance := _subx.wobalance;
90224      _subrow.woinvav_allocated := _subx.allocated;     
90225      _subrow.woinvav_ordered := _subx.ordered;         
90226      _subrow.woinvav_woavail := _subx.woavail;
90227      _subrow.woinvav_totalavail := _subx.totalavail;
90228      _subrow.woinvav_reorderlevel := _subx.reorderlevel;
90229      _subrow.woinvav_level := plevel;                                     
90230     RETURN NEXT _subrow; 
90231   END LOOP;            
90232   RETURN;
90233 END;
90234 $_$;
90235
90236
90237 ALTER FUNCTION public.woinvavailmatl(integer, integer, boolean, boolean) OWNER TO admin;
90238
90239 --
90240 -- TOC entry 2326 (class 1255 OID 146567197)
90241 -- Dependencies: 4536 8
90242 -- Name: wostarted(integer); Type: FUNCTION; Schema: public; Owner: admin
90243 --
90244
90245 CREATE FUNCTION wostarted(pwoid integer) RETURNS boolean
90246     LANGUAGE plpgsql
90247     AS $$
90248 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
90249 -- See www.xtuple.com/CPAL for the full text of the software license.
90250 DECLARE
90251   _result BOOLEAN := FALSE;
90252    
90253 BEGIN   
90254   -- is it really this simple?
90255   SELECT (wo_wipvalue > 0) INTO _result
90256     FROM wo
90257    WHERE wo_id=pWoid;
90258   
90259   RETURN COALESCE(_result, FALSE);
90260 END;
90261 $$;
90262
90263
90264 ALTER FUNCTION public.wostarted(pwoid integer) OWNER TO admin;
90265
90266 SET search_path = te, pg_catalog;
90267
90268 --
90269 -- TOC entry 2327 (class 1255 OID 146567198)
90270 -- Dependencies: 4536 9
90271 -- Name: calcrate(numeric, character); Type: FUNCTION; Schema: te; Owner: admin
90272 --
90273
90274 CREATE FUNCTION calcrate(numeric, character) RETURNS numeric
90275     LANGUAGE plpgsql
90276     AS $_$
90277 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90278 -- See www.xtuple.com/CPAL for the full text of the software license.
90279 DECLARE
90280 pAmount ALIAS FOR $1;
90281 pPeriod ALIAS FOR $2;
90282 _state integer;
90283 _count integer;
90284
90285 BEGIN
90286   -- Convert amount to hourly rate
90287   IF (pPeriod = 'H') THEN  -- hourly
90288     RETURN round(pAmount,2);
90289   ELSIF (pPeriod = 'D') THEN -- daily
90290     RETURN round(pAmount / 8, 2);
90291   ELSIF (pPeriod = 'W') THEN  -- weekly
90292     RETURN round(pAmount / 40, 2);
90293   ELSIF (pPeriod = 'BW') THEN  -- bi-weekly
90294     RETURN round(pAmount / 80, 2);
90295   ELSIF (pPeriod = 'M') THEN -- monthly
90296     RETURN round(pAmount / 160, 2);
90297   ELSIF (pPeriod = 'Y') THEN -- annually 
90298     RETURN round(pAmount / 2080, 2);
90299   ELSE
90300     RAISE EXCEPTION 'Unknown period type passed: %', pPeriod;
90301   END IF;
90302
90303 END;
90304 $_$;
90305
90306
90307 ALTER FUNCTION te.calcrate(numeric, character) OWNER TO admin;
90308
90309 --
90310 -- TOC entry 2328 (class 1255 OID 146567199)
90311 -- Dependencies: 4536 9
90312 -- Name: copyitem(integer, text); Type: FUNCTION; Schema: te; Owner: admin
90313 --
90314
90315 CREATE FUNCTION copyitem(integer, text) RETURNS integer
90316     LANGUAGE plpgsql
90317     AS $_$
90318 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90319 -- See www.xtuple.com/CPAL for the full text of the software license.
90320 DECLARE
90321   pSItemid ALIAS FOR $1;
90322   pTItemNumber ALIAS FOR $2;
90323   _itemid INTEGER;
90324   _r RECORD;
90325   _id INTEGER;
90326
90327 BEGIN
90328   _itemid := public.copyItem(pSItemid, pTItemNumber);
90329
90330   INSERT INTO te.teexp
90331   SELECT _itemid, teexp_expcat_id, teexp_accnt_id
90332   FROM te.teexp src
90333   WHERE (src.teexp_id=pSItemid);
90334
90335   RETURN _itemid;
90336 END;
90337 $_$;
90338
90339
90340 ALTER FUNCTION te.copyitem(integer, text) OWNER TO admin;
90341
90342 --
90343 -- TOC entry 2332 (class 1255 OID 146567200)
90344 -- Dependencies: 4536 9
90345 -- Name: invoicesheets(integer[]); Type: FUNCTION; Schema: te; Owner: admin
90346 --
90347
90348 CREATE FUNCTION invoicesheets(integer[]) RETURNS integer
90349     LANGUAGE plpgsql
90350     AS $_$
90351 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90352 -- See www.xtuple.com/CPAL for the full text of the software license.
90353 DECLARE
90354 pHeadIDs ALIAS FOR $1;
90355
90356 _invcnum text;
90357 _invcheadid integer;
90358 _invcitemid integer;
90359 _s record;
90360 _t record;
90361 _linenum integer;
90362
90363 BEGIN
90364        -- Loop through time sheet items with matching criteria and make invoices
90365        FOR _s in SELECT DISTINCT 
90366                    teitem_cust_id, 
90367                    teitem_po, 
90368                    prj_id, 
90369                    teitem_curr_id
90370        FROM te.tehead 
90371          JOIN te.teitem ON (teitem_tehead_id=tehead_id AND teitem_billable)
90372          JOIN prjtask ON (teitem_prjtask_id=prjtask_id)
90373          JOIN prj ON (prjtask_prj_id=prj_id)
90374        WHERE ((tehead_id IN (SELECT * FROM te.unnest(pHeadIDs) ) )
90375         AND (teitem_billable)
90376         AND (teitem_invcitem_id IS NULL))
90377
90378        -- loop thru records and create invoices by customer, by PO for the provided headid
90379        LOOP
90380          --select nextval('invchead_invchead_id_seq') into _invcid;
90381          _invcnum := CAST(fetchInvcNumber() AS TEXT);
90382          _invcheadid := nextval('invchead_invchead_id_seq');
90383          _linenum := 1;
90384
90385          INSERT INTO invchead
90386          SELECT _invcheadid, cust_id, -1, '', current_date, false, false, _invcnum,
90387            current_date, current_date, _s.teitem_po, '', '', cust_name, COALESCE(addr_line1,''),
90388            COALESCE(addr_line2,''), COALESCE(addr_line3,''), COALESCE(addr_city,''),
90389            COALESCE(addr_state,''), COALESCE(addr_postalcode,''), cntct_phone, 
90390            '', '', '', '', '', '', '', '', cust_salesrep_id, salesrep_commission, cust_terms_id,
90391            0, 0, '', -1, 0, '', '', COALESCE(addr_country,''), '', _s.prj_id, 
90392            _s.teitem_curr_id, current_date, false, null, null, null, null, null, cust_taxzone_id
90393          FROM custinfo
90394            JOIN salesrep ON (cust_salesrep_id=salesrep_id)
90395            LEFT OUTER JOIN cntct ON (cust_cntct_id=cntct_id)
90396            LEFT OUTER JOIN addr ON (cntct_addr_id=addr_id)
90397          WHERE (cust_id=_s.teitem_cust_id);
90398
90399           -- loop thru all lines of the sheet
90400           FOR _t IN SELECT 
90401                teitem_id,
90402                teitem_linenumber, 
90403                tehead_warehous_id,
90404                teitem_type,
90405                tehead_emp_id,
90406                cust_taxzone_id,
90407                item_number,
90408                teitem_cust_id,
90409                teitem_po,
90410                teitem_item_id,
90411                teitem_qty,
90412                teitem_uom_id,
90413                teitem_rate,
90414                teitem_notes
90415              FROM te.teitem
90416                JOIN te.tehead ON (teitem_tehead_id = tehead_id)
90417                JOIN custinfo ON (cust_id = teitem_cust_id)
90418                JOIN item ON (item_id = teitem_item_id)
90419                JOIN prjtask ON (teitem_prjtask_id=prjtask_id)
90420                JOIN prj ON (prjtask_prj_id=prj_id)
90421              WHERE ((tehead_id IN (SELECT * FROM te.unnest(pHeadIDs) ) )
90422               AND (teitem_billable)
90423               AND (teitem_invcitem_id IS NULL)
90424               AND (item_id = teitem_item_id)
90425               AND (teitem_cust_id = _s.teitem_cust_id)
90426               AND (teitem_po = _s.teitem_po)
90427               AND (prj_id = _s.prj_id)
90428               AND (teitem_curr_id = _s.teitem_curr_id))
90429              ORDER BY teitem_linenumber
90430           LOOP
90431             _invcitemid := nextval('invcitem_invcitem_id_seq');
90432
90433             INSERT INTO invcitem
90434             SELECT 
90435               _invcitemid, _invcheadid, _linenum, _t.teitem_item_id,
90436               _t.tehead_warehous_id, '', '', '', _t.teitem_qty, _t.teitem_qty, _t.teitem_rate,
90437               _t.teitem_rate, _t.teitem_notes, -1, getItemTaxType(item_id, _t.cust_taxzone_id), 
90438               _t.teitem_uom_id, itemuomtouomratio(item_id, _t.teitem_uom_id, item_inv_uom_id),
90439               _t.teitem_uom_id, itemuomtouomratio(item_id, _t.teitem_uom_id, item_inv_uom_id),
90440               null
90441             FROM item
90442             WHERE (item_id=_t.teitem_item_id);
90443
90444             _linenum := _linenum + 1;
90445             
90446             -- Update the time sheet item record
90447             UPDATE te.teitem SET teitem_invcitem_id = _invcitemid WHERE (teitem_id = _t.teitem_id);
90448             
90449           END LOOP;
90450        END LOOP;
90451
90452 RETURN 1;
90453 END;
90454 $_$;
90455
90456
90457 ALTER FUNCTION te.invoicesheets(integer[]) OWNER TO admin;
90458
90459 --
90460 -- TOC entry 2333 (class 1255 OID 146567201)
90461 -- Dependencies: 4536 9
90462 -- Name: postsheet(integer, text, text); Type: FUNCTION; Schema: te; Owner: admin
90463 --
90464
90465 CREATE FUNCTION postsheet(integer, text, text) RETURNS integer
90466     LANGUAGE plpgsql
90467     AS $_$
90468 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90469 -- See www.xtuple.com/CPAL for the full text of the software license.
90470 DECLARE
90471 pTeheadId ALIAS FOR $1;
90472 pPhrase1 ALIAS FOR $2;
90473 pPhrase2 ALIAS FOR $3; 
90474 _r record;
90475 _notes TEXT;
90476 _value NUMERIC;
90477 _olaccntid INTEGER;
90478 _expaccntid INTEGER;
90479 _count INTEGER;
90480
90481 BEGIN
90482   -- Validate: No posting for contractors
90483   IF (SELECT (count(teemp_id) > 0) 
90484       FROM te.tehead
90485         JOIN te.teemp ON (tehead_emp_id=teemp_emp_id)
90486       WHERE ((tehead_id=pTeheadId)
90487         AND (teemp_contractor))) THEN
90488     RAISE EXCEPTION 'Time and Expense Sheets can not be posted for contractors.  Voucher instead.';
90489   END IF;
90490   
90491   -- Get labor and overhead account
90492   SELECT accnt_id INTO _olaccntid
90493   FROM accnt
90494   WHERE (accnt_id=fetchmetricvalue('PrjLaborAndOverhead'));
90495
90496   GET DIAGNOSTICS _count = ROW_COUNT;
90497   IF (_count = 0) THEN
90498     RAISE EXCEPTION 'No valid Project Labor and Overhead Account Defined';
90499   END IF;
90500
90501   -- Get applicable time sheets
90502   FOR _r IN 
90503     SELECT tehead_number,
90504       teitem_id, teitem_linenumber, teitem_type, teitem_notes,
90505       item_descrip1, teitem_qty,
90506       teexp_expcat_id, teexp_accnt_id, 
90507       emp_code, emp_wage, emp_wage_period,
90508       prj_id, prj_number
90509     FROM te.tehead
90510      JOIN te.teitem ON (teitem_tehead_id=tehead_id)
90511      JOIN item ON (teitem_item_id=item_id)
90512      JOIN te.teexp ON (teitem_item_id=teexp_id)
90513      JOIN emp ON (tehead_emp_id=emp_id)
90514      JOIN prjtask ON (prjtask_id=teitem_prjtask_id)
90515      JOIN prj ON (prj_id=prjtask_prj_id)
90516     WHERE ((tehead_id = pTeheadId)
90517      AND (NOT teitem_posted)
90518      AND (teitem_vodist_id IS NULL)
90519      AND (teitem_type = 'T'))
90520
90521   LOOP  
90522     -- Determine value
90523     _value := te.calcRate(_r.emp_wage, _r.emp_wage_period) * _r.teitem_qty;
90524
90525     -- Determine G/L account to post to
90526     IF (_r.teexp_accnt_id > 1) THEN
90527       _expaccntid := getPrjAccntId(_r.prj_id, _r.teexp_accnt_id);
90528     ELSE
90529       SELECT getPrjAccntId(_r.prj_id, expcat_exp_accnt_id) INTO _expaccntid
90530       FROM expcat
90531       WHERE (expcat_id=_r.teexp_expcat_id);
90532     END IF;
90533
90534     -- Execute the posting
90535     _notes := (pPhrase1 || _r.item_descrip1 || '/' || _r.emp_code || pPhrase2 || ' ' || _r.prj_number);
90536     PERFORM insertGLTransaction( 'T/E', 'TE', _r.tehead_number, _notes,
90537                                  _olaccntid, _expaccntid, -1,
90538                                  _value, current_date );
90539
90540     -- Update the time sheet item
90541     UPDATE te.teitem SET 
90542       teitem_posted = true,
90543       teitem_postedvalue = teitem_postedvalue + _value
90544     WHERE (teitem_id=_r.teitem_id);
90545                         
90546   END LOOP;
90547           
90548 RETURN 1;
90549 END;
90550 $_$;
90551
90552
90553 ALTER FUNCTION te.postsheet(integer, text, text) OWNER TO admin;
90554
90555 --
90556 -- TOC entry 2334 (class 1255 OID 146567202)
90557 -- Dependencies: 4536 9
90558 -- Name: sheetstate(integer, character); Type: FUNCTION; Schema: te; Owner: admin
90559 --
90560
90561 CREATE FUNCTION sheetstate(integer, character) RETURNS integer
90562     LANGUAGE plpgsql
90563     AS $_$
90564 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90565 -- See www.xtuple.com/CPAL for the full text of the software license.
90566 DECLARE
90567   pTeheadId ALIAS FOR $1;
90568   pType     ALIAS FOR $2;
90569   _state    INTEGER := -1;
90570
90571 BEGIN
90572   -- Check and return the process state of the sheet
90573   --    1 = All processed
90574   --    0 = Processing required
90575   --   -1 = Not Applicable
90576
90577   IF (pType = 'I') THEN
90578     SELECT MIN(CASE teitem_invcitem_id IS NULL WHEN TRUE THEN 0 ELSE 1 END) INTO _state
90579       FROM te.teitem
90580      WHERE ((teitem_tehead_id=pTeheadId)
90581         AND (teitem_billable)
90582         AND (teitem_qty >= 0));
90583
90584   ELSIF (pType = 'V') THEN
90585     -- todo: why outer join then check teitem_type and vend_id is not null?
90586     SELECT MIN(CASE teitem_vodist_id IS NULL WHEN TRUE THEN 0 ELSE 1 END) INTO _state
90587       FROM te.tehead
90588         JOIN emp ON (tehead_emp_id=emp_id)
90589         LEFT OUTER JOIN te.teemp ON (emp_id=teemp_emp_id)
90590         LEFT OUTER JOIN te.teitem ON (teitem_tehead_id=tehead_id)
90591         LEFT OUTER JOIN vendinfo ON (UPPER(emp_code)=UPPER(vend_number))
90592       WHERE ((teitem_tehead_id=pTeheadId)
90593          AND ((teitem_type = 'E' AND NOT teitem_prepaid) 
90594            OR (teitem_type = 'T' AND COALESCE(teemp_contractor,false)))
90595          AND (vend_id IS NOT NULL)
90596          AND (teitem_qty > 0));
90597
90598   ELSIF (pType = 'P') THEN
90599     SELECT MIN(CASE teitem_posted WHEN FALSE THEN 0 ELSE 1 END) INTO _state
90600       FROM te.teitem
90601       JOIN te.tehead ON (teitem_tehead_id=tehead_id)
90602       JOIN te.teemp ON (tehead_emp_id=teemp_emp_id)
90603      WHERE ((teitem_tehead_id=pTeheadId)
90604         AND (teitem_type = 'T')
90605         AND (NOT teemp_contractor));
90606
90607   ELSE
90608     -- TODO: either make ErrorReporter::error find this or use xtuple
90609     RAISE EXCEPTION 'Unknown process type % [xtte: sheetstate, -2, %]',
90610                     pType, pType;
90611   END IF;
90612
90613   RETURN _state;
90614
90615 END;
90616 $_$;
90617
90618
90619 ALTER FUNCTION te.sheetstate(integer, character) OWNER TO admin;
90620
90621 --
90622 -- TOC entry 2335 (class 1255 OID 146567203)
90623 -- Dependencies: 4536 9
90624 -- Name: triggertehead(); Type: FUNCTION; Schema: te; Owner: admin
90625 --
90626
90627 CREATE FUNCTION triggertehead() RETURNS trigger
90628     LANGUAGE plpgsql
90629     AS $$
90630 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90631 -- See www.xtuple.com/CPAL for the full text of the software license.
90632 DECLARE
90633 _r RECORD;
90634 _sense INTEGER := 0;
90635
90636 BEGIN
90637
90638   -- Determine whether we are adding or subtracting totals
90639   IF (TG_OP = 'UPDATE') THEN
90640     IF (OLD.tehead_status = 'O' AND NEW.tehead_status = 'A') THEN
90641     -- Approving so add
90642       _sense := 1;
90643     ELSIF  (OLD.tehead_status = 'A' AND NEW.tehead_status = 'O') THEN
90644     -- Unapproving so subtract
90645       _sense := -1;
90646     END IF;
90647   END IF;
90648
90649   IF (_sense != 0) THEN
90650     -- Loop thru all lines of the sheet and update project
90651     FOR _r in 
90652       SELECT teitem_prjtask_id, teitem_type, teitem_qty, teitem_total 
90653       FROM te.teitem
90654       WHERE teitem_tehead_id = NEW.tehead_id
90655
90656     LOOP
90657       IF (_r.teitem_type = 'T') THEN
90658         UPDATE prjtask SET 
90659           prjtask_hours_actual = prjtask_hours_actual + _r.teitem_qty * _sense
90660         WHERE prjtask_id = _r.teitem_prjtask_id;
90661       ELSE
90662         UPDATE prjtask SET 
90663           prjtask_exp_actual = prjtask_exp_actual + _r.teitem_total * _sense
90664         WHERE prjtask_id = _r.teitem_prjtask_id;
90665       END IF;
90666             
90667     END LOOP;
90668   END IF;
90669
90670   RETURN NEW;
90671 END;
90672 $$;
90673
90674
90675 ALTER FUNCTION te.triggertehead() OWNER TO admin;
90676
90677 --
90678 -- TOC entry 2336 (class 1255 OID 146567204)
90679 -- Dependencies: 4536 9
90680 -- Name: triggerteitem(); Type: FUNCTION; Schema: te; Owner: admin
90681 --
90682
90683 CREATE FUNCTION triggerteitem() RETURNS trigger
90684     LANGUAGE plpgsql
90685     AS $$
90686 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90687 -- See www.xtuple.com/CPAL for the full text of the software license.
90688 DECLARE
90689 _r RECORD;
90690 _status CHAR(1) := 'O';
90691
90692 BEGIN
90693   -- Validate whether we can take this action
90694   IF (TG_OP = 'UPDATE') THEN
90695     IF ((OLD.teitem_type != NEW.teitem_type)
90696       OR (OLD.teitem_workdate != NEW.teitem_workdate)
90697       OR (OLD.teitem_cust_id != NEW.teitem_cust_id)
90698       OR (OLD.teitem_po != NEW.teitem_po)
90699       OR (OLD.teitem_item_id != NEW.teitem_item_id)
90700       OR (OLD.teitem_qty != NEW.teitem_qty)
90701       OR (OLD.teitem_rate != NEW.teitem_rate)
90702       OR (OLD.teitem_total != NEW.teitem_total)
90703       OR (OLD.teitem_billable != NEW.teitem_billable)
90704       OR (OLD.teitem_prepaid != NEW.teitem_prepaid)
90705       OR (OLD.teitem_notes != NEW.teitem_notes)) THEN
90706       
90707       SELECT tehead_status INTO _status FROM te.tehead WHERE tehead_id=NEW.teitem_tehead_id;
90708     END IF;
90709   ELSIF (TG_OP = 'INSERT') THEN
90710     SELECT tehead_status INTO _status FROM te.tehead WHERE tehead_id=NEW.teitem_tehead_id;
90711   ELSE -- Must be delete
90712     SELECT tehead_status INTO _status FROM te.tehead WHERE tehead_id=OLD.teitem_tehead_id;
90713   END IF;
90714
90715   IF (_status != 'O') THEN
90716     RAISE EXCEPTION 'Time and Expense Sheets may only be edited or deleted when the status is Open';
90717   END IF;
90718
90719   _status := 'C';
90720   
90721   -- Update header status, default is to close if all processing complete
90722   IF (TG_OP = 'UPDATE') THEN
90723     IF ((COALESCE(OLD.teitem_invcitem_id,-1) != COALESCE(NEW.teitem_invcitem_id,-1))
90724       OR (COALESCE(OLD.teitem_vodist_id,-1) != COALESCE(NEW.teitem_vodist_id,-1))
90725       OR (OLD.teitem_posted != NEW.teitem_posted)) THEN
90726
90727       SELECT 
90728         te.sheetstate(NEW.teitem_tehead_id, 'I') AS invoiced,
90729         te.sheetstate(NEW.teitem_tehead_id, 'V') AS vouchered,
90730         te.sheetstate(NEW.teitem_tehead_id, 'P') AS posted
90731       INTO _r;
90732
90733       IF (_r.invoiced = 0 OR _r.vouchered = 0 OR _r.posted = 0) THEN
90734         _status := 'A'; -- Something is still open, so approved
90735       END IF;
90736     
90737       UPDATE te.tehead SET tehead_status = _status WHERE (tehead_id=NEW.teitem_tehead_id);
90738     END IF;
90739   END IF;
90740
90741   -- Update header with last use info
90742   IF (TG_OP = 'DELETE') THEN
90743     UPDATE te.tehead SET
90744       tehead_lastupdated=('now'::text)::timestamp(6) with time zone
90745     WHERE (tehead_id=OLD.teitem_tehead_id);
90746   ELSE
90747     UPDATE te.tehead SET
90748       tehead_lastupdated=('now'::text)::timestamp(6) with time zone,
90749       tehead_username=current_user
90750     WHERE (tehead_id=NEW.teitem_tehead_id);
90751   END IF;
90752
90753   RETURN NEW;
90754 END;
90755 $$;
90756
90757
90758 ALTER FUNCTION te.triggerteitem() OWNER TO admin;
90759
90760 --
90761 -- TOC entry 2329 (class 1255 OID 146567205)
90762 -- Dependencies: 4536 9
90763 -- Name: triggerteprj(); Type: FUNCTION; Schema: te; Owner: admin
90764 --
90765
90766 CREATE FUNCTION triggerteprj() RETURNS trigger
90767     LANGUAGE plpgsql
90768     AS $$
90769 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple. 
90770 -- See www.xtuple.com/CPAL for the full text of the software license.
90771 DECLARE
90772   _update BOOLEAN := false;
90773 BEGIN
90774
90775   IF (TG_OP = 'INSERT') THEN
90776     _update = true;
90777   ELSIF (TG_OP = 'UPDATE') THEN
90778     IF (COALESCE(OLD.teprj_cust_id,-1) != COALESCE(NEW.teprj_cust_id,-1)) THEN
90779       _update = true;
90780     END IF;
90781   END IF;
90782
90783   IF (_update) THEN
90784       UPDATE te.teprjtask SET teprjtask_cust_id=NEW.teprj_cust_id
90785       FROM prjtask
90786       WHERE ((teprjtask_prjtask_id=prjtask_id)
90787       AND (prjtask_prj_id=NEW.teprj_prj_id));
90788   END IF;
90789   
90790   RETURN NEW;
90791 END;
90792 $$;
90793
90794
90795 ALTER FUNCTION te.triggerteprj() OWNER TO admin;
90796
90797 --
90798 -- TOC entry 2330 (class 1255 OID 146567206)
90799 -- Dependencies: 9
90800 -- Name: unnest(anyarray); Type: FUNCTION; Schema: te; Owner: admin
90801 --
90802
90803 CREATE FUNCTION unnest(anyarray) RETURNS SETOF anyelement
90804     LANGUAGE sql IMMUTABLE
90805     AS $_$
90806 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple.
90807 -- See www.xtuple.com/CPAL for the full text of the software license.
90808 SELECT $1[i] FROM
90809     generate_series(array_lower($1,1),
90810                     array_upper($1,1)) i;
90811 $_$;
90812
90813
90814 ALTER FUNCTION te.unnest(anyarray) OWNER TO admin;
90815
90816 --
90817 -- TOC entry 2331 (class 1255 OID 146567207)
90818 -- Dependencies: 4536 9
90819 -- Name: vouchersheet(integer); Type: FUNCTION; Schema: te; Owner: admin
90820 --
90821
90822 CREATE FUNCTION vouchersheet(integer) RETURNS integer
90823     LANGUAGE plpgsql
90824     AS $_$
90825 -- Copyright (c) 1999-2012 by OpenMFG LLC, d/b/a xTuple.
90826 -- See www.xtuple.com/CPAL for the full text of the software license.
90827 DECLARE
90828   pHeadID ALIAS FOR $1;
90829   _distamt  NUMERIC;
90830   _glaccnt  INTEGER;
90831   _notes    TEXT;
90832   _s        RECORD;
90833   _total    NUMERIC := 0;
90834   _v        RECORD;
90835   _vodistid INTEGER;
90836   _voheadid INTEGER;
90837
90838 BEGIN
90839   FOR _v IN
90840     -- distinct filters duplicate rows returned because of the teitem join
90841     -- TODO: can we push the teitem down into the loop and avoid the distinct?
90842     SELECT DISTINCT
90843            tehead_id, tehead_number,   tehead_weekending,          tehead_notes,
90844            teitem_curr_id,
90845            emp_wage, emp_wage_period,
90846            vend_id,   vend_taxzone_id, vend_terms_id, vend_number, vend_1099,
90847            COALESCE(teemp_contractor, false) AS isContractor
90848       FROM te.tehead
90849       JOIN te.teitem ON (teitem_tehead_id=tehead_id)
90850       JOIN emp       ON (tehead_emp_id=emp_id)
90851       JOIN vendinfo  ON (UPPER(emp_code)=UPPER(vend_number))
90852       LEFT OUTER JOIN te.teemp ON (emp_id=teemp_emp_id)
90853     WHERE ((tehead_id      = pHeadID)
90854        AND (teitem_prepaid = false)
90855        AND (teitem_vodist_id IS NULL)
90856        AND (teitem_type = 'E' OR (COALESCE(teemp_contractor,false) AND (teitem_empcost > 0 OR emp_wage > 0 ))))  LOOP
90857
90858      INSERT INTO vohead (vohead_id,        vohead_number,     vohead_vend_id,
90859                          vohead_distdate,  vohead_docdate,
90860                          vohead_duedate,
90861                          vohead_terms_id,  vohead_taxzone_id, vohead_invcnumber,
90862                          vohead_reference, vohead_amount,     vohead_1099,
90863                          vohead_curr_id,   vohead_notes,      vohead_posted,
90864                          vohead_misc,      vohead_pohead_id)
90865                  VALUES (DEFAULT,              fetchVoNumber(),    _v.vend_id,
90866                          _v.tehead_weekending, _v.tehead_weekending,
90867                          determineDueDate(_v.vend_terms_id, _v.tehead_weekending),
90868                          _v.vend_terms_id,     _v.vend_taxzone_id, 'N/A',
90869                          ('T&E Sheet ' || _v.tehead_number),    0, _v.vend_1099,
90870                          _v.teitem_curr_id,    _v.tehead_notes, false,
90871                          true,                 -1)
90872      RETURNING vohead_id INTO _voheadid;
90873
90874      FOR _s IN
90875        SELECT teitem_id,       teitem_linenumber, teitem_workdate, teitem_type,
90876               item_number,     teitem_item_id,    teitem_qty,      prjtask_prj_id,
90877               CASE
90878                 WHEN teitem_empcost > 0 THEN teitem_empcost
90879                 ELSE te.calcRate(_v.emp_wage, _v.emp_wage_period)
90880               END AS rate,
90881               teitem_total,    teitem_type,
90882               teexp_expcat_id, teexp_accnt_id
90883          FROM te.teitem
90884          JOIN te.teexp ON (teitem_item_id=teexp_id)
90885          JOIN item     ON (teitem_item_id=item_id)
90886          JOIN prjtask  ON (teitem_prjtask_id=prjtask_id)
90887         WHERE ((teitem_tehead_id = _v.tehead_id)
90888            AND (teitem_curr_id   = _v.teitem_curr_id)
90889            AND (teitem_prepaid   = false)
90890            AND (teitem_vodist_id IS NULL)
90891            AND (teitem_type = 'E' OR (_v.isContractor AND (teitem_empcost > 0 OR _v.emp_wage > 0 )))) 
90892
90893
90894        -- Loop thru records and create vouchers by supplier for the provided headid
90895      LOOP
90896         -- insert vodist records here
90897         _vodistid = nextval('vodist_vodist_id_seq');
90898
90899         -- Map expense directly to account so we can get project account mapping if applicable
90900         IF (_s.teexp_accnt_id > 1) THEN
90901           _glaccnt := getPrjAccntId(_s.prjtask_prj_id, _s.teexp_accnt_id);
90902         ELSE
90903           SELECT getPrjAccntId(_s.prjtask_prj_id, expcat_exp_accnt_id) INTO _glaccnt
90904             FROM expcat
90905            WHERE (expcat_id=_s.teexp_expcat_id);
90906         END IF;
90907
90908         IF (_s.teitem_type = 'T') THEN -- Time sheet record
90909           _notes := formatdate(_s.teitem_workdate) || E'\t' || _s.item_number ||
90910                     E'\t' || formatQty(_s.teitem_qty) || ' hours' || E'\t';
90911           _distamt := _s.rate * _s.teitem_qty;
90912         ELSE -- Expense record
90913           _notes := formatdate(_s.teitem_workdate) || E'\t' || _s.item_number ||
90914                     E'\t' || E'\t';
90915           _distamt := _s.teitem_total;
90916         END IF;
90917
90918         INSERT INTO vodist (vodist_id,          vodist_vohead_id, vodist_poitem_id,
90919                             vodist_costelem_id, vodist_accnt_id,  vodist_amount,
90920                             vodist_expcat_id,   vodist_notes)
90921                     VALUES (_vodistid, _voheadid, -1,
90922                             -1,        _glaccnt,  _distamt,
90923                             -1,        _notes);
90924         _total := _total + _distamt;
90925
90926         -- Update the te.teitem record with the relationship
90927         UPDATE te.teitem SET teitem_vodist_id = _vodistid WHERE teitem_id = _s.teitem_id;
90928      END LOOP;
90929
90930     UPDATE vohead SET vohead_amount = _total WHERE (vohead_id=_voheadid);
90931      _total := 0;
90932
90933   END LOOP;
90934
90935   RETURN 1;
90936 END;
90937 $_$;
90938
90939
90940 ALTER FUNCTION te.vouchersheet(integer) OWNER TO admin;
90941
90942 SET search_path = xtdesktop, pg_catalog;
90943
90944 --
90945 -- TOC entry 2337 (class 1255 OID 146567209)
90946 -- Dependencies: 4536 10
90947 -- Name: fetchwelcomehtml(); Type: FUNCTION; Schema: xtdesktop; Owner: admin
90948 --
90949
90950 CREATE FUNCTION fetchwelcomehtml() RETURNS text
90951     LANGUAGE plpgsql IMMUTABLE
90952     AS $$
90953 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
90954 -- See www.xtuple.com/CPAL for the full text of the software license.
90955 DECLARE
90956   _html TEXT;
90957
90958 BEGIN
90959
90960   _html := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
90961 <HTML> 
90962 <HEAD> 
90963         <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8"> 
90964         <TITLE></TITLE> 
90965         <META NAME="GENERATOR" CONTENT="OpenOffice.org 3.0  (Unix)"> 
90966         <META NAME="CREATED" CONTENT="20100422;16091500"> 
90967         <META NAME="CHANGED" CONTENT="20100422;16095800"> 
90968         <META NAME="Info 1" CONTENT=""> 
90969         <META NAME="Info 2" CONTENT=""> 
90970         <META NAME="Info 3" CONTENT=""> 
90971         <META NAME="Info 4" CONTENT=""> 
90972         <STYLE TYPE="text/css"> 
90973         <!--
90974                 @page { margin: 0.79in }
90975                 P { margin-bottom: 0.08in }
90976         --> 
90977         </STYLE> 
90978 </HEAD> 
90979 <BODY LANG="en-US" DIR="LTR"> 
90980 <P STYLE="margin-bottom: 0in"><B>Welcome to xTuple</B></P> 
90981 <P STYLE="margin-bottom: 0in"><BR> 
90982 </P> 
90983 <P STYLE="margin-bottom: 0in">You are not connected to the internet
90984 at this time</P> 
90985 </BODY> 
90986 </HTML>';
90987
90988   RETURN _html;
90989
90990 END;
90991 $$;
90992
90993
90994 ALTER FUNCTION xtdesktop.fetchwelcomehtml() OWNER TO admin;
90995
90996 --
90997 -- TOC entry 2338 (class 1255 OID 146567210)
90998 -- Dependencies: 2717 4536 10
90999 -- Name: usersonline(); Type: FUNCTION; Schema: xtdesktop; Owner: admin
91000 --
91001
91002 CREATE FUNCTION usersonline() RETURNS SETOF usersonline
91003     LANGUAGE plpgsql
91004     AS $$
91005 -- Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple. 
91006 -- See www.xtuple.com/CPAL for the full text of the software license.
91007 DECLARE
91008  _row xtdesktop.usersonline%ROWTYPE;
91009  _query TEXT;
91010 BEGIN
91011   -- first part of our query doesn't care what PG version it is
91012   _query :=    'SELECT usr.usr_id, usr.usr_username, usr.usr_propername, usr.usr_email, '
91013             || 'min(backend_start) AS client_start, max(query_start) AS query_start, '
91014             || 'sum(CASE WHEN(database IS NULL) THEN 0 ELSE 1 END) AS cnt_internal, '
91015             || 'sum(CASE WHEN(database IS NULL) THEN 1 ELSE 0 END) AS cnt_external, '
91016             || 'client_addr '
91017             || 'FROM pg_stat_activity '
91018             || 'JOIN public.usr ON (usr.usr_id=usesysid) ';
91019
91020    -- use the integer comparison to compare server version to 9.2.0, where procpid was changed to just pid
91021    IF (compareversion('9.2.0') <= 0)
91022    THEN
91023      _query := _query || 'LEFT OUTER JOIN pg_locks ON (database=datid AND classid=datid AND objid=pg_stat_activity.pid AND objsubid=2) ';
91024    ELSE
91025      _query := _query || 'LEFT OUTER JOIN pg_locks ON (database=datid AND classid=datid AND objid=procpid AND objsubid=2) ';
91026    END IF;
91027
91028    -- the rest of the query
91029    _query := _query || 'WHERE(datname=current_database()) '
91030                     || 'GROUP BY usr_id, usr_username, usr_propername, usr_email, client_addr ';
91031
91032    -- loop over the rows that executing this query returns, and return them to the calling user
91033    FOR _row IN
91034       EXECUTE _query
91035       LOOP
91036         RETURN NEXT _row;
91037       END LOOP;
91038    RETURN;
91039
91040 END;
91041 $$;
91042
91043
91044 ALTER FUNCTION xtdesktop.usersonline() OWNER TO admin;
91045
91046 --
91047 -- TOC entry 9080 (class 0 OID 0)
91048 -- Dependencies: 2338
91049 -- Name: FUNCTION usersonline(); Type: COMMENT; Schema: xtdesktop; Owner: admin
91050 --
91051
91052 COMMENT ON FUNCTION usersonline() IS 'A table function that returns a PostgreSQL-version aware count of users online.';
91053
91054
91055 SET search_path = public, pg_catalog;
91056
91057 --
91058 -- TOC entry 4537 (class 1255 OID 146567211)
91059 -- Dependencies: 1238 8
91060 -- Name: concatagg(text); Type: AGGREGATE; Schema: public; Owner: admin
91061 --
91062
91063 CREATE AGGREGATE concatagg(text) (
91064     SFUNC = concataggsfunc,
91065     STYPE = text,
91066     INITCOND = ''
91067 );
91068
91069
91070 ALTER AGGREGATE public.concatagg(text) OWNER TO admin;
91071
91072 --
91073 -- TOC entry 4538 (class 1255 OID 146567212)
91074 -- Dependencies: 1581 8
91075 -- Name: first(anyelement); Type: AGGREGATE; Schema: public; Owner: admin
91076 --
91077
91078 CREATE AGGREGATE first(anyelement) (
91079     SFUNC = first_agg,
91080     STYPE = anyelement
91081 );
91082
91083
91084 ALTER AGGREGATE public.first(anyelement) OWNER TO admin;
91085
91086 --
91087 -- TOC entry 4539 (class 1255 OID 146567213)
91088 -- Dependencies: 1903 8
91089 -- Name: last(anyelement); Type: AGGREGATE; Schema: public; Owner: admin
91090 --
91091
91092 CREATE AGGREGATE last(anyelement) (
91093     SFUNC = last_agg,
91094     STYPE = anyelement
91095 );
91096
91097
91098 ALTER AGGREGATE public.last(anyelement) OWNER TO admin;
91099
91100 --
91101 -- TOC entry 234 (class 1259 OID 146567214)
91102 -- Dependencies: 6046 6047 6048 6049 6050 6051 6052 6053 6054 6056 8
91103 -- Name: addr; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91104 --
91105
91106 CREATE TABLE addr (
91107     addr_id integer NOT NULL,
91108     addr_active boolean DEFAULT true,
91109     addr_line1 text DEFAULT ''::text,
91110     addr_line2 text DEFAULT ''::text,
91111     addr_line3 text DEFAULT ''::text,
91112     addr_city text DEFAULT ''::text,
91113     addr_state text DEFAULT ''::text,
91114     addr_postalcode text DEFAULT ''::text,
91115     addr_country text DEFAULT ''::text,
91116     addr_notes text DEFAULT ''::text,
91117     addr_number text NOT NULL,
91118     CONSTRAINT addr_addr_number_check CHECK ((addr_number <> ''::text))
91119 );
91120
91121
91122 ALTER TABLE public.addr OWNER TO admin;
91123
91124 --
91125 -- TOC entry 9081 (class 0 OID 0)
91126 -- Dependencies: 234
91127 -- Name: TABLE addr; Type: COMMENT; Schema: public; Owner: admin
91128 --
91129
91130 COMMENT ON TABLE addr IS 'Postal Address';
91131
91132
91133 SET search_path = api, pg_catalog;
91134
91135 --
91136 -- TOC entry 235 (class 1259 OID 146567230)
91137 -- Dependencies: 8477 6
91138 -- Name: account; Type: VIEW; Schema: api; Owner: admin
91139 --
91140
91141 CREATE VIEW account AS
91142     SELECT (c.crmacct_number)::character varying AS account_number, p.crmacct_number AS parent_account, c.crmacct_name AS account_name, c.crmacct_active AS active, CASE WHEN (c.crmacct_type = 'O'::bpchar) THEN 'Organization'::text ELSE 'Individual'::text END AS type, pc.cntct_number AS primary_contact_number, pc.cntct_honorific AS primary_contact_honorific, pc.cntct_first_name AS primary_contact_first, pc.cntct_middle AS primary_contact_middle, pc.cntct_last_name AS primary_contact_last, pc.cntct_suffix AS primary_contact_suffix, pc.cntct_title AS primary_contact_job_title, pc.cntct_phone AS primary_contact_voice, pc.cntct_fax AS primary_contact_fax, pc.cntct_email AS primary_contact_email, ''::text AS primary_contact_change, m.addr_number AS primary_contact_address_number, m.addr_line1 AS primary_contact_address1, m.addr_line2 AS primary_contact_address2, m.addr_line3 AS primary_contact_address3, m.addr_city AS primary_contact_city, m.addr_state AS primary_contact_state, m.addr_postalcode AS primary_contact_postalcode, m.addr_country AS primary_contact_country, ''::text AS primary_contact_address_change, sc.cntct_number AS secondary_contact_number, sc.cntct_honorific AS secondary_contact_honorific, sc.cntct_first_name AS secondary_contact_first, sc.cntct_middle AS secondary_contact_middle, sc.cntct_last_name AS secondary_contact_last, sc.cntct_suffix AS secondary_contact_suffix, sc.cntct_title AS secondary_contact_job_title, sc.cntct_phone AS secondary_contact_voice, sc.cntct_fax AS secondary_contact_fax, sc.cntct_email AS secondary_contact_email, sc.cntct_webaddr AS secondary_contact_web, ''::text AS secondary_contact_change, s.addr_number AS secondary_contact_address_number, s.addr_line1 AS secondary_contact_address1, s.addr_line2 AS secondary_contact_address2, s.addr_line3 AS secondary_contact_address3, s.addr_city AS secondary_contact_city, s.addr_state AS secondary_contact_state, s.addr_postalcode AS secondary_contact_postalcode, s.addr_country AS secondary_contact_country, ''::text AS secondary_contact_address_change, c.crmacct_notes AS notes FROM (((((public.crmacct c LEFT JOIN public.crmacct p ON ((c.crmacct_parent_id = p.crmacct_id))) LEFT JOIN public.cntct pc ON ((c.crmacct_cntct_id_1 = pc.cntct_id))) LEFT JOIN public.addr m ON ((pc.cntct_addr_id = m.addr_id))) LEFT JOIN public.cntct sc ON ((c.crmacct_cntct_id_2 = sc.cntct_id))) LEFT JOIN public.addr s ON ((sc.cntct_addr_id = s.addr_id)));
91143
91144
91145 ALTER TABLE api.account OWNER TO admin;
91146
91147 --
91148 -- TOC entry 9083 (class 0 OID 0)
91149 -- Dependencies: 235
91150 -- Name: VIEW account; Type: COMMENT; Schema: api; Owner: admin
91151 --
91152
91153 COMMENT ON VIEW account IS 'Account';
91154
91155
91156 SET search_path = public, pg_catalog;
91157
91158 --
91159 -- TOC entry 236 (class 1259 OID 146567235)
91160 -- Dependencies: 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6071 8
91161 -- Name: char; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91162 --
91163
91164 CREATE TABLE "char" (
91165     char_id integer NOT NULL,
91166     char_name text NOT NULL,
91167     char_items boolean,
91168     char_options boolean,
91169     char_attributes boolean,
91170     char_lotserial boolean,
91171     char_notes text,
91172     char_customers boolean,
91173     char_crmaccounts boolean,
91174     char_addresses boolean,
91175     char_contacts boolean,
91176     char_opportunity boolean,
91177     char_employees boolean DEFAULT false,
91178     char_mask text,
91179     char_validator text,
91180     char_incidents boolean DEFAULT false,
91181     char_type integer DEFAULT 0 NOT NULL,
91182     char_order integer DEFAULT 0 NOT NULL,
91183     char_search boolean DEFAULT true NOT NULL,
91184     char_quotes boolean DEFAULT false,
91185     char_salesorders boolean DEFAULT false,
91186     char_invoices boolean DEFAULT false,
91187     char_vendors boolean DEFAULT false,
91188     char_purchaseorders boolean DEFAULT false,
91189     char_vouchers boolean DEFAULT false,
91190     char_projects boolean DEFAULT false,
91191     char_tasks boolean DEFAULT false,
91192     CONSTRAINT char_char_name_check CHECK ((char_name <> ''::text))
91193 );
91194
91195
91196 ALTER TABLE public."char" OWNER TO admin;
91197
91198 --
91199 -- TOC entry 9085 (class 0 OID 0)
91200 -- Dependencies: 236
91201 -- Name: TABLE "char"; Type: COMMENT; Schema: public; Owner: admin
91202 --
91203
91204 COMMENT ON TABLE "char" IS 'Characteristic information';
91205
91206
91207 --
91208 -- TOC entry 237 (class 1259 OID 146567255)
91209 -- Dependencies: 6073 6074 8
91210 -- Name: charass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91211 --
91212
91213 CREATE TABLE charass (
91214     charass_id integer NOT NULL,
91215     charass_target_type text,
91216     charass_target_id integer,
91217     charass_char_id integer,
91218     charass_value text,
91219     charass_default boolean DEFAULT false NOT NULL,
91220     charass_price numeric(16,4) DEFAULT 0 NOT NULL
91221 );
91222
91223
91224 ALTER TABLE public.charass OWNER TO admin;
91225
91226 --
91227 -- TOC entry 9087 (class 0 OID 0)
91228 -- Dependencies: 237
91229 -- Name: TABLE charass; Type: COMMENT; Schema: public; Owner: admin
91230 --
91231
91232 COMMENT ON TABLE charass IS 'Characteristic assignment information';
91233
91234
91235 SET search_path = api, pg_catalog;
91236
91237 --
91238 -- TOC entry 238 (class 1259 OID 146567263)
91239 -- Dependencies: 8478 6
91240 -- Name: accountchar; Type: VIEW; Schema: api; Owner: admin
91241 --
91242
91243 CREATE VIEW accountchar AS
91244     SELECT (crmacct.crmacct_number)::character varying AS account_number, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value FROM public.crmacct, public."char", public.charass WHERE ((('CRMACCT'::text = charass.charass_target_type) AND (crmacct.crmacct_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
91245
91246
91247 ALTER TABLE api.accountchar OWNER TO admin;
91248
91249 --
91250 -- TOC entry 9089 (class 0 OID 0)
91251 -- Dependencies: 238
91252 -- Name: VIEW accountchar; Type: COMMENT; Schema: api; Owner: admin
91253 --
91254
91255 COMMENT ON VIEW accountchar IS 'Account Characteristics';
91256
91257
91258 SET search_path = public, pg_catalog;
91259
91260 --
91261 -- TOC entry 239 (class 1259 OID 146567267)
91262 -- Dependencies: 6076 6077 6078 8
91263 -- Name: cmnttype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91264 --
91265
91266 CREATE TABLE cmnttype (
91267     cmnttype_id integer NOT NULL,
91268     cmnttype_name text NOT NULL,
91269     cmnttype_descrip text NOT NULL,
91270     cmnttype_usedin text,
91271     cmnttype_sys boolean DEFAULT false NOT NULL,
91272     cmnttype_editable boolean DEFAULT false NOT NULL,
91273     cmnttype_order integer,
91274     CONSTRAINT cmnttype_cmnttype_name_check CHECK ((cmnttype_name <> ''::text))
91275 );
91276
91277
91278 ALTER TABLE public.cmnttype OWNER TO admin;
91279
91280 --
91281 -- TOC entry 9091 (class 0 OID 0)
91282 -- Dependencies: 239
91283 -- Name: TABLE cmnttype; Type: COMMENT; Schema: public; Owner: admin
91284 --
91285
91286 COMMENT ON TABLE cmnttype IS 'Comment Type information';
91287
91288
91289 --
91290 -- TOC entry 240 (class 1259 OID 146567276)
91291 -- Dependencies: 6079 8
91292 -- Name: comment; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91293 --
91294
91295 CREATE TABLE comment (
91296     comment_id integer DEFAULT nextval(('"comment_comment_id_seq"'::text)::regclass) NOT NULL,
91297     comment_source_id integer,
91298     comment_date timestamp with time zone,
91299     comment_user text,
91300     comment_text text,
91301     comment_cmnttype_id integer,
91302     comment_source text,
91303     comment_public boolean
91304 );
91305
91306
91307 ALTER TABLE public.comment OWNER TO admin;
91308
91309 --
91310 -- TOC entry 9093 (class 0 OID 0)
91311 -- Dependencies: 240
91312 -- Name: TABLE comment; Type: COMMENT; Schema: public; Owner: admin
91313 --
91314
91315 COMMENT ON TABLE comment IS 'Comment information';
91316
91317
91318 SET search_path = api, pg_catalog;
91319
91320 --
91321 -- TOC entry 241 (class 1259 OID 146567283)
91322 -- Dependencies: 8479 6
91323 -- Name: accountcomment; Type: VIEW; Schema: api; Owner: admin
91324 --
91325
91326 CREATE VIEW accountcomment AS
91327     SELECT (crmacct.crmacct_number)::character varying AS account_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.crmacct, public.cmnttype, public.comment WHERE (((comment.comment_source = 'CRMA'::text) AND (comment.comment_source_id = crmacct.crmacct_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
91328
91329
91330 ALTER TABLE api.accountcomment OWNER TO admin;
91331
91332 --
91333 -- TOC entry 9095 (class 0 OID 0)
91334 -- Dependencies: 241
91335 -- Name: VIEW accountcomment; Type: COMMENT; Schema: api; Owner: admin
91336 --
91337
91338 COMMENT ON VIEW accountcomment IS 'Account Comment';
91339
91340
91341 SET search_path = public, pg_catalog;
91342
91343 --
91344 -- TOC entry 242 (class 1259 OID 146567287)
91345 -- Dependencies: 6081 6082 6083 8
91346 -- Name: docass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91347 --
91348
91349 CREATE TABLE docass (
91350     docass_id integer NOT NULL,
91351     docass_source_id integer NOT NULL,
91352     docass_source_type text NOT NULL,
91353     docass_target_id integer NOT NULL,
91354     docass_target_type text DEFAULT 'URL'::text NOT NULL,
91355     docass_purpose character(1) DEFAULT 'S'::bpchar NOT NULL,
91356     CONSTRAINT docass_docass_purpose_check CHECK (((((((((docass_purpose = 'I'::bpchar) OR (docass_purpose = 'E'::bpchar)) OR (docass_purpose = 'M'::bpchar)) OR (docass_purpose = 'P'::bpchar)) OR (docass_purpose = 'A'::bpchar)) OR (docass_purpose = 'C'::bpchar)) OR (docass_purpose = 'S'::bpchar)) OR (docass_purpose = 'D'::bpchar)))
91357 );
91358
91359
91360 ALTER TABLE public.docass OWNER TO admin;
91361
91362 --
91363 -- TOC entry 9097 (class 0 OID 0)
91364 -- Dependencies: 242
91365 -- Name: TABLE docass; Type: COMMENT; Schema: public; Owner: admin
91366 --
91367
91368 COMMENT ON TABLE docass IS 'Document Assignement References';
91369
91370
91371 --
91372 -- TOC entry 243 (class 1259 OID 146567296)
91373 -- Dependencies: 8
91374 -- Name: file; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91375 --
91376
91377 CREATE TABLE file (
91378     file_id integer NOT NULL,
91379     file_title text NOT NULL,
91380     file_stream bytea,
91381     file_descrip text NOT NULL
91382 );
91383
91384
91385 ALTER TABLE public.file OWNER TO admin;
91386
91387 --
91388 -- TOC entry 244 (class 1259 OID 146567302)
91389 -- Dependencies: 8
91390 -- Name: urlinfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91391 --
91392
91393 CREATE TABLE urlinfo (
91394     url_id integer NOT NULL,
91395     url_title text NOT NULL,
91396     url_url text NOT NULL
91397 );
91398
91399
91400 ALTER TABLE public.urlinfo OWNER TO admin;
91401
91402 --
91403 -- TOC entry 245 (class 1259 OID 146567308)
91404 -- Dependencies: 8480 8
91405 -- Name: url; Type: VIEW; Schema: public; Owner: admin
91406 --
91407
91408 CREATE VIEW url AS
91409     SELECT docass.docass_id AS url_id, docass.docass_source_id AS url_source_id, docass.docass_source_type AS url_source, file.file_title AS url_title, file.file_descrip AS url_url, file.file_stream AS url_stream FROM (file JOIN docass ON (((docass.docass_target_id = file.file_id) AND (docass.docass_target_type = 'FILE'::text)))) UNION ALL SELECT docass.docass_id AS url_id, docass.docass_source_id AS url_source_id, docass.docass_source_type AS url_source, urlinfo.url_title, urlinfo.url_url, NULL::bytea AS url_stream FROM (urlinfo JOIN docass ON (((docass.docass_target_id = urlinfo.url_id) AND (docass.docass_target_type = 'URL'::text))));
91410
91411
91412 ALTER TABLE public.url OWNER TO admin;
91413
91414 SET search_path = api, pg_catalog;
91415
91416 --
91417 -- TOC entry 246 (class 1259 OID 146567313)
91418 -- Dependencies: 8481 6
91419 -- Name: accountfile; Type: VIEW; Schema: api; Owner: admin
91420 --
91421
91422 CREATE VIEW accountfile AS
91423     SELECT crmacct.crmacct_number AS account_number, url.url_title AS title, url.url_url AS url FROM public.crmacct, public.url WHERE ((crmacct.crmacct_id = url.url_source_id) AND (url.url_source = 'CRMA'::text));
91424
91425
91426 ALTER TABLE api.accountfile OWNER TO admin;
91427
91428 --
91429 -- TOC entry 9102 (class 0 OID 0)
91430 -- Dependencies: 246
91431 -- Name: VIEW accountfile; Type: COMMENT; Schema: api; Owner: admin
91432 --
91433
91434 COMMENT ON VIEW accountfile IS 'Account File';
91435
91436
91437 SET search_path = public, pg_catalog;
91438
91439 --
91440 -- TOC entry 247 (class 1259 OID 146567317)
91441 -- Dependencies: 242 8
91442 -- Name: docass_docass_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
91443 --
91444
91445 CREATE SEQUENCE docass_docass_id_seq
91446     START WITH 1
91447     INCREMENT BY 1
91448     NO MINVALUE
91449     NO MAXVALUE
91450     CACHE 1;
91451
91452
91453 ALTER TABLE public.docass_docass_id_seq OWNER TO admin;
91454
91455 --
91456 -- TOC entry 9104 (class 0 OID 0)
91457 -- Dependencies: 247
91458 -- Name: docass_docass_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
91459 --
91460
91461 ALTER SEQUENCE docass_docass_id_seq OWNED BY docass.docass_id;
91462
91463
91464 --
91465 -- TOC entry 248 (class 1259 OID 146567319)
91466 -- Dependencies: 6086 8
91467 -- Name: image; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91468 --
91469
91470 CREATE TABLE image (
91471     image_id integer DEFAULT nextval(('"image_image_id_seq"'::text)::regclass) NOT NULL,
91472     image_name text,
91473     image_descrip text,
91474     image_data text
91475 );
91476
91477
91478 ALTER TABLE public.image OWNER TO admin;
91479
91480 --
91481 -- TOC entry 9106 (class 0 OID 0)
91482 -- Dependencies: 248
91483 -- Name: TABLE image; Type: COMMENT; Schema: public; Owner: admin
91484 --
91485
91486 COMMENT ON TABLE image IS 'Image information';
91487
91488
91489 --
91490 -- TOC entry 249 (class 1259 OID 146567326)
91491 -- Dependencies: 6087 6088 8
91492 -- Name: imageass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91493 --
91494
91495 CREATE TABLE imageass (
91496     imageass_id integer DEFAULT nextval('docass_docass_id_seq'::regclass) NOT NULL,
91497     imageass_source_id integer NOT NULL,
91498     imageass_source text NOT NULL,
91499     imageass_image_id integer NOT NULL,
91500     imageass_purpose character(1) NOT NULL,
91501     CONSTRAINT imageass_imageass_purpose_check CHECK (((((((((imageass_purpose = 'I'::bpchar) OR (imageass_purpose = 'E'::bpchar)) OR (imageass_purpose = 'M'::bpchar)) OR (imageass_purpose = 'P'::bpchar)) OR (imageass_purpose = 'A'::bpchar)) OR (imageass_purpose = 'C'::bpchar)) OR (imageass_purpose = 'D'::bpchar)) OR (imageass_purpose = 'S'::bpchar)))
91502 );
91503
91504
91505 ALTER TABLE public.imageass OWNER TO admin;
91506
91507 --
91508 -- TOC entry 9108 (class 0 OID 0)
91509 -- Dependencies: 249
91510 -- Name: TABLE imageass; Type: COMMENT; Schema: public; Owner: admin
91511 --
91512
91513 COMMENT ON TABLE imageass IS 'Image Assignement References';
91514
91515
91516 SET search_path = api, pg_catalog;
91517
91518 --
91519 -- TOC entry 250 (class 1259 OID 146567334)
91520 -- Dependencies: 8482 6
91521 -- Name: accountimage; Type: VIEW; Schema: api; Owner: admin
91522 --
91523
91524 CREATE VIEW accountimage AS
91525     SELECT crmacct.crmacct_number AS account_number, image.image_name FROM public.crmacct, public.imageass, public.image WHERE (((crmacct.crmacct_id = imageass.imageass_source_id) AND (imageass.imageass_source = 'CRMA'::text)) AND (imageass.imageass_image_id = image.image_id));
91526
91527
91528 ALTER TABLE api.accountimage OWNER TO admin;
91529
91530 --
91531 -- TOC entry 9110 (class 0 OID 0)
91532 -- Dependencies: 250
91533 -- Name: VIEW accountimage; Type: COMMENT; Schema: api; Owner: admin
91534 --
91535
91536 COMMENT ON VIEW accountimage IS 'Account Image';
91537
91538
91539 --
91540 -- TOC entry 251 (class 1259 OID 146567338)
91541 -- Dependencies: 8483 6
91542 -- Name: address; Type: VIEW; Schema: api; Owner: admin
91543 --
91544
91545 CREATE VIEW address AS
91546     SELECT (addr.addr_number)::character varying AS address_number, addr.addr_line1 AS address1, addr.addr_line2 AS address2, addr.addr_line3 AS address3, addr.addr_city AS city, addr.addr_state AS state, addr.addr_postalcode AS postal_code, addr.addr_country AS country, addr.addr_active AS active, addr.addr_notes AS notes, ''::text AS change FROM public.addr;
91547
91548
91549 ALTER TABLE api.address OWNER TO admin;
91550
91551 --
91552 -- TOC entry 9112 (class 0 OID 0)
91553 -- Dependencies: 251
91554 -- Name: VIEW address; Type: COMMENT; Schema: api; Owner: admin
91555 --
91556
91557 COMMENT ON VIEW address IS 'Address';
91558
91559
91560 --
91561 -- TOC entry 252 (class 1259 OID 146567342)
91562 -- Dependencies: 8484 6
91563 -- Name: addresschar; Type: VIEW; Schema: api; Owner: admin
91564 --
91565
91566 CREATE VIEW addresschar AS
91567     SELECT (addr.addr_number)::character varying AS address_number, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value FROM public.addr, public."char", public.charass WHERE ((('ADDR'::text = charass.charass_target_type) AND (addr.addr_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
91568
91569
91570 ALTER TABLE api.addresschar OWNER TO admin;
91571
91572 --
91573 -- TOC entry 9114 (class 0 OID 0)
91574 -- Dependencies: 252
91575 -- Name: VIEW addresschar; Type: COMMENT; Schema: api; Owner: admin
91576 --
91577
91578 COMMENT ON VIEW addresschar IS 'Address Characteristics';
91579
91580
91581 --
91582 -- TOC entry 253 (class 1259 OID 146567346)
91583 -- Dependencies: 8485 6
91584 -- Name: addresscomment; Type: VIEW; Schema: api; Owner: admin
91585 --
91586
91587 CREATE VIEW addresscomment AS
91588     SELECT (addr.addr_number)::character varying AS address_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.addr, public.cmnttype, public.comment WHERE (((comment.comment_source = 'ADDR'::text) AND (comment.comment_source_id = addr.addr_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
91589
91590
91591 ALTER TABLE api.addresscomment OWNER TO admin;
91592
91593 --
91594 -- TOC entry 9116 (class 0 OID 0)
91595 -- Dependencies: 253
91596 -- Name: VIEW addresscomment; Type: COMMENT; Schema: api; Owner: admin
91597 --
91598
91599 COMMENT ON VIEW addresscomment IS 'Address Comment';
91600
91601
91602 SET search_path = public, pg_catalog;
91603
91604 --
91605 -- TOC entry 254 (class 1259 OID 146567350)
91606 -- Dependencies: 6089 6090 6091 8
91607 -- Name: bomhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91608 --
91609
91610 CREATE TABLE bomhead (
91611     bomhead_id integer DEFAULT nextval(('"bomhead_bomhead_id_seq"'::text)::regclass) NOT NULL,
91612     bomhead_item_id integer NOT NULL,
91613     bomhead_serial integer,
91614     bomhead_docnum text,
91615     bomhead_revision text,
91616     bomhead_revisiondate date,
91617     bomhead_batchsize numeric(18,6),
91618     bomhead_requiredqtyper numeric(20,8),
91619     bomhead_rev_id integer DEFAULT (-1),
91620     CONSTRAINT bomhead_bomhead_batchsize_check CHECK ((bomhead_batchsize > (0)::numeric))
91621 );
91622
91623
91624 ALTER TABLE public.bomhead OWNER TO admin;
91625
91626 --
91627 -- TOC entry 9118 (class 0 OID 0)
91628 -- Dependencies: 254
91629 -- Name: TABLE bomhead; Type: COMMENT; Schema: public; Owner: admin
91630 --
91631
91632 COMMENT ON TABLE bomhead IS 'Bill of Materials (BOM) header information';
91633
91634
91635 SET search_path = api, pg_catalog;
91636
91637 --
91638 -- TOC entry 255 (class 1259 OID 146567359)
91639 -- Dependencies: 8486 6
91640 -- Name: bom; Type: VIEW; Schema: api; Owner: admin
91641 --
91642
91643 CREATE VIEW bom AS
91644     SELECT (item.item_number)::character varying AS item_number, (bomhead.bomhead_revision)::character varying AS revision, bomhead.bomhead_docnum AS document_number, bomhead.bomhead_revisiondate AS revision_date, bomhead.bomhead_batchsize AS batch_size, bomhead.bomhead_requiredqtyper AS total_qty_per FROM public.bomhead, public.item WHERE (bomhead.bomhead_item_id = item.item_id);
91645
91646
91647 ALTER TABLE api.bom OWNER TO admin;
91648
91649 --
91650 -- TOC entry 9120 (class 0 OID 0)
91651 -- Dependencies: 255
91652 -- Name: VIEW bom; Type: COMMENT; Schema: api; Owner: admin
91653 --
91654
91655 COMMENT ON VIEW bom IS 'Bill of Material Header';
91656
91657
91658 --
91659 -- TOC entry 256 (class 1259 OID 146567363)
91660 -- Dependencies: 8487 6
91661 -- Name: bomitem; Type: VIEW; Schema: api; Owner: admin
91662 --
91663
91664 CREATE VIEW bomitem AS
91665     SELECT bomitem.bomitem_id AS id, (p.item_number)::character varying AS bom_item_number, (bomhead.bomhead_revision)::character varying AS bom_revision, bomitem.bomitem_seqnumber AS sequence_number, i.item_number, CASE WHEN (bomitem.bomitem_effective = public.startoftime()) THEN 'Always'::text ELSE public.formatdate(bomitem.bomitem_effective) END AS effective, CASE WHEN (bomitem.bomitem_expires = public.endoftime()) THEN 'Never'::text ELSE public.formatdate(bomitem.bomitem_expires) END AS expires, bomitem.bomitem_qtyper AS qty_per, uom.uom_name AS issue_uom, bomitem.bomitem_scrap AS scrap, bomitem.bomitem_createwo AS create_child_wo, CASE WHEN (bomitem.bomitem_issuemethod = 'M'::bpchar) THEN 'Mixed'::text WHEN (bomitem.bomitem_issuemethod = 'L'::bpchar) THEN 'Pull'::text WHEN (bomitem.bomitem_issuemethod = 'S'::bpchar) THEN 'Push'::text ELSE NULL::text END AS issue_method, public.formatbooseq(p.item_id, bomitem.bomitem_booitem_seq_id) AS used_at, bomitem.bomitem_schedatwooper AS schedule_at_wo_operation, bomitem.bomitem_ecn AS ecn_number, bomitem.bomitem_notes AS notes, bomitem.bomitem_ref AS reference, CASE WHEN (bomitem.bomitem_subtype = 'N'::bpchar) THEN 'No'::text WHEN (bomitem.bomitem_subtype = 'I'::bpchar) THEN 'Item-Defined'::text WHEN (bomitem.bomitem_subtype = 'B'::bpchar) THEN 'BOM-Defined'::text ELSE NULL::text END AS substitutions, "char".char_name AS characteristic, bomitem.bomitem_value AS value FROM ((public.bomitem LEFT JOIN public.bomhead ON (((bomitem.bomitem_parent_item_id = bomhead.bomhead_item_id) AND (bomitem.bomitem_rev_id = bomhead.bomhead_rev_id)))) LEFT JOIN public."char" ON ((bomitem.bomitem_char_id = "char".char_id))), public.item p, public.item i, public.uom WHERE (((bomitem.bomitem_parent_item_id = p.item_id) AND (bomitem.bomitem_item_id = i.item_id)) AND (bomitem.bomitem_uom_id = uom.uom_id)) ORDER BY p.item_number, bomitem.bomitem_seqnumber;
91666
91667
91668 ALTER TABLE api.bomitem OWNER TO admin;
91669
91670 --
91671 -- TOC entry 9122 (class 0 OID 0)
91672 -- Dependencies: 256
91673 -- Name: VIEW bomitem; Type: COMMENT; Schema: api; Owner: admin
91674 --
91675
91676 COMMENT ON VIEW bomitem IS 'Bill of Material Item';
91677
91678
91679 --
91680 -- TOC entry 257 (class 1259 OID 146567368)
91681 -- Dependencies: 8488 6
91682 -- Name: bomitemcomment; Type: VIEW; Schema: api; Owner: admin
91683 --
91684
91685 CREATE VIEW bomitemcomment AS
91686     SELECT bomitem.bomitem_id, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM (public.bomitem LEFT JOIN public.bomhead ON (((bomitem.bomitem_parent_item_id = bomhead.bomhead_item_id) AND (bomitem.bomitem_rev_id = bomhead.bomhead_rev_id)))), public.item, public.cmnttype, public.comment WHERE ((((comment.comment_source = 'BMI'::text) AND (comment.comment_source_id = bomitem.bomitem_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id)) AND (bomitem.bomitem_parent_item_id = item.item_id)) ORDER BY item.item_number, bomhead.bomhead_revision, bomitem.bomitem_seqnumber, comment.comment_date;
91687
91688
91689 ALTER TABLE api.bomitemcomment OWNER TO admin;
91690
91691 --
91692 -- TOC entry 9124 (class 0 OID 0)
91693 -- Dependencies: 257
91694 -- Name: VIEW bomitemcomment; Type: COMMENT; Schema: api; Owner: admin
91695 --
91696
91697 COMMENT ON VIEW bomitemcomment IS 'Bill of Material Comment';
91698
91699
91700 SET search_path = public, pg_catalog;
91701
91702 --
91703 -- TOC entry 258 (class 1259 OID 146567373)
91704 -- Dependencies: 8
91705 -- Name: bomitemsub; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91706 --
91707
91708 CREATE TABLE bomitemsub (
91709     bomitemsub_id integer NOT NULL,
91710     bomitemsub_bomitem_id integer NOT NULL,
91711     bomitemsub_item_id integer NOT NULL,
91712     bomitemsub_uomratio numeric(20,10) NOT NULL,
91713     bomitemsub_rank integer NOT NULL
91714 );
91715
91716
91717 ALTER TABLE public.bomitemsub OWNER TO admin;
91718
91719 --
91720 -- TOC entry 9126 (class 0 OID 0)
91721 -- Dependencies: 258
91722 -- Name: TABLE bomitemsub; Type: COMMENT; Schema: public; Owner: admin
91723 --
91724
91725 COMMENT ON TABLE bomitemsub IS 'Bill of Materials (BOM) defined Substitutions information';
91726
91727
91728 SET search_path = api, pg_catalog;
91729
91730 --
91731 -- TOC entry 259 (class 1259 OID 146567376)
91732 -- Dependencies: 8489 6
91733 -- Name: bomitemsubstitute; Type: VIEW; Schema: api; Owner: admin
91734 --
91735
91736 CREATE VIEW bomitemsubstitute AS
91737     SELECT bomitem.bomitem_id, (p.item_number)::character varying AS bom_item_number, (bomhead.bomhead_revision)::character varying AS bom_revision, bomitem.bomitem_seqnumber AS sequence_number, (s.item_number)::character varying AS substitute_item_number, bomitemsub.bomitemsub_uomratio AS sub_parent_uom_ratio, bomitemsub.bomitemsub_rank AS ranking FROM public.item p, public.item s, (public.bomitem LEFT JOIN public.bomhead ON (((bomitem.bomitem_parent_item_id = bomhead.bomhead_item_id) AND (bomitem.bomitem_rev_id = bomhead.bomhead_rev_id)))), public.bomitemsub WHERE (((p.item_id = bomitem.bomitem_parent_item_id) AND (s.item_id = bomitemsub.bomitemsub_item_id)) AND (bomitemsub.bomitemsub_bomitem_id = bomitem.bomitem_id));
91738
91739
91740 ALTER TABLE api.bomitemsubstitute OWNER TO admin;
91741
91742 --
91743 -- TOC entry 9128 (class 0 OID 0)
91744 -- Dependencies: 259
91745 -- Name: VIEW bomitemsubstitute; Type: COMMENT; Schema: api; Owner: admin
91746 --
91747
91748 COMMENT ON VIEW bomitemsubstitute IS 'Bill of Material Item Substitute';
91749
91750
91751 SET search_path = public, pg_catalog;
91752
91753 --
91754 -- TOC entry 260 (class 1259 OID 146567381)
91755 -- Dependencies: 6094 8
91756 -- Name: budghead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91757 --
91758
91759 CREATE TABLE budghead (
91760     budghead_id integer NOT NULL,
91761     budghead_name text NOT NULL,
91762     budghead_descrip text,
91763     CONSTRAINT budghead_budghead_name_check CHECK ((budghead_name <> ''::text))
91764 );
91765
91766
91767 ALTER TABLE public.budghead OWNER TO admin;
91768
91769 SET search_path = api, pg_catalog;
91770
91771 --
91772 -- TOC entry 261 (class 1259 OID 146567388)
91773 -- Dependencies: 8490 6
91774 -- Name: budget; Type: VIEW; Schema: api; Owner: admin
91775 --
91776
91777 CREATE VIEW budget AS
91778     SELECT budghead.budghead_name AS name, budghead.budghead_descrip AS description FROM public.budghead ORDER BY budghead.budghead_name;
91779
91780
91781 ALTER TABLE api.budget OWNER TO admin;
91782
91783 --
91784 -- TOC entry 9131 (class 0 OID 0)
91785 -- Dependencies: 261
91786 -- Name: VIEW budget; Type: COMMENT; Schema: api; Owner: admin
91787 --
91788
91789 COMMENT ON VIEW budget IS 'Budget Header';
91790
91791
91792 SET search_path = public, pg_catalog;
91793
91794 --
91795 -- TOC entry 262 (class 1259 OID 146567392)
91796 -- Dependencies: 6095 6096 6097 6098 8
91797 -- Name: accnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91798 --
91799
91800 CREATE TABLE accnt (
91801     accnt_id integer DEFAULT nextval(('accnt_accnt_id_seq'::text)::regclass) NOT NULL,
91802     accnt_number text,
91803     accnt_descrip text,
91804     accnt_comments text,
91805     accnt_profit text,
91806     accnt_sub text,
91807     accnt_type character(1) NOT NULL,
91808     accnt_extref text,
91809     accnt_company text,
91810     accnt_forwardupdate boolean,
91811     accnt_subaccnttype_code text,
91812     accnt_curr_id integer DEFAULT basecurrid(),
91813     accnt_active boolean DEFAULT true NOT NULL,
91814     accnt_name text,
91815     CONSTRAINT accnt_accnt_type_check CHECK ((accnt_type = ANY (ARRAY['A'::bpchar, 'E'::bpchar, 'L'::bpchar, 'Q'::bpchar, 'R'::bpchar])))
91816 );
91817
91818
91819 ALTER TABLE public.accnt OWNER TO admin;
91820
91821 --
91822 -- TOC entry 9133 (class 0 OID 0)
91823 -- Dependencies: 262
91824 -- Name: TABLE accnt; Type: COMMENT; Schema: public; Owner: admin
91825 --
91826
91827 COMMENT ON TABLE accnt IS 'General Ledger (G/L) Account Number information';
91828
91829
91830 --
91831 -- TOC entry 263 (class 1259 OID 146567402)
91832 -- Dependencies: 8
91833 -- Name: budgitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91834 --
91835
91836 CREATE TABLE budgitem (
91837     budgitem_id integer NOT NULL,
91838     budgitem_budghead_id integer NOT NULL,
91839     budgitem_period_id integer NOT NULL,
91840     budgitem_accnt_id integer NOT NULL,
91841     budgitem_amount numeric(20,4) NOT NULL
91842 );
91843
91844
91845 ALTER TABLE public.budgitem OWNER TO admin;
91846
91847 --
91848 -- TOC entry 264 (class 1259 OID 146567405)
91849 -- Dependencies: 6101 8
91850 -- Name: period; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91851 --
91852
91853 CREATE TABLE period (
91854     period_id integer NOT NULL,
91855     period_start date,
91856     period_end date,
91857     period_closed boolean,
91858     period_freeze boolean,
91859     period_initial boolean DEFAULT false,
91860     period_name text,
91861     period_yearperiod_id integer,
91862     period_quarter integer,
91863     period_number integer NOT NULL
91864 );
91865
91866
91867 ALTER TABLE public.period OWNER TO admin;
91868
91869 --
91870 -- TOC entry 9136 (class 0 OID 0)
91871 -- Dependencies: 264
91872 -- Name: TABLE period; Type: COMMENT; Schema: public; Owner: admin
91873 --
91874
91875 COMMENT ON TABLE period IS 'Accounting Period information';
91876
91877
91878 SET search_path = api, pg_catalog;
91879
91880 --
91881 -- TOC entry 265 (class 1259 OID 146567412)
91882 -- Dependencies: 8491 6
91883 -- Name: budgetentry; Type: VIEW; Schema: api; Owner: admin
91884 --
91885
91886 CREATE VIEW budgetentry AS
91887     SELECT budghead.budghead_name AS name, public.formatglaccount(accnt.accnt_id) AS account, period.period_start, budgitem.budgitem_amount AS amount FROM public.budgitem, public.budghead, public.period, public.accnt WHERE (((budgitem.budgitem_budghead_id = budghead.budghead_id) AND (budgitem.budgitem_period_id = period.period_id)) AND (budgitem.budgitem_accnt_id = accnt.accnt_id)) ORDER BY budghead.budghead_name, period.period_start, public.formatglaccount(accnt.accnt_id);
91888
91889
91890 ALTER TABLE api.budgetentry OWNER TO admin;
91891
91892 --
91893 -- TOC entry 9138 (class 0 OID 0)
91894 -- Dependencies: 265
91895 -- Name: VIEW budgetentry; Type: COMMENT; Schema: api; Owner: admin
91896 --
91897
91898 COMMENT ON VIEW budgetentry IS 'Budget Entry';
91899
91900
91901 SET search_path = public, pg_catalog;
91902
91903 --
91904 -- TOC entry 266 (class 1259 OID 146567416)
91905 -- Dependencies: 6102 6103 6104 6105 6106 6108 8
91906 -- Name: bankaccnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91907 --
91908
91909 CREATE TABLE bankaccnt (
91910     bankaccnt_id integer NOT NULL,
91911     bankaccnt_name text NOT NULL,
91912     bankaccnt_descrip text,
91913     bankaccnt_bankname text,
91914     bankaccnt_accntnumber text,
91915     bankaccnt_ar boolean,
91916     bankaccnt_ap boolean,
91917     bankaccnt_nextchknum integer,
91918     bankaccnt_type character(1),
91919     bankaccnt_accnt_id integer,
91920     bankaccnt_check_form_id integer,
91921     bankaccnt_userec boolean,
91922     bankaccnt_rec_accnt_id integer,
91923     bankaccnt_curr_id integer DEFAULT basecurrid(),
91924     bankaccnt_notes text,
91925     bankaccnt_routing text DEFAULT ''::text NOT NULL,
91926     bankaccnt_ach_enabled boolean DEFAULT false NOT NULL,
91927     bankaccnt_ach_origin text DEFAULT ''::text NOT NULL,
91928     bankaccnt_ach_genchecknum boolean DEFAULT false NOT NULL,
91929     bankaccnt_ach_leadtime integer,
91930     bankaccnt_ach_lastdate date,
91931     bankaccnt_ach_lastfileid character(1),
91932     bankaccnt_ach_origintype text,
91933     bankaccnt_ach_originname text,
91934     bankaccnt_ach_desttype text,
91935     bankaccnt_ach_fed_dest text,
91936     bankaccnt_ach_destname text,
91937     bankaccnt_ach_dest text,
91938     CONSTRAINT bankaccnt_bankaccnt_name_check CHECK ((bankaccnt_name <> ''::text))
91939 );
91940
91941
91942 ALTER TABLE public.bankaccnt OWNER TO admin;
91943
91944 --
91945 -- TOC entry 9140 (class 0 OID 0)
91946 -- Dependencies: 266
91947 -- Name: TABLE bankaccnt; Type: COMMENT; Schema: public; Owner: admin
91948 --
91949
91950 COMMENT ON TABLE bankaccnt IS 'Bank Account information';
91951
91952
91953 --
91954 -- TOC entry 267 (class 1259 OID 146567428)
91955 -- Dependencies: 6109 6110 6111 6112 6113 6114 6115 6117 8
91956 -- Name: cashrcpt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
91957 --
91958
91959 CREATE TABLE cashrcpt (
91960     cashrcpt_id integer NOT NULL,
91961     cashrcpt_cust_id integer NOT NULL,
91962     cashrcpt_amount numeric(20,2) NOT NULL,
91963     cashrcpt_fundstype character(1) NOT NULL,
91964     cashrcpt_docnumber text,
91965     cashrcpt_bankaccnt_id integer NOT NULL,
91966     cashrcpt_notes text,
91967     cashrcpt_distdate date DEFAULT ('now'::text)::date,
91968     cashrcpt_salescat_id integer DEFAULT (-1),
91969     cashrcpt_curr_id integer DEFAULT basecurrid(),
91970     cashrcpt_usecustdeposit boolean DEFAULT false NOT NULL,
91971     cashrcpt_void boolean DEFAULT false NOT NULL,
91972     cashrcpt_number text NOT NULL,
91973     cashrcpt_docdate date,
91974     cashrcpt_posted boolean DEFAULT false NOT NULL,
91975     cashrcpt_posteddate date,
91976     cashrcpt_postedby text,
91977     cashrcpt_applydate date,
91978     cashrcpt_discount numeric(20,2) DEFAULT 0.00 NOT NULL,
91979     cashrcpt_curr_rate numeric NOT NULL,
91980     CONSTRAINT cashrcpt_cashrcpt_number_check CHECK ((cashrcpt_number <> ''::text))
91981 );
91982
91983
91984 ALTER TABLE public.cashrcpt OWNER TO admin;
91985
91986 --
91987 -- TOC entry 9142 (class 0 OID 0)
91988 -- Dependencies: 267
91989 -- Name: TABLE cashrcpt; Type: COMMENT; Schema: public; Owner: admin
91990 --
91991
91992 COMMENT ON TABLE cashrcpt IS 'Temporary table for storing Cash Receipt information before Cash Receipts are posted';
91993
91994
91995 SET search_path = api, pg_catalog;
91996
91997 --
91998 -- TOC entry 268 (class 1259 OID 146567442)
91999 -- Dependencies: 8492 6
92000 -- Name: cashreceipt; Type: VIEW; Schema: api; Owner: admin
92001 --
92002
92003 CREATE VIEW cashreceipt AS
92004     SELECT (custinfo.cust_number)::character varying AS customer_number, cashrcpt.cashrcpt_number AS cashreceipt_number, CASE WHEN (cashrcpt.cashrcpt_fundstype = 'C'::bpchar) THEN 'Check'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'T'::bpchar) THEN 'Certified Check'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'M'::bpchar) THEN 'Master Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'V'::bpchar) THEN 'Visa'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'A'::bpchar) THEN 'American Express'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'D'::bpchar) THEN 'Discover Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'R'::bpchar) THEN 'Other Credit Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'K'::bpchar) THEN 'Cash'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'W'::bpchar) THEN 'Wire Transfer'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'O'::bpchar) THEN 'Other'::character varying ELSE NULL::character varying END AS funds_type, (cashrcpt.cashrcpt_docnumber)::character varying AS check_document_number, custinfo.cust_name AS customer_name, m.addr_line1 AS customer_address, curr_symbol.curr_abbr AS currency, cashrcpt.cashrcpt_amount AS amount_received, bankaccnt.bankaccnt_name AS post_to, public.formatdate(cashrcpt.cashrcpt_distdate) AS distribution_date, CASE WHEN cashrcpt.cashrcpt_usecustdeposit THEN 'Customer Deposit'::text ELSE 'Credit Memo'::text END AS apply_balance_as, salescat.salescat_name AS sales_category, cashrcpt.cashrcpt_notes AS notes FROM ((((((public.cashrcpt LEFT JOIN public.custinfo ON ((custinfo.cust_id = cashrcpt.cashrcpt_cust_id))) LEFT JOIN public.cntct mc ON ((custinfo.cust_cntct_id = mc.cntct_id))) LEFT JOIN public.addr m ON ((mc.cntct_addr_id = m.addr_id))) LEFT JOIN public.curr_symbol ON ((curr_symbol.curr_id = cashrcpt.cashrcpt_curr_id))) LEFT JOIN public.bankaccnt ON ((bankaccnt.bankaccnt_id = cashrcpt.cashrcpt_bankaccnt_id))) LEFT JOIN public.salescat ON ((salescat.salescat_id = cashrcpt.cashrcpt_salescat_id)));
92005
92006
92007 ALTER TABLE api.cashreceipt OWNER TO admin;
92008
92009 --
92010 -- TOC entry 9144 (class 0 OID 0)
92011 -- Dependencies: 268
92012 -- Name: VIEW cashreceipt; Type: COMMENT; Schema: api; Owner: admin
92013 --
92014
92015 COMMENT ON VIEW cashreceipt IS '
92016 This view can be used as an interface to import Cash Receipt data directly  
92017 into the system.  Required fields will be checked and default values will be 
92018 populated';
92019
92020
92021 SET search_path = public, pg_catalog;
92022
92023 --
92024 -- TOC entry 269 (class 1259 OID 146567447)
92025 -- Dependencies: 6119 6120 8
92026 -- Name: cashrcptitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92027 --
92028
92029 CREATE TABLE cashrcptitem (
92030     cashrcptitem_id integer NOT NULL,
92031     cashrcptitem_cashrcpt_id integer NOT NULL,
92032     cashrcptitem_aropen_id integer NOT NULL,
92033     cashrcptitem_amount numeric(20,2) NOT NULL,
92034     cashrcptitem_discount numeric(20,2) DEFAULT 0.00 NOT NULL,
92035     cashrcptitem_applied boolean DEFAULT true
92036 );
92037
92038
92039 ALTER TABLE public.cashrcptitem OWNER TO admin;
92040
92041 --
92042 -- TOC entry 9146 (class 0 OID 0)
92043 -- Dependencies: 269
92044 -- Name: TABLE cashrcptitem; Type: COMMENT; Schema: public; Owner: admin
92045 --
92046
92047 COMMENT ON TABLE cashrcptitem IS 'Temporary table for storing information about applications of Cash Receipts before Cash Receipts are posted';
92048
92049
92050 SET search_path = api, pg_catalog;
92051
92052 --
92053 -- TOC entry 270 (class 1259 OID 146567452)
92054 -- Dependencies: 8493 6
92055 -- Name: cashreceiptapply; Type: VIEW; Schema: api; Owner: admin
92056 --
92057
92058 CREATE VIEW cashreceiptapply AS
92059     SELECT (custinfo.cust_number)::character varying AS customer_number, CASE WHEN (cashrcpt.cashrcpt_fundstype = 'C'::bpchar) THEN 'Check'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'T'::bpchar) THEN 'Certified Check'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'M'::bpchar) THEN 'Master Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'V'::bpchar) THEN 'Visa'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'A'::bpchar) THEN 'American Express'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'D'::bpchar) THEN 'Discover Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'R'::bpchar) THEN 'Other Credit Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'K'::bpchar) THEN 'Cash'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'W'::bpchar) THEN 'Wire Transfer'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'O'::bpchar) THEN 'Other'::character varying ELSE NULL::character varying END AS funds_type, (cashrcpt.cashrcpt_docnumber)::character varying AS check_document_number, (aropen.aropen_doctype)::character varying AS doc_type, (aropen.aropen_docnumber)::character varying AS doc_number, custinfo.cust_name AS customer_name, m.addr_line1 AS customer_address, public.formatdate(aropen.aropen_docdate) AS doc_date, public.formatdate(aropen.aropen_duedate) AS due_date, curr_symbol.curr_abbr AS currency, aropen.aropen_amount AS open_amount, cashrcptitem.cashrcptitem_amount AS amount_to_apply, cashrcptitem.cashrcptitem_discount FROM ((((((public.cashrcptitem LEFT JOIN public.cashrcpt ON ((cashrcpt.cashrcpt_id = cashrcptitem.cashrcptitem_cashrcpt_id))) LEFT JOIN public.custinfo ON ((custinfo.cust_id = cashrcpt.cashrcpt_cust_id))) LEFT JOIN public.cntct mc ON ((custinfo.cust_cntct_id = mc.cntct_id))) LEFT JOIN public.addr m ON ((mc.cntct_addr_id = m.addr_id))) LEFT JOIN public.curr_symbol ON ((curr_symbol.curr_id = cashrcpt.cashrcpt_curr_id))) LEFT JOIN public.aropen ON ((aropen.aropen_id = cashrcptitem.cashrcptitem_aropen_id)));
92060
92061
92062 ALTER TABLE api.cashreceiptapply OWNER TO admin;
92063
92064 --
92065 -- TOC entry 9148 (class 0 OID 0)
92066 -- Dependencies: 270
92067 -- Name: VIEW cashreceiptapply; Type: COMMENT; Schema: api; Owner: admin
92068 --
92069
92070 COMMENT ON VIEW cashreceiptapply IS '
92071 This view can be used as an interface to import Cash Receipt Application data directly  
92072 into the system.  Required fields will be checked and default values will be 
92073 populated';
92074
92075
92076 SET search_path = public, pg_catalog;
92077
92078 --
92079 -- TOC entry 271 (class 1259 OID 146567457)
92080 -- Dependencies: 8
92081 -- Name: cashrcptmisc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92082 --
92083
92084 CREATE TABLE cashrcptmisc (
92085     cashrcptmisc_id integer NOT NULL,
92086     cashrcptmisc_cashrcpt_id integer NOT NULL,
92087     cashrcptmisc_accnt_id integer NOT NULL,
92088     cashrcptmisc_amount numeric(20,2) NOT NULL,
92089     cashrcptmisc_notes text
92090 );
92091
92092
92093 ALTER TABLE public.cashrcptmisc OWNER TO admin;
92094
92095 --
92096 -- TOC entry 9150 (class 0 OID 0)
92097 -- Dependencies: 271
92098 -- Name: TABLE cashrcptmisc; Type: COMMENT; Schema: public; Owner: admin
92099 --
92100
92101 COMMENT ON TABLE cashrcptmisc IS 'Cash Receipt Miscellaneous Application information';
92102
92103
92104 SET search_path = api, pg_catalog;
92105
92106 --
92107 -- TOC entry 272 (class 1259 OID 146567463)
92108 -- Dependencies: 8494 6
92109 -- Name: cashreceiptapplymisc; Type: VIEW; Schema: api; Owner: admin
92110 --
92111
92112 CREATE VIEW cashreceiptapplymisc AS
92113     SELECT (custinfo.cust_number)::character varying AS customer_number, CASE WHEN (cashrcpt.cashrcpt_fundstype = 'C'::bpchar) THEN 'Check'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'T'::bpchar) THEN 'Certified Check'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'M'::bpchar) THEN 'Master Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'V'::bpchar) THEN 'Visa'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'A'::bpchar) THEN 'American Express'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'D'::bpchar) THEN 'Discover Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'R'::bpchar) THEN 'Other Credit Card'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'K'::bpchar) THEN 'Cash'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'W'::bpchar) THEN 'Wire Transfer'::character varying WHEN (cashrcpt.cashrcpt_fundstype = 'O'::bpchar) THEN 'Other'::character varying ELSE NULL::character varying END AS funds_type, (cashrcpt.cashrcpt_docnumber)::character varying AS check_document_number, (public.formatglaccount(accnt.accnt_id))::character varying AS account, custinfo.cust_name AS customer_name, m.addr_line1 AS customer_address, accnt.accnt_descrip AS account_description, curr_symbol.curr_abbr AS currency, cashrcptmisc.cashrcptmisc_amount AS amount_to_distribute, cashrcptmisc.cashrcptmisc_notes AS notes FROM ((((((public.cashrcptmisc LEFT JOIN public.cashrcpt ON ((cashrcpt.cashrcpt_id = cashrcptmisc.cashrcptmisc_cashrcpt_id))) LEFT JOIN public.custinfo ON ((custinfo.cust_id = cashrcpt.cashrcpt_cust_id))) LEFT JOIN public.cntct mc ON ((custinfo.cust_cntct_id = mc.cntct_id))) LEFT JOIN public.addr m ON ((mc.cntct_addr_id = m.addr_id))) LEFT JOIN public.curr_symbol ON ((curr_symbol.curr_id = cashrcpt.cashrcpt_curr_id))) LEFT JOIN public.accnt ON ((accnt.accnt_id = cashrcptmisc.cashrcptmisc_accnt_id)));
92114
92115
92116 ALTER TABLE api.cashreceiptapplymisc OWNER TO admin;
92117
92118 --
92119 -- TOC entry 9152 (class 0 OID 0)
92120 -- Dependencies: 272
92121 -- Name: VIEW cashreceiptapplymisc; Type: COMMENT; Schema: api; Owner: admin
92122 --
92123
92124 COMMENT ON VIEW cashreceiptapplymisc IS '
92125 This view can be used as an interface to import Cash Receipt Miscellaneous Application
92126 data directly into the system.  Required fields will be checked and default values
92127 will be populated';
92128
92129
92130 --
92131 -- TOC entry 273 (class 1259 OID 146567468)
92132 -- Dependencies: 8495 6
92133 -- Name: contact; Type: VIEW; Schema: api; Owner: admin
92134 --
92135
92136 CREATE VIEW contact AS
92137     SELECT (cntct.cntct_number)::character varying AS contact_number, cntct.cntct_honorific AS honorific, cntct.cntct_first_name AS first, cntct.cntct_middle AS middle, cntct.cntct_last_name AS last, cntct.cntct_suffix AS suffix, cntct.cntct_initials AS initials, crmacct.crmacct_number AS crm_account, cntct.cntct_active AS active, cntct.cntct_title AS job_title, cntct.cntct_phone AS voice, cntct.cntct_phone2 AS alternate, cntct.cntct_fax AS fax, cntct.cntct_email AS email, cntct.cntct_webaddr AS web, ''::text AS contact_change, addr.addr_number AS address_number, addr.addr_line1 AS address1, addr.addr_line2 AS address2, addr.addr_line3 AS address3, addr.addr_city AS city, addr.addr_state AS state, addr.addr_postalcode AS postal_code, addr.addr_country AS country, cntct.cntct_notes AS notes, ''::text AS address_change FROM ((public.cntct LEFT JOIN public.addr ON ((cntct.cntct_addr_id = addr.addr_id))) LEFT JOIN public.crmacct ON ((cntct.cntct_crmacct_id = crmacct.crmacct_id)));
92138
92139
92140 ALTER TABLE api.contact OWNER TO admin;
92141
92142 --
92143 -- TOC entry 9154 (class 0 OID 0)
92144 -- Dependencies: 273
92145 -- Name: VIEW contact; Type: COMMENT; Schema: api; Owner: admin
92146 --
92147
92148 COMMENT ON VIEW contact IS 'Contact';
92149
92150
92151 --
92152 -- TOC entry 274 (class 1259 OID 146567473)
92153 -- Dependencies: 8496 6
92154 -- Name: contactchar; Type: VIEW; Schema: api; Owner: admin
92155 --
92156
92157 CREATE VIEW contactchar AS
92158     SELECT cntct.cntct_number AS contact_number, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value FROM public.cntct, public."char", public.charass WHERE ((('CNTCT'::text = charass.charass_target_type) AND (cntct.cntct_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
92159
92160
92161 ALTER TABLE api.contactchar OWNER TO admin;
92162
92163 --
92164 -- TOC entry 9156 (class 0 OID 0)
92165 -- Dependencies: 274
92166 -- Name: VIEW contactchar; Type: COMMENT; Schema: api; Owner: admin
92167 --
92168
92169 COMMENT ON VIEW contactchar IS 'Contact Characteristics';
92170
92171
92172 --
92173 -- TOC entry 275 (class 1259 OID 146567477)
92174 -- Dependencies: 8497 6
92175 -- Name: contactcomment; Type: VIEW; Schema: api; Owner: admin
92176 --
92177
92178 CREATE VIEW contactcomment AS
92179     SELECT cntct.cntct_number AS contact_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.cntct, public.cmnttype, public.comment WHERE (((comment.comment_source = 'T'::text) AND (comment.comment_source_id = cntct.cntct_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
92180
92181
92182 ALTER TABLE api.contactcomment OWNER TO admin;
92183
92184 --
92185 -- TOC entry 9158 (class 0 OID 0)
92186 -- Dependencies: 275
92187 -- Name: VIEW contactcomment; Type: COMMENT; Schema: api; Owner: admin
92188 --
92189
92190 COMMENT ON VIEW contactcomment IS 'Contact Comment';
92191
92192
92193 --
92194 -- TOC entry 276 (class 1259 OID 146567481)
92195 -- Dependencies: 8498 6
92196 -- Name: custchar; Type: VIEW; Schema: api; Owner: admin
92197 --
92198
92199 CREATE VIEW custchar AS
92200     SELECT (custinfo.cust_number)::character varying AS customer_number, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value FROM public.custinfo, public."char", public.charass WHERE ((('C'::text = charass.charass_target_type) AND (custinfo.cust_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
92201
92202
92203 ALTER TABLE api.custchar OWNER TO admin;
92204
92205 --
92206 -- TOC entry 9160 (class 0 OID 0)
92207 -- Dependencies: 276
92208 -- Name: VIEW custchar; Type: COMMENT; Schema: api; Owner: admin
92209 --
92210
92211 COMMENT ON VIEW custchar IS 'Customer Characteristics';
92212
92213
92214 --
92215 -- TOC entry 277 (class 1259 OID 146567486)
92216 -- Dependencies: 8499 6
92217 -- Name: custcomment; Type: VIEW; Schema: api; Owner: admin
92218 --
92219
92220 CREATE VIEW custcomment AS
92221     SELECT (custinfo.cust_number)::character varying AS customer_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.custinfo, public.cmnttype, public.comment WHERE (((comment.comment_source = 'C'::text) AND (comment.comment_source_id = custinfo.cust_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
92222
92223
92224 ALTER TABLE api.custcomment OWNER TO admin;
92225
92226 --
92227 -- TOC entry 9162 (class 0 OID 0)
92228 -- Dependencies: 277
92229 -- Name: VIEW custcomment; Type: COMMENT; Schema: api; Owner: admin
92230 --
92231
92232 COMMENT ON VIEW custcomment IS 'Customer Comment';
92233
92234
92235 SET search_path = public, pg_catalog;
92236
92237 --
92238 -- TOC entry 278 (class 1259 OID 146567491)
92239 -- Dependencies: 6122 6123 6124 6125 6126 6127 6128 8
92240 -- Name: ccard; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92241 --
92242
92243 CREATE TABLE ccard (
92244     ccard_id integer NOT NULL,
92245     ccard_seq integer DEFAULT 10 NOT NULL,
92246     ccard_cust_id integer NOT NULL,
92247     ccard_active boolean DEFAULT true,
92248     ccard_name bytea,
92249     ccard_address1 bytea,
92250     ccard_address2 bytea,
92251     ccard_city bytea,
92252     ccard_state bytea,
92253     ccard_zip bytea,
92254     ccard_country bytea,
92255     ccard_number bytea,
92256     ccard_debit boolean DEFAULT false,
92257     ccard_month_expired bytea,
92258     ccard_year_expired bytea,
92259     ccard_type character(1) NOT NULL,
92260     ccard_date_added timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
92261     ccard_lastupdated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
92262     ccard_added_by_username text DEFAULT geteffectivextuser() NOT NULL,
92263     ccard_last_updated_by_username text DEFAULT geteffectivextuser() NOT NULL
92264 );
92265
92266
92267 ALTER TABLE public.ccard OWNER TO admin;
92268
92269 --
92270 -- TOC entry 9164 (class 0 OID 0)
92271 -- Dependencies: 278
92272 -- Name: TABLE ccard; Type: COMMENT; Schema: public; Owner: admin
92273 --
92274
92275 COMMENT ON TABLE ccard IS 'Credit Card Information - all bytea data is encrypted';
92276
92277
92278 SET search_path = api, pg_catalog;
92279
92280 --
92281 -- TOC entry 279 (class 1259 OID 146567504)
92282 -- Dependencies: 8500 6
92283 -- Name: custcreditcard; Type: VIEW; Schema: api; Owner: admin
92284 --
92285
92286 CREATE VIEW custcreditcard AS
92287     SELECT (custinfo.cust_number)::character varying AS customer_number, CASE WHEN (ccard.ccard_type = 'V'::bpchar) THEN 'Visa'::text WHEN (ccard.ccard_type = 'M'::bpchar) THEN 'Master Card'::text WHEN (ccard.ccard_type = 'A'::bpchar) THEN 'American Express'::text WHEN (ccard.ccard_type = 'D'::bpchar) THEN 'Discover'::text ELSE 'Not Supported'::text END AS credit_card_type, ccard.ccard_active AS active, ccard.ccard_number AS credit_card_number, ccard.ccard_name AS name, ccard.ccard_address1 AS street_address1, ccard.ccard_address2 AS street_address2, ccard.ccard_city AS city, ccard.ccard_state AS state, ccard.ccard_zip AS postal_code, ccard.ccard_country AS country, ccard.ccard_month_expired AS expiration_month, ccard.ccard_year_expired AS expiration_year, ''::text AS key FROM public.ccard, public.custinfo WHERE (ccard.ccard_cust_id = custinfo.cust_id);
92288
92289
92290 ALTER TABLE api.custcreditcard OWNER TO admin;
92291
92292 --
92293 -- TOC entry 9166 (class 0 OID 0)
92294 -- Dependencies: 279
92295 -- Name: VIEW custcreditcard; Type: COMMENT; Schema: api; Owner: admin
92296 --
92297
92298 COMMENT ON VIEW custcreditcard IS 'Customer Credit Cards.';
92299
92300
92301 SET search_path = public, pg_catalog;
92302
92303 --
92304 -- TOC entry 280 (class 1259 OID 146567509)
92305 -- Dependencies: 6130 6131 6132 8
92306 -- Name: custtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92307 --
92308
92309 CREATE TABLE custtype (
92310     custtype_id integer DEFAULT nextval(('custtype_custtype_id_seq'::text)::regclass) NOT NULL,
92311     custtype_code text NOT NULL,
92312     custtype_descrip text NOT NULL,
92313     custtype_char boolean DEFAULT false NOT NULL,
92314     CONSTRAINT custtype_custtype_code_check CHECK ((custtype_code <> ''::text))
92315 );
92316
92317
92318 ALTER TABLE public.custtype OWNER TO admin;
92319
92320 --
92321 -- TOC entry 9168 (class 0 OID 0)
92322 -- Dependencies: 280
92323 -- Name: TABLE custtype; Type: COMMENT; Schema: public; Owner: admin
92324 --
92325
92326 COMMENT ON TABLE custtype IS 'Customer Type information';
92327
92328
92329 --
92330 -- TOC entry 281 (class 1259 OID 146567518)
92331 -- Dependencies: 6134 8
92332 -- Name: shipchrg; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92333 --
92334
92335 CREATE TABLE shipchrg (
92336     shipchrg_id integer NOT NULL,
92337     shipchrg_name text NOT NULL,
92338     shipchrg_descrip text,
92339     shipchrg_custfreight boolean,
92340     shipchrg_handling character(1),
92341     CONSTRAINT shipchrg_shipchrg_name_check CHECK ((shipchrg_name <> ''::text))
92342 );
92343
92344
92345 ALTER TABLE public.shipchrg OWNER TO admin;
92346
92347 --
92348 -- TOC entry 9170 (class 0 OID 0)
92349 -- Dependencies: 281
92350 -- Name: TABLE shipchrg; Type: COMMENT; Schema: public; Owner: admin
92351 --
92352
92353 COMMENT ON TABLE shipchrg IS 'Shipping Charge information';
92354
92355
92356 --
92357 -- TOC entry 282 (class 1259 OID 146567525)
92358 -- Dependencies: 6135 6136 8
92359 -- Name: shipform; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92360 --
92361
92362 CREATE TABLE shipform (
92363     shipform_id integer DEFAULT nextval(('"shipform_shipform_id_seq"'::text)::regclass) NOT NULL,
92364     shipform_name text NOT NULL,
92365     shipform_report_id integer,
92366     shipform_report_name text,
92367     CONSTRAINT shipform_shipform_name_check CHECK ((shipform_name <> ''::text))
92368 );
92369
92370
92371 ALTER TABLE public.shipform OWNER TO admin;
92372
92373 --
92374 -- TOC entry 9172 (class 0 OID 0)
92375 -- Dependencies: 282
92376 -- Name: TABLE shipform; Type: COMMENT; Schema: public; Owner: admin
92377 --
92378
92379 COMMENT ON TABLE shipform IS 'Shipping Form information';
92380
92381
92382 --
92383 -- TOC entry 9173 (class 0 OID 0)
92384 -- Dependencies: 282
92385 -- Name: COLUMN shipform.shipform_report_id; Type: COMMENT; Schema: public; Owner: admin
92386 --
92387
92388 COMMENT ON COLUMN shipform.shipform_report_id IS 'Obsolete -- reference shipform_report_name instead.';
92389
92390
92391 SET search_path = api, pg_catalog;
92392
92393 --
92394 -- TOC entry 283 (class 1259 OID 146567534)
92395 -- Dependencies: 8501 6
92396 -- Name: customer; Type: VIEW; Schema: api; Owner: admin
92397 --
92398
92399 CREATE VIEW customer AS
92400     SELECT (custinfo.cust_number)::character varying AS customer_number, custtype.custtype_code AS customer_type, custinfo.cust_name AS customer_name, custinfo.cust_active AS active, salesrep.salesrep_number AS sales_rep, (custinfo.cust_commprcnt * (100)::numeric) AS commission, custinfo.cust_shipvia AS ship_via, shipform.shipform_name AS ship_form, shipchrg.shipchrg_name AS shipping_charges, custinfo.cust_backorder AS accepts_backorders, custinfo.cust_partialship AS accepts_partial_shipments, custinfo.cust_ffshipto AS allow_free_form_shipto, custinfo.cust_ffbillto AS allow_free_form_billto, whsinfo.warehous_code AS preferred_selling_site, taxzone.taxzone_code AS default_tax_zone, terms.terms_code AS default_terms, CASE WHEN (custinfo.cust_balmethod = 'B'::bpchar) THEN 'Balance Forward'::text ELSE 'Open Item'::text END AS balance_method, custinfo.cust_discntprcnt AS default_discount, dc.curr_abbr AS default_currency, clc.curr_abbr AS credit_limit_currency, custinfo.cust_creditlmt AS credit_limit, CASE WHEN (COALESCE(custinfo.cust_gracedays, 0) > 0) THEN custinfo.cust_gracedays ELSE NULL::integer END AS alternate_grace_days, custinfo.cust_creditrating AS credit_rating, CASE WHEN (custinfo.cust_creditstatus = 'G'::bpchar) THEN 'In Good Standing'::text WHEN (custinfo.cust_creditstatus = 'W'::bpchar) THEN 'On Credit Warning'::text ELSE 'On Credit Hold'::text END AS credit_status, custinfo.cust_autoupdatestatus AS credit_status_exceed_warn, custinfo.cust_autoholdorders AS credit_status_exceed_hold, custinfo.cust_usespos AS uses_purchase_orders, custinfo.cust_blanketpos AS uses_blanket_pos, mc.cntct_number AS billing_contact_number, mc.cntct_honorific AS billing_contact_honorific, mc.cntct_first_name AS billing_contact_first, mc.cntct_middle AS billing_contact_middle, mc.cntct_last_name AS billing_contact_last, mc.cntct_suffix AS billing_contact_suffix, mc.cntct_title AS billing_contact_job_title, mc.cntct_phone AS billing_contact_voice, mc.cntct_phone2 AS billing_contact_alternate, mc.cntct_fax AS billing_contact_fax, mc.cntct_email AS billing_contact_email, mc.cntct_webaddr AS billing_contact_web, ''::text AS billing_contact_change, m.addr_number AS billing_contact_address_number, m.addr_line1 AS billing_contact_address1, m.addr_line2 AS billing_contact_address2, m.addr_line3 AS billing_contact_address3, m.addr_city AS billing_contact_city, m.addr_state AS billing_contact_state, m.addr_postalcode AS billing_contact_postalcode, m.addr_country AS billing_contact_country, ''::text AS billing_contact_address_change, cc.cntct_number AS correspond_contact_number, cc.cntct_honorific AS correspond_contact_honorific, cc.cntct_first_name AS correspond_contact_first, cc.cntct_middle AS correspond_contact_middle, cc.cntct_last_name AS correspond_contact_last, cc.cntct_suffix AS correspond_contact_suffix, cc.cntct_title AS correspond_contact_job_title, cc.cntct_phone AS correspond_contact_voice, cc.cntct_phone2 AS correspond_contact_alternate, cc.cntct_fax AS correspond_contact_fax, cc.cntct_email AS correspond_contact_email, cc.cntct_webaddr AS correspond_contact_web, ''::text AS correspond_contact_change, c.addr_number AS correspond_contact_address_number, c.addr_line1 AS correspond_contact_address1, c.addr_line2 AS correspond_contact_address2, c.addr_line3 AS correspond_contact_address3, c.addr_city AS correspond_contact_city, c.addr_state AS correspond_contact_state, c.addr_postalcode AS correspond_contact_postalcode, c.addr_country AS correspond_contact_country, ''::text AS correspond_contact_address_change, custinfo.cust_comments AS notes FROM ((((((((public.custinfo LEFT JOIN public.shipchrg ON ((custinfo.cust_shipchrg_id = shipchrg.shipchrg_id))) LEFT JOIN public.whsinfo ON ((custinfo.cust_preferred_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.cntct mc ON ((custinfo.cust_cntct_id = mc.cntct_id))) LEFT JOIN public.addr m ON ((mc.cntct_addr_id = m.addr_id))) LEFT JOIN public.cntct cc ON ((custinfo.cust_corrcntct_id = cc.cntct_id))) LEFT JOIN public.addr c ON ((cc.cntct_addr_id = c.addr_id))) LEFT JOIN public.taxzone ON ((custinfo.cust_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.shipform ON ((custinfo.cust_shipform_id = shipform.shipform_id))), public.custtype, public.salesrep, public.curr_symbol dc, public.curr_symbol clc, public.terms WHERE (((((custinfo.cust_custtype_id = custtype.custtype_id) AND (custinfo.cust_salesrep_id = salesrep.salesrep_id)) AND (custinfo.cust_curr_id = dc.curr_id)) AND (custinfo.cust_creditlmt_curr_id = clc.curr_id)) AND (custinfo.cust_terms_id = terms.terms_id));
92401
92402
92403 ALTER TABLE api.customer OWNER TO admin;
92404
92405 --
92406 -- TOC entry 9175 (class 0 OID 0)
92407 -- Dependencies: 283
92408 -- Name: VIEW customer; Type: COMMENT; Schema: api; Owner: admin
92409 --
92410
92411 COMMENT ON VIEW customer IS 'Customer';
92412
92413
92414 SET search_path = public, pg_catalog;
92415
92416 --
92417 -- TOC entry 284 (class 1259 OID 146567539)
92418 -- Dependencies: 6138 8
92419 -- Name: taxauth; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92420 --
92421
92422 CREATE TABLE taxauth (
92423     taxauth_id integer NOT NULL,
92424     taxauth_code text NOT NULL,
92425     taxauth_name text,
92426     taxauth_extref text,
92427     taxauth_addr_id integer,
92428     taxauth_curr_id integer,
92429     taxauth_county text,
92430     taxauth_accnt_id integer,
92431     CONSTRAINT taxauth_taxauth_code_check CHECK ((taxauth_code <> ''::text))
92432 );
92433
92434
92435 ALTER TABLE public.taxauth OWNER TO admin;
92436
92437 --
92438 -- TOC entry 9177 (class 0 OID 0)
92439 -- Dependencies: 284
92440 -- Name: TABLE taxauth; Type: COMMENT; Schema: public; Owner: admin
92441 --
92442
92443 COMMENT ON TABLE taxauth IS 'The Tax Authority table.';
92444
92445
92446 --
92447 -- TOC entry 9178 (class 0 OID 0)
92448 -- Dependencies: 284
92449 -- Name: COLUMN taxauth.taxauth_curr_id; Type: COMMENT; Schema: public; Owner: admin
92450 --
92451
92452 COMMENT ON COLUMN taxauth.taxauth_curr_id IS 'The required currency for recording tax information as. NULL means no preference.';
92453
92454
92455 --
92456 -- TOC entry 285 (class 1259 OID 146567549)
92457 -- Dependencies: 6139 6140 6141 6143 8
92458 -- Name: taxreg; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92459 --
92460
92461 CREATE TABLE taxreg (
92462     taxreg_id integer NOT NULL,
92463     taxreg_rel_id integer NOT NULL,
92464     taxreg_rel_type character(1),
92465     taxreg_taxauth_id integer,
92466     taxreg_number text NOT NULL,
92467     taxreg_taxzone_id integer,
92468     taxreg_effective date DEFAULT startoftime(),
92469     taxreg_expires date DEFAULT endoftime(),
92470     taxreg_notes text DEFAULT ''::text,
92471     CONSTRAINT taxreg_taxreg_number_check CHECK ((taxreg_number <> ''::text))
92472 );
92473
92474
92475 ALTER TABLE public.taxreg OWNER TO admin;
92476
92477 --
92478 -- TOC entry 9180 (class 0 OID 0)
92479 -- Dependencies: 285
92480 -- Name: TABLE taxreg; Type: COMMENT; Schema: public; Owner: admin
92481 --
92482
92483 COMMENT ON TABLE taxreg IS 'Stores Tax Registration numbers related to objects and a given tax authority. The rel_id specifies the object id and teh rel_type specifies the object type. See column comment for additional detail on types.';
92484
92485
92486 --
92487 -- TOC entry 9181 (class 0 OID 0)
92488 -- Dependencies: 285
92489 -- Name: COLUMN taxreg.taxreg_rel_type; Type: COMMENT; Schema: public; Owner: admin
92490 --
92491
92492 COMMENT ON COLUMN taxreg.taxreg_rel_type IS 'The type of relation this record is for. Known values are C=Customer, V=Vendor, NULL=This Manufacturer in which case taxreg_rel_id is meaningless and should be -1.';
92493
92494
92495 SET search_path = api, pg_catalog;
92496
92497 --
92498 -- TOC entry 286 (class 1259 OID 146567560)
92499 -- Dependencies: 8502 6
92500 -- Name: customertaxreg; Type: VIEW; Schema: api; Owner: admin
92501 --
92502
92503 CREATE VIEW customertaxreg AS
92504     SELECT (custinfo.cust_number)::character varying AS customer_number, (COALESCE(taxzone.taxzone_code, 'Any'::text))::character varying AS tax_zone, (taxauth.taxauth_code)::character varying AS tax_authority, taxreg.taxreg_number AS registration_number, CASE WHEN (taxreg.taxreg_effective = public.startoftime()) THEN 'Always'::text ELSE public.formatdate(taxreg.taxreg_effective) END AS start_date, CASE WHEN (taxreg.taxreg_expires = public.endoftime()) THEN 'Never'::text ELSE public.formatdate(taxreg.taxreg_expires) END AS end_date, taxreg.taxreg_notes AS notes FROM (((public.taxreg LEFT JOIN public.custinfo ON ((custinfo.cust_id = taxreg.taxreg_rel_id))) LEFT JOIN public.taxauth ON ((taxauth.taxauth_id = taxreg.taxreg_taxauth_id))) LEFT JOIN public.taxzone ON ((taxzone.taxzone_id = taxreg.taxreg_taxzone_id))) WHERE (taxreg.taxreg_rel_type = 'C'::bpchar) ORDER BY custinfo.cust_number, taxreg.taxreg_number;
92505
92506
92507 ALTER TABLE api.customertaxreg OWNER TO admin;
92508
92509 --
92510 -- TOC entry 9183 (class 0 OID 0)
92511 -- Dependencies: 286
92512 -- Name: VIEW customertaxreg; Type: COMMENT; Schema: api; Owner: admin
92513 --
92514
92515 COMMENT ON VIEW customertaxreg IS 'Customer Tax Registrations';
92516
92517
92518 --
92519 -- TOC entry 287 (class 1259 OID 146567566)
92520 -- Dependencies: 8503 6
92521 -- Name: customertype; Type: VIEW; Schema: api; Owner: admin
92522 --
92523
92524 CREATE VIEW customertype AS
92525     SELECT (custtype.custtype_code)::character varying AS code, custtype.custtype_descrip AS description, custtype.custtype_char AS enable_characteristics_profile FROM public.custtype ORDER BY custtype.custtype_code;
92526
92527
92528 ALTER TABLE api.customertype OWNER TO admin;
92529
92530 --
92531 -- TOC entry 9185 (class 0 OID 0)
92532 -- Dependencies: 287
92533 -- Name: VIEW customertype; Type: COMMENT; Schema: api; Owner: admin
92534 --
92535
92536 COMMENT ON VIEW customertype IS 'Customer Type';
92537
92538
92539 --
92540 -- TOC entry 288 (class 1259 OID 146567570)
92541 -- Dependencies: 8504 6
92542 -- Name: customertypechar; Type: VIEW; Schema: api; Owner: admin
92543 --
92544
92545 CREATE VIEW customertypechar AS
92546     SELECT (custtype.custtype_code)::character varying AS customer_type, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value, charass.charass_default AS is_default FROM public.custtype, public."char", public.charass WHERE ((('CT'::text = charass.charass_target_type) AND (custtype.custtype_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
92547
92548
92549 ALTER TABLE api.customertypechar OWNER TO admin;
92550
92551 --
92552 -- TOC entry 9187 (class 0 OID 0)
92553 -- Dependencies: 288
92554 -- Name: VIEW customertypechar; Type: COMMENT; Schema: api; Owner: admin
92555 --
92556
92557 COMMENT ON VIEW customertypechar IS 'Customer Type Characteristics';
92558
92559
92560 --
92561 -- TOC entry 289 (class 1259 OID 146567574)
92562 -- Dependencies: 8505 6
92563 -- Name: custshipto; Type: VIEW; Schema: api; Owner: admin
92564 --
92565
92566 CREATE VIEW custshipto AS
92567     SELECT (custinfo.cust_number)::character varying AS customer_number, (shiptoinfo.shipto_num)::character varying AS shipto_number, shiptoinfo.shipto_active AS active, shiptoinfo.shipto_name AS name, shiptoinfo.shipto_default AS default_flag, addr.addr_number AS address_number, addr.addr_line1 AS address1, addr.addr_line2 AS address2, addr.addr_line3 AS address3, addr.addr_city AS city, addr.addr_state AS state, addr.addr_postalcode AS postal_code, addr.addr_country AS country, ''::text AS address_change, cntct.cntct_number AS contact_number, cntct.cntct_honorific AS honorific, cntct.cntct_first_name AS first, cntct.cntct_middle AS middle, cntct.cntct_last_name AS last, cntct.cntct_suffix AS suffix, cntct.cntct_title AS job_title, cntct.cntct_phone AS phone, cntct.cntct_fax AS fax, cntct.cntct_email AS email, ''::text AS contact_change, salesrep.salesrep_number AS sales_rep, (shiptoinfo.shipto_commission * 100.0) AS commission, shipzone.shipzone_name AS zone, taxzone.taxzone_code AS tax_zone, shiptoinfo.shipto_shipvia AS ship_via, shipform.shipform_name AS ship_form, shipchrg.shipchrg_name AS shipping_charges, CASE WHEN (shiptoinfo.shipto_ediprofile_id = (-1)) THEN 'No EDI'::text WHEN (shiptoinfo.shipto_ediprofile_id = (-2)) THEN 'Use Customer Master'::text ELSE public.getediprofilename(shiptoinfo.shipto_ediprofile_id) END AS edi_profile, shiptoinfo.shipto_comments AS general_notes, shiptoinfo.shipto_shipcomments AS shipping_notes FROM public.custinfo, ((((((public.shiptoinfo LEFT JOIN public.shipchrg ON ((shiptoinfo.shipto_shipchrg_id = shipchrg.shipchrg_id))) LEFT JOIN public.cntct ON ((shiptoinfo.shipto_cntct_id = cntct.cntct_id))) LEFT JOIN public.addr ON ((shiptoinfo.shipto_addr_id = addr.addr_id))) LEFT JOIN public.taxzone ON ((shiptoinfo.shipto_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.shipzone ON ((shiptoinfo.shipto_shipzone_id = shipzone.shipzone_id))) LEFT JOIN public.salesrep ON ((shiptoinfo.shipto_salesrep_id = salesrep.salesrep_id))), public.shipform WHERE ((custinfo.cust_id = shiptoinfo.shipto_cust_id) AND (custinfo.cust_shipform_id = shipform.shipform_id));
92568
92569
92570 ALTER TABLE api.custshipto OWNER TO admin;
92571
92572 --
92573 -- TOC entry 9189 (class 0 OID 0)
92574 -- Dependencies: 289
92575 -- Name: VIEW custshipto; Type: COMMENT; Schema: api; Owner: admin
92576 --
92577
92578 COMMENT ON VIEW custshipto IS 'Customer Shipto Address';
92579
92580
92581 --
92582 -- TOC entry 290 (class 1259 OID 146567579)
92583 -- Dependencies: 8506 6
92584 -- Name: custtax; Type: VIEW; Schema: api; Owner: admin
92585 --
92586
92587 CREATE VIEW custtax AS
92588     SELECT (custinfo.cust_number)::character varying AS customer_number, (taxauth.taxauth_code)::character varying AS tax_authority, taxreg.taxreg_number AS registration_number FROM public.custinfo, public.taxauth, public.taxreg WHERE (((taxreg.taxreg_rel_type = 'C'::bpchar) AND (taxreg.taxreg_rel_id = custinfo.cust_id)) AND (taxreg.taxreg_taxauth_id = taxauth.taxauth_id));
92589
92590
92591 ALTER TABLE api.custtax OWNER TO admin;
92592
92593 --
92594 -- TOC entry 9191 (class 0 OID 0)
92595 -- Dependencies: 290
92596 -- Name: VIEW custtax; Type: COMMENT; Schema: api; Owner: admin
92597 --
92598
92599 COMMENT ON VIEW custtax IS 'Customer Tax Registration';
92600
92601
92602 SET search_path = public, pg_catalog;
92603
92604 --
92605 -- TOC entry 291 (class 1259 OID 146567583)
92606 -- Dependencies: 6145 8
92607 -- Name: dept; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92608 --
92609
92610 CREATE TABLE dept (
92611     dept_id integer NOT NULL,
92612     dept_number text NOT NULL,
92613     dept_name text NOT NULL,
92614     CONSTRAINT dept_dept_number_check CHECK ((dept_number <> ''::text))
92615 );
92616
92617
92618 ALTER TABLE public.dept OWNER TO admin;
92619
92620 --
92621 -- TOC entry 9193 (class 0 OID 0)
92622 -- Dependencies: 291
92623 -- Name: TABLE dept; Type: COMMENT; Schema: public; Owner: admin
92624 --
92625
92626 COMMENT ON TABLE dept IS 'List of Departments';
92627
92628
92629 --
92630 -- TOC entry 292 (class 1259 OID 146567590)
92631 -- Dependencies: 6146 6147 6148 6150 6151 6152 6153 8
92632 -- Name: emp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92633 --
92634
92635 CREATE TABLE emp (
92636     emp_id integer NOT NULL,
92637     emp_code text NOT NULL,
92638     emp_number text NOT NULL,
92639     emp_active boolean DEFAULT true NOT NULL,
92640     emp_cntct_id integer,
92641     emp_warehous_id integer,
92642     emp_mgr_emp_id integer,
92643     emp_wage_type text NOT NULL,
92644     emp_wage numeric,
92645     emp_wage_curr_id integer DEFAULT basecurrid(),
92646     emp_wage_period text NOT NULL,
92647     emp_dept_id integer,
92648     emp_shift_id integer,
92649     emp_notes text,
92650     emp_image_id integer,
92651     emp_username text,
92652     emp_extrate numeric,
92653     emp_extrate_period text NOT NULL,
92654     emp_startdate date DEFAULT ('now'::text)::date,
92655     emp_name text NOT NULL,
92656     CONSTRAINT emp_check CHECK (((((COALESCE(emp_wage_type, ''::text) = ''::text) OR (COALESCE(emp_wage_type, ''::text) = 'H'::text)) OR (COALESCE(emp_wage_type, ''::text) = 'S'::text)) AND ((COALESCE(emp_wage, (0)::numeric) = (0)::numeric) OR ((COALESCE(emp_wage_type, ''::text) <> ''::text) AND (emp_wage IS NOT NULL))))),
92657     CONSTRAINT emp_emp_code_check CHECK ((emp_code <> ''::text)),
92658     CONSTRAINT emp_emp_number_check CHECK ((emp_number <> ''::text)),
92659     CONSTRAINT emp_emp_wage_period_check CHECK ((((((((COALESCE(emp_wage_period, ''::text) = ''::text) OR (COALESCE(emp_wage_period, ''::text) = 'H'::text)) OR (COALESCE(emp_wage_period, ''::text) = 'D'::text)) OR (COALESCE(emp_wage_period, ''::text) = 'W'::text)) OR (COALESCE(emp_wage_period, ''::text) = 'BW'::text)) OR (COALESCE(emp_wage_period, ''::text) = 'M'::text)) OR (COALESCE(emp_wage_period, ''::text) = 'Y'::text)))
92660 );
92661
92662
92663 ALTER TABLE public.emp OWNER TO admin;
92664
92665 --
92666 -- TOC entry 9195 (class 0 OID 0)
92667 -- Dependencies: 292
92668 -- Name: TABLE emp; Type: COMMENT; Schema: public; Owner: admin
92669 --
92670
92671 COMMENT ON TABLE emp IS 'Employee table describing the basic properties of an employee. Employees need not be system users.';
92672
92673
92674 --
92675 -- TOC entry 9196 (class 0 OID 0)
92676 -- Dependencies: 292
92677 -- Name: COLUMN emp.emp_code; Type: COMMENT; Schema: public; Owner: admin
92678 --
92679
92680 COMMENT ON COLUMN emp.emp_code IS 'Short, human-readable name for employee. This value is kept synchronized with usr_username and salesrep_number, and so is unique across all three tables emp, usr, and salesrep.';
92681
92682
92683 --
92684 -- TOC entry 9197 (class 0 OID 0)
92685 -- Dependencies: 292
92686 -- Name: COLUMN emp.emp_number; Type: COMMENT; Schema: public; Owner: admin
92687 --
92688
92689 COMMENT ON COLUMN emp.emp_number IS 'Official employee number. This might be used for ID badges, payroll accounting, or other purposes.';
92690
92691
92692 --
92693 -- TOC entry 9198 (class 0 OID 0)
92694 -- Dependencies: 292
92695 -- Name: COLUMN emp.emp_mgr_emp_id; Type: COMMENT; Schema: public; Owner: admin
92696 --
92697
92698 COMMENT ON COLUMN emp.emp_mgr_emp_id IS 'Internal ID of this employee''s manager/supervisor.';
92699
92700
92701 --
92702 -- TOC entry 9199 (class 0 OID 0)
92703 -- Dependencies: 292
92704 -- Name: COLUMN emp.emp_wage_type; Type: COMMENT; Schema: public; Owner: admin
92705 --
92706
92707 COMMENT ON COLUMN emp.emp_wage_type IS 'The nature of the wage or employment agreement. ''H'' indicates this employee is paid on an hourly basis (or some other period) while ''S'' indicates this employee is salaried.';
92708
92709
92710 --
92711 -- TOC entry 9200 (class 0 OID 0)
92712 -- Dependencies: 292
92713 -- Name: COLUMN emp.emp_wage_period; Type: COMMENT; Schema: public; Owner: admin
92714 --
92715
92716 COMMENT ON COLUMN emp.emp_wage_period IS 'The periodicity of wage payment: ''H'' for hourly, ''D'' for daily, ''W'' for weekly, ''BW'' for biweekly, ''M'' for monthly, ''Y'' for yearly.';
92717
92718
92719 --
92720 -- TOC entry 9201 (class 0 OID 0)
92721 -- Dependencies: 292
92722 -- Name: COLUMN emp.emp_username; Type: COMMENT; Schema: public; Owner: admin
92723 --
92724
92725 COMMENT ON COLUMN emp.emp_username IS 'DEPRECATED - the relationship between Employee and User is now maintained through the crmacct table.';
92726
92727
92728 --
92729 -- TOC entry 9202 (class 0 OID 0)
92730 -- Dependencies: 292
92731 -- Name: COLUMN emp.emp_extrate_period; Type: COMMENT; Schema: public; Owner: admin
92732 --
92733
92734 COMMENT ON COLUMN emp.emp_extrate_period IS 'The periodicity of external rate payment: ''H'' for hourly, ''D'' for daily, ''W'' for weekly, ''BW'' for biweekly, ''M'' for monthly, ''Y'' for yearly.';
92735
92736
92737 --
92738 -- TOC entry 293 (class 1259 OID 146567603)
92739 -- Dependencies: 6155 8
92740 -- Name: shift; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92741 --
92742
92743 CREATE TABLE shift (
92744     shift_id integer NOT NULL,
92745     shift_number text NOT NULL,
92746     shift_name text NOT NULL,
92747     CONSTRAINT shift_shift_number_check CHECK ((shift_number <> ''::text))
92748 );
92749
92750
92751 ALTER TABLE public.shift OWNER TO admin;
92752
92753 --
92754 -- TOC entry 9204 (class 0 OID 0)
92755 -- Dependencies: 293
92756 -- Name: TABLE shift; Type: COMMENT; Schema: public; Owner: admin
92757 --
92758
92759 COMMENT ON TABLE shift IS 'List of work Shifts';
92760
92761
92762 SET search_path = api, pg_catalog;
92763
92764 --
92765 -- TOC entry 294 (class 1259 OID 146567610)
92766 -- Dependencies: 8507 6
92767 -- Name: employee; Type: VIEW; Schema: api; Owner: admin
92768 --
92769
92770 CREATE VIEW employee AS
92771     SELECT (e.emp_code)::character varying AS code, (e.emp_number)::character varying AS number, e.emp_active AS active, e.emp_startdate AS start_date, cntct.cntct_number AS contact_number, cntct.cntct_honorific AS honorific, cntct.cntct_first_name AS first, cntct.cntct_middle AS middle, cntct.cntct_last_name AS last, cntct.cntct_suffix AS suffix, cntct.cntct_title AS job_title, cntct.cntct_phone AS voice, cntct.cntct_phone2 AS alternate, cntct.cntct_fax AS fax, cntct.cntct_email AS email, cntct.cntct_webaddr AS web, ''::text AS contact_change, addr.addr_number AS address_number, addr.addr_line1 AS address1, addr.addr_line2 AS address2, addr.addr_line3 AS address3, addr.addr_city AS city, addr.addr_state AS state, addr.addr_postalcode AS postalcode, addr.addr_country AS country, ''::text AS address_change, whsinfo.warehous_code AS site, m.emp_code AS manager_code, CASE WHEN (e.emp_wage_type = 'H'::text) THEN 'Hourly'::text WHEN (e.emp_wage_type = 'S'::text) THEN 'Salaried'::text WHEN (e.emp_wage_type IS NULL) THEN NULL::text ELSE 'Error'::text END AS wage_type, e.emp_wage AS wage, curr_symbol.curr_abbr AS wage_currency, CASE WHEN (e.emp_wage_period = 'H'::text) THEN 'Hour'::text WHEN (e.emp_wage_period = 'D'::text) THEN 'Day'::text WHEN (e.emp_wage_period = 'W'::text) THEN 'Week'::text WHEN (e.emp_wage_period = 'BW'::text) THEN 'Biweek'::text WHEN (e.emp_wage_period = 'M'::text) THEN 'Month'::text WHEN (e.emp_wage_period = 'Y'::text) THEN 'Year'::text WHEN (e.emp_wage_period IS NULL) THEN NULL::text ELSE 'Error'::text END AS wage_period, dept.dept_number AS department, shift.shift_number AS shift, (crmacct.crmacct_usr_username IS NOT NULL) AS is_user, (salesrep.salesrep_id IS NOT NULL) AS is_salesrep, (vendinfo.vend_id IS NOT NULL) AS is_vendor, e.emp_notes AS notes, image.image_name AS image, e.emp_extrate AS rate, curr_symbol.curr_abbr AS billing_currency, CASE WHEN (e.emp_extrate_period = 'H'::text) THEN 'Hour'::text WHEN (e.emp_extrate_period = 'D'::text) THEN 'Day'::text WHEN (e.emp_extrate_period = 'W'::text) THEN 'Week'::text WHEN (e.emp_extrate_period = 'BW'::text) THEN 'Biweek'::text WHEN (e.emp_extrate_period = 'M'::text) THEN 'Month'::text WHEN (e.emp_extrate_period = 'Y'::text) THEN 'Year'::text WHEN (e.emp_extrate_period IS NULL) THEN NULL::text ELSE 'Error'::text END AS billing_period FROM (((((((((((public.emp e JOIN public.crmacct ON ((e.emp_id = crmacct.crmacct_emp_id))) LEFT JOIN public.cntct ON ((e.emp_cntct_id = cntct.cntct_id))) LEFT JOIN public.addr ON ((cntct.cntct_addr_id = addr.addr_id))) LEFT JOIN public.whsinfo ON ((e.emp_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.emp m ON ((e.emp_mgr_emp_id = m.emp_id))) LEFT JOIN public.dept ON ((e.emp_dept_id = dept.dept_id))) LEFT JOIN public.shift ON ((e.emp_shift_id = shift.shift_id))) LEFT JOIN public.salesrep ON ((crmacct.crmacct_salesrep_id = salesrep.salesrep_id))) LEFT JOIN public.vendinfo ON ((crmacct.crmacct_vend_id = vendinfo.vend_id))) LEFT JOIN public.image ON ((e.emp_image_id = image.image_id))) JOIN public.curr_symbol ON ((e.emp_wage_curr_id = curr_symbol.curr_id)));
92772
92773
92774 ALTER TABLE api.employee OWNER TO admin;
92775
92776 --
92777 -- TOC entry 9206 (class 0 OID 0)
92778 -- Dependencies: 294
92779 -- Name: VIEW employee; Type: COMMENT; Schema: api; Owner: admin
92780 --
92781
92782 COMMENT ON VIEW employee IS 'Employee';
92783
92784
92785 --
92786 -- TOC entry 295 (class 1259 OID 146567615)
92787 -- Dependencies: 8508 6
92788 -- Name: employeechar; Type: VIEW; Schema: api; Owner: admin
92789 --
92790
92791 CREATE VIEW employeechar AS
92792     SELECT (emp.emp_code)::character varying AS employee_code, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value FROM public.emp, public."char", public.charass WHERE ((('EMP'::text = charass.charass_target_type) AND (emp.emp_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
92793
92794
92795 ALTER TABLE api.employeechar OWNER TO admin;
92796
92797 --
92798 -- TOC entry 9208 (class 0 OID 0)
92799 -- Dependencies: 295
92800 -- Name: VIEW employeechar; Type: COMMENT; Schema: api; Owner: admin
92801 --
92802
92803 COMMENT ON VIEW employeechar IS 'Employee Characteristics';
92804
92805
92806 --
92807 -- TOC entry 296 (class 1259 OID 146567619)
92808 -- Dependencies: 8509 6
92809 -- Name: employeecomment; Type: VIEW; Schema: api; Owner: admin
92810 --
92811
92812 CREATE VIEW employeecomment AS
92813     SELECT (emp.emp_code)::character varying AS code, (cmnttype.cmnttype_name)::character varying AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.emp, public.cmnttype, public.comment WHERE (((comment.comment_source = 'EMP'::text) AND (comment.comment_source_id = emp.emp_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
92814
92815
92816 ALTER TABLE api.employeecomment OWNER TO admin;
92817
92818 --
92819 -- TOC entry 9210 (class 0 OID 0)
92820 -- Dependencies: 296
92821 -- Name: VIEW employeecomment; Type: COMMENT; Schema: api; Owner: admin
92822 --
92823
92824 COMMENT ON VIEW employeecomment IS 'Employee Comment';
92825
92826
92827 SET search_path = public, pg_catalog;
92828
92829 --
92830 -- TOC entry 297 (class 1259 OID 146567623)
92831 -- Dependencies: 6156 6157 6158 6159 8
92832 -- Name: shipdata; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92833 --
92834
92835 CREATE TABLE shipdata (
92836     shipdata_cohead_number text NOT NULL,
92837     shipdata_cosmisc_tracknum text NOT NULL,
92838     shipdata_cosmisc_packnum_tracknum text NOT NULL,
92839     shipdata_weight numeric(16,4),
92840     shipdata_base_freight numeric(16,4),
92841     shipdata_total_freight numeric(16,4),
92842     shipdata_shipper text DEFAULT 'UPS'::text,
92843     shipdata_billing_option text,
92844     shipdata_package_type text,
92845     shipdata_void_ind character(1) NOT NULL,
92846     shipdata_lastupdated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
92847     shipdata_shiphead_number text,
92848     shipdata_base_freight_curr_id integer DEFAULT basecurrid(),
92849     shipdata_total_freight_curr_id integer DEFAULT basecurrid()
92850 );
92851
92852
92853 ALTER TABLE public.shipdata OWNER TO admin;
92854
92855 --
92856 -- TOC entry 9212 (class 0 OID 0)
92857 -- Dependencies: 297
92858 -- Name: TABLE shipdata; Type: COMMENT; Schema: public; Owner: admin
92859 --
92860
92861 COMMENT ON TABLE shipdata IS 'Shipping Interface information - note that the shipdata_cohead_nember is text and not int.  That is due to ODBC chopping off during the transfer';
92862
92863
92864 SET search_path = api, pg_catalog;
92865
92866 --
92867 -- TOC entry 298 (class 1259 OID 146567633)
92868 -- Dependencies: 8510 6
92869 -- Name: extshipmaint; Type: VIEW; Schema: api; Owner: admin
92870 --
92871
92872 CREATE VIEW extshipmaint AS
92873     SELECT (shipdata.shipdata_cohead_number)::character varying AS so_number, (shipdata.shipdata_shiphead_number)::character varying AS shipment_number, (shipdata.shipdata_shipper)::character varying AS shipper, (shipdata.shipdata_cosmisc_packnum_tracknum)::character varying AS package_tracking_number, shipdata.shipdata_void_ind AS void, shipdata.shipdata_billing_option AS billing_option, shipdata.shipdata_weight AS weight, shipdata.shipdata_base_freight AS base_freight, base.curr_abbr AS base_freight_currency, shipdata.shipdata_total_freight AS total_freight, total.curr_abbr AS total_freight_currency, shipdata.shipdata_package_type AS package_type, shipdata.shipdata_cosmisc_tracknum AS tracking_number, shipdata.shipdata_lastupdated AS last_updated FROM public.shipdata, public.curr_symbol base, public.curr_symbol total WHERE ((shipdata.shipdata_base_freight_curr_id = base.curr_id) AND (shipdata.shipdata_total_freight_curr_id = total.curr_id)) ORDER BY shipdata.shipdata_cohead_number, shipdata.shipdata_shiphead_number;
92874
92875
92876 ALTER TABLE api.extshipmaint OWNER TO admin;
92877
92878 --
92879 -- TOC entry 9214 (class 0 OID 0)
92880 -- Dependencies: 298
92881 -- Name: VIEW extshipmaint; Type: COMMENT; Schema: api; Owner: admin
92882 --
92883
92884 COMMENT ON VIEW extshipmaint IS 'External Shipping Maintenance';
92885
92886
92887 SET search_path = public, pg_catalog;
92888
92889 --
92890 -- TOC entry 299 (class 1259 OID 146567638)
92891 -- Dependencies: 6161 8
92892 -- Name: freightclass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92893 --
92894
92895 CREATE TABLE freightclass (
92896     freightclass_id integer NOT NULL,
92897     freightclass_code text NOT NULL,
92898     freightclass_descrip text,
92899     CONSTRAINT freightclass_freightclass_code_check CHECK ((freightclass_code <> ''::text))
92900 );
92901
92902
92903 ALTER TABLE public.freightclass OWNER TO admin;
92904
92905 --
92906 -- TOC entry 9216 (class 0 OID 0)
92907 -- Dependencies: 299
92908 -- Name: TABLE freightclass; Type: COMMENT; Schema: public; Owner: admin
92909 --
92910
92911 COMMENT ON TABLE freightclass IS 'This table is the freight price schedules.';
92912
92913
92914 --
92915 -- TOC entry 300 (class 1259 OID 146567645)
92916 -- Dependencies: 6163 6164 8
92917 -- Name: ipsfreight; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92918 --
92919
92920 CREATE TABLE ipsfreight (
92921     ipsfreight_id integer NOT NULL,
92922     ipsfreight_ipshead_id integer NOT NULL,
92923     ipsfreight_qtybreak numeric DEFAULT 0 NOT NULL,
92924     ipsfreight_price numeric DEFAULT 0 NOT NULL,
92925     ipsfreight_type character(1) NOT NULL,
92926     ipsfreight_warehous_id integer,
92927     ipsfreight_shipzone_id integer,
92928     ipsfreight_freightclass_id integer,
92929     ipsfreight_shipvia text
92930 );
92931
92932
92933 ALTER TABLE public.ipsfreight OWNER TO admin;
92934
92935 --
92936 -- TOC entry 301 (class 1259 OID 146567653)
92937 -- Dependencies: 6165 6166 6167 8
92938 -- Name: ipshead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
92939 --
92940
92941 CREATE TABLE ipshead (
92942     ipshead_id integer DEFAULT nextval(('"ipshead_ipshead_id_seq"'::text)::regclass) NOT NULL,
92943     ipshead_name text NOT NULL,
92944     ipshead_descrip text,
92945     ipshead_effective date,
92946     ipshead_expires date,
92947     ipshead_curr_id integer DEFAULT basecurrid() NOT NULL,
92948     ipshead_updated date,
92949     CONSTRAINT ipshead_ipshead_name_check CHECK ((ipshead_name <> ''::text))
92950 );
92951
92952
92953 ALTER TABLE public.ipshead OWNER TO admin;
92954
92955 --
92956 -- TOC entry 9219 (class 0 OID 0)
92957 -- Dependencies: 301
92958 -- Name: TABLE ipshead; Type: COMMENT; Schema: public; Owner: admin
92959 --
92960
92961 COMMENT ON TABLE ipshead IS 'Pricing Schedule header information';
92962
92963
92964 SET search_path = api, pg_catalog;
92965
92966 --
92967 -- TOC entry 302 (class 1259 OID 146567662)
92968 -- Dependencies: 8511 6
92969 -- Name: freightpricingscheduleitem; Type: VIEW; Schema: api; Owner: admin
92970 --
92971
92972 CREATE VIEW freightpricingscheduleitem AS
92973     SELECT (ipshead.ipshead_name)::character varying AS pricing_schedule, ipsfreight.ipsfreight_qtybreak AS qty_break, (qtyuom.uom_name)::character varying AS qty_uom, ipsfreight.ipsfreight_price AS price, CASE WHEN (ipsfreight.ipsfreight_type = 'F'::bpchar) THEN 'Flat Rate'::text ELSE 'Price Per UOM'::text END AS price_type, COALESCE(whsinfo.warehous_code, 'Any'::text) AS from_site, COALESCE(shipzone.shipzone_name, 'Any'::text) AS to_shipzone, COALESCE(ipsfreight.ipsfreight_shipvia, 'Any'::text) AS ship_via, COALESCE(freightclass.freightclass_code, 'Any'::text) AS freight_class FROM (((((public.ipsfreight JOIN public.ipshead ON ((ipsfreight.ipsfreight_ipshead_id = ipshead.ipshead_id))) LEFT JOIN public.uom qtyuom ON (qtyuom.uom_item_weight)) LEFT JOIN public.whsinfo ON ((whsinfo.warehous_id = ipsfreight.ipsfreight_warehous_id))) LEFT JOIN public.shipzone ON ((shipzone.shipzone_id = ipsfreight.ipsfreight_shipzone_id))) LEFT JOIN public.freightclass ON ((freightclass.freightclass_id = ipsfreight.ipsfreight_freightclass_id)));
92974
92975
92976 ALTER TABLE api.freightpricingscheduleitem OWNER TO admin;
92977
92978 --
92979 -- TOC entry 9221 (class 0 OID 0)
92980 -- Dependencies: 302
92981 -- Name: VIEW freightpricingscheduleitem; Type: COMMENT; Schema: api; Owner: admin
92982 --
92983
92984 COMMENT ON VIEW freightpricingscheduleitem IS 'Freight Pricing Schedule Item';
92985
92986
92987 --
92988 -- TOC entry 303 (class 1259 OID 146567667)
92989 -- Dependencies: 8512 6
92990 -- Name: glaccount; Type: VIEW; Schema: api; Owner: admin
92991 --
92992
92993 CREATE VIEW glaccount AS
92994     SELECT (accnt.accnt_company)::character varying AS company, (accnt.accnt_profit)::character varying AS profit_center, (accnt.accnt_number)::character varying AS account_number, (accnt.accnt_sub)::character varying AS sub_account, accnt.accnt_descrip AS description, accnt.accnt_extref AS ext_reference, CASE WHEN (accnt.accnt_type = 'A'::bpchar) THEN 'Asset'::text WHEN (accnt.accnt_type = 'L'::bpchar) THEN 'Liability'::text WHEN (accnt.accnt_type = 'E'::bpchar) THEN 'Expense'::text WHEN (accnt.accnt_type = 'R'::bpchar) THEN 'Revenue'::text WHEN (accnt.accnt_type = 'Q'::bpchar) THEN 'Equity'::text ELSE '?'::text END AS type, accnt.accnt_subaccnttype_code AS sub_type, accnt.accnt_forwardupdate AS forward_update_trial_balances, accnt.accnt_comments AS notes FROM public.accnt ORDER BY accnt.accnt_company, accnt.accnt_profit, accnt.accnt_number, accnt.accnt_sub;
92995
92996
92997 ALTER TABLE api.glaccount OWNER TO admin;
92998
92999 --
93000 -- TOC entry 9223 (class 0 OID 0)
93001 -- Dependencies: 303
93002 -- Name: VIEW glaccount; Type: COMMENT; Schema: api; Owner: admin
93003 --
93004
93005 COMMENT ON VIEW glaccount IS 'GL Account';
93006
93007
93008 SET search_path = public, pg_catalog;
93009
93010 --
93011 -- TOC entry 304 (class 1259 OID 146567672)
93012 -- Dependencies: 6169 8
93013 -- Name: incdtcat; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93014 --
93015
93016 CREATE TABLE incdtcat (
93017     incdtcat_id integer NOT NULL,
93018     incdtcat_name text NOT NULL,
93019     incdtcat_order integer,
93020     incdtcat_descrip text,
93021     incdtcat_ediprofile_id integer,
93022     CONSTRAINT incdtcat_incdtcat_name_check CHECK ((incdtcat_name <> ''::text))
93023 );
93024
93025
93026 ALTER TABLE public.incdtcat OWNER TO admin;
93027
93028 --
93029 -- TOC entry 9225 (class 0 OID 0)
93030 -- Dependencies: 304
93031 -- Name: TABLE incdtcat; Type: COMMENT; Schema: public; Owner: admin
93032 --
93033
93034 COMMENT ON TABLE incdtcat IS 'Incident Category table';
93035
93036
93037 --
93038 -- TOC entry 305 (class 1259 OID 146567679)
93039 -- Dependencies: 6171 8
93040 -- Name: incdtpriority; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93041 --
93042
93043 CREATE TABLE incdtpriority (
93044     incdtpriority_id integer NOT NULL,
93045     incdtpriority_name text NOT NULL,
93046     incdtpriority_order integer,
93047     incdtpriority_descrip text,
93048     CONSTRAINT incdtpriority_incdtpriority_name_check CHECK ((incdtpriority_name <> ''::text))
93049 );
93050
93051
93052 ALTER TABLE public.incdtpriority OWNER TO admin;
93053
93054 --
93055 -- TOC entry 9227 (class 0 OID 0)
93056 -- Dependencies: 305
93057 -- Name: TABLE incdtpriority; Type: COMMENT; Schema: public; Owner: admin
93058 --
93059
93060 COMMENT ON TABLE incdtpriority IS 'Incident Priority table';
93061
93062
93063 --
93064 -- TOC entry 306 (class 1259 OID 146567686)
93065 -- Dependencies: 6173 8
93066 -- Name: incdtresolution; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93067 --
93068
93069 CREATE TABLE incdtresolution (
93070     incdtresolution_id integer NOT NULL,
93071     incdtresolution_name text NOT NULL,
93072     incdtresolution_order integer,
93073     incdtresolution_descrip text,
93074     CONSTRAINT incdtresolution_incdtresolution_name_check CHECK ((incdtresolution_name <> ''::text))
93075 );
93076
93077
93078 ALTER TABLE public.incdtresolution OWNER TO admin;
93079
93080 --
93081 -- TOC entry 9229 (class 0 OID 0)
93082 -- Dependencies: 306
93083 -- Name: TABLE incdtresolution; Type: COMMENT; Schema: public; Owner: admin
93084 --
93085
93086 COMMENT ON TABLE incdtresolution IS 'Incident Resolution table';
93087
93088
93089 --
93090 -- TOC entry 307 (class 1259 OID 146567693)
93091 -- Dependencies: 6175 8
93092 -- Name: incdtseverity; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93093 --
93094
93095 CREATE TABLE incdtseverity (
93096     incdtseverity_id integer NOT NULL,
93097     incdtseverity_name text NOT NULL,
93098     incdtseverity_order integer,
93099     incdtseverity_descrip text,
93100     CONSTRAINT incdtseverity_incdtseverity_name_check CHECK ((incdtseverity_name <> ''::text))
93101 );
93102
93103
93104 ALTER TABLE public.incdtseverity OWNER TO admin;
93105
93106 --
93107 -- TOC entry 9231 (class 0 OID 0)
93108 -- Dependencies: 307
93109 -- Name: TABLE incdtseverity; Type: COMMENT; Schema: public; Owner: admin
93110 --
93111
93112 COMMENT ON TABLE incdtseverity IS 'Incident Severity table';
93113
93114
93115 SET search_path = api, pg_catalog;
93116
93117 --
93118 -- TOC entry 308 (class 1259 OID 146567700)
93119 -- Dependencies: 8513 6
93120 -- Name: incident; Type: VIEW; Schema: api; Owner: admin
93121 --
93122
93123 CREATE VIEW incident AS
93124     SELECT incdt.incdt_number AS incident_number, incdtcat.incdtcat_name AS category, incdt.incdt_summary AS description, crmacct.crmacct_number AS crm_account, incdt.incdt_assigned_username AS assigned_to, CASE WHEN (incdt.incdt_status = 'N'::bpchar) THEN 'New'::text WHEN (incdt.incdt_status = 'F'::bpchar) THEN 'Feedback'::text WHEN (incdt.incdt_status = 'C'::bpchar) THEN 'Confirmed'::text WHEN (incdt.incdt_status = 'A'::bpchar) THEN 'Assigned'::text WHEN (incdt.incdt_status = 'R'::bpchar) THEN 'Resolved'::text WHEN (incdt.incdt_status = 'L'::bpchar) THEN 'Closed'::text ELSE '?'::text END AS status, incdtseverity.incdtseverity_name AS severity, incdtpriority.incdtpriority_name AS priority, incdtresolution.incdtresolution_name AS resolution, cntct.cntct_number AS contact_number, cntct.cntct_honorific AS honorific, cntct.cntct_first_name AS first, cntct.cntct_middle AS middle, cntct.cntct_last_name AS last, cntct.cntct_suffix AS suffix, cntct.cntct_title AS job_title, cntct.cntct_phone AS phone, cntct.cntct_fax AS fax, cntct.cntct_email AS email, ''::text AS contact_change, incdt.incdt_descrip AS notes, item.item_number, incdt.incdt_lotserial AS lot_serial_number, CASE WHEN (aropen.aropen_doctype = 'C'::bpchar) THEN 'C/M'::text WHEN (aropen.aropen_doctype = 'D'::bpchar) THEN 'D/M'::text WHEN (aropen.aropen_doctype = 'I'::bpchar) THEN 'Invoice'::text WHEN (aropen.aropen_doctype = 'R'::bpchar) THEN 'C/D'::text ELSE ''::text END AS ar_doc_type, aropen.aropen_docnumber AS ar_doc_number FROM ((((((((public.incdt LEFT JOIN public.incdtcat ON ((incdtcat.incdtcat_id = incdt.incdt_incdtcat_id))) LEFT JOIN public.crmacct ON ((crmacct.crmacct_id = incdt.incdt_crmacct_id))) LEFT JOIN public.incdtseverity ON ((incdtseverity.incdtseverity_id = incdt.incdt_incdtseverity_id))) LEFT JOIN public.incdtpriority ON ((incdtpriority.incdtpriority_id = incdt.incdt_incdtpriority_id))) LEFT JOIN public.incdtresolution ON ((incdtresolution.incdtresolution_id = incdt.incdt_incdtresolution_id))) LEFT JOIN public.cntct ON ((cntct.cntct_id = incdt.incdt_cntct_id))) LEFT JOIN public.item ON ((item.item_id = incdt.incdt_item_id))) LEFT JOIN public.aropen ON ((aropen.aropen_id = incdt.incdt_aropen_id)));
93125
93126
93127 ALTER TABLE api.incident OWNER TO admin;
93128
93129 --
93130 -- TOC entry 9233 (class 0 OID 0)
93131 -- Dependencies: 308
93132 -- Name: VIEW incident; Type: COMMENT; Schema: api; Owner: admin
93133 --
93134
93135 COMMENT ON VIEW incident IS 'Incident';
93136
93137
93138 --
93139 -- TOC entry 309 (class 1259 OID 146567705)
93140 -- Dependencies: 8514 6
93141 -- Name: incidentchar; Type: VIEW; Schema: api; Owner: admin
93142 --
93143
93144 CREATE VIEW incidentchar AS
93145     SELECT incdt.incdt_number AS incident_number, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value FROM public.incdt, public."char", public.charass WHERE ((('INCDT'::text = charass.charass_target_type) AND (incdt.incdt_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
93146
93147
93148 ALTER TABLE api.incidentchar OWNER TO admin;
93149
93150 --
93151 -- TOC entry 9235 (class 0 OID 0)
93152 -- Dependencies: 309
93153 -- Name: VIEW incidentchar; Type: COMMENT; Schema: api; Owner: admin
93154 --
93155
93156 COMMENT ON VIEW incidentchar IS 'Incident Characteristics';
93157
93158
93159 --
93160 -- TOC entry 310 (class 1259 OID 146567709)
93161 -- Dependencies: 8515 6
93162 -- Name: incidentcomment; Type: VIEW; Schema: api; Owner: admin
93163 --
93164
93165 CREATE VIEW incidentcomment AS
93166     SELECT incdt.incdt_number AS incident_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text, comment.comment_public AS public FROM public.incdt, public.cmnttype, public.comment WHERE (((comment.comment_source = 'INCDT'::text) AND (comment.comment_source_id = incdt.incdt_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
93167
93168
93169 ALTER TABLE api.incidentcomment OWNER TO admin;
93170
93171 --
93172 -- TOC entry 9237 (class 0 OID 0)
93173 -- Dependencies: 310
93174 -- Name: VIEW incidentcomment; Type: COMMENT; Schema: api; Owner: admin
93175 --
93176
93177 COMMENT ON VIEW incidentcomment IS 'Incident Comment';
93178
93179
93180 --
93181 -- TOC entry 311 (class 1259 OID 146567713)
93182 -- Dependencies: 8516 6
93183 -- Name: incidentfile; Type: VIEW; Schema: api; Owner: admin
93184 --
93185
93186 CREATE VIEW incidentfile AS
93187     SELECT incdt.incdt_number AS incident_number, url.url_title AS title, url.url_url AS url FROM public.incdt, public.url WHERE ((incdt.incdt_id = url.url_source_id) AND (url.url_source = 'INCDT'::text));
93188
93189
93190 ALTER TABLE api.incidentfile OWNER TO admin;
93191
93192 --
93193 -- TOC entry 9239 (class 0 OID 0)
93194 -- Dependencies: 311
93195 -- Name: VIEW incidentfile; Type: COMMENT; Schema: api; Owner: admin
93196 --
93197
93198 COMMENT ON VIEW incidentfile IS 'Incident File';
93199
93200
93201 --
93202 -- TOC entry 312 (class 1259 OID 146567717)
93203 -- Dependencies: 8517 6
93204 -- Name: incidentimage; Type: VIEW; Schema: api; Owner: admin
93205 --
93206
93207 CREATE VIEW incidentimage AS
93208     SELECT incdt.incdt_number AS incident_number, image.image_name FROM public.incdt, public.imageass, public.image WHERE (((incdt.incdt_id = imageass.imageass_source_id) AND (imageass.imageass_source = 'INCDT'::text)) AND (imageass.imageass_image_id = image.image_id));
93209
93210
93211 ALTER TABLE api.incidentimage OWNER TO admin;
93212
93213 --
93214 -- TOC entry 9241 (class 0 OID 0)
93215 -- Dependencies: 312
93216 -- Name: VIEW incidentimage; Type: COMMENT; Schema: api; Owner: admin
93217 --
93218
93219 COMMENT ON VIEW incidentimage IS 'Incident Image';
93220
93221
93222 SET search_path = public, pg_catalog;
93223
93224 --
93225 -- TOC entry 313 (class 1259 OID 146567721)
93226 -- Dependencies: 6176 6177 8
93227 -- Name: classcode; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93228 --
93229
93230 CREATE TABLE classcode (
93231     classcode_id integer DEFAULT nextval(('classcode_classcode_id_seq'::text)::regclass) NOT NULL,
93232     classcode_code text NOT NULL,
93233     classcode_descrip text,
93234     classcode_mfg boolean,
93235     classcode_creator text,
93236     classcode_created timestamp without time zone,
93237     classcode_modifier text,
93238     classcode_modified timestamp without time zone,
93239     classcode_type text,
93240     CONSTRAINT classcode_classcode_code_check CHECK ((classcode_code <> ''::text))
93241 );
93242
93243
93244 ALTER TABLE public.classcode OWNER TO admin;
93245
93246 --
93247 -- TOC entry 9243 (class 0 OID 0)
93248 -- Dependencies: 313
93249 -- Name: TABLE classcode; Type: COMMENT; Schema: public; Owner: admin
93250 --
93251
93252 COMMENT ON TABLE classcode IS 'Class Code information';
93253
93254
93255 --
93256 -- TOC entry 314 (class 1259 OID 146567729)
93257 -- Dependencies: 6178 6179 8
93258 -- Name: prodcat; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93259 --
93260
93261 CREATE TABLE prodcat (
93262     prodcat_id integer DEFAULT nextval(('prodcat_prodcat_id_seq'::text)::regclass) NOT NULL,
93263     prodcat_code text NOT NULL,
93264     prodcat_descrip text,
93265     CONSTRAINT prodcat_prodcat_code_check CHECK ((prodcat_code <> ''::text))
93266 );
93267
93268
93269 ALTER TABLE public.prodcat OWNER TO admin;
93270
93271 --
93272 -- TOC entry 9245 (class 0 OID 0)
93273 -- Dependencies: 314
93274 -- Name: TABLE prodcat; Type: COMMENT; Schema: public; Owner: admin
93275 --
93276
93277 COMMENT ON TABLE prodcat IS 'Product Category information';
93278
93279
93280 SET search_path = api, pg_catalog;
93281
93282 --
93283 -- TOC entry 315 (class 1259 OID 146567737)
93284 -- Dependencies: 8518 6
93285 -- Name: item; Type: VIEW; Schema: api; Owner: admin
93286 --
93287
93288 CREATE VIEW item AS
93289     SELECT (item.item_number)::character varying AS item_number, item.item_active AS active, item.item_descrip1 AS description1, item.item_descrip2 AS description2, CASE WHEN (item.item_type = 'P'::bpchar) THEN 'Purchased'::text WHEN (item.item_type = 'M'::bpchar) THEN 'Manufactured'::text WHEN (item.item_type = 'J'::bpchar) THEN 'Job'::text WHEN (item.item_type = 'K'::bpchar) THEN 'Kit'::text WHEN (item.item_type = 'F'::bpchar) THEN 'Phantom'::text WHEN (item.item_type = 'R'::bpchar) THEN 'Reference'::text WHEN (item.item_type = 'S'::bpchar) THEN 'Costing'::text WHEN (item.item_type = 'T'::bpchar) THEN 'Tooling'::text WHEN (item.item_type = 'O'::bpchar) THEN 'Outside Process'::text WHEN (item.item_type = 'L'::bpchar) THEN 'Planning'::text WHEN (item.item_type = 'B'::bpchar) THEN 'Breeder'::text WHEN (item.item_type = 'C'::bpchar) THEN 'Co-Product'::text WHEN (item.item_type = 'Y'::bpchar) THEN 'By-Product'::text ELSE NULL::text END AS item_type, item.item_maxcost AS maximum_desired_cost, classcode.classcode_code AS class_code, i.uom_name AS inventory_uom, item.item_picklist AS pick_list_item, item.item_fractional AS fractional, item.item_config AS configured, item.item_sold AS item_is_sold, prodcat.prodcat_code AS product_category, item.item_exclusive AS exclusive, item.item_listprice AS list_price, item.item_listcost AS list_cost, p.uom_name AS list_price_uom, item.item_upccode AS upc_code, item.item_prodweight AS product_weight, item.item_packweight AS packaging_weight, item.item_comments AS notes, item.item_extdescrip AS ext_description FROM (public.item LEFT JOIN public.prodcat ON ((item.item_prodcat_id = prodcat.prodcat_id))), public.classcode, public.uom i, public.uom p WHERE (((item.item_classcode_id = classcode.classcode_id) AND (item.item_inv_uom_id = i.uom_id)) AND (item.item_price_uom_id = p.uom_id)) ORDER BY (item.item_number)::character varying;
93290
93291
93292 ALTER TABLE api.item OWNER TO admin;
93293
93294 --
93295 -- TOC entry 9247 (class 0 OID 0)
93296 -- Dependencies: 315
93297 -- Name: VIEW item; Type: COMMENT; Schema: api; Owner: admin
93298 --
93299
93300 COMMENT ON VIEW item IS 'Item';
93301
93302
93303 SET search_path = public, pg_catalog;
93304
93305 --
93306 -- TOC entry 316 (class 1259 OID 146567742)
93307 -- Dependencies: 6180 6181 8
93308 -- Name: itemalias; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93309 --
93310
93311 CREATE TABLE itemalias (
93312     itemalias_id integer DEFAULT nextval(('"itemalias_itemalias_id_seq"'::text)::regclass) NOT NULL,
93313     itemalias_item_id integer NOT NULL,
93314     itemalias_number text NOT NULL,
93315     itemalias_comments text,
93316     itemalias_usedescrip boolean NOT NULL,
93317     itemalias_descrip1 text,
93318     itemalias_descrip2 text,
93319     itemalias_crmacct_id integer,
93320     CONSTRAINT itemalias_itemalias_number_check CHECK ((itemalias_number <> ''::text))
93321 );
93322
93323
93324 ALTER TABLE public.itemalias OWNER TO admin;
93325
93326 --
93327 -- TOC entry 9249 (class 0 OID 0)
93328 -- Dependencies: 316
93329 -- Name: TABLE itemalias; Type: COMMENT; Schema: public; Owner: admin
93330 --
93331
93332 COMMENT ON TABLE itemalias IS 'Item Alias information';
93333
93334
93335 --
93336 -- TOC entry 9250 (class 0 OID 0)
93337 -- Dependencies: 316
93338 -- Name: COLUMN itemalias.itemalias_crmacct_id; Type: COMMENT; Schema: public; Owner: admin
93339 --
93340
93341 COMMENT ON COLUMN itemalias.itemalias_crmacct_id IS 'Associated crmacct for item alias.';
93342
93343
93344 SET search_path = api, pg_catalog;
93345
93346 --
93347 -- TOC entry 317 (class 1259 OID 146567750)
93348 -- Dependencies: 8519 6
93349 -- Name: itemalias; Type: VIEW; Schema: api; Owner: admin
93350 --
93351
93352 CREATE VIEW itemalias AS
93353     SELECT (item.item_number)::character varying AS item_number, itemalias.itemalias_number AS alias_number, itemalias.itemalias_usedescrip AS use_description, itemalias.itemalias_descrip1 AS description1, itemalias.itemalias_descrip2 AS description2, itemalias.itemalias_comments AS comments FROM public.item, public.itemalias WHERE (item.item_id = itemalias.itemalias_item_id);
93354
93355
93356 ALTER TABLE api.itemalias OWNER TO admin;
93357
93358 --
93359 -- TOC entry 9252 (class 0 OID 0)
93360 -- Dependencies: 317
93361 -- Name: VIEW itemalias; Type: COMMENT; Schema: api; Owner: admin
93362 --
93363
93364 COMMENT ON VIEW itemalias IS 'Item Alias';
93365
93366
93367 --
93368 -- TOC entry 318 (class 1259 OID 146567754)
93369 -- Dependencies: 8520 6
93370 -- Name: itemchar; Type: VIEW; Schema: api; Owner: admin
93371 --
93372
93373 CREATE VIEW itemchar AS
93374     SELECT (item.item_number)::character varying AS item_number, ("char".char_name)::character varying AS characteristic, charass.charass_value AS value, charass.charass_default AS is_default FROM public.item, public."char", public.charass WHERE ((('I'::text = charass.charass_target_type) AND (item.item_id = charass.charass_target_id)) AND (charass.charass_char_id = "char".char_id));
93375
93376
93377 ALTER TABLE api.itemchar OWNER TO admin;
93378
93379 --
93380 -- TOC entry 9254 (class 0 OID 0)
93381 -- Dependencies: 318
93382 -- Name: VIEW itemchar; Type: COMMENT; Schema: api; Owner: admin
93383 --
93384
93385 COMMENT ON VIEW itemchar IS 'Item Characteristic';
93386
93387
93388 --
93389 -- TOC entry 319 (class 1259 OID 146567758)
93390 -- Dependencies: 8521 6
93391 -- Name: itemcomment; Type: VIEW; Schema: api; Owner: admin
93392 --
93393
93394 CREATE VIEW itemcomment AS
93395     SELECT (item.item_number)::character varying AS item_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.item, public.cmnttype, public.comment WHERE (((comment.comment_source = 'I'::text) AND (comment.comment_source_id = item.item_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
93396
93397
93398 ALTER TABLE api.itemcomment OWNER TO admin;
93399
93400 --
93401 -- TOC entry 9256 (class 0 OID 0)
93402 -- Dependencies: 319
93403 -- Name: VIEW itemcomment; Type: COMMENT; Schema: api; Owner: admin
93404 --
93405
93406 COMMENT ON VIEW itemcomment IS 'Item Comments';
93407
93408
93409 SET search_path = public, pg_catalog;
93410
93411 --
93412 -- TOC entry 320 (class 1259 OID 146567762)
93413 -- Dependencies: 6182 6183 8
93414 -- Name: costelem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93415 --
93416
93417 CREATE TABLE costelem (
93418     costelem_id integer DEFAULT nextval(('costelem_costelem_id_seq'::text)::regclass) NOT NULL,
93419     costelem_type text NOT NULL,
93420     costelem_sys boolean,
93421     costelem_po boolean,
93422     costelem_active boolean,
93423     costelem_exp_accnt_id integer,
93424     costelem_cost_item_id integer,
93425     CONSTRAINT costelem_costelem_type_check CHECK ((costelem_type <> ''::text))
93426 );
93427
93428
93429 ALTER TABLE public.costelem OWNER TO admin;
93430
93431 --
93432 -- TOC entry 9258 (class 0 OID 0)
93433 -- Dependencies: 320
93434 -- Name: TABLE costelem; Type: COMMENT; Schema: public; Owner: admin
93435 --
93436
93437 COMMENT ON TABLE costelem IS 'Costing Element information';
93438
93439
93440 --
93441 -- TOC entry 321 (class 1259 OID 146567770)
93442 -- Dependencies: 6184 6185 6186 6187 6188 8
93443 -- Name: itemcost; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93444 --
93445
93446 CREATE TABLE itemcost (
93447     itemcost_id integer DEFAULT nextval(('itemcost_itemcost_id_seq'::text)::regclass) NOT NULL,
93448     itemcost_item_id integer NOT NULL,
93449     itemcost_costelem_id integer NOT NULL,
93450     itemcost_lowlevel boolean DEFAULT false NOT NULL,
93451     itemcost_stdcost numeric(16,6) DEFAULT 0 NOT NULL,
93452     itemcost_posted date,
93453     itemcost_actcost numeric(16,6) DEFAULT 0 NOT NULL,
93454     itemcost_updated date,
93455     itemcost_curr_id integer DEFAULT basecurrid() NOT NULL
93456 );
93457
93458
93459 ALTER TABLE public.itemcost OWNER TO admin;
93460
93461 --
93462 -- TOC entry 9260 (class 0 OID 0)
93463 -- Dependencies: 321
93464 -- Name: TABLE itemcost; Type: COMMENT; Schema: public; Owner: admin
93465 --
93466
93467 COMMENT ON TABLE itemcost IS 'Item Cost information';
93468
93469
93470 SET search_path = api, pg_catalog;
93471
93472 --
93473 -- TOC entry 322 (class 1259 OID 146567778)
93474 -- Dependencies: 8522 6
93475 -- Name: itemcost; Type: VIEW; Schema: api; Owner: admin
93476 --
93477
93478 CREATE VIEW itemcost AS
93479     SELECT (item.item_number)::character varying(100) AS item_number, (costelem.costelem_type)::character varying(100) AS costing_element, itemcost.itemcost_actcost AS actual_cost, curr_symbol.curr_abbr AS currency, false AS post_to_standard FROM (((public.itemcost LEFT JOIN public.item ON ((itemcost.itemcost_item_id = item.item_id))) LEFT JOIN public.costelem ON ((itemcost.itemcost_costelem_id = costelem.costelem_id))) LEFT JOIN public.curr_symbol ON ((itemcost.itemcost_curr_id = curr_symbol.curr_id))) ORDER BY (item.item_number)::character varying(100), (costelem.costelem_type)::character varying(100);
93480
93481
93482 ALTER TABLE api.itemcost OWNER TO admin;
93483
93484 --
93485 -- TOC entry 9262 (class 0 OID 0)
93486 -- Dependencies: 322
93487 -- Name: VIEW itemcost; Type: COMMENT; Schema: api; Owner: admin
93488 --
93489
93490 COMMENT ON VIEW itemcost IS 'Item Cost';
93491
93492
93493 --
93494 -- TOC entry 323 (class 1259 OID 146567783)
93495 -- Dependencies: 8523 6
93496 -- Name: itemfile; Type: VIEW; Schema: api; Owner: admin
93497 --
93498
93499 CREATE VIEW itemfile AS
93500     SELECT (item.item_number)::character varying AS item_number, url.url_title AS title, url.url_url AS url FROM public.item, public.url WHERE ((item.item_id = url.url_source_id) AND (url.url_source = 'I'::text));
93501
93502
93503 ALTER TABLE api.itemfile OWNER TO admin;
93504
93505 --
93506 -- TOC entry 9264 (class 0 OID 0)
93507 -- Dependencies: 323
93508 -- Name: VIEW itemfile; Type: COMMENT; Schema: api; Owner: admin
93509 --
93510
93511 COMMENT ON VIEW itemfile IS 'Item File';
93512
93513
93514 --
93515 -- TOC entry 324 (class 1259 OID 146567787)
93516 -- Dependencies: 8524 6
93517 -- Name: itemimage; Type: VIEW; Schema: api; Owner: admin
93518 --
93519
93520 CREATE VIEW itemimage AS
93521     SELECT (item.item_number)::character varying AS item_number, CASE WHEN (imageass.imageass_purpose = 'P'::bpchar) THEN 'Product Description'::text WHEN (imageass.imageass_purpose = 'I'::bpchar) THEN 'Inventory Description'::text WHEN (imageass.imageass_purpose = 'E'::bpchar) THEN 'Engineering Reference'::text WHEN (imageass.imageass_purpose = 'M'::bpchar) THEN 'Miscellaneous'::text ELSE 'Other'::text END AS purpose, image.image_name FROM public.item, public.imageass, public.image WHERE (((item.item_id = imageass.imageass_source_id) AND (imageass.imageass_source = 'I'::text)) AND (imageass.imageass_image_id = image.image_id));
93522
93523
93524 ALTER TABLE api.itemimage OWNER TO admin;
93525
93526 --
93527 -- TOC entry 9266 (class 0 OID 0)
93528 -- Dependencies: 324
93529 -- Name: VIEW itemimage; Type: COMMENT; Schema: api; Owner: admin
93530 --
93531
93532 COMMENT ON VIEW itemimage IS 'Item Image';
93533
93534
93535 SET search_path = public, pg_catalog;
93536
93537 --
93538 -- TOC entry 325 (class 1259 OID 146567792)
93539 -- Dependencies: 6189 6190 8
93540 -- Name: costcat; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93541 --
93542
93543 CREATE TABLE costcat (
93544     costcat_id integer DEFAULT nextval(('costcat_costcat_id_seq'::text)::regclass) NOT NULL,
93545     costcat_code text NOT NULL,
93546     costcat_descrip text,
93547     costcat_asset_accnt_id integer,
93548     costcat_liability_accnt_id integer,
93549     costcat_adjustment_accnt_id integer,
93550     costcat_matusage_accnt_id integer,
93551     costcat_purchprice_accnt_id integer,
93552     costcat_laboroverhead_accnt_id integer,
93553     costcat_scrap_accnt_id integer,
93554     costcat_invcost_accnt_id integer,
93555     costcat_wip_accnt_id integer,
93556     costcat_shipasset_accnt_id integer,
93557     costcat_mfgscrap_accnt_id integer,
93558     costcat_transform_accnt_id integer,
93559     costcat_freight_accnt_id integer,
93560     costcat_toliability_accnt_id integer,
93561     costcat_exp_accnt_id integer,
93562     CONSTRAINT costcat_costcat_code_check CHECK ((costcat_code <> ''::text))
93563 );
93564
93565
93566 ALTER TABLE public.costcat OWNER TO admin;
93567
93568 --
93569 -- TOC entry 9268 (class 0 OID 0)
93570 -- Dependencies: 325
93571 -- Name: TABLE costcat; Type: COMMENT; Schema: public; Owner: admin
93572 --
93573
93574 COMMENT ON TABLE costcat IS 'Cost Category information';
93575
93576
93577 --
93578 -- TOC entry 326 (class 1259 OID 146567800)
93579 -- Dependencies: 6191 6192 8
93580 -- Name: plancode; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93581 --
93582
93583 CREATE TABLE plancode (
93584     plancode_id integer DEFAULT nextval(('plancode_plancode_id_seq'::text)::regclass) NOT NULL,
93585     plancode_code text NOT NULL,
93586     plancode_name text,
93587     plancode_mpsexplosion character(1),
93588     plancode_consumefcst boolean,
93589     plancode_mrpexcp_resched boolean,
93590     plancode_mrpexcp_delete boolean,
93591     CONSTRAINT plancode_plancode_code_check CHECK ((plancode_code <> ''::text))
93592 );
93593
93594
93595 ALTER TABLE public.plancode OWNER TO admin;
93596
93597 --
93598 -- TOC entry 9270 (class 0 OID 0)
93599 -- Dependencies: 326
93600 -- Name: TABLE plancode; Type: COMMENT; Schema: public; Owner: admin
93601 --
93602
93603 COMMENT ON TABLE plancode IS 'Planner Code information';
93604
93605
93606 SET search_path = api, pg_catalog;
93607
93608 --
93609 -- TOC entry 327 (class 1259 OID 146567808)
93610 -- Dependencies: 8525 6
93611 -- Name: itemsite; Type: VIEW; Schema: api; Owner: admin
93612 --
93613
93614 CREATE VIEW itemsite AS
93615     SELECT (item.item_number)::character varying AS item_number, (whsinfo.warehous_code)::character varying AS site, itemsite.itemsite_active AS active, itemsite.itemsite_wosupply AS wo_supplied_at_site, itemsite.itemsite_createwo AS create_wos, itemsite.itemsite_posupply AS po_supplied_at_site, itemsite.itemsite_createpr AS create_prs, itemsite.itemsite_createsopr AS create_soprs, itemsite.itemsite_createsopo AS create_sopos, itemsite.itemsite_dropship AS dropship, itemsite.itemsite_sold AS sold_from_site, itemsite.itemsite_soldranking AS ranking, CASE WHEN (itemsite.itemsite_costmethod = 'N'::bpchar) THEN 'None'::text WHEN (itemsite.itemsite_costmethod = 'A'::bpchar) THEN 'Average'::text WHEN (itemsite.itemsite_costmethod = 'S'::bpchar) THEN 'Standard'::text WHEN (itemsite.itemsite_costmethod = 'J'::bpchar) THEN 'Job'::text ELSE NULL::text END AS cost_method, CASE WHEN (itemsite.itemsite_controlmethod = 'N'::bpchar) THEN 'None'::text WHEN (itemsite.itemsite_controlmethod = 'R'::bpchar) THEN 'Regular'::text WHEN (itemsite.itemsite_controlmethod = 'S'::bpchar) THEN 'Serial #'::text WHEN (itemsite.itemsite_controlmethod = 'L'::bpchar) THEN 'Lot #'::text ELSE NULL::text END AS control_method, plancode.plancode_code AS planner_code, costcat.costcat_code AS cost_category, itemsite.itemsite_stocked AS stocked, itemsite.itemsite_abcclass AS abc_class, itemsite.itemsite_autoabcclass AS allow_automatic_updates, itemsite.itemsite_cyclecountfreq AS cycl_cnt_freq, itemsite.itemsite_eventfence AS event_fence, itemsite.itemsite_loccntrl AS multiple_location_control, public.formatlocationname(itemsite.itemsite_location_id) AS location, public.formatlocationname(itemsite.itemsite_recvlocation_id) AS receive_location, public.formatlocationname(itemsite.itemsite_issuelocation_id) AS issue_location, itemsite.itemsite_location_dist AS auto_distr_location, itemsite.itemsite_recvlocation_dist AS auto_distr_receive_location, itemsite.itemsite_issuelocation_dist AS auto_distr_issue_location, itemsite.itemsite_location AS user_defined_location, itemsite.itemsite_location_comments AS location_comment, itemsite.itemsite_disallowblankwip AS disallow_blank_wip_locations, itemsite.itemsite_useparams AS enforce_order_parameters, itemsite.itemsite_reorderlevel AS reorder_level, itemsite.itemsite_ordertoqty AS order_up_to, itemsite.itemsite_minordqty AS minimum_order, itemsite.itemsite_maxordqty AS maximum_order, itemsite.itemsite_multordqty AS order_multiple, itemsite.itemsite_useparamsmanual AS enforce_on_manual_orders, CASE WHEN (itemsite.itemsite_planning_type = 'N'::bpchar) THEN 'None'::text WHEN (itemsite.itemsite_planning_type = 'M'::bpchar) THEN 'MRP'::text WHEN (itemsite.itemsite_planning_type = 'S'::bpchar) THEN 'MPS'::text ELSE NULL::text END AS planning_system, itemsite.itemsite_ordergroup AS group_mps_mrp_orders, itemsite.itemsite_ordergroup_first AS first_group, itemsite.itemsite_mps_timefence AS mps_time_fence, itemsite.itemsite_leadtime AS lead_time, itemsite.itemsite_safetystock AS safety_stock, COALESCE((SELECT whsinfo.warehous_code FROM (public.itemsite supplysite JOIN public.whsinfo ON ((whsinfo.warehous_id = supplysite.itemsite_warehous_id))) WHERE (supplysite.itemsite_id = itemsite.itemsite_supply_itemsite_id)), 'None'::text) AS supplied_from_site, itemsite.itemsite_notes AS notes, itemsite.itemsite_perishable AS perishable, itemsite.itemsite_warrpurc AS require_warranty, itemsite.itemsite_autoreg AS auto_register FROM ((((public.itemsite JOIN public.item ON ((item.item_id = itemsite.itemsite_item_id))) JOIN public.plancode ON ((plancode.plancode_id = itemsite.itemsite_plancode_id))) JOIN public.costcat ON ((costcat.costcat_id = itemsite.itemsite_costcat_id))) JOIN public.whsinfo ON ((whsinfo.warehous_id = itemsite.itemsite_warehous_id)));
93616
93617
93618 ALTER TABLE api.itemsite OWNER TO admin;
93619
93620 --
93621 -- TOC entry 9272 (class 0 OID 0)
93622 -- Dependencies: 327
93623 -- Name: VIEW itemsite; Type: COMMENT; Schema: api; Owner: admin
93624 --
93625
93626 COMMENT ON VIEW itemsite IS 'Item Site';
93627
93628
93629 --
93630 -- TOC entry 328 (class 1259 OID 146567813)
93631 -- Dependencies: 8526 6
93632 -- Name: itemsitecomment; Type: VIEW; Schema: api; Owner: admin
93633 --
93634
93635 CREATE VIEW itemsitecomment AS
93636     SELECT (item.item_number)::character varying AS item_number, (whsinfo.warehous_code)::character varying AS site, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.itemsite, public.item, public.whsinfo, public.cmnttype, public.comment WHERE ((itemsite.itemsite_item_id = item.item_id) AND ((((itemsite.itemsite_warehous_id = whsinfo.warehous_id) AND (comment.comment_source = 'IS'::text)) AND (comment.comment_source_id = itemsite.itemsite_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id)));
93637
93638
93639 ALTER TABLE api.itemsitecomment OWNER TO admin;
93640
93641 --
93642 -- TOC entry 9274 (class 0 OID 0)
93643 -- Dependencies: 328
93644 -- Name: VIEW itemsitecomment; Type: COMMENT; Schema: api; Owner: admin
93645 --
93646
93647 COMMENT ON VIEW itemsitecomment IS 'Item Site Comments';
93648
93649
93650 SET search_path = public, pg_catalog;
93651
93652 --
93653 -- TOC entry 329 (class 1259 OID 146567818)
93654 -- Dependencies: 8
93655 -- Name: contrct; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93656 --
93657
93658 CREATE TABLE contrct (
93659     contrct_id integer NOT NULL,
93660     contrct_number text NOT NULL,
93661     contrct_vend_id integer NOT NULL,
93662     contrct_descrip text,
93663     contrct_effective date NOT NULL,
93664     contrct_expires date NOT NULL,
93665     contrct_note text
93666 );
93667
93668
93669 ALTER TABLE public.contrct OWNER TO admin;
93670
93671 --
93672 -- TOC entry 9276 (class 0 OID 0)
93673 -- Dependencies: 329
93674 -- Name: TABLE contrct; Type: COMMENT; Schema: public; Owner: admin
93675 --
93676
93677 COMMENT ON TABLE contrct IS 'Grouping of Item Sources for a Vendor with common effective and expiration dates.';
93678
93679
93680 --
93681 -- TOC entry 9277 (class 0 OID 0)
93682 -- Dependencies: 329
93683 -- Name: COLUMN contrct.contrct_id; Type: COMMENT; Schema: public; Owner: admin
93684 --
93685
93686 COMMENT ON COLUMN contrct.contrct_id IS 'Sequence identifier for contract.';
93687
93688
93689 --
93690 -- TOC entry 9278 (class 0 OID 0)
93691 -- Dependencies: 329
93692 -- Name: COLUMN contrct.contrct_number; Type: COMMENT; Schema: public; Owner: admin
93693 --
93694
93695 COMMENT ON COLUMN contrct.contrct_number IS 'User defined identifier for contract.';
93696
93697
93698 --
93699 -- TOC entry 9279 (class 0 OID 0)
93700 -- Dependencies: 329
93701 -- Name: COLUMN contrct.contrct_vend_id; Type: COMMENT; Schema: public; Owner: admin
93702 --
93703
93704 COMMENT ON COLUMN contrct.contrct_vend_id IS 'Vendor associated with contract.';
93705
93706
93707 --
93708 -- TOC entry 9280 (class 0 OID 0)
93709 -- Dependencies: 329
93710 -- Name: COLUMN contrct.contrct_descrip; Type: COMMENT; Schema: public; Owner: admin
93711 --
93712
93713 COMMENT ON COLUMN contrct.contrct_descrip IS 'Description for contract.';
93714
93715
93716 --
93717 -- TOC entry 9281 (class 0 OID 0)
93718 -- Dependencies: 329
93719 -- Name: COLUMN contrct.contrct_effective; Type: COMMENT; Schema: public; Owner: admin
93720 --
93721
93722 COMMENT ON COLUMN contrct.contrct_effective IS 'Effective date for contract.  Constraint for overlap.';
93723
93724
93725 --
93726 -- TOC entry 9282 (class 0 OID 0)
93727 -- Dependencies: 329
93728 -- Name: COLUMN contrct.contrct_expires; Type: COMMENT; Schema: public; Owner: admin
93729 --
93730
93731 COMMENT ON COLUMN contrct.contrct_expires IS 'Expiration date for contract.  Constraint for overlap.';
93732
93733
93734 --
93735 -- TOC entry 9283 (class 0 OID 0)
93736 -- Dependencies: 329
93737 -- Name: COLUMN contrct.contrct_note; Type: COMMENT; Schema: public; Owner: admin
93738 --
93739
93740 COMMENT ON COLUMN contrct.contrct_note IS 'Notes for contract.';
93741
93742
93743 --
93744 -- TOC entry 330 (class 1259 OID 146567824)
93745 -- Dependencies: 6194 6195 6196 6197 6198 6199 6200 8
93746 -- Name: itemsrc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93747 --
93748
93749 CREATE TABLE itemsrc (
93750     itemsrc_id integer DEFAULT nextval(('"itemsrc_itemsrc_id_seq"'::text)::regclass) NOT NULL,
93751     itemsrc_item_id integer NOT NULL,
93752     itemsrc_vend_id integer NOT NULL,
93753     itemsrc_vend_item_number text,
93754     itemsrc_vend_item_descrip text,
93755     itemsrc_comments text,
93756     itemsrc_vend_uom text NOT NULL,
93757     itemsrc_invvendoruomratio numeric(20,10) NOT NULL,
93758     itemsrc_minordqty numeric(18,6) NOT NULL,
93759     itemsrc_multordqty numeric(18,6) NOT NULL,
93760     itemsrc_leadtime integer NOT NULL,
93761     itemsrc_ranking integer NOT NULL,
93762     itemsrc_active boolean NOT NULL,
93763     itemsrc_manuf_name text DEFAULT ''::text NOT NULL,
93764     itemsrc_manuf_item_number text DEFAULT ''::text NOT NULL,
93765     itemsrc_manuf_item_descrip text,
93766     itemsrc_default boolean,
93767     itemsrc_upccode text,
93768     itemsrc_effective date DEFAULT startoftime() NOT NULL,
93769     itemsrc_expires date DEFAULT endoftime() NOT NULL,
93770     itemsrc_contrct_id integer,
93771     itemsrc_contrct_max numeric(18,6) DEFAULT 0.0 NOT NULL,
93772     itemsrc_contrct_min numeric(18,6) DEFAULT 0.0 NOT NULL
93773 );
93774
93775
93776 ALTER TABLE public.itemsrc OWNER TO admin;
93777
93778 --
93779 -- TOC entry 9285 (class 0 OID 0)
93780 -- Dependencies: 330
93781 -- Name: TABLE itemsrc; Type: COMMENT; Schema: public; Owner: admin
93782 --
93783
93784 COMMENT ON TABLE itemsrc IS 'Item Source information';
93785
93786
93787 --
93788 -- TOC entry 9286 (class 0 OID 0)
93789 -- Dependencies: 330
93790 -- Name: COLUMN itemsrc.itemsrc_effective; Type: COMMENT; Schema: public; Owner: admin
93791 --
93792
93793 COMMENT ON COLUMN itemsrc.itemsrc_effective IS 'Effective date for item source.  Constraint for overlap.';
93794
93795
93796 --
93797 -- TOC entry 9287 (class 0 OID 0)
93798 -- Dependencies: 330
93799 -- Name: COLUMN itemsrc.itemsrc_expires; Type: COMMENT; Schema: public; Owner: admin
93800 --
93801
93802 COMMENT ON COLUMN itemsrc.itemsrc_expires IS 'Expiration date for item source.  Constraint for overlap.';
93803
93804
93805 --
93806 -- TOC entry 9288 (class 0 OID 0)
93807 -- Dependencies: 330
93808 -- Name: COLUMN itemsrc.itemsrc_contrct_id; Type: COMMENT; Schema: public; Owner: admin
93809 --
93810
93811 COMMENT ON COLUMN itemsrc.itemsrc_contrct_id IS 'Associated contract for item source.  Inherits effective, expiration dates.';
93812
93813
93814 SET search_path = api, pg_catalog;
93815
93816 --
93817 -- TOC entry 331 (class 1259 OID 146567837)
93818 -- Dependencies: 8527 6
93819 -- Name: itemsource; Type: VIEW; Schema: api; Owner: admin
93820 --
93821
93822 CREATE VIEW itemsource AS
93823     SELECT (item.item_number)::character varying AS item_number, (vendinfo.vend_number)::character varying AS vendor, itemsrc.itemsrc_vend_item_number AS vendor_item_number, itemsrc.itemsrc_active AS active, itemsrc.itemsrc_default, itemsrc.itemsrc_vend_uom AS vendor_uom, itemsrc.itemsrc_invvendoruomratio AS inventory_vendor_uom_ratio, itemsrc.itemsrc_minordqty AS minimum_order, itemsrc.itemsrc_multordqty AS order_multiple, itemsrc.itemsrc_ranking AS vendor_ranking, itemsrc.itemsrc_leadtime AS lead_time, itemsrc.itemsrc_comments AS notes, itemsrc.itemsrc_vend_item_descrip AS vendor_description, itemsrc.itemsrc_manuf_name AS manufacturer_name, itemsrc.itemsrc_manuf_item_number AS manufacturer_item_number, itemsrc.itemsrc_manuf_item_descrip AS manufacturer_description, itemsrc.itemsrc_upccode AS bar_code, contrct.contrct_number AS contract_number, itemsrc.itemsrc_effective AS effective_date, itemsrc.itemsrc_expires AS expires_date FROM (((public.itemsrc LEFT JOIN public.item ON ((itemsrc.itemsrc_item_id = item.item_id))) LEFT JOIN public.vendinfo ON ((itemsrc.itemsrc_vend_id = vendinfo.vend_id))) LEFT JOIN public.contrct ON ((itemsrc.itemsrc_contrct_id = contrct.contrct_id))) ORDER BY (item.item_number)::character varying(100), (vendinfo.vend_number)::character varying(100);
93824
93825
93826 ALTER TABLE api.itemsource OWNER TO admin;
93827
93828 --
93829 -- TOC entry 9290 (class 0 OID 0)
93830 -- Dependencies: 331
93831 -- Name: VIEW itemsource; Type: COMMENT; Schema: api; Owner: admin
93832 --
93833
93834 COMMENT ON VIEW itemsource IS 'Item Source';
93835
93836
93837 SET search_path = public, pg_catalog;
93838
93839 --
93840 -- TOC entry 332 (class 1259 OID 146567842)
93841 -- Dependencies: 6201 6202 6203 6204 6205 8
93842 -- Name: itemsrcp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93843 --
93844
93845 CREATE TABLE itemsrcp (
93846     itemsrcp_id integer DEFAULT nextval(('itemsrcp_itemsrcp_id_seq'::text)::regclass) NOT NULL,
93847     itemsrcp_itemsrc_id integer NOT NULL,
93848     itemsrcp_qtybreak numeric(18,6) NOT NULL,
93849     itemsrcp_price numeric(16,6),
93850     itemsrcp_updated date,
93851     itemsrcp_curr_id integer DEFAULT basecurrid() NOT NULL,
93852     itemsrcp_dropship boolean DEFAULT false NOT NULL,
93853     itemsrcp_warehous_id integer DEFAULT (-1) NOT NULL,
93854     itemsrcp_type character(1) NOT NULL,
93855     itemsrcp_discntprcnt numeric(16,6),
93856     itemsrcp_fixedamtdiscount numeric(16,6),
93857     CONSTRAINT valid_itemsrcp_type CHECK ((itemsrcp_type = ANY (ARRAY['N'::bpchar, 'D'::bpchar])))
93858 );
93859
93860
93861 ALTER TABLE public.itemsrcp OWNER TO admin;
93862
93863 --
93864 -- TOC entry 9292 (class 0 OID 0)
93865 -- Dependencies: 332
93866 -- Name: TABLE itemsrcp; Type: COMMENT; Schema: public; Owner: admin
93867 --
93868
93869 COMMENT ON TABLE itemsrcp IS 'Item Source Price information';
93870
93871
93872 --
93873 -- TOC entry 9293 (class 0 OID 0)
93874 -- Dependencies: 332
93875 -- Name: COLUMN itemsrcp.itemsrcp_dropship; Type: COMMENT; Schema: public; Owner: admin
93876 --
93877
93878 COMMENT ON COLUMN itemsrcp.itemsrcp_dropship IS 'Used to determine if item source price applies only to drop ship purchase orders.';
93879
93880
93881 --
93882 -- TOC entry 9294 (class 0 OID 0)
93883 -- Dependencies: 332
93884 -- Name: COLUMN itemsrcp.itemsrcp_warehous_id; Type: COMMENT; Schema: public; Owner: admin
93885 --
93886
93887 COMMENT ON COLUMN itemsrcp.itemsrcp_warehous_id IS 'Used to determine if item source price applies only to specific site on purchase orders.';
93888
93889
93890 --
93891 -- TOC entry 9295 (class 0 OID 0)
93892 -- Dependencies: 332
93893 -- Name: COLUMN itemsrcp.itemsrcp_type; Type: COMMENT; Schema: public; Owner: admin
93894 --
93895
93896 COMMENT ON COLUMN itemsrcp.itemsrcp_type IS 'Pricing type for item source price.  Valid values are N-nominal and D-discount.';
93897
93898
93899 --
93900 -- TOC entry 9296 (class 0 OID 0)
93901 -- Dependencies: 332
93902 -- Name: COLUMN itemsrcp.itemsrcp_discntprcnt; Type: COMMENT; Schema: public; Owner: admin
93903 --
93904
93905 COMMENT ON COLUMN itemsrcp.itemsrcp_discntprcnt IS 'Discount percent for item source price.';
93906
93907
93908 --
93909 -- TOC entry 9297 (class 0 OID 0)
93910 -- Dependencies: 332
93911 -- Name: COLUMN itemsrcp.itemsrcp_fixedamtdiscount; Type: COMMENT; Schema: public; Owner: admin
93912 --
93913
93914 COMMENT ON COLUMN itemsrcp.itemsrcp_fixedamtdiscount IS 'Fixed amount discount for item source price.';
93915
93916
93917 SET search_path = api, pg_catalog;
93918
93919 --
93920 -- TOC entry 333 (class 1259 OID 146567850)
93921 -- Dependencies: 8528 6
93922 -- Name: itemsourceprice; Type: VIEW; Schema: api; Owner: admin
93923 --
93924
93925 CREATE VIEW itemsourceprice AS
93926     SELECT (item.item_number)::character varying AS item_number, (vendinfo.vend_number)::character varying AS vendor, itemsrcp.itemsrcp_qtybreak AS qty_break, CASE WHEN (itemsrcp.itemsrcp_type = 'N'::bpchar) THEN 'Nominal'::text ELSE 'Discount'::text END AS pricing_type, CASE WHEN (itemsrcp.itemsrcp_warehous_id = (-1)) THEN 'All'::text ELSE whsinfo.warehous_code END AS pricing_site, itemsrcp.itemsrcp_dropship AS dropship_only, itemsrcp.itemsrcp_price AS price_per_unit, curr_symbol.curr_abbr AS currency, (itemsrcp.itemsrcp_discntprcnt * 100.0) AS discount_percent, itemsrcp.itemsrcp_fixedamtdiscount AS discount_fixed_amount FROM (((((public.itemsrcp LEFT JOIN public.itemsrc ON ((itemsrc.itemsrc_id = itemsrcp.itemsrcp_itemsrc_id))) LEFT JOIN public.item ON ((itemsrc.itemsrc_item_id = item.item_id))) LEFT JOIN public.vendinfo ON ((itemsrc.itemsrc_vend_id = vendinfo.vend_id))) LEFT JOIN public.curr_symbol ON ((itemsrcp.itemsrcp_curr_id = curr_symbol.curr_id))) LEFT JOIN public.whsinfo ON ((itemsrcp.itemsrcp_warehous_id = whsinfo.warehous_id))) ORDER BY (item.item_number)::character varying(100), (vendinfo.vend_number)::character varying(100);
93927
93928
93929 ALTER TABLE api.itemsourceprice OWNER TO admin;
93930
93931 --
93932 -- TOC entry 9299 (class 0 OID 0)
93933 -- Dependencies: 333
93934 -- Name: VIEW itemsourceprice; Type: COMMENT; Schema: api; Owner: admin
93935 --
93936
93937 COMMENT ON VIEW itemsourceprice IS 'Item Source Price';
93938
93939
93940 SET search_path = public, pg_catalog;
93941
93942 --
93943 -- TOC entry 334 (class 1259 OID 146567855)
93944 -- Dependencies: 6206 8
93945 -- Name: itemsub; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93946 --
93947
93948 CREATE TABLE itemsub (
93949     itemsub_id integer DEFAULT nextval(('itemsub_itemsub_id_seq'::text)::regclass) NOT NULL,
93950     itemsub_parent_item_id integer NOT NULL,
93951     itemsub_sub_item_id integer NOT NULL,
93952     itemsub_uomratio numeric(20,10) NOT NULL,
93953     itemsub_rank integer NOT NULL
93954 );
93955
93956
93957 ALTER TABLE public.itemsub OWNER TO admin;
93958
93959 --
93960 -- TOC entry 9301 (class 0 OID 0)
93961 -- Dependencies: 334
93962 -- Name: TABLE itemsub; Type: COMMENT; Schema: public; Owner: admin
93963 --
93964
93965 COMMENT ON TABLE itemsub IS 'Item Substitutes information';
93966
93967
93968 SET search_path = api, pg_catalog;
93969
93970 --
93971 -- TOC entry 335 (class 1259 OID 146567859)
93972 -- Dependencies: 8529 6
93973 -- Name: itemsubstitute; Type: VIEW; Schema: api; Owner: admin
93974 --
93975
93976 CREATE VIEW itemsubstitute AS
93977     SELECT (p.item_number)::character varying AS root_item_number, (s.item_number)::character varying AS substitute_item_number, itemsub.itemsub_uomratio AS sub_parent_uom_ratio, itemsub.itemsub_rank AS ranking FROM public.item p, public.item s, public.itemsub WHERE ((p.item_id = itemsub.itemsub_parent_item_id) AND (s.item_id = itemsub.itemsub_sub_item_id));
93978
93979
93980 ALTER TABLE api.itemsubstitute OWNER TO admin;
93981
93982 --
93983 -- TOC entry 9303 (class 0 OID 0)
93984 -- Dependencies: 335
93985 -- Name: VIEW itemsubstitute; Type: COMMENT; Schema: api; Owner: admin
93986 --
93987
93988 COMMENT ON VIEW itemsubstitute IS 'Item Substitute';
93989
93990
93991 SET search_path = public, pg_catalog;
93992
93993 --
93994 -- TOC entry 336 (class 1259 OID 146567863)
93995 -- Dependencies: 8
93996 -- Name: itemtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
93997 --
93998
93999 CREATE TABLE itemtax (
94000     itemtax_id integer NOT NULL,
94001     itemtax_item_id integer NOT NULL,
94002     itemtax_taxtype_id integer NOT NULL,
94003     itemtax_taxzone_id integer
94004 );
94005
94006
94007 ALTER TABLE public.itemtax OWNER TO admin;
94008
94009 --
94010 -- TOC entry 9305 (class 0 OID 0)
94011 -- Dependencies: 336
94012 -- Name: TABLE itemtax; Type: COMMENT; Schema: public; Owner: admin
94013 --
94014
94015 COMMENT ON TABLE itemtax IS 'This table associates tax types in a specified tax authority for the given item.';
94016
94017
94018 SET search_path = api, pg_catalog;
94019
94020 --
94021 -- TOC entry 337 (class 1259 OID 146567866)
94022 -- Dependencies: 8530 6
94023 -- Name: itemtaxtype; Type: VIEW; Schema: api; Owner: admin
94024 --
94025
94026 CREATE VIEW itemtaxtype AS
94027     SELECT (item.item_number)::character varying AS item_number, CASE WHEN (taxzone.taxzone_id IS NULL) THEN 'Any'::character varying ELSE (taxzone.taxzone_code)::character varying END AS tax_zone, taxtype.taxtype_name AS tax_type FROM public.item, (public.itemtax LEFT JOIN public.taxzone ON ((itemtax.itemtax_taxzone_id = taxzone.taxzone_id))), public.taxtype WHERE ((item.item_id = itemtax.itemtax_item_id) AND (itemtax.itemtax_taxtype_id = taxtype.taxtype_id));
94028
94029
94030 ALTER TABLE api.itemtaxtype OWNER TO admin;
94031
94032 --
94033 -- TOC entry 9307 (class 0 OID 0)
94034 -- Dependencies: 337
94035 -- Name: VIEW itemtaxtype; Type: COMMENT; Schema: api; Owner: admin
94036 --
94037
94038 COMMENT ON VIEW itemtaxtype IS 'Item Tax Type';
94039
94040
94041 SET search_path = public, pg_catalog;
94042
94043 --
94044 -- TOC entry 338 (class 1259 OID 146567870)
94045 -- Dependencies: 6209 6210 8
94046 -- Name: itemuomconv; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94047 --
94048
94049 CREATE TABLE itemuomconv (
94050     itemuomconv_id integer NOT NULL,
94051     itemuomconv_item_id integer NOT NULL,
94052     itemuomconv_from_uom_id integer NOT NULL,
94053     itemuomconv_from_value numeric(20,10) NOT NULL,
94054     itemuomconv_to_uom_id integer NOT NULL,
94055     itemuomconv_to_value numeric(20,10) NOT NULL,
94056     itemuomconv_fractional boolean DEFAULT false NOT NULL,
94057     CONSTRAINT itemuomconv_uom CHECK ((itemuomconv_from_uom_id <> itemuomconv_to_uom_id))
94058 );
94059
94060
94061 ALTER TABLE public.itemuomconv OWNER TO admin;
94062
94063 --
94064 -- TOC entry 9309 (class 0 OID 0)
94065 -- Dependencies: 338
94066 -- Name: TABLE itemuomconv; Type: COMMENT; Schema: public; Owner: admin
94067 --
94068
94069 COMMENT ON TABLE itemuomconv IS 'UOM conversion information. From Unit to To Unit with a value per.';
94070
94071
94072 SET search_path = api, pg_catalog;
94073
94074 --
94075 -- TOC entry 339 (class 1259 OID 146567875)
94076 -- Dependencies: 8531 6
94077 -- Name: itemuomconversion; Type: VIEW; Schema: api; Owner: admin
94078 --
94079
94080 CREATE VIEW itemuomconversion AS
94081     SELECT (item.item_number)::character varying AS item_number, (f.uom_name)::character varying AS uom, itemuomconv.itemuomconv_from_value AS uom_value, p.uom_name AS per_uom, itemuomconv.itemuomconv_to_value AS per_uom_value, itemuomconv.itemuomconv_fractional AS fractional, public.fetchitemuomconvtypes(itemuomconv.itemuomconv_id) AS selected_types FROM public.item, public.itemuomconv, public.uom f, public.uom p WHERE (((item.item_id = itemuomconv.itemuomconv_item_id) AND (itemuomconv.itemuomconv_from_uom_id = f.uom_id)) AND (itemuomconv.itemuomconv_to_uom_id = p.uom_id));
94082
94083
94084 ALTER TABLE api.itemuomconversion OWNER TO admin;
94085
94086 --
94087 -- TOC entry 9311 (class 0 OID 0)
94088 -- Dependencies: 339
94089 -- Name: VIEW itemuomconversion; Type: COMMENT; Schema: api; Owner: admin
94090 --
94091
94092 COMMENT ON VIEW itemuomconversion IS 'Item Unit of Measure Conversion';
94093
94094
94095 SET search_path = public, pg_catalog;
94096
94097 --
94098 -- TOC entry 340 (class 1259 OID 146567879)
94099 -- Dependencies: 6211 6212 6213 6214 8
94100 -- Name: gltrans; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94101 --
94102
94103 CREATE TABLE gltrans (
94104     gltrans_id integer DEFAULT nextval(('"gltrans_gltrans_id_seq"'::text)::regclass) NOT NULL,
94105     gltrans_exported boolean,
94106     gltrans_created timestamp with time zone,
94107     gltrans_date date NOT NULL,
94108     gltrans_sequence integer,
94109     gltrans_accnt_id integer NOT NULL,
94110     gltrans_source text,
94111     gltrans_docnumber text,
94112     gltrans_misc_id integer,
94113     gltrans_amount numeric(20,2) NOT NULL,
94114     gltrans_notes text,
94115     gltrans_journalnumber integer,
94116     gltrans_posted boolean NOT NULL,
94117     gltrans_doctype text,
94118     gltrans_rec boolean DEFAULT false NOT NULL,
94119     gltrans_username text DEFAULT geteffectivextuser() NOT NULL,
94120     gltrans_deleted boolean DEFAULT false
94121 );
94122
94123
94124 ALTER TABLE public.gltrans OWNER TO admin;
94125
94126 --
94127 -- TOC entry 9313 (class 0 OID 0)
94128 -- Dependencies: 340
94129 -- Name: TABLE gltrans; Type: COMMENT; Schema: public; Owner: admin
94130 --
94131
94132 COMMENT ON TABLE gltrans IS 'General Ledger (G/L) transaction information';
94133
94134
94135 SET search_path = api, pg_catalog;
94136
94137 --
94138 -- TOC entry 341 (class 1259 OID 146567889)
94139 -- Dependencies: 8532 6
94140 -- Name: journalentry; Type: VIEW; Schema: api; Owner: admin
94141 --
94142
94143 CREATE VIEW journalentry AS
94144     SELECT curr_symbol.curr_abbr AS currency, c.gltrans_amount AS amount, c.gltrans_date AS dist_date, c.gltrans_docnumber AS doc_number, public.formatglaccount(da.accnt_id) AS debit, public.formatglaccount(ca.accnt_id) AS credit, c.gltrans_notes AS notes FROM public.gltrans d, public.gltrans c, public.accnt da, public.accnt ca, public.curr_symbol WHERE ((((((((d.gltrans_sequence = c.gltrans_sequence) AND (d.gltrans_accnt_id = da.accnt_id)) AND (c.gltrans_accnt_id = ca.accnt_id)) AND (d.gltrans_amount < (0)::numeric)) AND (c.gltrans_amount > (0)::numeric)) AND (d.gltrans_doctype = 'JE'::text)) AND (c.gltrans_doctype = 'JE'::text)) AND (curr_symbol.curr_id = public.basecurrid())) ORDER BY d.gltrans_date DESC;
94145
94146
94147 ALTER TABLE api.journalentry OWNER TO admin;
94148
94149 --
94150 -- TOC entry 9315 (class 0 OID 0)
94151 -- Dependencies: 341
94152 -- Name: VIEW journalentry; Type: COMMENT; Schema: api; Owner: admin
94153 --
94154
94155 COMMENT ON VIEW journalentry IS 'Journal Entry';
94156
94157
94158 SET search_path = public, pg_catalog;
94159
94160 --
94161 -- TOC entry 342 (class 1259 OID 146567894)
94162 -- Dependencies: 6215 8
94163 -- Name: location; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94164 --
94165
94166 CREATE TABLE location (
94167     location_id integer DEFAULT nextval(('location_location_id_seq'::text)::regclass) NOT NULL,
94168     location_warehous_id integer NOT NULL,
94169     location_name text NOT NULL,
94170     location_descrip text,
94171     location_restrict boolean,
94172     location_netable boolean,
94173     location_whsezone_id integer,
94174     location_aisle text,
94175     location_rack text,
94176     location_bin text
94177 );
94178
94179
94180 ALTER TABLE public.location OWNER TO admin;
94181
94182 --
94183 -- TOC entry 9317 (class 0 OID 0)
94184 -- Dependencies: 342
94185 -- Name: TABLE location; Type: COMMENT; Schema: public; Owner: admin
94186 --
94187
94188 COMMENT ON TABLE location IS 'Warehouse Location information';
94189
94190
94191 --
94192 -- TOC entry 343 (class 1259 OID 146567901)
94193 -- Dependencies: 8
94194 -- Name: whsezone; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94195 --
94196
94197 CREATE TABLE whsezone (
94198     whsezone_id integer NOT NULL,
94199     whsezone_warehous_id integer NOT NULL,
94200     whsezone_name text NOT NULL,
94201     whsezone_descrip text
94202 );
94203
94204
94205 ALTER TABLE public.whsezone OWNER TO admin;
94206
94207 --
94208 -- TOC entry 9319 (class 0 OID 0)
94209 -- Dependencies: 343
94210 -- Name: TABLE whsezone; Type: COMMENT; Schema: public; Owner: admin
94211 --
94212
94213 COMMENT ON TABLE whsezone IS 'Warehouse Zone information';
94214
94215
94216 SET search_path = api, pg_catalog;
94217
94218 --
94219 -- TOC entry 344 (class 1259 OID 146567907)
94220 -- Dependencies: 8533 6
94221 -- Name: location; Type: VIEW; Schema: api; Owner: admin
94222 --
94223
94224 CREATE VIEW location AS
94225     SELECT (whsinfo.warehous_code)::character varying AS site, (location.location_aisle)::character varying AS aisle, (location.location_rack)::character varying AS rack, (location.location_bin)::character varying AS bin, (location.location_name)::character varying AS location, whsezone.whsezone_name AS zone, location.location_netable AS netable, location.location_restrict AS restricted, location.location_descrip AS description FROM ((public.location LEFT JOIN public.whsinfo ON ((whsinfo.warehous_id = location.location_warehous_id))) LEFT JOIN public.whsezone ON ((whsezone.whsezone_id = location.location_whsezone_id)));
94226
94227
94228 ALTER TABLE api.location OWNER TO admin;
94229
94230 --
94231 -- TOC entry 9321 (class 0 OID 0)
94232 -- Dependencies: 344
94233 -- Name: VIEW location; Type: COMMENT; Schema: api; Owner: admin
94234 --
94235
94236 COMMENT ON VIEW location IS 'Location';
94237
94238
94239 --
94240 -- TOC entry 345 (class 1259 OID 146567912)
94241 -- Dependencies: 8534 6
94242 -- Name: misccounttag; Type: VIEW; Schema: api; Owner: admin
94243 --
94244
94245 CREATE VIEW misccounttag AS
94246     SELECT 'This view is for inserts only'::text AS site, 'This view is for inserts only'::text AS item_number, (0)::numeric AS quantity, 'This view is for inserts only'::text AS comment;
94247
94248
94249 ALTER TABLE api.misccounttag OWNER TO admin;
94250
94251 --
94252 -- TOC entry 9323 (class 0 OID 0)
94253 -- Dependencies: 345
94254 -- Name: VIEW misccounttag; Type: COMMENT; Schema: api; Owner: admin
94255 --
94256
94257 COMMENT ON VIEW misccounttag IS 'Miscellaneous Count Tag';
94258
94259
94260 --
94261 -- TOC entry 346 (class 1259 OID 146567916)
94262 -- Dependencies: 8535 6
94263 -- Name: pricingschedule; Type: VIEW; Schema: api; Owner: admin
94264 --
94265
94266 CREATE VIEW pricingschedule AS
94267     SELECT (ipshead.ipshead_name)::character varying AS name, ipshead.ipshead_descrip AS description, public.formatdate(ipshead.ipshead_effective, 'Always'::text) AS effective, public.formatdate(ipshead.ipshead_expires, 'Never'::text) AS expires, curr_symbol.curr_abbr AS currency FROM public.ipshead, public.curr_symbol WHERE (curr_symbol.curr_id = ipshead.ipshead_curr_id);
94268
94269
94270 ALTER TABLE api.pricingschedule OWNER TO admin;
94271
94272 --
94273 -- TOC entry 9325 (class 0 OID 0)
94274 -- Dependencies: 346
94275 -- Name: VIEW pricingschedule; Type: COMMENT; Schema: api; Owner: admin
94276 --
94277
94278 COMMENT ON VIEW pricingschedule IS 'Pricing Schedule';
94279
94280
94281 SET search_path = public, pg_catalog;
94282
94283 --
94284 -- TOC entry 347 (class 1259 OID 146567920)
94285 -- Dependencies: 6218 8
94286 -- Name: ipsass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94287 --
94288
94289 CREATE TABLE ipsass (
94290     ipsass_id integer NOT NULL,
94291     ipsass_ipshead_id integer NOT NULL,
94292     ipsass_cust_id integer,
94293     ipsass_custtype_id integer,
94294     ipsass_custtype_pattern text,
94295     ipsass_shipto_id integer DEFAULT (-1),
94296     ipsass_shipto_pattern text
94297 );
94298
94299
94300 ALTER TABLE public.ipsass OWNER TO admin;
94301
94302 --
94303 -- TOC entry 9327 (class 0 OID 0)
94304 -- Dependencies: 347
94305 -- Name: TABLE ipsass; Type: COMMENT; Schema: public; Owner: admin
94306 --
94307
94308 COMMENT ON TABLE ipsass IS 'Pricing Schedule assignment information';
94309
94310
94311 SET search_path = api, pg_catalog;
94312
94313 --
94314 -- TOC entry 348 (class 1259 OID 146567927)
94315 -- Dependencies: 8536 6
94316 -- Name: pricingscheduleassign; Type: VIEW; Schema: api; Owner: admin
94317 --
94318
94319 CREATE VIEW pricingscheduleassign AS
94320     SELECT (COALESCE(custinfo.cust_number, 'Any'::text))::character varying AS customer_number, (COALESCE(shiptoinfo.shipto_num, 'Any'::text))::character varying AS customer_shipto, (COALESCE(ipsass.ipsass_shipto_pattern, 'N/A'::text))::character varying AS customer_shipto_pattern, (COALESCE(custtype.custtype_code, 'N/A'::text))::character varying AS customer_type, (COALESCE(ipsass.ipsass_custtype_pattern, 'N/A'::text))::character varying AS customer_type_pattern, (ipshead.ipshead_name)::character varying AS pricing_schedule FROM ((((public.ipshead JOIN public.ipsass ON ((ipshead.ipshead_id = ipsass.ipsass_ipshead_id))) LEFT JOIN public.custinfo ON ((ipsass.ipsass_cust_id = custinfo.cust_id))) LEFT JOIN public.custtype ON ((ipsass.ipsass_custtype_id = custtype.custtype_id))) LEFT JOIN public.shiptoinfo ON ((ipsass.ipsass_shipto_id = shiptoinfo.shipto_id))) ORDER BY (COALESCE(custinfo.cust_number, 'Any'::text))::character varying, (COALESCE(shiptoinfo.shipto_num, 'Any'::text))::character varying, (COALESCE(custtype.custtype_code, 'N/A'::text))::character varying, (COALESCE(ipsass.ipsass_custtype_pattern, 'N/A'::text))::character varying, (ipshead.ipshead_name)::character varying;
94321
94322
94323 ALTER TABLE api.pricingscheduleassign OWNER TO admin;
94324
94325 --
94326 -- TOC entry 9329 (class 0 OID 0)
94327 -- Dependencies: 348
94328 -- Name: VIEW pricingscheduleassign; Type: COMMENT; Schema: api; Owner: admin
94329 --
94330
94331 COMMENT ON VIEW pricingscheduleassign IS 'Pricing Schedule Assignments';
94332
94333
94334 SET search_path = public, pg_catalog;
94335
94336 --
94337 -- TOC entry 349 (class 1259 OID 146567932)
94338 -- Dependencies: 6219 6220 6221 6222 8
94339 -- Name: ipsiteminfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94340 --
94341
94342 CREATE TABLE ipsiteminfo (
94343     ipsitem_id integer DEFAULT nextval(('"ipsitem_ipsitem_id_seq"'::text)::regclass) NOT NULL,
94344     ipsitem_ipshead_id integer,
94345     ipsitem_item_id integer,
94346     ipsitem_qtybreak numeric(18,6) NOT NULL,
94347     ipsitem_price numeric(16,4) NOT NULL,
94348     ipsitem_qty_uom_id integer,
94349     ipsitem_price_uom_id integer,
94350     ipsitem_discntprcnt numeric(10,6) DEFAULT 0.00 NOT NULL,
94351     ipsitem_fixedamtdiscount numeric(16,4) DEFAULT 0.00 NOT NULL,
94352     ipsitem_prodcat_id integer,
94353     ipsitem_type character(1) NOT NULL,
94354     ipsitem_warehous_id integer,
94355     CONSTRAINT valid_ipsitem_type CHECK ((ipsitem_type = ANY (ARRAY['N'::bpchar, 'D'::bpchar, 'M'::bpchar])))
94356 );
94357
94358
94359 ALTER TABLE public.ipsiteminfo OWNER TO admin;
94360
94361 --
94362 -- TOC entry 9331 (class 0 OID 0)
94363 -- Dependencies: 349
94364 -- Name: TABLE ipsiteminfo; Type: COMMENT; Schema: public; Owner: admin
94365 --
94366
94367 COMMENT ON TABLE ipsiteminfo IS 'Pricing Schedule Item information';
94368
94369
94370 --
94371 -- TOC entry 9332 (class 0 OID 0)
94372 -- Dependencies: 349
94373 -- Name: COLUMN ipsiteminfo.ipsitem_prodcat_id; Type: COMMENT; Schema: public; Owner: admin
94374 --
94375
94376 COMMENT ON COLUMN ipsiteminfo.ipsitem_prodcat_id IS 'Product category for pricing schedule item.';
94377
94378
94379 --
94380 -- TOC entry 9333 (class 0 OID 0)
94381 -- Dependencies: 349
94382 -- Name: COLUMN ipsiteminfo.ipsitem_type; Type: COMMENT; Schema: public; Owner: admin
94383 --
94384
94385 COMMENT ON COLUMN ipsiteminfo.ipsitem_type IS 'Pricing type for pricing schedule item.  Valid values are N-nominal, D-discount, and M-markup';
94386
94387
94388 --
94389 -- TOC entry 9334 (class 0 OID 0)
94390 -- Dependencies: 349
94391 -- Name: COLUMN ipsiteminfo.ipsitem_warehous_id; Type: COMMENT; Schema: public; Owner: admin
94392 --
94393
94394 COMMENT ON COLUMN ipsiteminfo.ipsitem_warehous_id IS 'Site for pricing schedule item which enables pricing by site.';
94395
94396
94397 SET search_path = api, pg_catalog;
94398
94399 --
94400 -- TOC entry 350 (class 1259 OID 146567939)
94401 -- Dependencies: 8537 6
94402 -- Name: pricingscheduleitem; Type: VIEW; Schema: api; Owner: admin
94403 --
94404
94405 CREATE VIEW pricingscheduleitem AS
94406     SELECT (ipshead.ipshead_name)::character varying AS pricing_schedule, CASE WHEN (COALESCE(ipsiteminfo.ipsitem_item_id, (-1)) > 0) THEN 'Item'::character varying ELSE 'Product Category'::character varying END AS type, (COALESCE(item.item_number, ''::text))::character varying AS item_number, (COALESCE(prodcat.prodcat_code, ''::text))::character varying AS product_category, ipsiteminfo.ipsitem_qtybreak AS qty_break, (qtyuom.uom_name)::character varying AS qty_uom, (priceuom.uom_name)::character varying AS price_uom, ipsiteminfo.ipsitem_price AS price, ipsiteminfo.ipsitem_discntprcnt AS percent, ipsiteminfo.ipsitem_fixedamtdiscount AS fixedamt, CASE WHEN (ipsiteminfo.ipsitem_type = 'N'::bpchar) THEN 'Nominal'::character varying WHEN (ipsiteminfo.ipsitem_type = 'D'::bpchar) THEN 'Discount'::character varying WHEN (ipsiteminfo.ipsitem_type = 'M'::bpchar) THEN 'Markup'::character varying ELSE NULL::character varying END AS pricing_type FROM (((((public.ipsiteminfo JOIN public.ipshead ON ((ipsiteminfo.ipsitem_ipshead_id = ipshead.ipshead_id))) LEFT JOIN public.item ON ((ipsiteminfo.ipsitem_item_id = item.item_id))) LEFT JOIN public.prodcat ON ((ipsiteminfo.ipsitem_prodcat_id = prodcat.prodcat_id))) LEFT JOIN public.uom qtyuom ON ((ipsiteminfo.ipsitem_qty_uom_id = qtyuom.uom_id))) LEFT JOIN public.uom priceuom ON ((ipsiteminfo.ipsitem_price_uom_id = priceuom.uom_id)));
94407
94408
94409 ALTER TABLE api.pricingscheduleitem OWNER TO admin;
94410
94411 --
94412 -- TOC entry 9336 (class 0 OID 0)
94413 -- Dependencies: 350
94414 -- Name: VIEW pricingscheduleitem; Type: COMMENT; Schema: api; Owner: admin
94415 --
94416
94417 COMMENT ON VIEW pricingscheduleitem IS 'Pricing Schedule Item';
94418
94419
94420 SET search_path = public, pg_catalog;
94421
94422 --
94423 -- TOC entry 351 (class 1259 OID 146567944)
94424 -- Dependencies: 8
94425 -- Name: ipsitemchar; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94426 --
94427
94428 CREATE TABLE ipsitemchar (
94429     ipsitemchar_id integer NOT NULL,
94430     ipsitemchar_ipsitem_id integer NOT NULL,
94431     ipsitemchar_char_id integer NOT NULL,
94432     ipsitemchar_value text NOT NULL,
94433     ipsitemchar_price numeric(16,4)
94434 );
94435
94436
94437 ALTER TABLE public.ipsitemchar OWNER TO admin;
94438
94439 --
94440 -- TOC entry 9338 (class 0 OID 0)
94441 -- Dependencies: 351
94442 -- Name: TABLE ipsitemchar; Type: COMMENT; Schema: public; Owner: admin
94443 --
94444
94445 COMMENT ON TABLE ipsitemchar IS 'Item Price Schedule Characteristic Prices.';
94446
94447
94448 SET search_path = api, pg_catalog;
94449
94450 --
94451 -- TOC entry 352 (class 1259 OID 146567950)
94452 -- Dependencies: 8538 6
94453 -- Name: pricingscheduleitemchar; Type: VIEW; Schema: api; Owner: admin
94454 --
94455
94456 CREATE VIEW pricingscheduleitemchar AS
94457     SELECT (ipshead.ipshead_name)::character varying AS pricing_schedule, (item.item_number)::character varying AS item_number, ipsiteminfo.ipsitem_qtybreak AS qty_break, (qtyuom.uom_name)::character varying AS qty_uom, (priceuom.uom_name)::character varying AS price_uom, ("char".char_name)::character varying AS characteristic, (ipsitemchar.ipsitemchar_value)::character varying AS value, ipsitemchar.ipsitemchar_price AS price FROM public.ipshead, public.ipsiteminfo, public.ipsitemchar, public.item, public."char", public.uom qtyuom, public.uom priceuom WHERE ((((((ipshead.ipshead_id = ipsiteminfo.ipsitem_ipshead_id) AND (ipsiteminfo.ipsitem_id = ipsitemchar.ipsitemchar_ipsitem_id)) AND (ipsiteminfo.ipsitem_item_id = item.item_id)) AND (ipsiteminfo.ipsitem_qty_uom_id = qtyuom.uom_id)) AND (ipsiteminfo.ipsitem_price_uom_id = priceuom.uom_id)) AND (ipsitemchar.ipsitemchar_char_id = "char".char_id));
94458
94459
94460 ALTER TABLE api.pricingscheduleitemchar OWNER TO admin;
94461
94462 --
94463 -- TOC entry 9340 (class 0 OID 0)
94464 -- Dependencies: 352
94465 -- Name: VIEW pricingscheduleitemchar; Type: COMMENT; Schema: api; Owner: admin
94466 --
94467
94468 COMMENT ON VIEW pricingscheduleitemchar IS 'Pricing Schedule Item Characteristics';
94469
94470
94471 --
94472 -- TOC entry 353 (class 1259 OID 146567955)
94473 -- Dependencies: 8539 6
94474 -- Name: project; Type: VIEW; Schema: api; Owner: admin
94475 --
94476
94477 CREATE VIEW project AS
94478     SELECT prj.prj_number AS number, prj.prj_name AS name, prj.prj_descrip AS description, prj.prj_owner_username AS owner, prj.prj_username AS assigned_to, prj.prj_so AS sales_orders, prj.prj_wo AS work_orders, prj.prj_po AS purchase_orders, CASE WHEN (prj.prj_status = 'P'::bpchar) THEN 'Concept'::text WHEN (prj.prj_status = 'O'::bpchar) THEN 'In-Process'::text WHEN (prj.prj_status = 'C'::bpchar) THEN 'Closed'::text ELSE 'Error'::text END AS status, prj.prj_due_date AS due, prj.prj_assigned_date AS assigned, prj.prj_start_date AS started, prj.prj_completed_date AS completed FROM public.prj;
94479
94480
94481 ALTER TABLE api.project OWNER TO admin;
94482
94483 --
94484 -- TOC entry 9342 (class 0 OID 0)
94485 -- Dependencies: 353
94486 -- Name: VIEW project; Type: COMMENT; Schema: api; Owner: admin
94487 --
94488
94489 COMMENT ON VIEW project IS 'Project';
94490
94491
94492 --
94493 -- TOC entry 354 (class 1259 OID 146567959)
94494 -- Dependencies: 8540 6
94495 -- Name: projectcomment; Type: VIEW; Schema: api; Owner: admin
94496 --
94497
94498 CREATE VIEW projectcomment AS
94499     SELECT (prj.prj_number)::character varying AS project_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.prj, public.cmnttype, public.comment WHERE (((comment.comment_source = 'J'::text) AND (comment.comment_source_id = prj.prj_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
94500
94501
94502 ALTER TABLE api.projectcomment OWNER TO admin;
94503
94504 --
94505 -- TOC entry 9344 (class 0 OID 0)
94506 -- Dependencies: 354
94507 -- Name: VIEW projectcomment; Type: COMMENT; Schema: api; Owner: admin
94508 --
94509
94510 COMMENT ON VIEW projectcomment IS 'Project Comment';
94511
94512
94513 SET search_path = public, pg_catalog;
94514
94515 --
94516 -- TOC entry 355 (class 1259 OID 146567963)
94517 -- Dependencies: 8
94518 -- Name: cust_cust_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
94519 --
94520
94521 CREATE SEQUENCE cust_cust_id_seq
94522     START WITH 1
94523     INCREMENT BY 1
94524     NO MINVALUE
94525     NO MAXVALUE
94526     CACHE 1;
94527
94528
94529 ALTER TABLE public.cust_cust_id_seq OWNER TO admin;
94530
94531 --
94532 -- TOC entry 356 (class 1259 OID 146567965)
94533 -- Dependencies: 6224 6225 6226 6227 8
94534 -- Name: prospect; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94535 --
94536
94537 CREATE TABLE prospect (
94538     prospect_id integer DEFAULT nextval('cust_cust_id_seq'::regclass) NOT NULL,
94539     prospect_active boolean DEFAULT true NOT NULL,
94540     prospect_number text NOT NULL,
94541     prospect_name text NOT NULL,
94542     prospect_cntct_id integer,
94543     prospect_comments text,
94544     prospect_created date DEFAULT ('now'::text)::date NOT NULL,
94545     prospect_salesrep_id integer,
94546     prospect_warehous_id integer,
94547     prospect_taxzone_id integer,
94548     CONSTRAINT prospect_prospect_number_check CHECK ((prospect_number <> ''::text))
94549 );
94550
94551
94552 ALTER TABLE public.prospect OWNER TO admin;
94553
94554 --
94555 -- TOC entry 9347 (class 0 OID 0)
94556 -- Dependencies: 356
94557 -- Name: TABLE prospect; Type: COMMENT; Schema: public; Owner: admin
94558 --
94559
94560 COMMENT ON TABLE prospect IS 'Prospect Information';
94561
94562
94563 SET search_path = api, pg_catalog;
94564
94565 --
94566 -- TOC entry 357 (class 1259 OID 146567975)
94567 -- Dependencies: 8541 6
94568 -- Name: prospect; Type: VIEW; Schema: api; Owner: admin
94569 --
94570
94571 CREATE VIEW prospect AS
94572     SELECT (prospect.prospect_number)::character varying AS prospect_number, prospect.prospect_name, prospect.prospect_active AS active, salesrep.salesrep_number AS sales_rep, whsinfo.warehous_code AS site_code, taxzone.taxzone_code AS default_tax_zone, prospect.prospect_comments AS notes, cntct.cntct_number AS contact_number, cntct.cntct_honorific AS contact_honorific, cntct.cntct_first_name AS contact_first, cntct.cntct_middle AS contact_middle, cntct.cntct_last_name AS contact_last, cntct.cntct_suffix AS contact_suffix, cntct.cntct_title AS contact_job_title, cntct.cntct_phone AS contact_voice, cntct.cntct_phone2 AS contact_alternate, cntct.cntct_fax AS contact_fax, cntct.cntct_email AS contact_email, cntct.cntct_webaddr AS contact_web, ''::text AS contact_change, addr.addr_number AS contact_address_number, addr.addr_line1 AS contact_address1, addr.addr_line2 AS contact_address2, addr.addr_line3 AS contact_address3, addr.addr_city AS contact_city, addr.addr_state AS contact_state, addr.addr_postalcode AS contact_postalcode, addr.addr_country AS contact_country, ''::text AS contact_address_change FROM (((((public.prospect LEFT JOIN public.cntct ON ((prospect.prospect_cntct_id = cntct.cntct_id))) LEFT JOIN public.addr ON ((cntct.cntct_addr_id = addr.addr_id))) LEFT JOIN public.taxzone ON ((prospect.prospect_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.salesrep ON ((prospect.prospect_salesrep_id = salesrep.salesrep_id))) LEFT JOIN public.whsinfo ON ((prospect.prospect_warehous_id = whsinfo.warehous_id)));
94573
94574
94575 ALTER TABLE api.prospect OWNER TO admin;
94576
94577 --
94578 -- TOC entry 9349 (class 0 OID 0)
94579 -- Dependencies: 357
94580 -- Name: VIEW prospect; Type: COMMENT; Schema: api; Owner: admin
94581 --
94582
94583 COMMENT ON VIEW prospect IS 'Prospect';
94584
94585
94586 SET search_path = public, pg_catalog;
94587
94588 --
94589 -- TOC entry 358 (class 1259 OID 146567980)
94590 -- Dependencies: 6229 8
94591 -- Name: expcat; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94592 --
94593
94594 CREATE TABLE expcat (
94595     expcat_id integer NOT NULL,
94596     expcat_code text NOT NULL,
94597     expcat_descrip text,
94598     expcat_exp_accnt_id integer,
94599     expcat_liability_accnt_id integer,
94600     expcat_active boolean,
94601     expcat_purchprice_accnt_id integer,
94602     expcat_freight_accnt_id integer,
94603     CONSTRAINT expcat_expcat_code_check CHECK ((expcat_code <> ''::text))
94604 );
94605
94606
94607 ALTER TABLE public.expcat OWNER TO admin;
94608
94609 --
94610 -- TOC entry 9351 (class 0 OID 0)
94611 -- Dependencies: 358
94612 -- Name: TABLE expcat; Type: COMMENT; Schema: public; Owner: admin
94613 --
94614
94615 COMMENT ON TABLE expcat IS 'Expense Category information';
94616
94617
94618 --
94619 -- TOC entry 359 (class 1259 OID 146567987)
94620 -- Dependencies: 6230 6231 6232 6233 6234 6235 8
94621 -- Name: womatl; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94622 --
94623
94624 CREATE TABLE womatl (
94625     womatl_id integer DEFAULT nextval(('womatl_womatl_id_seq'::text)::regclass) NOT NULL,
94626     womatl_wo_id integer,
94627     womatl_itemsite_id integer,
94628     womatl_qtyper numeric(20,8) NOT NULL,
94629     womatl_scrap numeric(8,4) NOT NULL,
94630     womatl_qtyreq numeric(18,6) NOT NULL,
94631     womatl_qtyiss numeric(18,6) NOT NULL,
94632     womatl_qtywipscrap numeric(18,6) NOT NULL,
94633     womatl_lastissue date,
94634     womatl_lastreturn date,
94635     womatl_cost numeric(16,6),
94636     womatl_picklist boolean,
94637     womatl_status character(1),
94638     womatl_imported boolean DEFAULT false,
94639     womatl_createwo boolean,
94640     womatl_issuemethod character(1),
94641     womatl_wooper_id integer,
94642     womatl_bomitem_id integer,
94643     womatl_duedate date,
94644     womatl_schedatwooper boolean,
94645     womatl_uom_id integer NOT NULL,
94646     womatl_notes text,
94647     womatl_ref text,
94648     womatl_scrapvalue numeric(16,6) DEFAULT 0,
94649     womatl_qtyfxd numeric(20,8) DEFAULT 0 NOT NULL,
94650     womatl_issuewo boolean DEFAULT false NOT NULL,
94651     womatl_price numeric(16,6) DEFAULT 0 NOT NULL
94652 );
94653
94654
94655 ALTER TABLE public.womatl OWNER TO admin;
94656
94657 --
94658 -- TOC entry 9353 (class 0 OID 0)
94659 -- Dependencies: 359
94660 -- Name: TABLE womatl; Type: COMMENT; Schema: public; Owner: admin
94661 --
94662
94663 COMMENT ON TABLE womatl IS 'Work Order Material Requirements information';
94664
94665
94666 --
94667 -- TOC entry 9354 (class 0 OID 0)
94668 -- Dependencies: 359
94669 -- Name: COLUMN womatl.womatl_qtyfxd; Type: COMMENT; Schema: public; Owner: admin
94670 --
94671
94672 COMMENT ON COLUMN womatl.womatl_qtyfxd IS 'The fixed quantity required';
94673
94674
94675 SET search_path = api, pg_catalog;
94676
94677 --
94678 -- TOC entry 360 (class 1259 OID 146567999)
94679 -- Dependencies: 8542 6
94680 -- Name: purchaseline; Type: VIEW; Schema: api; Owner: admin
94681 --
94682
94683 CREATE VIEW purchaseline AS
94684     SELECT (pohead.pohead_number)::character varying AS order_number, poitem.poitem_linenumber AS line_number, item.item_number, whsinfo.warehous_code AS site, expcat.expcat_code AS expense_category, poitem.poitem_qty_ordered AS qty_ordered, poitem.poitem_unitprice AS unit_price, poitem.poitem_freight AS freight, poitem.poitem_duedate AS due_date, prj.prj_number AS project_number, poitem.poitem_vend_item_number AS vend_item_number, poitem.poitem_vend_item_descrip AS vendor_description, poitem.poitem_manuf_name AS manufacturer_name, poitem.poitem_manuf_item_number AS manufacturer_item_number, poitem.poitem_manuf_item_descrip AS manufacturer_description, poitem.poitem_comments AS notes, public.formatrevnumber('BOM'::text, poitem.poitem_bom_rev_id) AS bill_of_materials_revision, public.formatrevnumber('BOO'::text, poitem.poitem_boo_rev_id) AS bill_of_operations_revision, public.formatsonumber(coitem.coitem_id) AS sales_order_number, public.formatwonumber(womatl.womatl_wo_id) AS work_order_number FROM ((((((((public.pohead JOIN public.poitem ON ((pohead.pohead_id = poitem.poitem_pohead_id))) LEFT JOIN public.prj ON ((poitem.poitem_prj_id = prj.prj_id))) LEFT JOIN public.expcat ON ((poitem.poitem_expcat_id = expcat.expcat_id))) LEFT JOIN public.itemsite ON ((poitem.poitem_itemsite_id = itemsite.itemsite_id))) LEFT JOIN public.item ON ((itemsite.itemsite_item_id = item.item_id))) LEFT JOIN public.whsinfo ON ((itemsite.itemsite_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.coitem ON (((coitem.coitem_id = poitem.poitem_order_id) AND (poitem.poitem_order_type = 'S'::bpchar)))) LEFT JOIN public.womatl ON (((womatl.womatl_id = poitem.poitem_order_id) AND (poitem.poitem_order_type = 'W'::bpchar)))) ORDER BY pohead.pohead_number, poitem.poitem_linenumber;
94685
94686
94687 ALTER TABLE api.purchaseline OWNER TO admin;
94688
94689 --
94690 -- TOC entry 9356 (class 0 OID 0)
94691 -- Dependencies: 360
94692 -- Name: VIEW purchaseline; Type: COMMENT; Schema: api; Owner: admin
94693 --
94694
94695 COMMENT ON VIEW purchaseline IS 'Purchase Order Line';
94696
94697
94698 --
94699 -- TOC entry 361 (class 1259 OID 146568004)
94700 -- Dependencies: 8543 6
94701 -- Name: purchaselinechar; Type: VIEW; Schema: api; Owner: admin
94702 --
94703
94704 CREATE VIEW purchaselinechar AS
94705     SELECT (data.order_number)::character varying AS order_number, data.line_number, data.characteristic, COALESCE(pi.charass_value, i3.charass_value) AS value FROM (((((SELECT DISTINCT "char".char_id, poitem.poitem_id, poitem.poitem_itemsite_id, pohead.pohead_number AS order_number, poitem.poitem_linenumber AS line_number, "char".char_name AS characteristic FROM public.pohead, public.poitem, public.itemsite, public.item, public.charass, public."char" WHERE ((((((pohead.pohead_id = poitem.poitem_pohead_id) AND (poitem.poitem_itemsite_id = itemsite.itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id)) AND (charass.charass_char_id = "char".char_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id))) data LEFT JOIN public.charass pi ON ((((data.poitem_id = pi.charass_target_id) AND ('PI'::text = pi.charass_target_type)) AND (pi.charass_char_id = data.char_id)))) LEFT JOIN public.itemsite i1 ON ((data.poitem_itemsite_id = i1.itemsite_id))) LEFT JOIN public.item i2 ON ((i1.itemsite_item_id = i2.item_id))) LEFT JOIN public.charass i3 ON (((((i2.item_id = i3.charass_target_id) AND ('I'::text = i3.charass_target_type)) AND (i3.charass_char_id = data.char_id)) AND i3.charass_default))) ORDER BY (data.order_number)::character varying, data.line_number, data.characteristic;
94706
94707
94708 ALTER TABLE api.purchaselinechar OWNER TO admin;
94709
94710 --
94711 -- TOC entry 9358 (class 0 OID 0)
94712 -- Dependencies: 361
94713 -- Name: VIEW purchaselinechar; Type: COMMENT; Schema: api; Owner: admin
94714 --
94715
94716 COMMENT ON VIEW purchaselinechar IS 'Purchase Order Line Item Characteristic';
94717
94718
94719 --
94720 -- TOC entry 362 (class 1259 OID 146568009)
94721 -- Dependencies: 8544 6
94722 -- Name: purchaselinecomment; Type: VIEW; Schema: api; Owner: admin
94723 --
94724
94725 CREATE VIEW purchaselinecomment AS
94726     SELECT (pohead.pohead_number)::character varying AS order_number, poitem.poitem_linenumber AS line_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.pohead, public.poitem, public.cmnttype, public.comment WHERE ((((pohead.pohead_id = poitem.poitem_pohead_id) AND (comment.comment_source = 'PI'::text)) AND (comment.comment_source_id = poitem.poitem_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id)) ORDER BY pohead.pohead_number, poitem.poitem_linenumber, comment.comment_date DESC;
94727
94728
94729 ALTER TABLE api.purchaselinecomment OWNER TO admin;
94730
94731 --
94732 -- TOC entry 9360 (class 0 OID 0)
94733 -- Dependencies: 362
94734 -- Name: VIEW purchaselinecomment; Type: COMMENT; Schema: api; Owner: admin
94735 --
94736
94737 COMMENT ON VIEW purchaselinecomment IS 'Purchase Order Line Item Comment';
94738
94739
94740 SET search_path = public, pg_catalog;
94741
94742 --
94743 -- TOC entry 363 (class 1259 OID 146568014)
94744 -- Dependencies: 6236 6237 8
94745 -- Name: tax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94746 --
94747
94748 CREATE TABLE tax (
94749     tax_id integer DEFAULT nextval(('"tax_tax_id_seq"'::text)::regclass) NOT NULL,
94750     tax_code text NOT NULL,
94751     tax_descrip text,
94752     tax_sales_accnt_id integer,
94753     tax_taxclass_id integer,
94754     tax_taxauth_id integer,
94755     tax_basis_tax_id integer,
94756     CONSTRAINT tax_tax_code_check CHECK ((tax_code <> ''::text))
94757 );
94758
94759
94760 ALTER TABLE public.tax OWNER TO admin;
94761
94762 --
94763 -- TOC entry 9362 (class 0 OID 0)
94764 -- Dependencies: 363
94765 -- Name: TABLE tax; Type: COMMENT; Schema: public; Owner: admin
94766 --
94767
94768 COMMENT ON TABLE tax IS 'Tax information';
94769
94770
94771 --
94772 -- TOC entry 9363 (class 0 OID 0)
94773 -- Dependencies: 363
94774 -- Name: COLUMN tax.tax_sales_accnt_id; Type: COMMENT; Schema: public; Owner: admin
94775 --
94776
94777 COMMENT ON COLUMN tax.tax_sales_accnt_id IS 'Deprecated column - DO NOT USE';
94778
94779
94780 --
94781 -- TOC entry 364 (class 1259 OID 146568022)
94782 -- Dependencies: 6238 8
94783 -- Name: vendaddrinfo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94784 --
94785
94786 CREATE TABLE vendaddrinfo (
94787     vendaddr_id integer DEFAULT nextval(('vendaddr_vendaddr_id_seq'::text)::regclass) NOT NULL,
94788     vendaddr_vend_id integer,
94789     vendaddr_code text,
94790     vendaddr_name text,
94791     vendaddr_comments text,
94792     vendaddr_cntct_id integer,
94793     vendaddr_addr_id integer,
94794     vendaddr_taxzone_id integer
94795 );
94796
94797
94798 ALTER TABLE public.vendaddrinfo OWNER TO admin;
94799
94800 --
94801 -- TOC entry 9365 (class 0 OID 0)
94802 -- Dependencies: 364
94803 -- Name: TABLE vendaddrinfo; Type: COMMENT; Schema: public; Owner: admin
94804 --
94805
94806 COMMENT ON TABLE vendaddrinfo IS 'Vendor Address information';
94807
94808
94809 SET search_path = api, pg_catalog;
94810
94811 --
94812 -- TOC entry 365 (class 1259 OID 146568029)
94813 -- Dependencies: 8545 6
94814 -- Name: purchaseorder; Type: VIEW; Schema: api; Owner: admin
94815 --
94816
94817 CREATE VIEW purchaseorder AS
94818     SELECT (pohead.pohead_number)::character varying AS order_number, pohead.pohead_orderdate AS order_date, terms.terms_code AS terms, taxzone.taxzone_code AS tax_zone, whsinfo.warehous_code AS receiving_site, pohead.pohead_agent_username AS purchasing_agent, vendinfo.vend_number AS vendor_number, COALESCE(ua.vendaddr_code, 'MAIN'::text) AS alt_address, pohead.pohead_fob AS fob, pohead.pohead_shipvia AS ship_via, curr_symbol.curr_abbr AS currency, (SELECT COALESCE(sum(data.tax), 0.00) AS tax FROM (SELECT round(sum(calculatetaxdetailsummary.taxdetail_tax), 2) AS tax FROM (public.tax JOIN public.calculatetaxdetailsummary('PO'::text, pohead.pohead_id, 'T'::text) calculatetaxdetailsummary(taxdetail_tax_id, taxdetail_tax_code, taxdetail_tax_descrip, taxdetail_tax_basis_tax_id, taxdetail_taxrate_percent, taxdetail_taxrate_amount, taxdetail_level, taxdetail_taxclass_id, taxdetail_taxclass_code, taxdetail_taxclass_sequence, taxdetail_tax, taxdetail_curr_id, taxdetail_curr_abbr) ON ((calculatetaxdetailsummary.taxdetail_tax_id = tax.tax_id))) GROUP BY tax.tax_id) data) AS tax, pohead.pohead_freight AS freight, pohead.pohead_comments AS notes, pohead.pohead_dropship AS dropship, vc.cntct_number AS vend_contact_number, pohead.pohead_vend_cntct_honorific AS vend_cntct_honorific, pohead.pohead_vend_cntct_first_name AS vend_cntct_first_name, pohead.pohead_vend_cntct_middle AS vend_cntct_middle, pohead.pohead_vend_cntct_last_name AS vend_cntct_last_name, pohead.pohead_vend_cntct_suffix AS vend_cntct_suffix, pohead.pohead_vend_cntct_phone AS vend_cntct_phone, pohead.pohead_vend_cntct_title AS vend_cntct_title, pohead.pohead_vend_cntct_fax AS vend_cntct_fax, pohead.pohead_vend_cntct_email AS vend_cntct_email, pohead.pohead_vendaddress1 AS vendaddress1, pohead.pohead_vendaddress2 AS vendaddress2, pohead.pohead_vendaddress3 AS vendaddress3, pohead.pohead_vendcity AS vendcity, pohead.pohead_vendstate AS vendstate, pohead.pohead_vendzipcode AS vendzipcode, pohead.pohead_vendcountry AS vendcountry, sc.cntct_number AS shipto_contact_number, pohead.pohead_shipto_cntct_honorific AS shipto_cntct_honorific, pohead.pohead_shipto_cntct_first_name AS shipto_cntct_first_name, pohead.pohead_shipto_cntct_middle AS shipto_cntct_middle, pohead.pohead_shipto_cntct_last_name AS shipto_cntct_last_name, pohead.pohead_shipto_cntct_suffix AS shipto_cntct_suffix, pohead.pohead_shipto_cntct_phone AS shipto_cntct_phone, pohead.pohead_shipto_cntct_title AS shipto_cntct_title, pohead.pohead_shipto_cntct_fax AS shipto_cntct_fax, pohead.pohead_shipto_cntct_email AS shipto_cntct_email, addr.addr_number AS shiptoaddress_number, pohead.pohead_shiptoaddress1 AS shiptoaddress1, pohead.pohead_shiptoaddress2 AS shiptoaddress2, pohead.pohead_shiptoaddress3 AS shiptoaddress3, pohead.pohead_shiptocity AS shiptocity, pohead.pohead_shiptostate AS shiptostate, pohead.pohead_shiptozipcode AS shiptozipcode, pohead.pohead_shiptocountry AS shiptocountry, cohead.cohead_number AS sales_order_number FROM ((((((((((public.pohead LEFT JOIN public.cntct vc ON ((pohead.pohead_vend_cntct_id = vc.cntct_id))) LEFT JOIN public.cntct sc ON ((pohead.pohead_shipto_cntct_id = sc.cntct_id))) LEFT JOIN public.addr ON ((pohead.pohead_shiptoaddress_id = addr.addr_id))) LEFT JOIN public.terms ON ((pohead.pohead_terms_id = terms.terms_id))) LEFT JOIN public.taxzone ON ((pohead.pohead_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.whsinfo ON ((pohead.pohead_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.vendaddrinfo ua ON ((pohead.pohead_vendaddr_id = ua.vendaddr_id))) LEFT JOIN public.cohead ON ((pohead.pohead_cohead_id = cohead.cohead_id))) JOIN public.vendinfo ON ((pohead.pohead_vend_id = vendinfo.vend_id))) JOIN public.curr_symbol ON ((pohead.pohead_curr_id = curr_symbol.curr_id))) ORDER BY pohead.pohead_number;
94819
94820
94821 ALTER TABLE api.purchaseorder OWNER TO admin;
94822
94823 --
94824 -- TOC entry 9367 (class 0 OID 0)
94825 -- Dependencies: 365
94826 -- Name: VIEW purchaseorder; Type: COMMENT; Schema: api; Owner: admin
94827 --
94828
94829 COMMENT ON VIEW purchaseorder IS 'Purchase Order';
94830
94831
94832 --
94833 -- TOC entry 366 (class 1259 OID 146568034)
94834 -- Dependencies: 8546 6
94835 -- Name: purchaseordercomment; Type: VIEW; Schema: api; Owner: admin
94836 --
94837
94838 CREATE VIEW purchaseordercomment AS
94839     SELECT (pohead.pohead_number)::character varying AS order_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.pohead, public.cmnttype, public.comment WHERE (((comment.comment_source = 'P'::text) AND (comment.comment_source_id = pohead.pohead_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
94840
94841
94842 ALTER TABLE api.purchaseordercomment OWNER TO admin;
94843
94844 --
94845 -- TOC entry 9369 (class 0 OID 0)
94846 -- Dependencies: 366
94847 -- Name: VIEW purchaseordercomment; Type: COMMENT; Schema: api; Owner: admin
94848 --
94849
94850 COMMENT ON VIEW purchaseordercomment IS 'Purchase Order Comment';
94851
94852
94853 SET search_path = public, pg_catalog;
94854
94855 --
94856 -- TOC entry 367 (class 1259 OID 146568038)
94857 -- Dependencies: 6239 6240 6241 6242 6243 6244 6245 6246 8
94858 -- Name: quhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
94859 --
94860
94861 CREATE TABLE quhead (
94862     quhead_id integer DEFAULT nextval(('"quhead_quhead_id_seq"'::text)::regclass) NOT NULL,
94863     quhead_number text NOT NULL,
94864     quhead_cust_id integer NOT NULL,
94865     quhead_quotedate date,
94866     quhead_shipto_id integer,
94867     quhead_shiptoname text,
94868     quhead_shiptoaddress1 text,
94869     quhead_shiptoaddress2 text,
94870     quhead_shiptoaddress3 text,
94871     quhead_shiptocity text,
94872     quhead_shiptostate text,
94873     quhead_shiptozipcode text,
94874     quhead_shiptophone text,
94875     quhead_salesrep_id integer,
94876     quhead_terms_id integer,
94877     quhead_freight numeric(16,4),
94878     quhead_ordercomments text,
94879     quhead_shipcomments text,
94880     quhead_billtoname text,
94881     quhead_billtoaddress1 text,
94882     quhead_billtoaddress2 text,
94883     quhead_billtoaddress3 text,
94884     quhead_billtocity text,
94885     quhead_billtostate text,
94886     quhead_billtozip text,
94887     quhead_commission numeric(16,4),
94888     quhead_custponumber text,
94889     quhead_fob text,
94890     quhead_shipvia text,
94891     quhead_warehous_id integer,
94892     quhead_packdate date,
94893     quhead_prj_id integer,
94894     quhead_misc numeric(16,4) DEFAULT 0 NOT NULL,
94895     quhead_misc_accnt_id integer,
94896     quhead_misc_descrip text,
94897     quhead_billtocountry text,
94898     quhead_shiptocountry text,
94899     quhead_curr_id integer DEFAULT basecurrid(),
94900     quhead_imported boolean DEFAULT false,
94901     quhead_expire date,
94902     quhead_calcfreight boolean DEFAULT false NOT NULL,
94903     quhead_shipto_cntct_id integer,
94904     quhead_shipto_cntct_honorific text,
94905     quhead_shipto_cntct_first_name text,
94906     quhead_shipto_cntct_middle text,
94907     quhead_shipto_cntct_last_name text,
94908     quhead_shipto_cntct_suffix text,
94909     quhead_shipto_cntct_phone text,
94910     quhead_shipto_cntct_title text,
94911     quhead_shipto_cntct_fax text,
94912     quhead_shipto_cntct_email text,
94913     quhead_billto_cntct_id integer,
94914     quhead_billto_cntct_honorific text,
94915     quhead_billto_cntct_first_name text,
94916     quhead_billto_cntct_middle text,
94917     quhead_billto_cntct_last_name text,
94918     quhead_billto_cntct_suffix text,
94919     quhead_billto_cntct_phone text,
94920     quhead_billto_cntct_title text,
94921     quhead_billto_cntct_fax text,
94922     quhead_billto_cntct_email text,
94923     quhead_taxzone_id integer,
94924     quhead_taxtype_id integer,
94925     quhead_ophead_id integer,
94926     quhead_status text,
94927     quhead_saletype_id integer,
94928     quhead_shipzone_id integer,
94929     CONSTRAINT quhead_check CHECK ((((quhead_misc = (0)::numeric) AND (quhead_misc_accnt_id IS NULL)) OR ((quhead_misc <> (0)::numeric) AND (quhead_misc_accnt_id IS NOT NULL)))),
94930     CONSTRAINT quhead_quhead_number_check CHECK ((quhead_number <> ''::text)),
94931     CONSTRAINT quhead_quhead_status_check CHECK ((((quhead_status = 'O'::text) OR (quhead_status = 'C'::text)) OR (quhead_status = 'X'::text)))
94932 );
94933
94934
94935 ALTER TABLE public.quhead OWNER TO admin;
94936
94937 --
94938 -- TOC entry 9371 (class 0 OID 0)
94939 -- Dependencies: 367
94940 -- Name: TABLE quhead; Type: COMMENT; Schema: public; Owner: admin
94941 --
94942
94943 COMMENT ON TABLE quhead IS 'Quote header information';
94944
94945
94946 --
94947 -- TOC entry 9372 (class 0 OID 0)
94948 -- Dependencies: 367
94949 -- Name: COLUMN quhead.quhead_saletype_id; Type: COMMENT; Schema: public; Owner: admin
94950 --
94951
94952 COMMENT ON COLUMN quhead.quhead_saletype_id IS 'Associated sale type for quote.';
94953
94954
94955 --
94956 -- TOC entry 9373 (class 0 OID 0)
94957 -- Dependencies: 367
94958 -- Name: COLUMN quhead.quhead_shipzone_id; Type: COMMENT; Schema: public; Owner: admin
94959 --
94960
94961 COMMENT ON COLUMN quhead.quhead_shipzone_id IS 'Associated shipping zone for quote.';
94962
94963
94964 SET search_path = api, pg_catalog;
94965
94966 --
94967 -- TOC entry 368 (class 1259 OID 146568052)
94968 -- Dependencies: 8547 6
94969 -- Name: quote; Type: VIEW; Schema: api; Owner: admin
94970 --
94971
94972 CREATE VIEW quote AS
94973     SELECT (quhead.quhead_number)::character varying AS quote_number, whsinfo.warehous_code AS site, quhead.quhead_quotedate AS quote_date, quhead.quhead_packdate AS pack_date, saletype.saletype_code AS sale_type, salesrep.salesrep_number AS sales_rep, quhead.quhead_commission AS commission, taxzone.taxzone_code AS tax_zone, taxtype.taxtype_name AS tax_type, terms.terms_code AS terms, prj.prj_number AS project_number, COALESCE(custinfo.cust_number, prospect.prospect_number) AS customer_number, quhead.quhead_billtoname AS billto_name, quhead.quhead_billtoaddress1 AS billto_address1, quhead.quhead_billtoaddress2 AS billto_address2, quhead.quhead_billtoaddress3 AS billto_address3, quhead.quhead_billtocity AS billto_city, quhead.quhead_billtostate AS billto_state, quhead.quhead_billtozip AS billto_postal_code, quhead.quhead_billtocountry AS billto_country, shiptoinfo.shipto_num AS shipto_number, quhead.quhead_shiptoname AS shipto_name, quhead.quhead_shiptophone AS shipto_phone, quhead.quhead_shiptoaddress1 AS shipto_address1, quhead.quhead_shiptoaddress2 AS shipto_address2, quhead.quhead_shiptoaddress3 AS shipto_address3, quhead.quhead_shiptocity AS shipto_city, quhead.quhead_shiptostate AS shipto_state, quhead.quhead_shiptozipcode AS shipto_postal_code, quhead.quhead_shiptocountry AS shipto_country, shipzone.shipzone_name AS shipto_shipzone, quhead.quhead_custponumber AS cust_po_number, quhead.quhead_fob AS fob, quhead.quhead_shipvia AS ship_via, curr_symbol.curr_abbr AS currency, quhead.quhead_misc_descrip AS misc_charge_description, CASE WHEN (quhead.quhead_misc_accnt_id IS NULL) THEN NULL::text ELSE public.formatglaccount(quhead.quhead_misc_accnt_id) END AS misc_account_number, quhead.quhead_misc AS misc_charge, quhead.quhead_freight AS freight, quhead.quhead_ordercomments AS order_notes, quhead.quhead_shipcomments AS shipping_notes, false AS add_to_packing_list_batch, quhead.quhead_expire AS expire_date, CASE WHEN (quhead.quhead_status = 'C'::text) THEN 'Converted'::text ELSE 'Open'::text END AS status FROM public.curr_symbol, (((((((((((public.quhead LEFT JOIN public.whsinfo ON ((quhead.quhead_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.prj ON ((quhead.quhead_prj_id = prj.prj_id))) LEFT JOIN public.shiptoinfo ON ((quhead.quhead_shipto_id = shiptoinfo.shipto_id))) LEFT JOIN public.taxzone ON ((quhead.quhead_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.taxtype ON ((quhead.quhead_taxtype_id = taxtype.taxtype_id))) LEFT JOIN public.custinfo ON ((quhead.quhead_cust_id = custinfo.cust_id))) LEFT JOIN public.prospect ON ((quhead.quhead_cust_id = prospect.prospect_id))) LEFT JOIN public.salesrep ON ((quhead.quhead_salesrep_id = salesrep.salesrep_id))) LEFT JOIN public.terms ON ((quhead.quhead_terms_id = terms.terms_id))) LEFT JOIN public.saletype ON ((quhead.quhead_saletype_id = saletype.saletype_id))) LEFT JOIN public.shipzone ON ((quhead.quhead_shipzone_id = shipzone.shipzone_id))) WHERE (quhead.quhead_curr_id = curr_symbol.curr_id);
94974
94975
94976 ALTER TABLE api.quote OWNER TO admin;
94977
94978 --
94979 -- TOC entry 9375 (class 0 OID 0)
94980 -- Dependencies: 368
94981 -- Name: VIEW quote; Type: COMMENT; Schema: api; Owner: admin
94982 --
94983
94984 COMMENT ON VIEW quote IS 'Quote';
94985
94986
94987 --
94988 -- TOC entry 369 (class 1259 OID 146568057)
94989 -- Dependencies: 8548 6
94990 -- Name: quotecomment; Type: VIEW; Schema: api; Owner: admin
94991 --
94992
94993 CREATE VIEW quotecomment AS
94994     SELECT quhead.quhead_number AS quote_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.quhead, public.cmnttype, public.comment WHERE (((comment.comment_source = 'Q'::text) AND (comment.comment_source_id = quhead.quhead_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
94995
94996
94997 ALTER TABLE api.quotecomment OWNER TO admin;
94998
94999 --
95000 -- TOC entry 9377 (class 0 OID 0)
95001 -- Dependencies: 369
95002 -- Name: VIEW quotecomment; Type: COMMENT; Schema: api; Owner: admin
95003 --
95004
95005 COMMENT ON VIEW quotecomment IS 'Quote Comment';
95006
95007
95008 SET search_path = public, pg_catalog;
95009
95010 --
95011 -- TOC entry 370 (class 1259 OID 146568061)
95012 -- Dependencies: 6247 6248 6249 6250 6251 8
95013 -- Name: quitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95014 --
95015
95016 CREATE TABLE quitem (
95017     quitem_id integer DEFAULT nextval(('"quitem_quitem_id_seq"'::text)::regclass) NOT NULL,
95018     quitem_quhead_id integer,
95019     quitem_linenumber integer,
95020     quitem_itemsite_id integer,
95021     quitem_scheddate date,
95022     quitem_qtyord numeric(18,6),
95023     quitem_unitcost numeric(16,6),
95024     quitem_price numeric(16,4),
95025     quitem_custprice numeric(16,4),
95026     quitem_memo text,
95027     quitem_custpn text,
95028     quitem_createorder boolean,
95029     quitem_order_warehous_id integer,
95030     quitem_item_id integer,
95031     quitem_prcost numeric(16,6),
95032     quitem_imported boolean DEFAULT false,
95033     quitem_qty_uom_id integer NOT NULL,
95034     quitem_qty_invuomratio numeric(20,10) NOT NULL,
95035     quitem_price_uom_id integer NOT NULL,
95036     quitem_price_invuomratio numeric(20,10) NOT NULL,
95037     quitem_promdate date,
95038     quitem_taxtype_id integer,
95039     quitem_dropship boolean DEFAULT false,
95040     quitem_itemsrc_id integer,
95041     quitem_pricemode character(1) DEFAULT 'D'::bpchar NOT NULL,
95042     CONSTRAINT valid_quitem_pricemode CHECK ((quitem_pricemode = ANY (ARRAY['D'::bpchar, 'M'::bpchar])))
95043 );
95044
95045
95046 ALTER TABLE public.quitem OWNER TO admin;
95047
95048 --
95049 -- TOC entry 9379 (class 0 OID 0)
95050 -- Dependencies: 370
95051 -- Name: TABLE quitem; Type: COMMENT; Schema: public; Owner: admin
95052 --
95053
95054 COMMENT ON TABLE quitem IS 'Quote Line Item information';
95055
95056
95057 --
95058 -- TOC entry 9380 (class 0 OID 0)
95059 -- Dependencies: 370
95060 -- Name: COLUMN quitem.quitem_pricemode; Type: COMMENT; Schema: public; Owner: admin
95061 --
95062
95063 COMMENT ON COLUMN quitem.quitem_pricemode IS 'Pricing mode for quote item.  Valid values are D-discount, and M-markup';
95064
95065
95066 SET search_path = api, pg_catalog;
95067
95068 --
95069 -- TOC entry 371 (class 1259 OID 146568072)
95070 -- Dependencies: 8549 6
95071 -- Name: quoteline; Type: VIEW; Schema: api; Owner: admin
95072 --
95073
95074 CREATE VIEW quoteline AS
95075     SELECT quhead.quhead_number AS quote_number, quitem.quitem_linenumber AS line_number, l.item_number, quitem.quitem_custpn AS customer_pn, i.warehous_code AS sold_from_site, quitem.quitem_qtyord AS qty_ordered, q.uom_name AS qty_uom, quitem.quitem_price AS net_unit_price, p.uom_name AS price_uom, quitem.quitem_scheddate AS scheduled_date, COALESCE((SELECT taxtype.taxtype_name FROM public.taxtype WHERE (taxtype.taxtype_id = public.getitemtaxtype(l.item_id, quhead.quhead_taxzone_id))), 'None'::text) AS tax_type, CASE WHEN (quitem.quitem_price = (0)::numeric) THEN '100'::text WHEN (quitem.quitem_custprice = (0)::numeric) THEN 'N/A'::text ELSE (round((((1)::numeric - (quitem.quitem_price / quitem.quitem_custprice)) * (100)::numeric), 4))::text END AS discount_pct_from_list, quitem.quitem_createorder AS create_order, s.warehous_code AS supplying_site, quitem.quitem_prcost AS overwrite_po_price, quitem.quitem_memo AS notes FROM public.quhead, public.uom q, public.uom p, (public.quitem LEFT JOIN public.whsinfo s ON ((quitem.quitem_order_warehous_id = s.warehous_id))), public.itemsite il, public.item l, public.whsinfo i WHERE ((((((quhead.quhead_id = quitem.quitem_quhead_id) AND (quitem.quitem_itemsite_id = il.itemsite_id)) AND (il.itemsite_item_id = l.item_id)) AND (il.itemsite_warehous_id = i.warehous_id)) AND (quitem.quitem_qty_uom_id = q.uom_id)) AND (quitem.quitem_price_uom_id = p.uom_id)) ORDER BY quhead.quhead_number, quitem.quitem_linenumber;
95076
95077
95078 ALTER TABLE api.quoteline OWNER TO admin;
95079
95080 --
95081 -- TOC entry 9382 (class 0 OID 0)
95082 -- Dependencies: 371
95083 -- Name: VIEW quoteline; Type: COMMENT; Schema: api; Owner: admin
95084 --
95085
95086 COMMENT ON VIEW quoteline IS 'Quote Line Item';
95087
95088
95089 --
95090 -- TOC entry 372 (class 1259 OID 146568077)
95091 -- Dependencies: 8550 6
95092 -- Name: quotelinechar; Type: VIEW; Schema: api; Owner: admin
95093 --
95094
95095 CREATE VIEW quotelinechar AS
95096     SELECT DISTINCT quhead.quhead_number AS quote_number, quitem.quitem_linenumber AS line_number, "char".char_name AS characteristic, COALESCE((SELECT b.charass_value FROM public.charass b WHERE (((b.charass_target_type = 'QI'::text) AND (b.charass_target_id = quitem.quitem_id)) AND (b.charass_char_id = "char".char_id))), (SELECT c.charass_value FROM public.charass c WHERE ((((c.charass_target_type = 'I'::text) AND (c.charass_target_id = item.item_id)) AND c.charass_default) AND (c.charass_char_id = "char".char_id)) LIMIT 1)) AS value FROM public.quhead, public.quitem, public.itemsite, public.item, public.charass a, public."char" WHERE ((((((quhead.quhead_id = quitem.quitem_quhead_id) AND (quitem.quitem_itemsite_id = itemsite.itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id)) AND (a.charass_char_id = "char".char_id)) AND (a.charass_target_type = 'I'::text)) AND (a.charass_target_id = item.item_id)) ORDER BY quhead.quhead_number, quitem.quitem_linenumber, "char".char_name;
95097
95098
95099 ALTER TABLE api.quotelinechar OWNER TO admin;
95100
95101 --
95102 -- TOC entry 9384 (class 0 OID 0)
95103 -- Dependencies: 372
95104 -- Name: VIEW quotelinechar; Type: COMMENT; Schema: api; Owner: admin
95105 --
95106
95107 COMMENT ON VIEW quotelinechar IS 'Quote Line Item Characteristics';
95108
95109
95110 --
95111 -- TOC entry 373 (class 1259 OID 146568082)
95112 -- Dependencies: 8551 6
95113 -- Name: quotelinecomment; Type: VIEW; Schema: api; Owner: admin
95114 --
95115
95116 CREATE VIEW quotelinecomment AS
95117     SELECT quhead.quhead_number AS quote_number, quitem.quitem_linenumber AS line_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.quhead, public.quitem, public.cmnttype, public.comment WHERE ((((quhead.quhead_id = quitem.quitem_quhead_id) AND (comment.comment_source = 'QI'::text)) AND (comment.comment_source_id = quitem.quitem_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id)) ORDER BY quhead.quhead_number, quitem.quitem_linenumber, comment.comment_date DESC;
95118
95119
95120 ALTER TABLE api.quotelinecomment OWNER TO admin;
95121
95122 --
95123 -- TOC entry 9386 (class 0 OID 0)
95124 -- Dependencies: 373
95125 -- Name: VIEW quotelinecomment; Type: COMMENT; Schema: api; Owner: admin
95126 --
95127
95128 COMMENT ON VIEW quotelinecomment IS 'Quote Line Item Comment';
95129
95130
95131 SET search_path = public, pg_catalog;
95132
95133 --
95134 -- TOC entry 374 (class 1259 OID 146568087)
95135 -- Dependencies: 6252 6253 8
95136 -- Name: aropenalloc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95137 --
95138
95139 CREATE TABLE aropenalloc (
95140     aropenalloc_aropen_id integer NOT NULL,
95141     aropenalloc_doctype character(1) NOT NULL,
95142     aropenalloc_doc_id integer NOT NULL,
95143     aropenalloc_amount numeric(20,2) DEFAULT 0.00 NOT NULL,
95144     aropenalloc_curr_id integer DEFAULT basecurrid()
95145 );
95146
95147
95148 ALTER TABLE public.aropenalloc OWNER TO admin;
95149
95150 SET search_path = api, pg_catalog;
95151
95152 --
95153 -- TOC entry 375 (class 1259 OID 146568092)
95154 -- Dependencies: 8552 6
95155 -- Name: salescredit; Type: VIEW; Schema: api; Owner: admin
95156 --
95157
95158 CREATE VIEW salescredit AS
95159     SELECT custinfo.cust_number AS customer_number, aropen.aropen_docnumber AS cm_number, cohead.cohead_number AS so_number, (aropenalloc.aropenalloc_amount)::numeric(16,4) AS amount, curr.curr_abbr AS currency FROM ((((public.aropenalloc LEFT JOIN public.aropen ON ((aropen.aropen_id = aropenalloc.aropenalloc_aropen_id))) LEFT JOIN public.custinfo ON ((custinfo.cust_id = aropen.aropen_cust_id))) LEFT JOIN public.cohead ON (((aropenalloc.aropenalloc_doctype = 'S'::bpchar) AND (cohead.cohead_id = aropenalloc.aropenalloc_doc_id)))) LEFT JOIN public.curr_symbol curr ON ((curr.curr_id = aropenalloc.aropenalloc_curr_id))) WHERE (aropenalloc.aropenalloc_doctype = 'S'::bpchar);
95160
95161
95162 ALTER TABLE api.salescredit OWNER TO admin;
95163
95164 --
95165 -- TOC entry 9389 (class 0 OID 0)
95166 -- Dependencies: 375
95167 -- Name: VIEW salescredit; Type: COMMENT; Schema: api; Owner: admin
95168 --
95169
95170 COMMENT ON VIEW salescredit IS 'Payments (credit memos) pre-applied to sales orders';
95171
95172
95173 SET search_path = public, pg_catalog;
95174
95175 --
95176 -- TOC entry 376 (class 1259 OID 146568097)
95177 -- Dependencies: 6254 6255 6256 8
95178 -- Name: cohist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95179 --
95180
95181 CREATE TABLE cohist (
95182     cohist_id integer DEFAULT nextval(('cohist_cohist_id_seq'::text)::regclass) NOT NULL,
95183     cohist_cust_id integer,
95184     cohist_itemsite_id integer,
95185     cohist_shipdate date,
95186     cohist_shipvia text,
95187     cohist_ordernumber text,
95188     cohist_orderdate date,
95189     cohist_invcnumber text,
95190     cohist_invcdate date,
95191     cohist_qtyshipped numeric(18,6),
95192     cohist_unitprice numeric(16,4),
95193     cohist_shipto_id integer,
95194     cohist_salesrep_id integer,
95195     cohist_duedate date,
95196     cohist_imported boolean DEFAULT false,
95197     cohist_billtoname text,
95198     cohist_billtoaddress1 text,
95199     cohist_billtoaddress2 text,
95200     cohist_billtoaddress3 text,
95201     cohist_billtocity text,
95202     cohist_billtostate text,
95203     cohist_billtozip text,
95204     cohist_shiptoname text,
95205     cohist_shiptoaddress1 text,
95206     cohist_shiptoaddress2 text,
95207     cohist_shiptoaddress3 text,
95208     cohist_shiptocity text,
95209     cohist_shiptostate text,
95210     cohist_shiptozip text,
95211     cohist_commission numeric(16,4),
95212     cohist_commissionpaid boolean,
95213     cohist_unitcost numeric(18,6),
95214     cohist_misc_type character(1),
95215     cohist_misc_descrip text,
95216     cohist_misc_id integer,
95217     cohist_doctype text,
95218     cohist_promisedate date,
95219     cohist_ponumber text,
95220     cohist_curr_id integer DEFAULT basecurrid(),
95221     cohist_sequence integer,
95222     cohist_taxtype_id integer,
95223     cohist_taxzone_id integer,
95224     cohist_cohead_ccpay_id integer,
95225     cohist_saletype_id integer,
95226     cohist_shipzone_id integer
95227 );
95228
95229
95230 ALTER TABLE public.cohist OWNER TO admin;
95231
95232 --
95233 -- TOC entry 9391 (class 0 OID 0)
95234 -- Dependencies: 376
95235 -- Name: TABLE cohist; Type: COMMENT; Schema: public; Owner: admin
95236 --
95237
95238 COMMENT ON TABLE cohist IS 'Sales Order history';
95239
95240
95241 --
95242 -- TOC entry 9392 (class 0 OID 0)
95243 -- Dependencies: 376
95244 -- Name: COLUMN cohist.cohist_cohead_ccpay_id; Type: COMMENT; Schema: public; Owner: admin
95245 --
95246
95247 COMMENT ON COLUMN cohist.cohist_cohead_ccpay_id IS 'Credit card payments made at sales order time (as opposed to invoice time) need special treatment. This field allows checking for this case.';
95248
95249
95250 --
95251 -- TOC entry 9393 (class 0 OID 0)
95252 -- Dependencies: 376
95253 -- Name: COLUMN cohist.cohist_saletype_id; Type: COMMENT; Schema: public; Owner: admin
95254 --
95255
95256 COMMENT ON COLUMN cohist.cohist_saletype_id IS 'Associated sale type for sales history.';
95257
95258
95259 --
95260 -- TOC entry 9394 (class 0 OID 0)
95261 -- Dependencies: 376
95262 -- Name: COLUMN cohist.cohist_shipzone_id; Type: COMMENT; Schema: public; Owner: admin
95263 --
95264
95265 COMMENT ON COLUMN cohist.cohist_shipzone_id IS 'Associated shipping zone for sales history.';
95266
95267
95268 --
95269 -- TOC entry 377 (class 1259 OID 146568106)
95270 -- Dependencies: 8
95271 -- Name: taxhist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95272 --
95273
95274 CREATE TABLE taxhist (
95275     taxhist_id integer NOT NULL,
95276     taxhist_parent_id integer NOT NULL,
95277     taxhist_taxtype_id integer,
95278     taxhist_tax_id integer NOT NULL,
95279     taxhist_basis numeric(16,2) NOT NULL,
95280     taxhist_basis_tax_id integer,
95281     taxhist_sequence integer,
95282     taxhist_percent numeric(10,6) NOT NULL,
95283     taxhist_amount numeric(16,2) NOT NULL,
95284     taxhist_tax numeric(16,6) NOT NULL,
95285     taxhist_docdate date NOT NULL,
95286     taxhist_distdate date,
95287     taxhist_curr_id integer,
95288     taxhist_curr_rate numeric,
95289     taxhist_journalnumber integer
95290 );
95291
95292
95293 ALTER TABLE public.taxhist OWNER TO admin;
95294
95295 --
95296 -- TOC entry 9396 (class 0 OID 0)
95297 -- Dependencies: 377
95298 -- Name: TABLE taxhist; Type: COMMENT; Schema: public; Owner: admin
95299 --
95300
95301 COMMENT ON TABLE taxhist IS 'A table type to record tax transaction history. Inherited by other tables that actually record history. As the parent, queries can be run against it that will join all child tables. ';
95302
95303
95304 --
95305 -- TOC entry 9397 (class 0 OID 0)
95306 -- Dependencies: 377
95307 -- Name: COLUMN taxhist.taxhist_id; Type: COMMENT; Schema: public; Owner: admin
95308 --
95309
95310 COMMENT ON COLUMN taxhist.taxhist_id IS 'Primary key';
95311
95312
95313 --
95314 -- TOC entry 9398 (class 0 OID 0)
95315 -- Dependencies: 377
95316 -- Name: COLUMN taxhist.taxhist_parent_id; Type: COMMENT; Schema: public; Owner: admin
95317 --
95318
95319 COMMENT ON COLUMN taxhist.taxhist_parent_id IS 'Source parent id.';
95320
95321
95322 --
95323 -- TOC entry 9399 (class 0 OID 0)
95324 -- Dependencies: 377
95325 -- Name: COLUMN taxhist.taxhist_taxtype_id; Type: COMMENT; Schema: public; Owner: admin
95326 --
95327
95328 COMMENT ON COLUMN taxhist.taxhist_taxtype_id IS 'Tax type id';
95329
95330
95331 --
95332 -- TOC entry 9400 (class 0 OID 0)
95333 -- Dependencies: 377
95334 -- Name: COLUMN taxhist.taxhist_tax_id; Type: COMMENT; Schema: public; Owner: admin
95335 --
95336
95337 COMMENT ON COLUMN taxhist.taxhist_tax_id IS 'Tax code id.';
95338
95339
95340 --
95341 -- TOC entry 9401 (class 0 OID 0)
95342 -- Dependencies: 377
95343 -- Name: COLUMN taxhist.taxhist_basis; Type: COMMENT; Schema: public; Owner: admin
95344 --
95345
95346 COMMENT ON COLUMN taxhist.taxhist_basis IS 'Base price amount on which the tax calculation is based.';
95347
95348
95349 --
95350 -- TOC entry 9402 (class 0 OID 0)
95351 -- Dependencies: 377
95352 -- Name: COLUMN taxhist.taxhist_basis_tax_id; Type: COMMENT; Schema: public; Owner: admin
95353 --
95354
95355 COMMENT ON COLUMN taxhist.taxhist_basis_tax_id IS 'Tax rate calculation basis.  If null, then the amount of the parent document, otherwise calculated on the result amount of the tax code id referenced.';
95356
95357
95358 --
95359 -- TOC entry 9403 (class 0 OID 0)
95360 -- Dependencies: 377
95361 -- Name: COLUMN taxhist.taxhist_amount; Type: COMMENT; Schema: public; Owner: admin
95362 --
95363
95364 COMMENT ON COLUMN taxhist.taxhist_amount IS 'Flat tax amount.';
95365
95366
95367 --
95368 -- TOC entry 9404 (class 0 OID 0)
95369 -- Dependencies: 377
95370 -- Name: COLUMN taxhist.taxhist_tax; Type: COMMENT; Schema: public; Owner: admin
95371 --
95372
95373 COMMENT ON COLUMN taxhist.taxhist_tax IS 'Calculated tax amount.';
95374
95375
95376 --
95377 -- TOC entry 9405 (class 0 OID 0)
95378 -- Dependencies: 377
95379 -- Name: COLUMN taxhist.taxhist_docdate; Type: COMMENT; Schema: public; Owner: admin
95380 --
95381
95382 COMMENT ON COLUMN taxhist.taxhist_docdate IS 'The date of the parent document.';
95383
95384
95385 --
95386 -- TOC entry 9406 (class 0 OID 0)
95387 -- Dependencies: 377
95388 -- Name: COLUMN taxhist.taxhist_distdate; Type: COMMENT; Schema: public; Owner: admin
95389 --
95390
95391 COMMENT ON COLUMN taxhist.taxhist_distdate IS 'The G/L distribution date of the parent document.';
95392
95393
95394 --
95395 -- TOC entry 379 (class 1259 OID 146568114)
95396 -- Dependencies: 377 8
95397 -- Name: cohisttax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95398 --
95399
95400 CREATE TABLE cohisttax (
95401 )
95402 INHERITS (taxhist);
95403
95404
95405 ALTER TABLE public.cohisttax OWNER TO admin;
95406
95407 SET search_path = api, pg_catalog;
95408
95409 --
95410 -- TOC entry 380 (class 1259 OID 146568120)
95411 -- Dependencies: 8553 6
95412 -- Name: saleshistory; Type: VIEW; Schema: api; Owner: admin
95413 --
95414
95415 CREATE VIEW saleshistory AS
95416     SELECT custinfo.cust_number AS customer_number, item.item_number, whsinfo.warehous_code AS site_code, cohist.cohist_shipdate AS ship_date, cohist.cohist_shipvia AS ship_via, cohist.cohist_ordernumber AS order_number, cohist.cohist_ponumber AS purchase_order_number, cohist.cohist_orderdate AS order_date, cohist.cohist_invcnumber AS invoice_number, cohist.cohist_invcdate AS invoice_date, cohist.cohist_qtyshipped AS quantity_shipped, cohist.cohist_unitprice AS unit_price, shiptoinfo.shipto_num AS shipto_number, salesrep.salesrep_number AS sales_rep, cohist.cohist_duedate AS due_date, cohist.cohist_promisedate AS promise_date, cohist.cohist_imported AS imported, cohist.cohist_billtoname AS billto_name, cohist.cohist_billtoaddress1 AS billto_address1, cohist.cohist_billtoaddress2 AS billto_address2, cohist.cohist_billtoaddress3 AS billto_address3, cohist.cohist_billtocity AS billto_city, cohist.cohist_billtostate AS billto_state, cohist.cohist_billtozip AS billto_zip, cohist.cohist_shiptoname AS shipto_name, cohist.cohist_shiptoaddress1 AS shipto_address1, cohist.cohist_shiptoaddress2 AS shipto_address2, cohist.cohist_shiptoaddress3 AS shipto_address3, cohist.cohist_shiptocity AS shipto_city, cohist.cohist_shiptostate AS shipto_state, cohist.cohist_shiptozip AS shipto_zip, cohist.cohist_commission AS commission, cohist.cohist_commissionpaid AS commission_paid, cohist.cohist_unitcost AS unit_cost, CASE WHEN (cohist.cohist_misc_type IS NULL) THEN ''::text WHEN (cohist.cohist_misc_type = 'M'::bpchar) THEN 'Misc. Charge'::text WHEN (cohist.cohist_misc_type = 'F'::bpchar) THEN 'Freight'::text ELSE 'Unknown'::text END AS misc_type, cohist.cohist_misc_descrip AS misc_description, CASE WHEN (cohist.cohist_misc_id IS NULL) THEN ''::text WHEN (cohist.cohist_misc_type = 'M'::bpchar) THEN public.formatglaccount(cohist.cohist_misc_id) ELSE 'Unknown'::text END AS misc_info, taxzone.taxzone_code AS tax_zone, taxtype.taxtype_name AS tax_type, CASE WHEN (cohist.cohist_doctype = 'I'::text) THEN 'Invoice'::text WHEN (cohist.cohist_doctype = 'C'::text) THEN 'Credit Memo'::text ELSE 'Unknown'::text END AS document_type, curr_symbol.curr_abbr AS currency, cohist.cohist_sequence AS gl_sequence, (SELECT sum(cohisttax.taxhist_tax) AS sum FROM public.cohisttax WHERE (cohisttax.taxhist_parent_id = cohist.cohist_id)) AS tax FROM (((((((((public.cohist LEFT JOIN public.custinfo ON ((cohist.cohist_cust_id = custinfo.cust_id))) LEFT JOIN public.shiptoinfo ON ((cohist.cohist_shipto_id = shiptoinfo.shipto_id))) LEFT JOIN public.taxzone ON ((cohist.cohist_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.taxtype ON ((cohist.cohist_taxtype_id = taxtype.taxtype_id))) LEFT JOIN public.salesrep ON ((cohist.cohist_salesrep_id = salesrep.salesrep_id))) LEFT JOIN public.itemsite ON ((cohist.cohist_itemsite_id = itemsite.itemsite_id))) LEFT JOIN public.item ON ((itemsite.itemsite_item_id = item.item_id))) LEFT JOIN public.whsinfo ON ((itemsite.itemsite_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.curr_symbol ON ((cohist.cohist_curr_id = curr_symbol.curr_id)));
95417
95418
95419 ALTER TABLE api.saleshistory OWNER TO admin;
95420
95421 --
95422 -- TOC entry 9409 (class 0 OID 0)
95423 -- Dependencies: 380
95424 -- Name: VIEW saleshistory; Type: COMMENT; Schema: api; Owner: admin
95425 --
95426
95427 COMMENT ON VIEW saleshistory IS 'Sales History';
95428
95429
95430 --
95431 -- TOC entry 381 (class 1259 OID 146568125)
95432 -- Dependencies: 8554 6
95433 -- Name: saleslinechar; Type: VIEW; Schema: api; Owner: admin
95434 --
95435
95436 CREATE VIEW saleslinechar AS
95437     SELECT (data.order_number)::character varying AS order_number, data.line_number, data.characteristic, COALESCE(si.charass_value, i3.charass_value) AS value, (COALESCE(si.charass_price, public.itemcharprice(data.item_id, data.char_id, COALESCE(si.charass_value, i3.charass_value), data.cohead_cust_id, data.cohead_shipto_id, data.coitem_qtyord, data.cohead_curr_id, data.cohead_orderdate), (0)::numeric))::numeric(16,4) AS price FROM (((((SELECT DISTINCT cohead.cohead_cust_id, cohead.cohead_shipto_id, cohead.cohead_curr_id, cohead.cohead_orderdate, coitem.coitem_id, coitem.coitem_itemsite_id, coitem.coitem_qtyord, "char".char_id, item.item_id, cohead.cohead_number AS order_number, CASE WHEN (coitem.coitem_subnumber = 0) THEN ((coitem.coitem_linenumber)::character varying)::text ELSE ((((coitem.coitem_linenumber)::character varying)::text || ('.'::character varying)::text) || ((coitem.coitem_subnumber)::character varying)::text) END AS line_number, "char".char_name AS characteristic FROM public.cohead, public.coitem, public.itemsite, public.item, public.charass, public."char" WHERE ((((((cohead.cohead_id = coitem.coitem_cohead_id) AND (coitem.coitem_itemsite_id = itemsite.itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id)) AND (charass.charass_char_id = "char".char_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id))) data LEFT JOIN public.charass si ON ((((data.coitem_id = si.charass_target_id) AND ('SI'::text = si.charass_target_type)) AND (si.charass_char_id = data.char_id)))) LEFT JOIN public.itemsite i1 ON ((data.coitem_itemsite_id = i1.itemsite_id))) LEFT JOIN public.item i2 ON ((i1.itemsite_item_id = i2.item_id))) LEFT JOIN public.charass i3 ON (((((i2.item_id = i3.charass_target_id) AND ('I'::text = i3.charass_target_type)) AND (i3.charass_char_id = data.char_id)) AND i3.charass_default))) ORDER BY (data.order_number)::character varying, data.line_number, data.characteristic;
95438
95439
95440 ALTER TABLE api.saleslinechar OWNER TO admin;
95441
95442 --
95443 -- TOC entry 9411 (class 0 OID 0)
95444 -- Dependencies: 381
95445 -- Name: VIEW saleslinechar; Type: COMMENT; Schema: api; Owner: admin
95446 --
95447
95448 COMMENT ON VIEW saleslinechar IS 'Sales Order Line Item Characteristic';
95449
95450
95451 --
95452 -- TOC entry 382 (class 1259 OID 146568130)
95453 -- Dependencies: 8555 6
95454 -- Name: saleslinecomment; Type: VIEW; Schema: api; Owner: admin
95455 --
95456
95457 CREATE VIEW saleslinecomment AS
95458     SELECT (cohead.cohead_number)::character varying AS order_number, CASE WHEN (coitem.coitem_subnumber = 0) THEN ((coitem.coitem_linenumber)::character varying)::text ELSE ((((coitem.coitem_linenumber)::character varying)::text || ('.'::character varying)::text) || ((coitem.coitem_subnumber)::character varying)::text) END AS line_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.cohead, public.coitem, public.cmnttype, public.comment WHERE ((((cohead.cohead_id = coitem.coitem_cohead_id) AND (comment.comment_source = 'SI'::text)) AND (comment.comment_source_id = coitem.coitem_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id)) ORDER BY cohead.cohead_number, coitem.coitem_linenumber, comment.comment_date DESC;
95459
95460
95461 ALTER TABLE api.saleslinecomment OWNER TO admin;
95462
95463 --
95464 -- TOC entry 9413 (class 0 OID 0)
95465 -- Dependencies: 382
95466 -- Name: VIEW saleslinecomment; Type: COMMENT; Schema: api; Owner: admin
95467 --
95468
95469 COMMENT ON VIEW saleslinecomment IS 'Sales Order Line Item Comment';
95470
95471
95472 --
95473 -- TOC entry 383 (class 1259 OID 146568135)
95474 -- Dependencies: 8556 6
95475 -- Name: salesorder; Type: VIEW; Schema: api; Owner: admin
95476 --
95477
95478 CREATE VIEW salesorder AS
95479     SELECT (cohead.cohead_number)::character varying AS order_number, whsinfo.warehous_code AS site, cohead.cohead_orderdate AS order_date, cohead.cohead_packdate AS pack_date, saletype.saletype_code AS sale_type, salesrep.salesrep_number AS sales_rep, cohead.cohead_commission AS commission, COALESCE(taxzone.taxzone_code, 'None'::text) AS tax_zone, terms.terms_code AS terms, prj.prj_number AS project_number, custinfo.cust_number AS customer_number, bc.cntct_number AS billto_contact_number, cohead.cohead_billto_cntct_honorific AS billto_contact_name, cohead.cohead_billto_cntct_first_name AS billto_contact_first, cohead.cohead_billto_cntct_middle AS billto_contact_middle, cohead.cohead_billto_cntct_last_name AS billto_contact_last, cohead.cohead_billto_cntct_suffix AS billto_contact_suffix, cohead.cohead_billto_cntct_phone AS billto_contact_phone, cohead.cohead_billto_cntct_title AS billto_contact_title, cohead.cohead_billto_cntct_fax AS billto_contct_fax, cohead.cohead_billto_cntct_email AS billto_contact_email, cohead.cohead_billtoname AS billto_name, cohead.cohead_billtoaddress1 AS billto_address1, cohead.cohead_billtoaddress2 AS billto_address2, cohead.cohead_billtoaddress3 AS billto_address3, cohead.cohead_billtocity AS billto_city, cohead.cohead_billtostate AS billto_state, cohead.cohead_billtozipcode AS billto_postal_code, cohead.cohead_billtocountry AS billto_country, shiptoinfo.shipto_num AS shipto_number, sc.cntct_number AS shipto_contact_number, cohead.cohead_shipto_cntct_honorific AS shipto_contact_honorific, cohead.cohead_shipto_cntct_first_name AS shipto_contact_first, cohead.cohead_shipto_cntct_middle AS shipto_contact_middle, cohead.cohead_shipto_cntct_last_name AS shipto_contact_last, cohead.cohead_shipto_cntct_suffix AS shipto_contact_suffix, cohead.cohead_shipto_cntct_phone AS shipto_contact_phone, cohead.cohead_shipto_cntct_title AS shipto_contact_title, cohead.cohead_shipto_cntct_fax AS shipto_contact_fax, cohead.cohead_shipto_cntct_email AS shipto_contact_email, cohead.cohead_shiptoname AS shipto_name, cohead.cohead_shiptophone AS shipto_phone, cohead.cohead_shiptoaddress1 AS shipto_address1, cohead.cohead_shiptoaddress2 AS shipto_address2, cohead.cohead_shiptoaddress3 AS shipto_address3, cohead.cohead_shiptocity AS shipto_city, cohead.cohead_shiptostate AS shipto_state, cohead.cohead_shiptozipcode AS shipto_postal_code, cohead.cohead_shiptocountry AS shipto_country, shipzone.shipzone_name AS shipto_shipzone, cohead.cohead_custponumber AS cust_po_number, cohead.cohead_fob AS fob, cohead.cohead_shipvia AS ship_via, CASE WHEN (cohead.cohead_holdtype = 'N'::bpchar) THEN 'None'::text WHEN (cohead.cohead_holdtype = 'C'::bpchar) THEN 'Credit'::text WHEN (cohead.cohead_holdtype = 'S'::bpchar) THEN 'Shipping'::text WHEN (cohead.cohead_holdtype = 'P'::bpchar) THEN 'Packing'::text WHEN (cohead.cohead_holdtype = 'R'::bpchar) THEN 'Return'::text ELSE 'Error'::text END AS hold_type, shipchrg.shipchrg_name AS shipping_chgs, shipform.shipform_name AS shipping_form, cohead.cohead_shipcomplete AS ship_complete, curr_symbol.curr_abbr AS currency, cohead.cohead_misc_descrip AS misc_charge_description, CASE WHEN (cohead.cohead_misc_accnt_id IS NULL) THEN NULL::text ELSE public.formatglaccount(cohead.cohead_misc_accnt_id) END AS misc_account_number, cohead.cohead_misc AS misc_charge, cohead.cohead_freight AS freight, cohead.cohead_calcfreight AS calculate_freight, cohead.cohead_ordercomments AS order_notes, cohead.cohead_shipcomments AS shipping_notes, false AS add_to_packing_list_batch FROM (((((((((public.cohead LEFT JOIN public.cntct bc ON ((cohead.cohead_billto_cntct_id = bc.cntct_id))) LEFT JOIN public.cntct sc ON ((cohead.cohead_shipto_cntct_id = sc.cntct_id))) LEFT JOIN public.whsinfo ON ((cohead.cohead_warehous_id = whsinfo.warehous_id))) LEFT JOIN public.prj ON ((cohead.cohead_prj_id = prj.prj_id))) LEFT JOIN public.shiptoinfo ON ((cohead.cohead_shipto_id = shiptoinfo.shipto_id))) LEFT JOIN public.shipchrg ON ((cohead.cohead_shipchrg_id = shipchrg.shipchrg_id))) LEFT JOIN public.taxzone ON ((cohead.cohead_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.saletype ON ((cohead.cohead_saletype_id = saletype.saletype_id))) LEFT JOIN public.shipzone ON ((cohead.cohead_shipzone_id = shipzone.shipzone_id))), public.custinfo, public.shipform, public.salesrep, public.terms, public.curr_symbol WHERE (((((cohead.cohead_cust_id = custinfo.cust_id) AND (cohead.cohead_shipform_id = shipform.shipform_id)) AND (cohead.cohead_salesrep_id = salesrep.salesrep_id)) AND (cohead.cohead_terms_id = terms.terms_id)) AND (cohead.cohead_curr_id = curr_symbol.curr_id));
95480
95481
95482 ALTER TABLE api.salesorder OWNER TO admin;
95483
95484 --
95485 -- TOC entry 9415 (class 0 OID 0)
95486 -- Dependencies: 383
95487 -- Name: VIEW salesorder; Type: COMMENT; Schema: api; Owner: admin
95488 --
95489
95490 COMMENT ON VIEW salesorder IS 'Sales Order';
95491
95492
95493 --
95494 -- TOC entry 384 (class 1259 OID 146568140)
95495 -- Dependencies: 8557 6
95496 -- Name: salesordercomment; Type: VIEW; Schema: api; Owner: admin
95497 --
95498
95499 CREATE VIEW salesordercomment AS
95500     SELECT (cohead.cohead_number)::character varying AS order_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.cohead, public.cmnttype, public.comment WHERE (((comment.comment_source = 'S'::text) AND (comment.comment_source_id = cohead.cohead_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
95501
95502
95503 ALTER TABLE api.salesordercomment OWNER TO admin;
95504
95505 --
95506 -- TOC entry 9417 (class 0 OID 0)
95507 -- Dependencies: 384
95508 -- Name: VIEW salesordercomment; Type: COMMENT; Schema: api; Owner: admin
95509 --
95510
95511 COMMENT ON VIEW salesordercomment IS 'Sales Order Comment';
95512
95513
95514 --
95515 -- TOC entry 385 (class 1259 OID 146568145)
95516 -- Dependencies: 8558 6
95517 -- Name: salesrep; Type: VIEW; Schema: api; Owner: admin
95518 --
95519
95520 CREATE VIEW salesrep AS
95521     SELECT (salesrep.salesrep_number)::character varying AS number, salesrep.salesrep_active AS active, salesrep.salesrep_name AS name, (salesrep.salesrep_commission * (100)::numeric) AS commission_percent, emp.emp_number AS employee FROM (public.salesrep LEFT JOIN public.emp ON ((emp.emp_id = salesrep.salesrep_emp_id))) ORDER BY salesrep.salesrep_number;
95522
95523
95524 ALTER TABLE api.salesrep OWNER TO admin;
95525
95526 --
95527 -- TOC entry 9419 (class 0 OID 0)
95528 -- Dependencies: 385
95529 -- Name: VIEW salesrep; Type: COMMENT; Schema: api; Owner: admin
95530 --
95531
95532 COMMENT ON VIEW salesrep IS 'Sales Rep';
95533
95534
95535 SET search_path = public, pg_catalog;
95536
95537 --
95538 -- TOC entry 386 (class 1259 OID 146568150)
95539 -- Dependencies: 6259 6260 8
95540 -- Name: shipvia; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95541 --
95542
95543 CREATE TABLE shipvia (
95544     shipvia_id integer DEFAULT nextval(('shipvia_shipvia_id_seq'::text)::regclass) NOT NULL,
95545     shipvia_code text NOT NULL,
95546     shipvia_descrip text,
95547     CONSTRAINT shipvia_shipvia_code_check CHECK ((shipvia_code <> ''::text))
95548 );
95549
95550
95551 ALTER TABLE public.shipvia OWNER TO admin;
95552
95553 --
95554 -- TOC entry 9421 (class 0 OID 0)
95555 -- Dependencies: 386
95556 -- Name: TABLE shipvia; Type: COMMENT; Schema: public; Owner: admin
95557 --
95558
95559 COMMENT ON TABLE shipvia IS 'Ship Via information';
95560
95561
95562 --
95563 -- TOC entry 387 (class 1259 OID 146568158)
95564 -- Dependencies: 6262 8
95565 -- Name: sitetype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95566 --
95567
95568 CREATE TABLE sitetype (
95569     sitetype_id integer NOT NULL,
95570     sitetype_name text NOT NULL,
95571     sitetype_descrip text,
95572     CONSTRAINT sitetype_sitetype_name_check CHECK ((sitetype_name <> ''::text))
95573 );
95574
95575
95576 ALTER TABLE public.sitetype OWNER TO admin;
95577
95578 --
95579 -- TOC entry 9423 (class 0 OID 0)
95580 -- Dependencies: 387
95581 -- Name: TABLE sitetype; Type: COMMENT; Schema: public; Owner: admin
95582 --
95583
95584 COMMENT ON TABLE sitetype IS 'This table is the different types of sites.';
95585
95586
95587 SET search_path = api, pg_catalog;
95588
95589 --
95590 -- TOC entry 388 (class 1259 OID 146568165)
95591 -- Dependencies: 8559 6
95592 -- Name: site; Type: VIEW; Schema: api; Owner: admin
95593 --
95594
95595 CREATE VIEW site AS
95596     SELECT (whsinfo.warehous_code)::character varying AS code, st.sitetype_name AS type, whsinfo.warehous_active AS active, whsinfo.warehous_descrip AS description, m.addr_number AS address_number, m.addr_line1 AS address1, m.addr_line2 AS address2, m.addr_line3 AS address3, m.addr_city AS city, m.addr_state AS state, m.addr_postalcode AS postal_code, m.addr_country AS country, ''::text AS address_change, c.cntct_number AS contact_number, c.cntct_honorific AS honorific, c.cntct_first_name AS first, c.cntct_middle AS middle, c.cntct_last_name AS last, c.cntct_suffix AS suffix, c.cntct_title AS job_title, c.cntct_phone AS phone, c.cntct_fax AS fax, c.cntct_email AS email, ''::text AS contact_change, public.formatglaccount(a.accnt_id) AS post_unassigned_transactions_to, a.accnt_descrip AS post_unassigned_transactions_to_description, whsinfo.warehous_transit AS transit_type, CASE WHEN whsinfo.warehous_transit THEN false ELSE true END AS inventory_type, CASE WHEN whsinfo.warehous_transit THEN ''::text ELSE whsinfo.warehous_bol_prefix END AS next_bill_of_lading_prefix, CASE WHEN whsinfo.warehous_transit THEN 0 ELSE whsinfo.warehous_bol_number END AS next_bill_of_lading_number, CASE WHEN whsinfo.warehous_transit THEN false ELSE whsinfo.warehous_shipping END AS shipping_site, CASE WHEN whsinfo.warehous_transit THEN ''::text ELSE whsinfo.warehous_counttag_prefix END AS next_count_tag_prefix, CASE WHEN whsinfo.warehous_transit THEN 0 ELSE whsinfo.warehous_counttag_number END AS next_count_tag_number, CASE WHEN whsinfo.warehous_transit THEN false ELSE whsinfo.warehous_useslips END AS force_the_use_of_count_slips, CASE WHEN whsinfo.warehous_transit THEN false ELSE whsinfo.warehous_usezones END AS force_the_use_of_zones, CASE WHEN whsinfo.warehous_transit THEN 0 ELSE whsinfo.warehous_sequence END AS scheduling_sequence, CASE WHEN whsinfo.warehous_transit THEN (0)::numeric ELSE (whsinfo.warehous_shipping_commission * 100.0) END AS shipping_commission, CASE WHEN whsinfo.warehous_transit THEN ''::text ELSE t.taxzone_code END AS tax_zone, CASE WHEN whsinfo.warehous_transit THEN ''::text ELSE whsinfo.warehous_fob END AS default_fob, CASE WHEN whsinfo.warehous_transit THEN s.shipvia_code ELSE ''::text END AS default_ship_via, CASE WHEN whsinfo.warehous_transit THEN f.shipform_name ELSE ''::text END AS default_shipping_form, CASE WHEN whsinfo.warehous_transit THEN cc.costcat_code ELSE ''::text END AS default_cost_category, CASE WHEN whsinfo.warehous_transit THEN whsinfo.warehous_shipcomments ELSE ''::text END AS shipping_comments, CASE WHEN whsinfo.warehous_transit THEN false ELSE whsinfo.warehous_enforcearbl END AS enforce_arbl_naming_convention, CASE WHEN whsinfo.warehous_transit THEN 0 WHEN whsinfo.warehous_enforcearbl THEN whsinfo.warehous_aislesize ELSE 0 END AS aisle_size, CASE WHEN whsinfo.warehous_transit THEN false WHEN (whsinfo.warehous_enforcearbl AND whsinfo.warehous_aislealpha) THEN true ELSE false END AS aisle_allow_alpha_characters, CASE WHEN whsinfo.warehous_transit THEN 0 WHEN whsinfo.warehous_enforcearbl THEN whsinfo.warehous_racksize ELSE 0 END AS rack_size, CASE WHEN whsinfo.warehous_transit THEN false WHEN (whsinfo.warehous_enforcearbl AND whsinfo.warehous_rackalpha) THEN true ELSE false END AS rack_allow_alpha_characters, CASE WHEN whsinfo.warehous_transit THEN 0 WHEN whsinfo.warehous_enforcearbl THEN whsinfo.warehous_binsize ELSE 0 END AS bin_size, CASE WHEN whsinfo.warehous_transit THEN false WHEN (whsinfo.warehous_enforcearbl AND whsinfo.warehous_binalpha) THEN true ELSE false END AS bin_allow_alpha_characters, CASE WHEN whsinfo.warehous_transit THEN 0 WHEN whsinfo.warehous_enforcearbl THEN whsinfo.warehous_locationsize ELSE 0 END AS location_size, CASE WHEN whsinfo.warehous_transit THEN false WHEN (whsinfo.warehous_enforcearbl AND whsinfo.warehous_locationalpha) THEN true ELSE false END AS location_allow_alpha_characters FROM ((((((((public.whsinfo LEFT JOIN public.addr m ON ((whsinfo.warehous_addr_id = m.addr_id))) LEFT JOIN public.cntct c ON ((whsinfo.warehous_cntct_id = c.cntct_id))) LEFT JOIN public.accnt a ON ((whsinfo.warehous_default_accnt_id = a.accnt_id))) LEFT JOIN public.taxzone t ON ((whsinfo.warehous_taxzone_id = t.taxzone_id))) LEFT JOIN public.shipvia s ON ((whsinfo.warehous_shipvia_id = s.shipvia_id))) LEFT JOIN public.shipform f ON ((whsinfo.warehous_shipform_id = f.shipform_id))) LEFT JOIN public.costcat cc ON ((whsinfo.warehous_costcat_id = cc.costcat_id))) LEFT JOIN public.sitetype st ON ((whsinfo.warehous_sitetype_id = st.sitetype_id))) ORDER BY whsinfo.warehous_code;
95597
95598
95599 ALTER TABLE api.site OWNER TO admin;
95600
95601 --
95602 -- TOC entry 9425 (class 0 OID 0)
95603 -- Dependencies: 388
95604 -- Name: VIEW site; Type: COMMENT; Schema: api; Owner: admin
95605 --
95606
95607 COMMENT ON VIEW site IS 'Site';
95608
95609
95610 --
95611 -- TOC entry 389 (class 1259 OID 146568170)
95612 -- Dependencies: 8560 6
95613 -- Name: sitezone; Type: VIEW; Schema: api; Owner: admin
95614 --
95615
95616 CREATE VIEW sitezone AS
95617     SELECT (whsinfo.warehous_code)::character varying AS site, (whsezone.whsezone_name)::character varying AS name, whsezone.whsezone_descrip AS description FROM (public.whsezone LEFT JOIN public.whsinfo ON ((whsinfo.warehous_id = whsezone.whsezone_warehous_id)));
95618
95619
95620 ALTER TABLE api.sitezone OWNER TO admin;
95621
95622 --
95623 -- TOC entry 9427 (class 0 OID 0)
95624 -- Dependencies: 389
95625 -- Name: VIEW sitezone; Type: COMMENT; Schema: api; Owner: admin
95626 --
95627
95628 COMMENT ON VIEW sitezone IS 'Site Zone';
95629
95630
95631 --
95632 -- TOC entry 390 (class 1259 OID 146568175)
95633 -- Dependencies: 8561 6
95634 -- Name: task; Type: VIEW; Schema: api; Owner: admin
95635 --
95636
95637 CREATE VIEW task AS
95638     SELECT prj.prj_number AS project_number, prjtask.prjtask_number AS number, CASE WHEN (prjtask.prjtask_status = 'P'::bpchar) THEN 'Concept'::text WHEN (prjtask.prjtask_status = 'O'::bpchar) THEN 'In-Process'::text WHEN (prjtask.prjtask_status = 'C'::bpchar) THEN 'Closed'::text ELSE 'Error'::text END AS status, prjtask.prjtask_name AS name, prjtask.prjtask_descrip AS description, prjtask.prjtask_owner_username AS owner, prjtask.prjtask_username AS assigned_to, prjtask.prjtask_hours_budget AS hours_budgeted, prjtask.prjtask_hours_actual AS hours_actual, prjtask.prjtask_exp_budget AS expenses_budgeted, prjtask.prjtask_exp_actual AS expenses_actual, prjtask.prjtask_due_date AS due, prjtask.prjtask_assigned_date AS assigned, prjtask.prjtask_start_date AS started, prjtask.prjtask_completed_date AS completed FROM (public.prjtask JOIN public.prj ON ((prj.prj_id = prjtask.prjtask_prj_id)));
95639
95640
95641 ALTER TABLE api.task OWNER TO admin;
95642
95643 --
95644 -- TOC entry 9429 (class 0 OID 0)
95645 -- Dependencies: 390
95646 -- Name: VIEW task; Type: COMMENT; Schema: api; Owner: admin
95647 --
95648
95649 COMMENT ON VIEW task IS 'Task';
95650
95651
95652 --
95653 -- TOC entry 391 (class 1259 OID 146568180)
95654 -- Dependencies: 8562 6
95655 -- Name: taskcomment; Type: VIEW; Schema: api; Owner: admin
95656 --
95657
95658 CREATE VIEW taskcomment AS
95659     SELECT (prj.prj_number)::character varying AS project_number, (prjtask.prjtask_number)::character varying AS task_number, cmnttype.cmnttype_name AS type, comment.comment_date AS date, comment.comment_user AS username, comment.comment_text AS text FROM public.prj, public.prjtask, public.cmnttype, public.comment WHERE ((((comment.comment_source = 'TA'::text) AND (prj.prj_id = prjtask.prjtask_prj_id)) AND (comment.comment_source_id = prjtask.prjtask_id)) AND (comment.comment_cmnttype_id = cmnttype.cmnttype_id));
95660
95661
95662 ALTER TABLE api.taskcomment OWNER TO admin;
95663
95664 --
95665 -- TOC entry 9431 (class 0 OID 0)
95666 -- Dependencies: 391
95667 -- Name: VIEW taskcomment; Type: COMMENT; Schema: api; Owner: admin
95668 --
95669
95670 COMMENT ON VIEW taskcomment IS 'Task Comment';
95671
95672
95673 --
95674 -- TOC entry 392 (class 1259 OID 146568184)
95675 -- Dependencies: 8563 6
95676 -- Name: todo; Type: VIEW; Schema: api; Owner: admin
95677 --
95678
95679 CREATE VIEW todo AS
95680     SELECT todoitem.todoitem_id AS task_number, todoitem.todoitem_owner_username AS owner, todoitem.todoitem_username AS assigned_to, todoitem.todoitem_name AS task_name, incdtpriority.incdtpriority_name AS priority, incdt.incdt_number AS incident, ophead.ophead_name AS opportunity, crmacct.crmacct_number AS account, public.formatdate(todoitem.todoitem_due_date) AS date_due, public.formatdate(todoitem.todoitem_assigned_date) AS date_assigned, public.formatdate(todoitem.todoitem_start_date) AS date_started, public.formatdate(todoitem.todoitem_completed_date) AS date_completed, CASE WHEN (todoitem.todoitem_status = 'P'::bpchar) THEN 'Pending Input'::text WHEN (todoitem.todoitem_status = 'D'::bpchar) THEN 'Deferred'::text ELSE 'Neither'::text END AS status, todoitem.todoitem_active AS active, todoitem.todoitem_description AS description, todoitem.todoitem_notes AS notes FROM ((((public.todoitem LEFT JOIN public.incdt ON ((incdt.incdt_id = todoitem.todoitem_incdt_id))) LEFT JOIN public.ophead ON ((ophead.ophead_id = todoitem.todoitem_ophead_id))) LEFT JOIN public.crmacct ON ((crmacct.crmacct_id = todoitem.todoitem_crmacct_id))) LEFT JOIN public.incdtpriority ON ((incdtpriority.incdtpriority_id = todoitem.todoitem_priority_id)));
95681
95682
95683 ALTER TABLE api.todo OWNER TO admin;
95684
95685 --
95686 -- TOC entry 9433 (class 0 OID 0)
95687 -- Dependencies: 392
95688 -- Name: VIEW todo; Type: COMMENT; Schema: api; Owner: admin
95689 --
95690
95691 COMMENT ON VIEW todo IS 'To-Do List';
95692
95693
95694 SET search_path = public, pg_catalog;
95695
95696 --
95697 -- TOC entry 393 (class 1259 OID 146568189)
95698 -- Dependencies: 6264 8
95699 -- Name: vendtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95700 --
95701
95702 CREATE TABLE vendtype (
95703     vendtype_id integer NOT NULL,
95704     vendtype_code text NOT NULL,
95705     vendtype_descrip text,
95706     CONSTRAINT vendtype_vendtype_code_check CHECK ((vendtype_code <> ''::text))
95707 );
95708
95709
95710 ALTER TABLE public.vendtype OWNER TO admin;
95711
95712 --
95713 -- TOC entry 9435 (class 0 OID 0)
95714 -- Dependencies: 393
95715 -- Name: TABLE vendtype; Type: COMMENT; Schema: public; Owner: admin
95716 --
95717
95718 COMMENT ON TABLE vendtype IS 'Vendor Type information';
95719
95720
95721 SET search_path = api, pg_catalog;
95722
95723 --
95724 -- TOC entry 394 (class 1259 OID 146568196)
95725 -- Dependencies: 8564 6
95726 -- Name: vendor; Type: VIEW; Schema: api; Owner: admin
95727 --
95728
95729 CREATE VIEW vendor AS
95730     SELECT (vendinfo.vend_number)::character varying AS vendor_number, vendtype.vendtype_code AS vendor_type, vendinfo.vend_name AS vendor_name, vendinfo.vend_active AS active, vendinfo.vend_accntnum AS account_number, addr.addr_number AS address_number, addr.addr_line1 AS address1, addr.addr_line2 AS address2, addr.addr_line3 AS address3, addr.addr_city AS city, addr.addr_state AS state, addr.addr_postalcode AS postalcode, addr.addr_country AS country, ''::text AS address_change, terms.terms_code AS default_terms, vendinfo.vend_shipvia AS ship_via, curr_symbol.curr_abbr AS default_currency, CASE WHEN (vendinfo.vend_fobsource = 'W'::bpchar) THEN 'Receiving Site'::text ELSE vendinfo.vend_fob END AS default_fob, vendinfo.vend_po AS sells_purchase_order_items, vendinfo.vend_restrictpurch AS may_only_sell_item_source, vendinfo.vend_qualified AS qualified, vendinfo.vend_match AS matching_vo_po_amounts, vendinfo.vend_1099 AS receives_1099, taxzone.taxzone_code AS default_tax_zone, CASE WHEN (accnt.accnt_id IS NULL) THEN 'N/A'::text ELSE public.formatglaccount(accnt.accnt_id) END AS default_dist_gl_account, CASE WHEN (expcat.expcat_id IS NULL) THEN 'N/A'::text ELSE expcat.expcat_code END AS default_dist_expense_category, CASE WHEN (tax.tax_id IS NULL) THEN 'N/A'::text ELSE tax.tax_code END AS default_dist_tax_code, c1.cntct_number AS contact1_number, c1.cntct_honorific AS contact1_honorific, c1.cntct_first_name AS contact1_first, c1.cntct_middle AS contact1_middle, c1.cntct_last_name AS contact1_last, c1.cntct_suffix AS contact1_suffix, c1.cntct_title AS contact1_job_title, c1.cntct_phone AS contact1_voice, c1.cntct_phone2 AS contact1_alternate, c1.cntct_fax AS contact1_fax, c1.cntct_email AS contact1_email, c1.cntct_webaddr AS contact1_web, ''::text AS contact1_change, c2.cntct_number AS contact2_number, c2.cntct_honorific AS contact2_honorific, c2.cntct_first_name AS contact2_first, c2.cntct_middle AS contact2_middle, c2.cntct_last_name AS contact2_last, c2.cntct_suffix AS contact2_suffix, c2.cntct_title AS contact2_job_title, c2.cntct_phone AS contact2_voice, c2.cntct_phone2 AS contact2_alternate, c2.cntct_fax AS contact2_fax, c2.cntct_email AS contact2_email, c2.cntct_webaddr AS contact2_web, ''::text AS contact2_change, vendinfo.vend_comments AS notes, vendinfo.vend_pocomments AS po_comments, vendinfo.vend_emailpodelivery AS allow_email_po_delivery, vendinfo.vend_ediemail AS po_edi_email, vendinfo.vend_edicc AS po_edi_cc, vendinfo.vend_edisubject AS po_edi_subject, vendinfo.vend_edifilename AS po_edi_filename, vendinfo.vend_ediemailbody AS po_edi_emailbody FROM ((((((((((public.vendinfo LEFT JOIN public.addr ON ((vendinfo.vend_addr_id = addr.addr_id))) LEFT JOIN public.cntct c1 ON ((vendinfo.vend_cntct1_id = c1.cntct_id))) LEFT JOIN public.cntct c2 ON ((vendinfo.vend_cntct2_id = c2.cntct_id))) LEFT JOIN public.taxzone ON ((vendinfo.vend_taxzone_id = taxzone.taxzone_id))) LEFT JOIN public.curr_symbol ON ((vendinfo.vend_curr_id = curr_symbol.curr_id))) LEFT JOIN public.terms ON ((vendinfo.vend_terms_id = terms.terms_id))) LEFT JOIN public.vendtype ON ((vendinfo.vend_vendtype_id = vendtype.vendtype_id))) LEFT JOIN public.accnt ON ((vendinfo.vend_accnt_id = accnt.accnt_id))) LEFT JOIN public.expcat ON ((vendinfo.vend_expcat_id = expcat.expcat_id))) LEFT JOIN public.tax ON ((vendinfo.vend_tax_id = tax.tax_id))) ORDER BY vendinfo.vend_number;
95731
95732
95733 ALTER TABLE api.vendor OWNER TO admin;
95734
95735 --
95736 -- TOC entry 9437 (class 0 OID 0)
95737 -- Dependencies: 394
95738 -- Name: VIEW vendor; Type: COMMENT; Schema: api; Owner: admin
95739 --
95740
95741 COMMENT ON VIEW vendor IS 'vendor';
95742
95743
95744 --
95745 -- TOC entry 395 (class 1259 OID 146568201)
95746 -- Dependencies: 8565 6
95747 -- Name: vendoraddress; Type: VIEW; Schema: api; Owner: admin
95748 --
95749
95750 CREATE VIEW vendoraddress AS
95751     SELECT (vendinfo.vend_number)::character varying AS vendor_number, vendinfo.vend_name AS vendor_name, (vendaddrinfo.vendaddr_code)::character varying AS vendor_address_number, vendaddrinfo.vendaddr_name AS vendor_address_name, addr.addr_number AS address_number, addr.addr_line1 AS address1, addr.addr_line2 AS address2, addr.addr_line3 AS address3, addr.addr_city AS city, addr.addr_state AS state, addr.addr_postalcode AS postalcode, addr.addr_country AS country, ''::text AS address_change, cntct.cntct_number AS contact_number, cntct.cntct_honorific AS contact_honorific, cntct.cntct_first_name AS contact_first, cntct.cntct_middle AS contact_middle, cntct.cntct_last_name AS contact_last, cntct.cntct_suffix AS contact_suffix, cntct.cntct_title AS contact_job_title, cntct.cntct_phone AS contact_voice, cntct.cntct_phone2 AS contact_alternate, cntct.cntct_fax AS contact_fax, cntct.cntct_email AS contact_email, cntct.cntct_webaddr AS contact_web, ''::text AS contact_change, vendaddrinfo.vendaddr_comments AS notes FROM (((public.vendaddrinfo LEFT JOIN public.vendinfo ON ((vendinfo.vend_id = vendaddrinfo.vendaddr_vend_id))) LEFT JOIN public.addr ON ((vendaddrinfo.vendaddr_addr_id = addr.addr_id))) LEFT JOIN public.cntct ON ((vendaddrinfo.vendaddr_cntct_id = cntct.cntct_id))) ORDER BY vendaddrinfo.vendaddr_code;
95752
95753
95754 ALTER TABLE api.vendoraddress OWNER TO admin;
95755
95756 --
95757 -- TOC entry 9439 (class 0 OID 0)
95758 -- Dependencies: 395
95759 -- Name: VIEW vendoraddress; Type: COMMENT; Schema: api; Owner: admin
95760 --
95761
95762 COMMENT ON VIEW vendoraddress IS 'vendor address';
95763
95764
95765 --
95766 -- TOC entry 396 (class 1259 OID 146568206)
95767 -- Dependencies: 8566 6
95768 -- Name: vendortype; Type: VIEW; Schema: api; Owner: admin
95769 --
95770
95771 CREATE VIEW vendortype AS
95772     SELECT (vendtype.vendtype_code)::character varying AS code, vendtype.vendtype_descrip AS description FROM public.vendtype ORDER BY vendtype.vendtype_code;
95773
95774
95775 ALTER TABLE api.vendortype OWNER TO admin;
95776
95777 --
95778 -- TOC entry 9441 (class 0 OID 0)
95779 -- Dependencies: 396
95780 -- Name: VIEW vendortype; Type: COMMENT; Schema: api; Owner: admin
95781 --
95782
95783 COMMENT ON VIEW vendortype IS 'Vendor Type';
95784
95785
95786 SET search_path = public, pg_catalog;
95787
95788 --
95789 -- TOC entry 397 (class 1259 OID 146568210)
95790 -- Dependencies: 8
95791 -- Name: cmd; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95792 --
95793
95794 CREATE TABLE cmd (
95795     cmd_id integer NOT NULL,
95796     cmd_module text NOT NULL,
95797     cmd_title text NOT NULL,
95798     cmd_descrip text,
95799     cmd_privname text,
95800     cmd_executable text NOT NULL,
95801     cmd_name text
95802 );
95803
95804
95805 ALTER TABLE public.cmd OWNER TO admin;
95806
95807 --
95808 -- TOC entry 9443 (class 0 OID 0)
95809 -- Dependencies: 397
95810 -- Name: TABLE cmd; Type: COMMENT; Schema: public; Owner: admin
95811 --
95812
95813 COMMENT ON TABLE cmd IS 'Custom menu command table.';
95814
95815
95816 --
95817 -- TOC entry 398 (class 1259 OID 146568216)
95818 -- Dependencies: 397 8
95819 -- Name: cmd_cmd_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
95820 --
95821
95822 CREATE SEQUENCE cmd_cmd_id_seq
95823     START WITH 1
95824     INCREMENT BY 1
95825     NO MINVALUE
95826     NO MAXVALUE
95827     CACHE 1;
95828
95829
95830 ALTER TABLE public.cmd_cmd_id_seq OWNER TO admin;
95831
95832 --
95833 -- TOC entry 9445 (class 0 OID 0)
95834 -- Dependencies: 398
95835 -- Name: cmd_cmd_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
95836 --
95837
95838 ALTER SEQUENCE cmd_cmd_id_seq OWNED BY cmd.cmd_id;
95839
95840
95841 SET search_path = fixcountry, pg_catalog;
95842
95843 --
95844 -- TOC entry 399 (class 1259 OID 146568219)
95845 -- Dependencies: 6266 397 7
95846 -- Name: pkgcmd; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
95847 --
95848
95849 CREATE TABLE pkgcmd (
95850     cmd_id integer DEFAULT nextval('public.cmd_cmd_id_seq'::regclass)
95851 )
95852 INHERITS (public.cmd);
95853
95854
95855 ALTER TABLE fixcountry.pkgcmd OWNER TO admin;
95856
95857 SET search_path = public, pg_catalog;
95858
95859 --
95860 -- TOC entry 400 (class 1259 OID 146568226)
95861 -- Dependencies: 8
95862 -- Name: cmdarg; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95863 --
95864
95865 CREATE TABLE cmdarg (
95866     cmdarg_id integer NOT NULL,
95867     cmdarg_cmd_id integer NOT NULL,
95868     cmdarg_order integer NOT NULL,
95869     cmdarg_arg text NOT NULL
95870 );
95871
95872
95873 ALTER TABLE public.cmdarg OWNER TO admin;
95874
95875 --
95876 -- TOC entry 9448 (class 0 OID 0)
95877 -- Dependencies: 400
95878 -- Name: TABLE cmdarg; Type: COMMENT; Schema: public; Owner: admin
95879 --
95880
95881 COMMENT ON TABLE cmdarg IS 'Command argument for custom menu command table.';
95882
95883
95884 --
95885 -- TOC entry 401 (class 1259 OID 146568232)
95886 -- Dependencies: 400 8
95887 -- Name: cmdarg_cmdarg_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
95888 --
95889
95890 CREATE SEQUENCE cmdarg_cmdarg_id_seq
95891     START WITH 1
95892     INCREMENT BY 1
95893     NO MINVALUE
95894     NO MAXVALUE
95895     CACHE 1;
95896
95897
95898 ALTER TABLE public.cmdarg_cmdarg_id_seq OWNER TO admin;
95899
95900 --
95901 -- TOC entry 9450 (class 0 OID 0)
95902 -- Dependencies: 401
95903 -- Name: cmdarg_cmdarg_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
95904 --
95905
95906 ALTER SEQUENCE cmdarg_cmdarg_id_seq OWNED BY cmdarg.cmdarg_id;
95907
95908
95909 SET search_path = fixcountry, pg_catalog;
95910
95911 --
95912 -- TOC entry 402 (class 1259 OID 146568235)
95913 -- Dependencies: 6268 400 7
95914 -- Name: pkgcmdarg; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
95915 --
95916
95917 CREATE TABLE pkgcmdarg (
95918     cmdarg_id integer DEFAULT nextval('public.cmdarg_cmdarg_id_seq'::regclass)
95919 )
95920 INHERITS (public.cmdarg);
95921
95922
95923 ALTER TABLE fixcountry.pkgcmdarg OWNER TO admin;
95924
95925 SET search_path = public, pg_catalog;
95926
95927 --
95928 -- TOC entry 403 (class 1259 OID 146568242)
95929 -- Dependencies: 8
95930 -- Name: image_image_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
95931 --
95932
95933 CREATE SEQUENCE image_image_id_seq
95934     START WITH 1
95935     INCREMENT BY 1
95936     NO MINVALUE
95937     MAXVALUE 2147483647
95938     CACHE 1;
95939
95940
95941 ALTER TABLE public.image_image_id_seq OWNER TO admin;
95942
95943 SET search_path = fixcountry, pg_catalog;
95944
95945 --
95946 -- TOC entry 404 (class 1259 OID 146568244)
95947 -- Dependencies: 6269 248 7
95948 -- Name: pkgimage; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
95949 --
95950
95951 CREATE TABLE pkgimage (
95952     image_id integer DEFAULT nextval('public.image_image_id_seq'::regclass)
95953 )
95954 INHERITS (public.image);
95955
95956
95957 ALTER TABLE fixcountry.pkgimage OWNER TO admin;
95958
95959 SET search_path = public, pg_catalog;
95960
95961 --
95962 -- TOC entry 405 (class 1259 OID 146568251)
95963 -- Dependencies: 6271 8
95964 -- Name: metasql; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
95965 --
95966
95967 CREATE TABLE metasql (
95968     metasql_id integer NOT NULL,
95969     metasql_group text,
95970     metasql_name text,
95971     metasql_notes text,
95972     metasql_query text,
95973     metasql_lastuser text,
95974     metasql_lastupdate date,
95975     metasql_grade integer DEFAULT 0 NOT NULL
95976 );
95977
95978
95979 ALTER TABLE public.metasql OWNER TO admin;
95980
95981 --
95982 -- TOC entry 9455 (class 0 OID 0)
95983 -- Dependencies: 405
95984 -- Name: TABLE metasql; Type: COMMENT; Schema: public; Owner: admin
95985 --
95986
95987 COMMENT ON TABLE metasql IS 'MetaSQL Table';
95988
95989
95990 --
95991 -- TOC entry 406 (class 1259 OID 146568258)
95992 -- Dependencies: 405 8
95993 -- Name: metasql_metasql_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
95994 --
95995
95996 CREATE SEQUENCE metasql_metasql_id_seq
95997     START WITH 1
95998     INCREMENT BY 1
95999     NO MINVALUE
96000     NO MAXVALUE
96001     CACHE 1;
96002
96003
96004 ALTER TABLE public.metasql_metasql_id_seq OWNER TO admin;
96005
96006 --
96007 -- TOC entry 9457 (class 0 OID 0)
96008 -- Dependencies: 406
96009 -- Name: metasql_metasql_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96010 --
96011
96012 ALTER SEQUENCE metasql_metasql_id_seq OWNED BY metasql.metasql_id;
96013
96014
96015 SET search_path = fixcountry, pg_catalog;
96016
96017 --
96018 -- TOC entry 407 (class 1259 OID 146568261)
96019 -- Dependencies: 6272 405 7
96020 -- Name: pkgmetasql; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
96021 --
96022
96023 CREATE TABLE pkgmetasql (
96024     metasql_id integer DEFAULT nextval('public.metasql_metasql_id_seq'::regclass)
96025 )
96026 INHERITS (public.metasql);
96027
96028
96029 ALTER TABLE fixcountry.pkgmetasql OWNER TO admin;
96030
96031 SET search_path = public, pg_catalog;
96032
96033 --
96034 -- TOC entry 408 (class 1259 OID 146568269)
96035 -- Dependencies: 6274 8
96036 -- Name: priv; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96037 --
96038
96039 CREATE TABLE priv (
96040     priv_id integer DEFAULT nextval(('priv_priv_id_seq'::text)::regclass) NOT NULL,
96041     priv_module text,
96042     priv_name text,
96043     priv_descrip text,
96044     priv_seq integer
96045 );
96046
96047
96048 ALTER TABLE public.priv OWNER TO admin;
96049
96050 --
96051 -- TOC entry 9460 (class 0 OID 0)
96052 -- Dependencies: 408
96053 -- Name: TABLE priv; Type: COMMENT; Schema: public; Owner: admin
96054 --
96055
96056 COMMENT ON TABLE priv IS 'System Privilege information';
96057
96058
96059 --
96060 -- TOC entry 409 (class 1259 OID 146568276)
96061 -- Dependencies: 8
96062 -- Name: priv_priv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96063 --
96064
96065 CREATE SEQUENCE priv_priv_id_seq
96066     START WITH 1
96067     INCREMENT BY 1
96068     NO MINVALUE
96069     MAXVALUE 2147483647
96070     CACHE 1;
96071
96072
96073 ALTER TABLE public.priv_priv_id_seq OWNER TO admin;
96074
96075 SET search_path = fixcountry, pg_catalog;
96076
96077 --
96078 -- TOC entry 410 (class 1259 OID 146568278)
96079 -- Dependencies: 6275 408 7
96080 -- Name: pkgpriv; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
96081 --
96082
96083 CREATE TABLE pkgpriv (
96084     priv_id integer DEFAULT nextval('public.priv_priv_id_seq'::regclass)
96085 )
96086 INHERITS (public.priv);
96087
96088
96089 ALTER TABLE fixcountry.pkgpriv OWNER TO admin;
96090
96091 SET search_path = public, pg_catalog;
96092
96093 --
96094 -- TOC entry 411 (class 1259 OID 146568285)
96095 -- Dependencies: 6276 8
96096 -- Name: report; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96097 --
96098
96099 CREATE TABLE report (
96100     report_id integer DEFAULT nextval(('report_report_id_seq'::text)::regclass) NOT NULL,
96101     report_name text,
96102     report_sys boolean,
96103     report_source text,
96104     report_descrip text,
96105     report_grade integer NOT NULL,
96106     report_loaddate timestamp without time zone
96107 );
96108
96109
96110 ALTER TABLE public.report OWNER TO admin;
96111
96112 --
96113 -- TOC entry 9464 (class 0 OID 0)
96114 -- Dependencies: 411
96115 -- Name: TABLE report; Type: COMMENT; Schema: public; Owner: admin
96116 --
96117
96118 COMMENT ON TABLE report IS 'Report definition information';
96119
96120
96121 --
96122 -- TOC entry 412 (class 1259 OID 146568292)
96123 -- Dependencies: 8
96124 -- Name: report_report_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96125 --
96126
96127 CREATE SEQUENCE report_report_id_seq
96128     START WITH 1
96129     INCREMENT BY 1
96130     NO MINVALUE
96131     MAXVALUE 2147483647
96132     CACHE 1;
96133
96134
96135 ALTER TABLE public.report_report_id_seq OWNER TO admin;
96136
96137 SET search_path = fixcountry, pg_catalog;
96138
96139 --
96140 -- TOC entry 413 (class 1259 OID 146568294)
96141 -- Dependencies: 6277 411 7
96142 -- Name: pkgreport; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
96143 --
96144
96145 CREATE TABLE pkgreport (
96146     report_id integer DEFAULT nextval('public.report_report_id_seq'::regclass)
96147 )
96148 INHERITS (public.report);
96149
96150
96151 ALTER TABLE fixcountry.pkgreport OWNER TO admin;
96152
96153 SET search_path = public, pg_catalog;
96154
96155 --
96156 -- TOC entry 414 (class 1259 OID 146568301)
96157 -- Dependencies: 6279 8
96158 -- Name: script; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96159 --
96160
96161 CREATE TABLE script (
96162     script_id integer NOT NULL,
96163     script_name text NOT NULL,
96164     script_order integer NOT NULL,
96165     script_enabled boolean DEFAULT false NOT NULL,
96166     script_source text NOT NULL,
96167     script_notes text
96168 );
96169
96170
96171 ALTER TABLE public.script OWNER TO admin;
96172
96173 --
96174 -- TOC entry 415 (class 1259 OID 146568308)
96175 -- Dependencies: 414 8
96176 -- Name: script_script_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96177 --
96178
96179 CREATE SEQUENCE script_script_id_seq
96180     START WITH 1
96181     INCREMENT BY 1
96182     NO MINVALUE
96183     NO MAXVALUE
96184     CACHE 1;
96185
96186
96187 ALTER TABLE public.script_script_id_seq OWNER TO admin;
96188
96189 --
96190 -- TOC entry 9469 (class 0 OID 0)
96191 -- Dependencies: 415
96192 -- Name: script_script_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96193 --
96194
96195 ALTER SEQUENCE script_script_id_seq OWNED BY script.script_id;
96196
96197
96198 SET search_path = fixcountry, pg_catalog;
96199
96200 --
96201 -- TOC entry 416 (class 1259 OID 146568311)
96202 -- Dependencies: 6280 414 7
96203 -- Name: pkgscript; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
96204 --
96205
96206 CREATE TABLE pkgscript (
96207     script_id integer DEFAULT nextval('public.script_script_id_seq'::regclass)
96208 )
96209 INHERITS (public.script);
96210
96211
96212 ALTER TABLE fixcountry.pkgscript OWNER TO admin;
96213
96214 SET search_path = public, pg_catalog;
96215
96216 --
96217 -- TOC entry 417 (class 1259 OID 146568319)
96218 -- Dependencies: 6283 8
96219 -- Name: uiform; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96220 --
96221
96222 CREATE TABLE uiform (
96223     uiform_id integer NOT NULL,
96224     uiform_name text NOT NULL,
96225     uiform_order integer NOT NULL,
96226     uiform_enabled boolean DEFAULT false NOT NULL,
96227     uiform_source text NOT NULL,
96228     uiform_notes text
96229 );
96230
96231
96232 ALTER TABLE public.uiform OWNER TO admin;
96233
96234 --
96235 -- TOC entry 418 (class 1259 OID 146568326)
96236 -- Dependencies: 417 8
96237 -- Name: uiform_uiform_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96238 --
96239
96240 CREATE SEQUENCE uiform_uiform_id_seq
96241     START WITH 1
96242     INCREMENT BY 1
96243     NO MINVALUE
96244     NO MAXVALUE
96245     CACHE 1;
96246
96247
96248 ALTER TABLE public.uiform_uiform_id_seq OWNER TO admin;
96249
96250 --
96251 -- TOC entry 9473 (class 0 OID 0)
96252 -- Dependencies: 418
96253 -- Name: uiform_uiform_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96254 --
96255
96256 ALTER SEQUENCE uiform_uiform_id_seq OWNED BY uiform.uiform_id;
96257
96258
96259 SET search_path = fixcountry, pg_catalog;
96260
96261 --
96262 -- TOC entry 419 (class 1259 OID 146568329)
96263 -- Dependencies: 6284 417 7
96264 -- Name: pkguiform; Type: TABLE; Schema: fixcountry; Owner: admin; Tablespace: 
96265 --
96266
96267 CREATE TABLE pkguiform (
96268     uiform_id integer DEFAULT nextval('public.uiform_uiform_id_seq'::regclass)
96269 )
96270 INHERITS (public.uiform);
96271
96272
96273 ALTER TABLE fixcountry.pkguiform OWNER TO admin;
96274
96275 SET search_path = public, pg_catalog;
96276
96277 --
96278 -- TOC entry 420 (class 1259 OID 146568337)
96279 -- Dependencies: 6286 8
96280 -- Name: acalitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96281 --
96282
96283 CREATE TABLE acalitem (
96284     acalitem_id integer DEFAULT nextval(('"xcalitem_xcalitem_id_seq"'::text)::regclass) NOT NULL,
96285     acalitem_calhead_id integer,
96286     acalitem_periodstart date,
96287     acalitem_periodlength integer,
96288     acalitem_name text
96289 );
96290
96291
96292 ALTER TABLE public.acalitem OWNER TO admin;
96293
96294 --
96295 -- TOC entry 9476 (class 0 OID 0)
96296 -- Dependencies: 420
96297 -- Name: TABLE acalitem; Type: COMMENT; Schema: public; Owner: admin
96298 --
96299
96300 COMMENT ON TABLE acalitem IS 'Absolute Calendar Item information';
96301
96302
96303 --
96304 -- TOC entry 421 (class 1259 OID 146568344)
96305 -- Dependencies: 8
96306 -- Name: accnt_accnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96307 --
96308
96309 CREATE SEQUENCE accnt_accnt_id_seq
96310     START WITH 1
96311     INCREMENT BY 1
96312     NO MINVALUE
96313     MAXVALUE 2147483647
96314     CACHE 1;
96315
96316
96317 ALTER TABLE public.accnt_accnt_id_seq OWNER TO admin;
96318
96319 --
96320 -- TOC entry 422 (class 1259 OID 146568346)
96321 -- Dependencies: 234 8
96322 -- Name: addr_addr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96323 --
96324
96325 CREATE SEQUENCE addr_addr_id_seq
96326     START WITH 1
96327     INCREMENT BY 1
96328     NO MINVALUE
96329     NO MAXVALUE
96330     CACHE 1;
96331
96332
96333 ALTER TABLE public.addr_addr_id_seq OWNER TO admin;
96334
96335 --
96336 -- TOC entry 9479 (class 0 OID 0)
96337 -- Dependencies: 422
96338 -- Name: addr_addr_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96339 --
96340
96341 ALTER SEQUENCE addr_addr_id_seq OWNED BY addr.addr_id;
96342
96343
96344 --
96345 -- TOC entry 423 (class 1259 OID 146568348)
96346 -- Dependencies: 8567 8
96347 -- Name: address; Type: VIEW; Schema: public; Owner: admin
96348 --
96349
96350 CREATE VIEW address AS
96351     SELECT addresses.addr_id, addresses.addr_active, addresses.addr_line1, addresses.addr_line2, addresses.addr_line3, addresses.addr_city, addresses.addr_state, addresses.addr_postalcode, addresses.addr_country, addresses.addr_notes, addresses.addr_number, addresses.crmacct_id, addresses.crmacct_number, addresses.crmacct_name FROM ((((SELECT base.addr_id, base.addr_active, base.addr_line1, base.addr_line2, base.addr_line3, base.addr_city, base.addr_state, base.addr_postalcode, base.addr_country, base.addr_notes, base.addr_number, base.crmacct_id, base.crmacct_number, base.crmacct_name FROM ((((SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, COALESCE(crmacct.crmacct_id, (-1)) AS crmacct_id, crmacct.crmacct_number, crmacct.crmacct_name FROM ((addr LEFT JOIN cntct ON ((cntct.cntct_addr_id = addr.addr_id))) LEFT JOIN crmacct ON ((crmacct.crmacct_id = cntct.cntct_crmacct_id))) EXCEPT SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, (-1), NULL::text AS unknown, NULL::text AS unknown FROM ((addr JOIN vendinfo ON ((vendinfo.vend_addr_id = addr.addr_id))) JOIN crmacct ON ((vendinfo.vend_id = crmacct.crmacct_vend_id)))) EXCEPT SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, (-1), NULL::text AS unknown, NULL::text AS unknown FROM ((addr JOIN vendaddrinfo ON ((vendaddrinfo.vendaddr_addr_id = addr.addr_id))) JOIN crmacct ON ((vendaddrinfo.vendaddr_vend_id = crmacct.crmacct_vend_id)))) EXCEPT SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, (-1), NULL::text AS unknown, NULL::text AS unknown FROM ((addr JOIN taxauth ON ((taxauth.taxauth_addr_id = addr.addr_id))) JOIN crmacct ON ((taxauth.taxauth_id = crmacct.crmacct_taxauth_id)))) EXCEPT SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, (-1), NULL::text AS unknown, NULL::text AS unknown FROM ((addr JOIN shiptoinfo ON ((shiptoinfo.shipto_addr_id = addr.addr_id))) JOIN crmacct ON ((shiptoinfo.shipto_cust_id = crmacct.crmacct_cust_id)))) base UNION SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, crmacct.crmacct_id, crmacct.crmacct_number, crmacct.crmacct_name FROM ((addr JOIN vendinfo ON ((vendinfo.vend_addr_id = addr.addr_id))) JOIN crmacct ON ((vendinfo.vend_id = crmacct.crmacct_vend_id)))) UNION SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, crmacct.crmacct_id, crmacct.crmacct_number, crmacct.crmacct_name FROM ((addr JOIN vendaddrinfo ON ((vendaddrinfo.vendaddr_addr_id = addr.addr_id))) JOIN crmacct ON ((vendaddrinfo.vendaddr_vend_id = crmacct.crmacct_vend_id)))) UNION SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, crmacct.crmacct_id, crmacct.crmacct_number, crmacct.crmacct_name FROM ((addr JOIN taxauth ON ((taxauth.taxauth_addr_id = addr.addr_id))) JOIN crmacct ON ((taxauth.taxauth_id = crmacct.crmacct_taxauth_id)))) UNION SELECT addr.addr_id, addr.addr_active, addr.addr_line1, addr.addr_line2, addr.addr_line3, addr.addr_city, addr.addr_state, addr.addr_postalcode, addr.addr_country, addr.addr_notes, addr.addr_number, crmacct.crmacct_id, crmacct.crmacct_number, crmacct.crmacct_name FROM ((addr JOIN shiptoinfo ON ((shiptoinfo.shipto_addr_id = addr.addr_id))) JOIN crmacct ON ((shiptoinfo.shipto_cust_id = crmacct.crmacct_cust_id)))) addresses ORDER BY addresses.addr_country, addresses.addr_state, addresses.addr_postalcode, addresses.addr_line1, addresses.addr_line2, addresses.addr_line3;
96352
96353
96354 ALTER TABLE public.address OWNER TO admin;
96355
96356 --
96357 -- TOC entry 424 (class 1259 OID 146568353)
96358 -- Dependencies: 6287 6288 6289 8
96359 -- Name: alarm; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96360 --
96361
96362 CREATE TABLE alarm (
96363     alarm_id integer NOT NULL,
96364     alarm_number text NOT NULL,
96365     alarm_event boolean DEFAULT false NOT NULL,
96366     alarm_email boolean DEFAULT false NOT NULL,
96367     alarm_sysmsg boolean DEFAULT false NOT NULL,
96368     alarm_trigger timestamp with time zone,
96369     alarm_time timestamp with time zone,
96370     alarm_time_offset integer,
96371     alarm_time_qualifier text,
96372     alarm_creator text,
96373     alarm_event_recipient text,
96374     alarm_email_recipient text,
96375     alarm_sysmsg_recipient text,
96376     alarm_source text,
96377     alarm_source_id integer
96378 );
96379
96380
96381 ALTER TABLE public.alarm OWNER TO admin;
96382
96383 --
96384 -- TOC entry 9482 (class 0 OID 0)
96385 -- Dependencies: 424
96386 -- Name: TABLE alarm; Type: COMMENT; Schema: public; Owner: admin
96387 --
96388
96389 COMMENT ON TABLE alarm IS 'This table is the open alarms.';
96390
96391
96392 --
96393 -- TOC entry 425 (class 1259 OID 146568362)
96394 -- Dependencies: 424 8
96395 -- Name: alarm_alarm_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96396 --
96397
96398 CREATE SEQUENCE alarm_alarm_id_seq
96399     START WITH 1
96400     INCREMENT BY 1
96401     NO MINVALUE
96402     NO MAXVALUE
96403     CACHE 1;
96404
96405
96406 ALTER TABLE public.alarm_alarm_id_seq OWNER TO admin;
96407
96408 --
96409 -- TOC entry 9484 (class 0 OID 0)
96410 -- Dependencies: 425
96411 -- Name: alarm_alarm_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96412 --
96413
96414 ALTER SEQUENCE alarm_alarm_id_seq OWNED BY alarm.alarm_id;
96415
96416
96417 --
96418 -- TOC entry 426 (class 1259 OID 146568364)
96419 -- Dependencies: 8
96420 -- Name: apaccnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96421 --
96422
96423 CREATE TABLE apaccnt (
96424     apaccnt_id integer NOT NULL,
96425     apaccnt_vendtype_id integer,
96426     apaccnt_vendtype text,
96427     apaccnt_ap_accnt_id integer NOT NULL,
96428     apaccnt_prepaid_accnt_id integer,
96429     apaccnt_discount_accnt_id integer
96430 );
96431
96432
96433 ALTER TABLE public.apaccnt OWNER TO admin;
96434
96435 --
96436 -- TOC entry 9486 (class 0 OID 0)
96437 -- Dependencies: 426
96438 -- Name: TABLE apaccnt; Type: COMMENT; Schema: public; Owner: admin
96439 --
96440
96441 COMMENT ON TABLE apaccnt IS 'Accounts Payable (A/P) Account assignment information';
96442
96443
96444 --
96445 -- TOC entry 427 (class 1259 OID 146568370)
96446 -- Dependencies: 426 8
96447 -- Name: apaccnt_apaccnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96448 --
96449
96450 CREATE SEQUENCE apaccnt_apaccnt_id_seq
96451     START WITH 1
96452     INCREMENT BY 1
96453     NO MINVALUE
96454     NO MAXVALUE
96455     CACHE 1;
96456
96457
96458 ALTER TABLE public.apaccnt_apaccnt_id_seq OWNER TO admin;
96459
96460 --
96461 -- TOC entry 9488 (class 0 OID 0)
96462 -- Dependencies: 427
96463 -- Name: apaccnt_apaccnt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96464 --
96465
96466 ALTER SEQUENCE apaccnt_apaccnt_id_seq OWNED BY apaccnt.apaccnt_id;
96467
96468
96469 --
96470 -- TOC entry 428 (class 1259 OID 146568372)
96471 -- Dependencies: 6293 8
96472 -- Name: apapply; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96473 --
96474
96475 CREATE TABLE apapply (
96476     apapply_id integer NOT NULL,
96477     apapply_vend_id integer,
96478     apapply_postdate date,
96479     apapply_username text,
96480     apapply_source_apopen_id integer,
96481     apapply_source_doctype text,
96482     apapply_source_docnumber text,
96483     apapply_target_apopen_id integer,
96484     apapply_target_doctype text,
96485     apapply_target_docnumber text,
96486     apapply_journalnumber integer,
96487     apapply_amount numeric(20,2),
96488     apapply_curr_id integer DEFAULT basecurrid(),
96489     apapply_target_paid numeric(20,2),
96490     apapply_checkhead_id integer
96491 );
96492
96493
96494 ALTER TABLE public.apapply OWNER TO admin;
96495
96496 --
96497 -- TOC entry 9490 (class 0 OID 0)
96498 -- Dependencies: 428
96499 -- Name: TABLE apapply; Type: COMMENT; Schema: public; Owner: admin
96500 --
96501
96502 COMMENT ON TABLE apapply IS 'Applications (e.g., Payments, A/P Credit Memos) made to Accounts Payable (A/P) Documents';
96503
96504
96505 --
96506 -- TOC entry 9491 (class 0 OID 0)
96507 -- Dependencies: 428
96508 -- Name: COLUMN apapply.apapply_source_apopen_id; Type: COMMENT; Schema: public; Owner: admin
96509 --
96510
96511 COMMENT ON COLUMN apapply.apapply_source_apopen_id IS 'If apapply_source_doctype is "C" (credit memo) then apapply_source_apopen_id acts as a foreign key to the apopen table. If the source doctype is "K" (check) then the apapply_source_apopen_id acts as a foreign key to the checkhead table. If the apapply_source_apopen_id is -1 then the internal id of the source document is not known (always the case for checks posted before release 3.2.0BETA).';
96512
96513
96514 --
96515 -- TOC entry 429 (class 1259 OID 146568379)
96516 -- Dependencies: 428 8
96517 -- Name: apapply_apapply_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96518 --
96519
96520 CREATE SEQUENCE apapply_apapply_id_seq
96521     START WITH 1
96522     INCREMENT BY 1
96523     NO MINVALUE
96524     NO MAXVALUE
96525     CACHE 1;
96526
96527
96528 ALTER TABLE public.apapply_apapply_id_seq OWNER TO admin;
96529
96530 --
96531 -- TOC entry 9493 (class 0 OID 0)
96532 -- Dependencies: 429
96533 -- Name: apapply_apapply_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96534 --
96535
96536 ALTER SEQUENCE apapply_apapply_id_seq OWNED BY apapply.apapply_id;
96537
96538
96539 --
96540 -- TOC entry 430 (class 1259 OID 146568381)
96541 -- Dependencies: 6294 6295 6296 6297 6298 6299 6300 6301 6303 6304 8
96542 -- Name: checkhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96543 --
96544
96545 CREATE TABLE checkhead (
96546     checkhead_id integer NOT NULL,
96547     checkhead_recip_id integer NOT NULL,
96548     checkhead_recip_type text NOT NULL,
96549     checkhead_bankaccnt_id integer NOT NULL,
96550     checkhead_printed boolean DEFAULT false NOT NULL,
96551     checkhead_checkdate date NOT NULL,
96552     checkhead_number integer NOT NULL,
96553     checkhead_amount numeric(20,2) NOT NULL,
96554     checkhead_void boolean DEFAULT false NOT NULL,
96555     checkhead_replaced boolean DEFAULT false NOT NULL,
96556     checkhead_posted boolean DEFAULT false NOT NULL,
96557     checkhead_rec boolean DEFAULT false NOT NULL,
96558     checkhead_misc boolean DEFAULT false NOT NULL,
96559     checkhead_expcat_id integer,
96560     checkhead_for text NOT NULL,
96561     checkhead_notes text NOT NULL,
96562     checkhead_journalnumber integer,
96563     checkhead_curr_id integer DEFAULT basecurrid() NOT NULL,
96564     checkhead_deleted boolean DEFAULT false NOT NULL,
96565     checkhead_ach_batch text,
96566     checkhead_curr_rate numeric NOT NULL,
96567     CONSTRAINT checkhead_checkhead_amount_check CHECK ((checkhead_amount > (0)::numeric)),
96568     CONSTRAINT checkhead_checkhead_recip_type_check CHECK ((((checkhead_recip_type = 'C'::text) OR (checkhead_recip_type = 'V'::text)) OR (checkhead_recip_type = 'T'::text)))
96569 );
96570
96571
96572 ALTER TABLE public.checkhead OWNER TO admin;
96573
96574 --
96575 -- TOC entry 9495 (class 0 OID 0)
96576 -- Dependencies: 430
96577 -- Name: TABLE checkhead; Type: COMMENT; Schema: public; Owner: admin
96578 --
96579
96580 COMMENT ON TABLE checkhead IS 'Accounts Payable Check Information';
96581
96582
96583 --
96584 -- TOC entry 431 (class 1259 OID 146568397)
96585 -- Dependencies: 8568 8
96586 -- Name: apchk; Type: VIEW; Schema: public; Owner: admin
96587 --
96588
96589 CREATE VIEW apchk AS
96590     SELECT checkhead.checkhead_id AS apchk_id, checkhead.checkhead_recip_id AS apchk_vend_id, checkhead.checkhead_bankaccnt_id AS apchk_bankaccnt_id, checkhead.checkhead_printed AS apchk_printed, checkhead.checkhead_checkdate AS apchk_checkdate, checkhead.checkhead_number AS apchk_number, checkhead.checkhead_amount AS apchk_amount, checkhead.checkhead_void AS apchk_void, checkhead.checkhead_replaced AS apchk_replaced, checkhead.checkhead_posted AS apchk_posted, checkhead.checkhead_rec AS apchk_rec, checkhead.checkhead_misc AS apchk_misc, checkhead.checkhead_expcat_id AS apchk_expcat_id, checkhead.checkhead_for AS apchk_for, checkhead.checkhead_notes AS apchk_notes, checkhead.checkhead_journalnumber AS apchk_journalnumber, checkhead.checkhead_curr_id AS apchk_curr_id, checkhead.checkhead_deleted AS apchk_deleted FROM checkhead WHERE (checkhead.checkhead_recip_type = 'V'::text);
96591
96592
96593 ALTER TABLE public.apchk OWNER TO admin;
96594
96595 --
96596 -- TOC entry 432 (class 1259 OID 146568401)
96597 -- Dependencies: 6305 6306 6307 6309 8
96598 -- Name: checkitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96599 --
96600
96601 CREATE TABLE checkitem (
96602     checkitem_id integer NOT NULL,
96603     checkitem_checkhead_id integer NOT NULL,
96604     checkitem_amount numeric(20,2) DEFAULT 0.0 NOT NULL,
96605     checkitem_discount numeric(20,2) DEFAULT 0.0 NOT NULL,
96606     checkitem_ponumber text,
96607     checkitem_vouchernumber text,
96608     checkitem_invcnumber text,
96609     checkitem_apopen_id integer,
96610     checkitem_aropen_id integer,
96611     checkitem_docdate date,
96612     checkitem_curr_id integer DEFAULT basecurrid() NOT NULL,
96613     checkitem_cmnumber text,
96614     checkitem_ranumber text,
96615     checkitem_curr_rate numeric,
96616     CONSTRAINT checkitem_check CHECK ((NOT ((checkitem_apopen_id IS NOT NULL) AND (checkitem_aropen_id IS NOT NULL))))
96617 );
96618
96619
96620 ALTER TABLE public.checkitem OWNER TO admin;
96621
96622 --
96623 -- TOC entry 9498 (class 0 OID 0)
96624 -- Dependencies: 432
96625 -- Name: TABLE checkitem; Type: COMMENT; Schema: public; Owner: admin
96626 --
96627
96628 COMMENT ON TABLE checkitem IS 'Accounts Payable Check Line Item Information';
96629
96630
96631 --
96632 -- TOC entry 433 (class 1259 OID 146568411)
96633 -- Dependencies: 8569 8
96634 -- Name: apchkitem; Type: VIEW; Schema: public; Owner: admin
96635 --
96636
96637 CREATE VIEW apchkitem AS
96638     SELECT checkitem.checkitem_id AS apchkitem_id, checkitem.checkitem_checkhead_id AS apchkitem_apchk_id, checkitem.checkitem_vouchernumber AS apchkitem_vouchernumber, checkitem.checkitem_ponumber AS apchkitem_ponumber, checkitem.checkitem_amount AS apchkitem_amount, checkitem.checkitem_invcnumber AS apchkitem_invcnumber, checkitem.checkitem_apopen_id AS apchkitem_apopen_id, checkitem.checkitem_docdate AS apchkitem_docdate, checkitem.checkitem_curr_id AS apchkitem_curr_id, checkitem.checkitem_discount AS apchkitem_discount FROM checkhead, checkitem WHERE ((checkitem.checkitem_checkhead_id = checkhead.checkhead_id) AND (checkhead.checkhead_recip_type = 'V'::text));
96639
96640
96641 ALTER TABLE public.apchkitem OWNER TO admin;
96642
96643 --
96644 -- TOC entry 434 (class 1259 OID 146568415)
96645 -- Dependencies: 6311 8
96646 -- Name: apcreditapply; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96647 --
96648
96649 CREATE TABLE apcreditapply (
96650     apcreditapply_id integer NOT NULL,
96651     apcreditapply_source_apopen_id integer,
96652     apcreditapply_target_apopen_id integer,
96653     apcreditapply_amount numeric(20,2),
96654     apcreditapply_curr_id integer DEFAULT basecurrid()
96655 );
96656
96657
96658 ALTER TABLE public.apcreditapply OWNER TO admin;
96659
96660 --
96661 -- TOC entry 9501 (class 0 OID 0)
96662 -- Dependencies: 434
96663 -- Name: TABLE apcreditapply; Type: COMMENT; Schema: public; Owner: admin
96664 --
96665
96666 COMMENT ON TABLE apcreditapply IS 'Temporary table for storing details of Accounts Payable (A/P) Credit Memo applications before those applications are posted';
96667
96668
96669 --
96670 -- TOC entry 435 (class 1259 OID 146568419)
96671 -- Dependencies: 434 8
96672 -- Name: apcreditapply_apcreditapply_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96673 --
96674
96675 CREATE SEQUENCE apcreditapply_apcreditapply_id_seq
96676     START WITH 1
96677     INCREMENT BY 1
96678     NO MINVALUE
96679     NO MAXVALUE
96680     CACHE 1;
96681
96682
96683 ALTER TABLE public.apcreditapply_apcreditapply_id_seq OWNER TO admin;
96684
96685 --
96686 -- TOC entry 9503 (class 0 OID 0)
96687 -- Dependencies: 435
96688 -- Name: apcreditapply_apcreditapply_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96689 --
96690
96691 ALTER SEQUENCE apcreditapply_apcreditapply_id_seq OWNED BY apcreditapply.apcreditapply_id;
96692
96693
96694 --
96695 -- TOC entry 436 (class 1259 OID 146568421)
96696 -- Dependencies: 8570 8
96697 -- Name: apmemo; Type: VIEW; Schema: public; Owner: admin
96698 --
96699
96700 CREATE VIEW apmemo AS
96701     SELECT apopen.apopen_id, apopen.apopen_docnumber FROM apopen WHERE (apopen.apopen_doctype = ANY (ARRAY['D'::bpchar, 'C'::bpchar]));
96702
96703
96704 ALTER TABLE public.apmemo OWNER TO admin;
96705
96706 --
96707 -- TOC entry 437 (class 1259 OID 146568425)
96708 -- Dependencies: 8
96709 -- Name: apopen_apopen_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96710 --
96711
96712 CREATE SEQUENCE apopen_apopen_id_seq
96713     START WITH 1
96714     INCREMENT BY 1
96715     NO MINVALUE
96716     NO MAXVALUE
96717     CACHE 1;
96718
96719
96720 ALTER TABLE public.apopen_apopen_id_seq OWNER TO admin;
96721
96722 --
96723 -- TOC entry 438 (class 1259 OID 146568427)
96724 -- Dependencies: 377 8
96725 -- Name: apopentax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96726 --
96727
96728 CREATE TABLE apopentax (
96729 )
96730 INHERITS (taxhist);
96731
96732
96733 ALTER TABLE public.apopentax OWNER TO admin;
96734
96735 --
96736 -- TOC entry 439 (class 1259 OID 146568433)
96737 -- Dependencies: 6314 6315 8
96738 -- Name: apselect; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96739 --
96740
96741 CREATE TABLE apselect (
96742     apselect_id integer NOT NULL,
96743     apselect_apopen_id integer NOT NULL,
96744     apselect_amount numeric(20,2) NOT NULL,
96745     apselect_bankaccnt_id integer,
96746     apselect_curr_id integer DEFAULT basecurrid(),
96747     apselect_date date,
96748     apselect_discount numeric(20,2) DEFAULT 0.0 NOT NULL
96749 );
96750
96751
96752 ALTER TABLE public.apselect OWNER TO admin;
96753
96754 --
96755 -- TOC entry 9508 (class 0 OID 0)
96756 -- Dependencies: 439
96757 -- Name: TABLE apselect; Type: COMMENT; Schema: public; Owner: admin
96758 --
96759
96760 COMMENT ON TABLE apselect IS 'Temporary table for storing details of Accounts Payable (A/P) Payment selections';
96761
96762
96763 --
96764 -- TOC entry 440 (class 1259 OID 146568438)
96765 -- Dependencies: 439 8
96766 -- Name: apselect_apselect_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96767 --
96768
96769 CREATE SEQUENCE apselect_apselect_id_seq
96770     START WITH 1
96771     INCREMENT BY 1
96772     NO MINVALUE
96773     NO MAXVALUE
96774     CACHE 1;
96775
96776
96777 ALTER TABLE public.apselect_apselect_id_seq OWNER TO admin;
96778
96779 --
96780 -- TOC entry 9510 (class 0 OID 0)
96781 -- Dependencies: 440
96782 -- Name: apselect_apselect_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96783 --
96784
96785 ALTER SEQUENCE apselect_apselect_id_seq OWNED BY apselect.apselect_id;
96786
96787
96788 --
96789 -- TOC entry 441 (class 1259 OID 146568440)
96790 -- Dependencies: 6316 8
96791 -- Name: araccnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96792 --
96793
96794 CREATE TABLE araccnt (
96795     araccnt_id integer DEFAULT nextval(('araccnt_araccnt_id_seq'::text)::regclass) NOT NULL,
96796     araccnt_custtype_id integer,
96797     araccnt_custtype text,
96798     araccnt_freight_accnt_id integer,
96799     araccnt_ar_accnt_id integer,
96800     araccnt_prepaid_accnt_id integer,
96801     araccnt_deferred_accnt_id integer,
96802     araccnt_discount_accnt_id integer
96803 );
96804
96805
96806 ALTER TABLE public.araccnt OWNER TO admin;
96807
96808 --
96809 -- TOC entry 9512 (class 0 OID 0)
96810 -- Dependencies: 441
96811 -- Name: TABLE araccnt; Type: COMMENT; Schema: public; Owner: admin
96812 --
96813
96814 COMMENT ON TABLE araccnt IS 'Accounts Receivable (A/R) Account assignment information';
96815
96816
96817 --
96818 -- TOC entry 442 (class 1259 OID 146568447)
96819 -- Dependencies: 8
96820 -- Name: araccnt_araccnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96821 --
96822
96823 CREATE SEQUENCE araccnt_araccnt_id_seq
96824     START WITH 1
96825     INCREMENT BY 1
96826     NO MINVALUE
96827     NO MAXVALUE
96828     CACHE 1;
96829
96830
96831 ALTER TABLE public.araccnt_araccnt_id_seq OWNER TO admin;
96832
96833 --
96834 -- TOC entry 443 (class 1259 OID 146568449)
96835 -- Dependencies: 6318 8
96836 -- Name: arapply; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96837 --
96838
96839 CREATE TABLE arapply (
96840     arapply_id integer NOT NULL,
96841     arapply_postdate date,
96842     arapply_cust_id integer,
96843     arapply_source_doctype text,
96844     arapply_source_docnumber text,
96845     arapply_target_doctype text,
96846     arapply_target_docnumber text,
96847     arapply_fundstype text,
96848     arapply_refnumber text,
96849     arapply_applied numeric(20,2),
96850     arapply_closed boolean,
96851     arapply_journalnumber text,
96852     arapply_source_aropen_id integer,
96853     arapply_target_aropen_id integer,
96854     arapply_username text,
96855     arapply_curr_id integer DEFAULT basecurrid(),
96856     arapply_distdate date NOT NULL,
96857     arapply_target_paid numeric(20,2),
96858     arapply_reftype text,
96859     arapply_ref_id integer
96860 );
96861
96862
96863 ALTER TABLE public.arapply OWNER TO admin;
96864
96865 --
96866 -- TOC entry 9515 (class 0 OID 0)
96867 -- Dependencies: 443
96868 -- Name: TABLE arapply; Type: COMMENT; Schema: public; Owner: admin
96869 --
96870
96871 COMMENT ON TABLE arapply IS 'Applications (e.g., Cash Receipts, A/R Credit Memos) made to Accounts Receivable (A/R) Documents';
96872
96873
96874 --
96875 -- TOC entry 444 (class 1259 OID 146568456)
96876 -- Dependencies: 443 8
96877 -- Name: arapply_arapply_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96878 --
96879
96880 CREATE SEQUENCE arapply_arapply_id_seq
96881     START WITH 1
96882     INCREMENT BY 1
96883     NO MINVALUE
96884     NO MAXVALUE
96885     CACHE 1;
96886
96887
96888 ALTER TABLE public.arapply_arapply_id_seq OWNER TO admin;
96889
96890 --
96891 -- TOC entry 9517 (class 0 OID 0)
96892 -- Dependencies: 444
96893 -- Name: arapply_arapply_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96894 --
96895
96896 ALTER SEQUENCE arapply_arapply_id_seq OWNED BY arapply.arapply_id;
96897
96898
96899 --
96900 -- TOC entry 445 (class 1259 OID 146568458)
96901 -- Dependencies: 269 8
96902 -- Name: cashrcptitem_cashrcptitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96903 --
96904
96905 CREATE SEQUENCE cashrcptitem_cashrcptitem_id_seq
96906     START WITH 1
96907     INCREMENT BY 1
96908     NO MINVALUE
96909     NO MAXVALUE
96910     CACHE 1;
96911
96912
96913 ALTER TABLE public.cashrcptitem_cashrcptitem_id_seq OWNER TO admin;
96914
96915 --
96916 -- TOC entry 9519 (class 0 OID 0)
96917 -- Dependencies: 445
96918 -- Name: cashrcptitem_cashrcptitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96919 --
96920
96921 ALTER SEQUENCE cashrcptitem_cashrcptitem_id_seq OWNED BY cashrcptitem.cashrcptitem_id;
96922
96923
96924 --
96925 -- TOC entry 446 (class 1259 OID 146568460)
96926 -- Dependencies: 6319 6320 8
96927 -- Name: arcreditapply; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
96928 --
96929
96930 CREATE TABLE arcreditapply (
96931     arcreditapply_id integer DEFAULT nextval('cashrcptitem_cashrcptitem_id_seq'::regclass) NOT NULL,
96932     arcreditapply_source_aropen_id integer,
96933     arcreditapply_target_aropen_id integer,
96934     arcreditapply_amount numeric(20,2),
96935     arcreditapply_curr_id integer DEFAULT basecurrid(),
96936     arcreditapply_reftype text,
96937     arcreditapply_ref_id integer
96938 );
96939
96940
96941 ALTER TABLE public.arcreditapply OWNER TO admin;
96942
96943 --
96944 -- TOC entry 9521 (class 0 OID 0)
96945 -- Dependencies: 446
96946 -- Name: TABLE arcreditapply; Type: COMMENT; Schema: public; Owner: admin
96947 --
96948
96949 COMMENT ON TABLE arcreditapply IS 'Temporary table for storing details of Accounts Receivable (A/R) Credit Memo applications before those applications are posted';
96950
96951
96952 --
96953 -- TOC entry 447 (class 1259 OID 146568468)
96954 -- Dependencies: 446 8
96955 -- Name: arcreditapply_arcreditapply_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96956 --
96957
96958 CREATE SEQUENCE arcreditapply_arcreditapply_id_seq
96959     START WITH 1
96960     INCREMENT BY 1
96961     NO MINVALUE
96962     NO MAXVALUE
96963     CACHE 1;
96964
96965
96966 ALTER TABLE public.arcreditapply_arcreditapply_id_seq OWNER TO admin;
96967
96968 --
96969 -- TOC entry 9523 (class 0 OID 0)
96970 -- Dependencies: 447
96971 -- Name: arcreditapply_arcreditapply_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
96972 --
96973
96974 ALTER SEQUENCE arcreditapply_arcreditapply_id_seq OWNED BY arcreditapply.arcreditapply_id;
96975
96976
96977 --
96978 -- TOC entry 448 (class 1259 OID 146568470)
96979 -- Dependencies: 8571 8
96980 -- Name: armemo; Type: VIEW; Schema: public; Owner: admin
96981 --
96982
96983 CREATE VIEW armemo AS
96984     SELECT aropen.aropen_id, aropen.aropen_docnumber FROM aropen WHERE (aropen.aropen_doctype = ANY (ARRAY['D'::bpchar, 'C'::bpchar, 'R'::bpchar])) UNION SELECT cmhead.cmhead_id AS aropen_id, cmhead.cmhead_number AS aropen_docnumber FROM cmhead;
96985
96986
96987 ALTER TABLE public.armemo OWNER TO admin;
96988
96989 --
96990 -- TOC entry 449 (class 1259 OID 146568474)
96991 -- Dependencies: 8
96992 -- Name: aropen_aropen_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
96993 --
96994
96995 CREATE SEQUENCE aropen_aropen_id_seq
96996     START WITH 1
96997     INCREMENT BY 1
96998     NO MINVALUE
96999     MAXVALUE 2147483647
97000     CACHE 1;
97001
97002
97003 ALTER TABLE public.aropen_aropen_id_seq OWNER TO admin;
97004
97005 --
97006 -- TOC entry 450 (class 1259 OID 146568476)
97007 -- Dependencies: 377 8
97008 -- Name: aropentax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97009 --
97010
97011 CREATE TABLE aropentax (
97012 )
97013 INHERITS (taxhist);
97014
97015
97016 ALTER TABLE public.aropentax OWNER TO admin;
97017
97018 --
97019 -- TOC entry 451 (class 1259 OID 146568482)
97020 -- Dependencies: 6323 8
97021 -- Name: asohist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97022 --
97023
97024 CREATE TABLE asohist (
97025     asohist_id integer NOT NULL,
97026     asohist_cust_id integer,
97027     asohist_itemsite_id integer,
97028     asohist_shipdate date,
97029     asohist_invcdate date,
97030     asohist_duedate date,
97031     asohist_promisedate date,
97032     asohist_ordernumber text,
97033     asohist_invcnumber text,
97034     asohist_qtyshipped numeric(18,6),
97035     asohist_unitprice numeric(16,4),
97036     asohist_unitcost numeric(16,6),
97037     asohist_billtoname text,
97038     asohist_billtoaddress1 text,
97039     asohist_billtoaddress2 text,
97040     asohist_billtoaddress3 text,
97041     asohist_billtocity text,
97042     asohist_billtostate text,
97043     asohist_billtozip text,
97044     asohist_shiptoname text,
97045     asohist_shiptoaddress1 text,
97046     asohist_shiptoaddress2 text,
97047     asohist_shiptoaddress3 text,
97048     asohist_shiptocity text,
97049     asohist_shiptostate text,
97050     asohist_shiptozip text,
97051     asohist_shipto_id integer,
97052     asohist_shipvia text,
97053     asohist_salesrep_id integer,
97054     asohist_misc_type character(1),
97055     asohist_misc_descrip text,
97056     asohist_misc_id integer,
97057     asohist_commission numeric(16,4),
97058     asohist_commissionpaid boolean,
97059     asohist_doctype text,
97060     asohist_orderdate date,
97061     asohist_imported boolean,
97062     asohist_ponumber text,
97063     asohist_curr_id integer DEFAULT basecurrid(),
97064     asohist_taxtype_id integer,
97065     asohist_taxzone_id integer
97066 );
97067
97068
97069 ALTER TABLE public.asohist OWNER TO admin;
97070
97071 --
97072 -- TOC entry 9528 (class 0 OID 0)
97073 -- Dependencies: 451
97074 -- Name: TABLE asohist; Type: COMMENT; Schema: public; Owner: admin
97075 --
97076
97077 COMMENT ON TABLE asohist IS 'Archived Sales history';
97078
97079
97080 --
97081 -- TOC entry 452 (class 1259 OID 146568489)
97082 -- Dependencies: 451 8
97083 -- Name: asohist_asohist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97084 --
97085
97086 CREATE SEQUENCE asohist_asohist_id_seq
97087     START WITH 1
97088     INCREMENT BY 1
97089     NO MINVALUE
97090     NO MAXVALUE
97091     CACHE 1;
97092
97093
97094 ALTER TABLE public.asohist_asohist_id_seq OWNER TO admin;
97095
97096 --
97097 -- TOC entry 9530 (class 0 OID 0)
97098 -- Dependencies: 452
97099 -- Name: asohist_asohist_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97100 --
97101
97102 ALTER SEQUENCE asohist_asohist_id_seq OWNED BY asohist.asohist_id;
97103
97104
97105 --
97106 -- TOC entry 453 (class 1259 OID 146568491)
97107 -- Dependencies: 377 8
97108 -- Name: asohisttax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97109 --
97110
97111 CREATE TABLE asohisttax (
97112 )
97113 INHERITS (taxhist);
97114
97115
97116 ALTER TABLE public.asohisttax OWNER TO admin;
97117
97118 --
97119 -- TOC entry 454 (class 1259 OID 146568497)
97120 -- Dependencies: 6326 6327 8
97121 -- Name: atlasmap; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97122 --
97123
97124 CREATE TABLE atlasmap (
97125     atlasmap_id integer NOT NULL,
97126     atlasmap_name text NOT NULL,
97127     atlasmap_filter text NOT NULL,
97128     atlasmap_filtertype text NOT NULL,
97129     atlasmap_atlas text NOT NULL,
97130     atlasmap_map text NOT NULL,
97131     atlasmap_headerline boolean DEFAULT false NOT NULL,
97132     CONSTRAINT atlasmap_atlasmap_name_check CHECK ((atlasmap_name <> ''::text))
97133 );
97134
97135
97136 ALTER TABLE public.atlasmap OWNER TO admin;
97137
97138 --
97139 -- TOC entry 9533 (class 0 OID 0)
97140 -- Dependencies: 454
97141 -- Name: TABLE atlasmap; Type: COMMENT; Schema: public; Owner: admin
97142 --
97143
97144 COMMENT ON TABLE atlasmap IS 'Describes heuristics for finding a CSVImp atlas for a given CSV file. When looking for a CSV Atlas to use when importing a CSV file, the first atlasmap record found that matches the CSV file is used to select the Atlas file and Map in that Atlas to import the CSV file.';
97145
97146
97147 --
97148 -- TOC entry 9534 (class 0 OID 0)
97149 -- Dependencies: 454
97150 -- Name: COLUMN atlasmap.atlasmap_id; Type: COMMENT; Schema: public; Owner: admin
97151 --
97152
97153 COMMENT ON COLUMN atlasmap.atlasmap_id IS 'The internal id of this CSVImp atlas mapping.';
97154
97155
97156 --
97157 -- TOC entry 9535 (class 0 OID 0)
97158 -- Dependencies: 454
97159 -- Name: COLUMN atlasmap.atlasmap_name; Type: COMMENT; Schema: public; Owner: admin
97160 --
97161
97162 COMMENT ON COLUMN atlasmap.atlasmap_name IS 'The human-readable name of this atlas mapping.';
97163
97164
97165 --
97166 -- TOC entry 9536 (class 0 OID 0)
97167 -- Dependencies: 454
97168 -- Name: COLUMN atlasmap.atlasmap_filter; Type: COMMENT; Schema: public; Owner: admin
97169 --
97170
97171 COMMENT ON COLUMN atlasmap.atlasmap_filter IS 'A regular expression that should match the CSV file. Which part of the file that matches is determined by the filter type.';
97172
97173
97174 --
97175 -- TOC entry 9537 (class 0 OID 0)
97176 -- Dependencies: 454
97177 -- Name: COLUMN atlasmap.atlasmap_filtertype; Type: COMMENT; Schema: public; Owner: admin
97178 --
97179
97180 COMMENT ON COLUMN atlasmap.atlasmap_filtertype IS 'A description of what aspect of the CSV file the filter should be compared with. Handled values are: ''filename'' - the filter is matched against the name of the file; and ''firstline'' - the filter is matched against the first line of the file contents.';
97181
97182
97183 --
97184 -- TOC entry 9538 (class 0 OID 0)
97185 -- Dependencies: 454
97186 -- Name: COLUMN atlasmap.atlasmap_atlas; Type: COMMENT; Schema: public; Owner: admin
97187 --
97188
97189 COMMENT ON COLUMN atlasmap.atlasmap_atlas IS 'The name of the CSVImp Atlas file. This should be a simple pathname, not an absolute or relative name if possible. The full path will be determined by concatenating the operating-system-specific CSV Atlas default directory with the value here unless this is an absolute pathname.';
97190
97191
97192 --
97193 -- TOC entry 9539 (class 0 OID 0)
97194 -- Dependencies: 454
97195 -- Name: COLUMN atlasmap.atlasmap_map; Type: COMMENT; Schema: public; Owner: admin
97196 --
97197
97198 COMMENT ON COLUMN atlasmap.atlasmap_map IS 'The name of the Map inside the Atlas to use if the filter and filter type match the CVS file.';
97199
97200
97201 --
97202 -- TOC entry 9540 (class 0 OID 0)
97203 -- Dependencies: 454
97204 -- Name: COLUMN atlasmap.atlasmap_headerline; Type: COMMENT; Schema: public; Owner: admin
97205 --
97206
97207 COMMENT ON COLUMN atlasmap.atlasmap_headerline IS 'An indicator of whether the first line of the CSV file should be treated as a header line or as data.';
97208
97209
97210 --
97211 -- TOC entry 455 (class 1259 OID 146568505)
97212 -- Dependencies: 454 8
97213 -- Name: atlasmap_atlasmap_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97214 --
97215
97216 CREATE SEQUENCE atlasmap_atlasmap_id_seq
97217     START WITH 1
97218     INCREMENT BY 1
97219     NO MINVALUE
97220     NO MAXVALUE
97221     CACHE 1;
97222
97223
97224 ALTER TABLE public.atlasmap_atlasmap_id_seq OWNER TO admin;
97225
97226 --
97227 -- TOC entry 9542 (class 0 OID 0)
97228 -- Dependencies: 455
97229 -- Name: atlasmap_atlasmap_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97230 --
97231
97232 ALTER SEQUENCE atlasmap_atlasmap_id_seq OWNED BY atlasmap.atlasmap_id;
97233
97234
97235 --
97236 -- TOC entry 456 (class 1259 OID 146568507)
97237 -- Dependencies: 8
97238 -- Name: backup_usr; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97239 --
97240
97241 CREATE TABLE backup_usr (
97242     usr_id integer,
97243     usr_username text,
97244     usr_propername text,
97245     usr_passwd text,
97246     usr_locale_id integer,
97247     usr_initials text,
97248     usr_agent boolean,
97249     usr_active boolean,
97250     usr_email text,
97251     usr_dept_id integer,
97252     usr_shift_id integer,
97253     usr_window text
97254 );
97255
97256
97257 ALTER TABLE public.backup_usr OWNER TO admin;
97258
97259 --
97260 -- TOC entry 457 (class 1259 OID 146568513)
97261 -- Dependencies: 266 8
97262 -- Name: bankaccnt_bankaccnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97263 --
97264
97265 CREATE SEQUENCE bankaccnt_bankaccnt_id_seq
97266     START WITH 1
97267     INCREMENT BY 1
97268     NO MINVALUE
97269     NO MAXVALUE
97270     CACHE 1;
97271
97272
97273 ALTER TABLE public.bankaccnt_bankaccnt_id_seq OWNER TO admin;
97274
97275 --
97276 -- TOC entry 9545 (class 0 OID 0)
97277 -- Dependencies: 457
97278 -- Name: bankaccnt_bankaccnt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97279 --
97280
97281 ALTER SEQUENCE bankaccnt_bankaccnt_id_seq OWNED BY bankaccnt.bankaccnt_id;
97282
97283
97284 --
97285 -- TOC entry 458 (class 1259 OID 146568515)
97286 -- Dependencies: 6328 6329 6330 6331 8
97287 -- Name: bankadj; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97288 --
97289
97290 CREATE TABLE bankadj (
97291     bankadj_id integer NOT NULL,
97292     bankadj_bankaccnt_id integer NOT NULL,
97293     bankadj_bankadjtype_id integer NOT NULL,
97294     bankadj_created timestamp without time zone DEFAULT now() NOT NULL,
97295     bankadj_username text DEFAULT geteffectivextuser() NOT NULL,
97296     bankadj_date date NOT NULL,
97297     bankadj_docnumber text,
97298     bankadj_amount numeric(10,2) NOT NULL,
97299     bankadj_notes text,
97300     bankadj_sequence integer,
97301     bankadj_posted boolean DEFAULT false NOT NULL,
97302     bankadj_curr_id integer DEFAULT basecurrid(),
97303     bankadj_curr_rate numeric
97304 );
97305
97306
97307 ALTER TABLE public.bankadj OWNER TO admin;
97308
97309 --
97310 -- TOC entry 9547 (class 0 OID 0)
97311 -- Dependencies: 458
97312 -- Name: TABLE bankadj; Type: COMMENT; Schema: public; Owner: admin
97313 --
97314
97315 COMMENT ON TABLE bankadj IS 'Bank Adjustments information';
97316
97317
97318 --
97319 -- TOC entry 459 (class 1259 OID 146568525)
97320 -- Dependencies: 458 8
97321 -- Name: bankadj_bankadj_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97322 --
97323
97324 CREATE SEQUENCE bankadj_bankadj_id_seq
97325     START WITH 1
97326     INCREMENT BY 1
97327     NO MINVALUE
97328     NO MAXVALUE
97329     CACHE 1;
97330
97331
97332 ALTER TABLE public.bankadj_bankadj_id_seq OWNER TO admin;
97333
97334 --
97335 -- TOC entry 9549 (class 0 OID 0)
97336 -- Dependencies: 459
97337 -- Name: bankadj_bankadj_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97338 --
97339
97340 ALTER SEQUENCE bankadj_bankadj_id_seq OWNED BY bankadj.bankadj_id;
97341
97342
97343 --
97344 -- TOC entry 460 (class 1259 OID 146568527)
97345 -- Dependencies: 6334 6335 8
97346 -- Name: bankadjtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97347 --
97348
97349 CREATE TABLE bankadjtype (
97350     bankadjtype_id integer NOT NULL,
97351     bankadjtype_name text NOT NULL,
97352     bankadjtype_descrip text,
97353     bankadjtype_accnt_id integer NOT NULL,
97354     bankadjtype_iscredit boolean DEFAULT false NOT NULL,
97355     CONSTRAINT bankadjtype_bankadjtype_name_check CHECK ((bankadjtype_name <> ''::text))
97356 );
97357
97358
97359 ALTER TABLE public.bankadjtype OWNER TO admin;
97360
97361 --
97362 -- TOC entry 9551 (class 0 OID 0)
97363 -- Dependencies: 460
97364 -- Name: TABLE bankadjtype; Type: COMMENT; Schema: public; Owner: admin
97365 --
97366
97367 COMMENT ON TABLE bankadjtype IS 'Bank Adjustment Types information';
97368
97369
97370 --
97371 -- TOC entry 461 (class 1259 OID 146568535)
97372 -- Dependencies: 460 8
97373 -- Name: bankadjtype_bankadjtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97374 --
97375
97376 CREATE SEQUENCE bankadjtype_bankadjtype_id_seq
97377     START WITH 1
97378     INCREMENT BY 1
97379     NO MINVALUE
97380     NO MAXVALUE
97381     CACHE 1;
97382
97383
97384 ALTER TABLE public.bankadjtype_bankadjtype_id_seq OWNER TO admin;
97385
97386 --
97387 -- TOC entry 9553 (class 0 OID 0)
97388 -- Dependencies: 461
97389 -- Name: bankadjtype_bankadjtype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97390 --
97391
97392 ALTER SEQUENCE bankadjtype_bankadjtype_id_seq OWNED BY bankadjtype.bankadjtype_id;
97393
97394
97395 --
97396 -- TOC entry 462 (class 1259 OID 146568537)
97397 -- Dependencies: 6336 6337 6338 8
97398 -- Name: bankrec; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97399 --
97400
97401 CREATE TABLE bankrec (
97402     bankrec_id integer NOT NULL,
97403     bankrec_created timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
97404     bankrec_username text DEFAULT geteffectivextuser() NOT NULL,
97405     bankrec_bankaccnt_id integer,
97406     bankrec_opendate date,
97407     bankrec_enddate date,
97408     bankrec_openbal numeric(20,2),
97409     bankrec_endbal numeric(20,2),
97410     bankrec_posted boolean DEFAULT false,
97411     bankrec_postdate timestamp without time zone
97412 );
97413
97414
97415 ALTER TABLE public.bankrec OWNER TO admin;
97416
97417 --
97418 -- TOC entry 9555 (class 0 OID 0)
97419 -- Dependencies: 462
97420 -- Name: TABLE bankrec; Type: COMMENT; Schema: public; Owner: admin
97421 --
97422
97423 COMMENT ON TABLE bankrec IS 'Bank Reconciliation posting history';
97424
97425
97426 --
97427 -- TOC entry 463 (class 1259 OID 146568546)
97428 -- Dependencies: 462 8
97429 -- Name: bankrec_bankrec_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97430 --
97431
97432 CREATE SEQUENCE bankrec_bankrec_id_seq
97433     START WITH 1
97434     INCREMENT BY 1
97435     NO MINVALUE
97436     NO MAXVALUE
97437     CACHE 1;
97438
97439
97440 ALTER TABLE public.bankrec_bankrec_id_seq OWNER TO admin;
97441
97442 --
97443 -- TOC entry 9557 (class 0 OID 0)
97444 -- Dependencies: 463
97445 -- Name: bankrec_bankrec_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97446 --
97447
97448 ALTER SEQUENCE bankrec_bankrec_id_seq OWNED BY bankrec.bankrec_id;
97449
97450
97451 --
97452 -- TOC entry 464 (class 1259 OID 146568548)
97453 -- Dependencies: 6341 8
97454 -- Name: bankrecitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97455 --
97456
97457 CREATE TABLE bankrecitem (
97458     bankrecitem_id integer NOT NULL,
97459     bankrecitem_bankrec_id integer NOT NULL,
97460     bankrecitem_source text NOT NULL,
97461     bankrecitem_source_id integer NOT NULL,
97462     bankrecitem_cleared boolean DEFAULT false,
97463     bankrecitem_curr_rate numeric,
97464     bankrecitem_amount numeric
97465 );
97466
97467
97468 ALTER TABLE public.bankrecitem OWNER TO admin;
97469
97470 --
97471 -- TOC entry 9559 (class 0 OID 0)
97472 -- Dependencies: 464
97473 -- Name: TABLE bankrecitem; Type: COMMENT; Schema: public; Owner: admin
97474 --
97475
97476 COMMENT ON TABLE bankrecitem IS 'Posted Bank Reconciliation Line Item information';
97477
97478
97479 --
97480 -- TOC entry 465 (class 1259 OID 146568555)
97481 -- Dependencies: 464 8
97482 -- Name: bankrecitem_bankrecitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97483 --
97484
97485 CREATE SEQUENCE bankrecitem_bankrecitem_id_seq
97486     START WITH 1
97487     INCREMENT BY 1
97488     NO MINVALUE
97489     NO MAXVALUE
97490     CACHE 1;
97491
97492
97493 ALTER TABLE public.bankrecitem_bankrecitem_id_seq OWNER TO admin;
97494
97495 --
97496 -- TOC entry 9561 (class 0 OID 0)
97497 -- Dependencies: 465
97498 -- Name: bankrecitem_bankrecitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97499 --
97500
97501 ALTER SEQUENCE bankrecitem_bankrecitem_id_seq OWNED BY bankrecitem.bankrecitem_id;
97502
97503
97504 --
97505 -- TOC entry 466 (class 1259 OID 146568557)
97506 -- Dependencies: 8
97507 -- Name: bomhead_bomhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97508 --
97509
97510 CREATE SEQUENCE bomhead_bomhead_id_seq
97511     START WITH 1
97512     INCREMENT BY 1
97513     NO MINVALUE
97514     MAXVALUE 2147483647
97515     CACHE 1;
97516
97517
97518 ALTER TABLE public.bomhead_bomhead_id_seq OWNER TO admin;
97519
97520 --
97521 -- TOC entry 467 (class 1259 OID 146568559)
97522 -- Dependencies: 8
97523 -- Name: bomitem_bomitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97524 --
97525
97526 CREATE SEQUENCE bomitem_bomitem_id_seq
97527     START WITH 1
97528     INCREMENT BY 1
97529     NO MINVALUE
97530     MAXVALUE 2147483647
97531     CACHE 1;
97532
97533
97534 ALTER TABLE public.bomitem_bomitem_id_seq OWNER TO admin;
97535
97536 --
97537 -- TOC entry 468 (class 1259 OID 146568561)
97538 -- Dependencies: 6342 6343 6344 6345 8
97539 -- Name: bomitemcost; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97540 --
97541
97542 CREATE TABLE bomitemcost (
97543     bomitemcost_id integer NOT NULL,
97544     bomitemcost_bomitem_id integer NOT NULL,
97545     bomitemcost_costelem_id integer NOT NULL,
97546     bomitemcost_lowlevel boolean DEFAULT false NOT NULL,
97547     bomitemcost_stdcost numeric(16,6) DEFAULT 0 NOT NULL,
97548     bomitemcost_posted date,
97549     bomitemcost_actcost numeric(16,6) DEFAULT 0 NOT NULL,
97550     bomitemcost_updated date,
97551     bomitemcost_curr_id integer DEFAULT basecurrid() NOT NULL
97552 );
97553
97554
97555 ALTER TABLE public.bomitemcost OWNER TO admin;
97556
97557 --
97558 -- TOC entry 9565 (class 0 OID 0)
97559 -- Dependencies: 468
97560 -- Name: TABLE bomitemcost; Type: COMMENT; Schema: public; Owner: admin
97561 --
97562
97563 COMMENT ON TABLE bomitemcost IS 'Bomitem Cost information';
97564
97565
97566 --
97567 -- TOC entry 469 (class 1259 OID 146568568)
97568 -- Dependencies: 468 8
97569 -- Name: bomitemcost_bomitemcost_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97570 --
97571
97572 CREATE SEQUENCE bomitemcost_bomitemcost_id_seq
97573     START WITH 1
97574     INCREMENT BY 1
97575     NO MINVALUE
97576     NO MAXVALUE
97577     CACHE 1;
97578
97579
97580 ALTER TABLE public.bomitemcost_bomitemcost_id_seq OWNER TO admin;
97581
97582 --
97583 -- TOC entry 9567 (class 0 OID 0)
97584 -- Dependencies: 469
97585 -- Name: bomitemcost_bomitemcost_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97586 --
97587
97588 ALTER SEQUENCE bomitemcost_bomitemcost_id_seq OWNED BY bomitemcost.bomitemcost_id;
97589
97590
97591 --
97592 -- TOC entry 470 (class 1259 OID 146568570)
97593 -- Dependencies: 258 8
97594 -- Name: bomitemsub_bomitemsub_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97595 --
97596
97597 CREATE SEQUENCE bomitemsub_bomitemsub_id_seq
97598     START WITH 1
97599     INCREMENT BY 1
97600     NO MINVALUE
97601     NO MAXVALUE
97602     CACHE 1;
97603
97604
97605 ALTER TABLE public.bomitemsub_bomitemsub_id_seq OWNER TO admin;
97606
97607 --
97608 -- TOC entry 9569 (class 0 OID 0)
97609 -- Dependencies: 470
97610 -- Name: bomitemsub_bomitemsub_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97611 --
97612
97613 ALTER SEQUENCE bomitemsub_bomitemsub_id_seq OWNED BY bomitemsub.bomitemsub_id;
97614
97615
97616 --
97617 -- TOC entry 471 (class 1259 OID 146568572)
97618 -- Dependencies: 6348 6349 8
97619 -- Name: bomwork; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97620 --
97621
97622 CREATE TABLE bomwork (
97623     bomwork_id integer NOT NULL,
97624     bomwork_set_id integer,
97625     bomwork_seqnumber integer,
97626     bomwork_item_id integer,
97627     bomwork_item_type character(1),
97628     bomwork_qtyper numeric(20,8),
97629     bomwork_scrap numeric(20,10),
97630     bomwork_status character(1),
97631     bomwork_level integer,
97632     bomwork_parent_id integer,
97633     bomwork_effective date,
97634     bomwork_expires date,
97635     bomwork_stdunitcost numeric(16,6),
97636     bomwork_actunitcost numeric(16,6),
97637     bomwork_parent_seqnumber integer,
97638     bomwork_createwo boolean,
97639     bomwork_issuemethod character(1),
97640     bomwork_char_id integer,
97641     bomwork_value text,
97642     bomwork_notes text,
97643     bomwork_ref text,
97644     bomwork_bomitem_id integer,
97645     bomwork_ecn text,
97646     bomwork_qtyfxd numeric(20,8) DEFAULT 0 NOT NULL,
97647     bomwork_qtyreq numeric(20,8) DEFAULT 0 NOT NULL
97648 );
97649
97650
97651 ALTER TABLE public.bomwork OWNER TO admin;
97652
97653 --
97654 -- TOC entry 9571 (class 0 OID 0)
97655 -- Dependencies: 471
97656 -- Name: TABLE bomwork; Type: COMMENT; Schema: public; Owner: admin
97657 --
97658
97659 COMMENT ON TABLE bomwork IS 'Temporary table for storing information requested by Bill of Materials (BOM) displays and reports';
97660
97661
97662 --
97663 -- TOC entry 9572 (class 0 OID 0)
97664 -- Dependencies: 471
97665 -- Name: COLUMN bomwork.bomwork_qtyfxd; Type: COMMENT; Schema: public; Owner: admin
97666 --
97667
97668 COMMENT ON COLUMN bomwork.bomwork_qtyfxd IS 'The fixed quantity required';
97669
97670
97671 --
97672 -- TOC entry 9573 (class 0 OID 0)
97673 -- Dependencies: 471
97674 -- Name: COLUMN bomwork.bomwork_qtyreq; Type: COMMENT; Schema: public; Owner: admin
97675 --
97676
97677 COMMENT ON COLUMN bomwork.bomwork_qtyreq IS 'The total quantity required';
97678
97679
97680 --
97681 -- TOC entry 472 (class 1259 OID 146568580)
97682 -- Dependencies: 471 8
97683 -- Name: bomwork_bomwork_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97684 --
97685
97686 CREATE SEQUENCE bomwork_bomwork_id_seq
97687     START WITH 1
97688     INCREMENT BY 1
97689     NO MINVALUE
97690     NO MAXVALUE
97691     CACHE 1;
97692
97693
97694 ALTER TABLE public.bomwork_bomwork_id_seq OWNER TO admin;
97695
97696 --
97697 -- TOC entry 9575 (class 0 OID 0)
97698 -- Dependencies: 472
97699 -- Name: bomwork_bomwork_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97700 --
97701
97702 ALTER SEQUENCE bomwork_bomwork_id_seq OWNED BY bomwork.bomwork_id;
97703
97704
97705 --
97706 -- TOC entry 473 (class 1259 OID 146568582)
97707 -- Dependencies: 8572 8
97708 -- Name: budget; Type: VIEW; Schema: public; Owner: admin
97709 --
97710
97711 CREATE VIEW budget AS
97712     SELECT budgitem.budgitem_id AS budget_id, budgitem.budgitem_period_id AS budget_period_id, budgitem.budgitem_accnt_id AS budget_accnt_id, budgitem.budgitem_amount AS budget_amount FROM budgitem;
97713
97714
97715 ALTER TABLE public.budget OWNER TO admin;
97716
97717 --
97718 -- TOC entry 474 (class 1259 OID 146568586)
97719 -- Dependencies: 260 8
97720 -- Name: budghead_budghead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97721 --
97722
97723 CREATE SEQUENCE budghead_budghead_id_seq
97724     START WITH 1
97725     INCREMENT BY 1
97726     NO MINVALUE
97727     NO MAXVALUE
97728     CACHE 1;
97729
97730
97731 ALTER TABLE public.budghead_budghead_id_seq OWNER TO admin;
97732
97733 --
97734 -- TOC entry 9578 (class 0 OID 0)
97735 -- Dependencies: 474
97736 -- Name: budghead_budghead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97737 --
97738
97739 ALTER SEQUENCE budghead_budghead_id_seq OWNED BY budghead.budghead_id;
97740
97741
97742 --
97743 -- TOC entry 475 (class 1259 OID 146568588)
97744 -- Dependencies: 263 8
97745 -- Name: budgitem_budgitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97746 --
97747
97748 CREATE SEQUENCE budgitem_budgitem_id_seq
97749     START WITH 1
97750     INCREMENT BY 1
97751     NO MINVALUE
97752     NO MAXVALUE
97753     CACHE 1;
97754
97755
97756 ALTER TABLE public.budgitem_budgitem_id_seq OWNER TO admin;
97757
97758 --
97759 -- TOC entry 9580 (class 0 OID 0)
97760 -- Dependencies: 475
97761 -- Name: budgitem_budgitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97762 --
97763
97764 ALTER SEQUENCE budgitem_budgitem_id_seq OWNED BY budgitem.budgitem_id;
97765
97766
97767 --
97768 -- TOC entry 476 (class 1259 OID 146568590)
97769 -- Dependencies: 6350 6351 8
97770 -- Name: calhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97771 --
97772
97773 CREATE TABLE calhead (
97774     calhead_id integer DEFAULT nextval(('"calhead_calhead_id_seq"'::text)::regclass) NOT NULL,
97775     calhead_type character(1),
97776     calhead_name text NOT NULL,
97777     calhead_descrip text,
97778     calhead_origin character(1),
97779     CONSTRAINT calhead_calhead_name_check CHECK ((calhead_name <> ''::text))
97780 );
97781
97782
97783 ALTER TABLE public.calhead OWNER TO admin;
97784
97785 --
97786 -- TOC entry 9582 (class 0 OID 0)
97787 -- Dependencies: 476
97788 -- Name: TABLE calhead; Type: COMMENT; Schema: public; Owner: admin
97789 --
97790
97791 COMMENT ON TABLE calhead IS 'Calendar header information';
97792
97793
97794 --
97795 -- TOC entry 477 (class 1259 OID 146568598)
97796 -- Dependencies: 8
97797 -- Name: calhead_calhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97798 --
97799
97800 CREATE SEQUENCE calhead_calhead_id_seq
97801     START WITH 1
97802     INCREMENT BY 1
97803     NO MINVALUE
97804     MAXVALUE 2147483647
97805     CACHE 1;
97806
97807
97808 ALTER TABLE public.calhead_calhead_id_seq OWNER TO admin;
97809
97810 --
97811 -- TOC entry 478 (class 1259 OID 146568600)
97812 -- Dependencies: 8
97813 -- Name: carrier_carrier_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97814 --
97815
97816 CREATE SEQUENCE carrier_carrier_id_seq
97817     START WITH 1
97818     INCREMENT BY 1
97819     NO MINVALUE
97820     MAXVALUE 2147483647
97821     CACHE 1;
97822
97823
97824 ALTER TABLE public.carrier_carrier_id_seq OWNER TO admin;
97825
97826 --
97827 -- TOC entry 479 (class 1259 OID 146568602)
97828 -- Dependencies: 267 8
97829 -- Name: cashrcpt_cashrcpt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97830 --
97831
97832 CREATE SEQUENCE cashrcpt_cashrcpt_id_seq
97833     START WITH 1
97834     INCREMENT BY 1
97835     NO MINVALUE
97836     NO MAXVALUE
97837     CACHE 1;
97838
97839
97840 ALTER TABLE public.cashrcpt_cashrcpt_id_seq OWNER TO admin;
97841
97842 --
97843 -- TOC entry 9586 (class 0 OID 0)
97844 -- Dependencies: 479
97845 -- Name: cashrcpt_cashrcpt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97846 --
97847
97848 ALTER SEQUENCE cashrcpt_cashrcpt_id_seq OWNED BY cashrcpt.cashrcpt_id;
97849
97850
97851 --
97852 -- TOC entry 480 (class 1259 OID 146568604)
97853 -- Dependencies: 271 8
97854 -- Name: cashrcptmisc_cashrcptmisc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97855 --
97856
97857 CREATE SEQUENCE cashrcptmisc_cashrcptmisc_id_seq
97858     START WITH 1
97859     INCREMENT BY 1
97860     NO MINVALUE
97861     NO MAXVALUE
97862     CACHE 1;
97863
97864
97865 ALTER TABLE public.cashrcptmisc_cashrcptmisc_id_seq OWNER TO admin;
97866
97867 --
97868 -- TOC entry 9588 (class 0 OID 0)
97869 -- Dependencies: 480
97870 -- Name: cashrcptmisc_cashrcptmisc_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97871 --
97872
97873 ALTER SEQUENCE cashrcptmisc_cashrcptmisc_id_seq OWNED BY cashrcptmisc.cashrcptmisc_id;
97874
97875
97876 --
97877 -- TOC entry 481 (class 1259 OID 146568606)
97878 -- Dependencies: 278 8
97879 -- Name: ccard_ccard_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97880 --
97881
97882 CREATE SEQUENCE ccard_ccard_id_seq
97883     START WITH 1
97884     INCREMENT BY 1
97885     NO MINVALUE
97886     NO MAXVALUE
97887     CACHE 1;
97888
97889
97890 ALTER TABLE public.ccard_ccard_id_seq OWNER TO admin;
97891
97892 --
97893 -- TOC entry 9590 (class 0 OID 0)
97894 -- Dependencies: 481
97895 -- Name: ccard_ccard_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97896 --
97897
97898 ALTER SEQUENCE ccard_ccard_id_seq OWNED BY ccard.ccard_id;
97899
97900
97901 --
97902 -- TOC entry 482 (class 1259 OID 146568608)
97903 -- Dependencies: 6353 6354 8
97904 -- Name: ccardaud; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97905 --
97906
97907 CREATE TABLE ccardaud (
97908     ccardaud_id integer NOT NULL,
97909     ccardaud_ccard_id integer,
97910     ccardaud_ccard_seq_old integer,
97911     ccardaud_ccard_seq_new integer,
97912     ccardaud_ccard_cust_id_old integer,
97913     ccardaud_ccard_cust_id_new integer,
97914     ccardaud_ccard_active_old boolean,
97915     ccardaud_ccard_active_new boolean,
97916     ccardaud_ccard_name_old bytea,
97917     ccardaud_ccard_name_new bytea,
97918     ccardaud_ccard_address1_old bytea,
97919     ccardaud_ccard_address1_new bytea,
97920     ccardaud_ccard_address2_old bytea,
97921     ccardaud_ccard_address2_new bytea,
97922     ccardaud_ccard_city_old bytea,
97923     ccardaud_ccard_city_new bytea,
97924     ccardaud_ccard_state_old bytea,
97925     ccardaud_ccard_state_new bytea,
97926     ccardaud_ccard_zip_old bytea,
97927     ccardaud_ccard_zip_new bytea,
97928     ccardaud_ccard_country_old bytea,
97929     ccardaud_ccard_country_new bytea,
97930     ccardaud_ccard_number_old bytea,
97931     ccardaud_ccard_number_new bytea,
97932     ccardaud_ccard_debit_old boolean,
97933     ccardaud_ccard_debit_new boolean,
97934     ccardaud_ccard_month_expired_old bytea,
97935     ccardaud_ccard_month_expired_new bytea,
97936     ccardaud_ccard_year_expired_old bytea,
97937     ccardaud_ccard_year_expired_new bytea,
97938     ccardaud_ccard_type_old character(1),
97939     ccardaud_ccard_type_new character(1),
97940     ccardaud_ccard_last_updated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
97941     ccardaud_ccard_last_updated_by_username text DEFAULT geteffectivextuser() NOT NULL
97942 );
97943
97944
97945 ALTER TABLE public.ccardaud OWNER TO admin;
97946
97947 --
97948 -- TOC entry 9592 (class 0 OID 0)
97949 -- Dependencies: 482
97950 -- Name: TABLE ccardaud; Type: COMMENT; Schema: public; Owner: admin
97951 --
97952
97953 COMMENT ON TABLE ccardaud IS 'Credit Card Information tracking data';
97954
97955
97956 --
97957 -- TOC entry 483 (class 1259 OID 146568616)
97958 -- Dependencies: 482 8
97959 -- Name: ccardaud_ccardaud_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
97960 --
97961
97962 CREATE SEQUENCE ccardaud_ccardaud_id_seq
97963     START WITH 1
97964     INCREMENT BY 1
97965     NO MINVALUE
97966     NO MAXVALUE
97967     CACHE 1;
97968
97969
97970 ALTER TABLE public.ccardaud_ccardaud_id_seq OWNER TO admin;
97971
97972 --
97973 -- TOC entry 9594 (class 0 OID 0)
97974 -- Dependencies: 483
97975 -- Name: ccardaud_ccardaud_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
97976 --
97977
97978 ALTER SEQUENCE ccardaud_ccardaud_id_seq OWNED BY ccardaud.ccardaud_id;
97979
97980
97981 --
97982 -- TOC entry 484 (class 1259 OID 146568618)
97983 -- Dependencies: 6356 8
97984 -- Name: ccbank; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
97985 --
97986
97987 CREATE TABLE ccbank (
97988     ccbank_id integer NOT NULL,
97989     ccbank_ccard_type text NOT NULL,
97990     ccbank_bankaccnt_id integer,
97991     CONSTRAINT ccbank_ccbank_ccard_type_check CHECK ((ccbank_ccard_type = ANY (ARRAY['A'::text, 'D'::text, 'M'::text, 'P'::text, 'V'::text])))
97992 );
97993
97994
97995 ALTER TABLE public.ccbank OWNER TO admin;
97996
97997 --
97998 -- TOC entry 485 (class 1259 OID 146568625)
97999 -- Dependencies: 484 8
98000 -- Name: ccbank_ccbank_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98001 --
98002
98003 CREATE SEQUENCE ccbank_ccbank_id_seq
98004     START WITH 1
98005     INCREMENT BY 1
98006     NO MINVALUE
98007     NO MAXVALUE
98008     CACHE 1;
98009
98010
98011 ALTER TABLE public.ccbank_ccbank_id_seq OWNER TO admin;
98012
98013 --
98014 -- TOC entry 9597 (class 0 OID 0)
98015 -- Dependencies: 485
98016 -- Name: ccbank_ccbank_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98017 --
98018
98019 ALTER SEQUENCE ccbank_ccbank_id_seq OWNED BY ccbank.ccbank_id;
98020
98021
98022 --
98023 -- TOC entry 486 (class 1259 OID 146568627)
98024 -- Dependencies: 6357 6358 6359 6360 6361 8
98025 -- Name: ccpay; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98026 --
98027
98028 CREATE TABLE ccpay (
98029     ccpay_id integer NOT NULL,
98030     ccpay_ccard_id integer,
98031     ccpay_cust_id integer,
98032     ccpay_amount numeric(20,2) DEFAULT 0.00 NOT NULL,
98033     ccpay_auth boolean DEFAULT true NOT NULL,
98034     ccpay_status character(1) NOT NULL,
98035     ccpay_type character(1) NOT NULL,
98036     ccpay_auth_charge character(1) NOT NULL,
98037     ccpay_order_number text,
98038     ccpay_order_number_seq integer,
98039     ccpay_r_avs text,
98040     ccpay_r_ordernum text,
98041     ccpay_r_error text,
98042     ccpay_r_approved text,
98043     ccpay_r_code text,
98044     ccpay_r_message text,
98045     ccpay_yp_r_time timestamp without time zone,
98046     ccpay_r_ref text,
98047     ccpay_yp_r_tdate text,
98048     ccpay_r_tax text,
98049     ccpay_r_shipping text,
98050     ccpay_yp_r_score integer,
98051     ccpay_transaction_datetime timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
98052     ccpay_by_username text DEFAULT geteffectivextuser() NOT NULL,
98053     ccpay_curr_id integer DEFAULT basecurrid(),
98054     ccpay_ccpay_id integer
98055 );
98056
98057
98058 ALTER TABLE public.ccpay OWNER TO admin;
98059
98060 --
98061 -- TOC entry 9599 (class 0 OID 0)
98062 -- Dependencies: 486
98063 -- Name: TABLE ccpay; Type: COMMENT; Schema: public; Owner: admin
98064 --
98065
98066 COMMENT ON TABLE ccpay IS 'Track Credit Card PAYments, although really this table tracs communications with Credit Card processing companies. Records in this table may progress from preauthorizations through captures to credits, or they may simply remain in their original state if there is no further processing.';
98067
98068
98069 --
98070 -- TOC entry 9600 (class 0 OID 0)
98071 -- Dependencies: 486
98072 -- Name: COLUMN ccpay.ccpay_id; Type: COMMENT; Schema: public; Owner: admin
98073 --
98074
98075 COMMENT ON COLUMN ccpay.ccpay_id IS 'Internal ID of this ccpay record.';
98076
98077
98078 --
98079 -- TOC entry 9601 (class 0 OID 0)
98080 -- Dependencies: 486
98081 -- Name: COLUMN ccpay.ccpay_ccard_id; Type: COMMENT; Schema: public; Owner: admin
98082 --
98083
98084 COMMENT ON COLUMN ccpay.ccpay_ccard_id IS 'Internal ID of the Credit Card used for this transaction.';
98085
98086
98087 --
98088 -- TOC entry 9602 (class 0 OID 0)
98089 -- Dependencies: 486
98090 -- Name: COLUMN ccpay.ccpay_cust_id; Type: COMMENT; Schema: public; Owner: admin
98091 --
98092
98093 COMMENT ON COLUMN ccpay.ccpay_cust_id IS 'Internal ID of the Customer owning the Credit Card';
98094
98095
98096 --
98097 -- TOC entry 9603 (class 0 OID 0)
98098 -- Dependencies: 486
98099 -- Name: COLUMN ccpay.ccpay_amount; Type: COMMENT; Schema: public; Owner: admin
98100 --
98101
98102 COMMENT ON COLUMN ccpay.ccpay_amount IS 'Actual amount of this transaction.';
98103
98104
98105 --
98106 -- TOC entry 9604 (class 0 OID 0)
98107 -- Dependencies: 486
98108 -- Name: COLUMN ccpay.ccpay_auth; Type: COMMENT; Schema: public; Owner: admin
98109 --
98110
98111 COMMENT ON COLUMN ccpay.ccpay_auth IS 'Boolean indicator of whether this transaction started out as a pre-authorization or not.';
98112
98113
98114 --
98115 -- TOC entry 9605 (class 0 OID 0)
98116 -- Dependencies: 486
98117 -- Name: COLUMN ccpay.ccpay_status; Type: COMMENT; Schema: public; Owner: admin
98118 --
98119
98120 COMMENT ON COLUMN ccpay.ccpay_status IS 'The status of the last attempted transaction for this record. Values include A = Authorized, C = Charged, D = Declined or otherwise rejected, V = Voided, X = Error.';
98121
98122
98123 --
98124 -- TOC entry 9606 (class 0 OID 0)
98125 -- Dependencies: 486
98126 -- Name: COLUMN ccpay.ccpay_type; Type: COMMENT; Schema: public; Owner: admin
98127 --
98128
98129 COMMENT ON COLUMN ccpay.ccpay_type IS 'The most recent type of transaction attempted with this record. Values include A = Authorize, C = Capture or Charge, R = cRedit, V = reVerse or Void.';
98130
98131
98132 --
98133 -- TOC entry 9607 (class 0 OID 0)
98134 -- Dependencies: 486
98135 -- Name: COLUMN ccpay.ccpay_auth_charge; Type: COMMENT; Schema: public; Owner: admin
98136 --
98137
98138 COMMENT ON COLUMN ccpay.ccpay_auth_charge IS 'The original type of transaction attempted with this record. Values are the same as for ccpay_type.';
98139
98140
98141 --
98142 -- TOC entry 9608 (class 0 OID 0)
98143 -- Dependencies: 486
98144 -- Name: COLUMN ccpay.ccpay_order_number; Type: COMMENT; Schema: public; Owner: admin
98145 --
98146
98147 COMMENT ON COLUMN ccpay.ccpay_order_number IS 'The original xTuple ERP order for which this credit card transaction applies. This will usually be either a Sales Order number or Credit Memo number.';
98148
98149
98150 --
98151 -- TOC entry 9609 (class 0 OID 0)
98152 -- Dependencies: 486
98153 -- Name: COLUMN ccpay.ccpay_order_number_seq; Type: COMMENT; Schema: public; Owner: admin
98154 --
98155
98156 COMMENT ON COLUMN ccpay.ccpay_order_number_seq IS 'A sequence number to differentiate between different transactions for the same ccpay_order_number. For example, if a Customer makes a down payment and a final payment for a single order, there will be two distinct ccpay records with the same ccpay_order_number but different ccpay_order_number_seq values (1 and 2, respectively).';
98157
98158
98159 --
98160 -- TOC entry 9610 (class 0 OID 0)
98161 -- Dependencies: 486
98162 -- Name: COLUMN ccpay.ccpay_r_avs; Type: COMMENT; Schema: public; Owner: admin
98163 --
98164
98165 COMMENT ON COLUMN ccpay.ccpay_r_avs IS 'The Address Verification System code returned by the credit card processing company.';
98166
98167
98168 --
98169 -- TOC entry 9611 (class 0 OID 0)
98170 -- Dependencies: 486
98171 -- Name: COLUMN ccpay.ccpay_r_ordernum; Type: COMMENT; Schema: public; Owner: admin
98172 --
98173
98174 COMMENT ON COLUMN ccpay.ccpay_r_ordernum IS 'A transaction ID returned by the credit card processing company to be used when referring to this transaction later. It may be used for voiding, crediting, or capturing previous transactions.';
98175
98176
98177 --
98178 -- TOC entry 9612 (class 0 OID 0)
98179 -- Dependencies: 486
98180 -- Name: COLUMN ccpay.ccpay_r_error; Type: COMMENT; Schema: public; Owner: admin
98181 --
98182
98183 COMMENT ON COLUMN ccpay.ccpay_r_error IS 'Error message, if any, describing why this record failed to be processed properly.';
98184
98185
98186 --
98187 -- TOC entry 9613 (class 0 OID 0)
98188 -- Dependencies: 486
98189 -- Name: COLUMN ccpay.ccpay_r_approved; Type: COMMENT; Schema: public; Owner: admin
98190 --
98191
98192 COMMENT ON COLUMN ccpay.ccpay_r_approved IS 'English text stating whether the transaction was approved, declined, hit an error, or was held for review. Specific values differ depending on the credit card processor.';
98193
98194
98195 --
98196 -- TOC entry 9614 (class 0 OID 0)
98197 -- Dependencies: 486
98198 -- Name: COLUMN ccpay.ccpay_r_code; Type: COMMENT; Schema: public; Owner: admin
98199 --
98200
98201 COMMENT ON COLUMN ccpay.ccpay_r_code IS 'The transaction Approval code returned by the credit card processor. Specific values differ depending on the credit card processor.';
98202
98203
98204 --
98205 -- TOC entry 9615 (class 0 OID 0)
98206 -- Dependencies: 486
98207 -- Name: COLUMN ccpay.ccpay_r_message; Type: COMMENT; Schema: public; Owner: admin
98208 --
98209
98210 COMMENT ON COLUMN ccpay.ccpay_r_message IS 'Additional text that describes the status of the transaction. This may be empty.';
98211
98212
98213 --
98214 -- TOC entry 9616 (class 0 OID 0)
98215 -- Dependencies: 486
98216 -- Name: COLUMN ccpay.ccpay_yp_r_time; Type: COMMENT; Schema: public; Owner: admin
98217 --
98218
98219 COMMENT ON COLUMN ccpay.ccpay_yp_r_time IS 'The time the transaction was posted according to the credit card processing company. May be blank.';
98220
98221
98222 --
98223 -- TOC entry 9617 (class 0 OID 0)
98224 -- Dependencies: 486
98225 -- Name: COLUMN ccpay.ccpay_r_ref; Type: COMMENT; Schema: public; Owner: admin
98226 --
98227
98228 COMMENT ON COLUMN ccpay.ccpay_r_ref IS 'An additional reference number assigned to this transaction by the credit card processing company.';
98229
98230
98231 --
98232 -- TOC entry 9618 (class 0 OID 0)
98233 -- Dependencies: 486
98234 -- Name: COLUMN ccpay.ccpay_yp_r_tdate; Type: COMMENT; Schema: public; Owner: admin
98235 --
98236
98237 COMMENT ON COLUMN ccpay.ccpay_yp_r_tdate IS 'The date the transaction was posted according to the credit card processing company. May be blank.';
98238
98239
98240 --
98241 -- TOC entry 9619 (class 0 OID 0)
98242 -- Dependencies: 486
98243 -- Name: COLUMN ccpay.ccpay_r_tax; Type: COMMENT; Schema: public; Owner: admin
98244 --
98245
98246 COMMENT ON COLUMN ccpay.ccpay_r_tax IS '[ deprecated ]';
98247
98248
98249 --
98250 -- TOC entry 9620 (class 0 OID 0)
98251 -- Dependencies: 486
98252 -- Name: COLUMN ccpay.ccpay_r_shipping; Type: COMMENT; Schema: public; Owner: admin
98253 --
98254
98255 COMMENT ON COLUMN ccpay.ccpay_r_shipping IS '[ deprecated ]';
98256
98257
98258 --
98259 -- TOC entry 9621 (class 0 OID 0)
98260 -- Dependencies: 486
98261 -- Name: COLUMN ccpay.ccpay_yp_r_score; Type: COMMENT; Schema: public; Owner: admin
98262 --
98263
98264 COMMENT ON COLUMN ccpay.ccpay_yp_r_score IS 'A potential fraud score returned by the credit card company. May be blank.';
98265
98266
98267 --
98268 -- TOC entry 9622 (class 0 OID 0)
98269 -- Dependencies: 486
98270 -- Name: COLUMN ccpay.ccpay_transaction_datetime; Type: COMMENT; Schema: public; Owner: admin
98271 --
98272
98273 COMMENT ON COLUMN ccpay.ccpay_transaction_datetime IS 'The date and time this record was created, unless explicitly set by the application.';
98274
98275
98276 --
98277 -- TOC entry 9623 (class 0 OID 0)
98278 -- Dependencies: 486
98279 -- Name: COLUMN ccpay.ccpay_by_username; Type: COMMENT; Schema: public; Owner: admin
98280 --
98281
98282 COMMENT ON COLUMN ccpay.ccpay_by_username IS 'The user who created this record, unless explicitly set by the application.';
98283
98284
98285 --
98286 -- TOC entry 9624 (class 0 OID 0)
98287 -- Dependencies: 486
98288 -- Name: COLUMN ccpay.ccpay_curr_id; Type: COMMENT; Schema: public; Owner: admin
98289 --
98290
98291 COMMENT ON COLUMN ccpay.ccpay_curr_id IS 'The internal ID of the currency of the ccpay_amount.';
98292
98293
98294 --
98295 -- TOC entry 9625 (class 0 OID 0)
98296 -- Dependencies: 486
98297 -- Name: COLUMN ccpay.ccpay_ccpay_id; Type: COMMENT; Schema: public; Owner: admin
98298 --
98299
98300 COMMENT ON COLUMN ccpay.ccpay_ccpay_id IS 'Foreign key to another ccpay record. This will have a value if a new ccpay record is created to record a Refund for part or all of another ccpay record.';
98301
98302
98303 --
98304 -- TOC entry 487 (class 1259 OID 146568638)
98305 -- Dependencies: 486 8
98306 -- Name: ccpay_ccpay_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98307 --
98308
98309 CREATE SEQUENCE ccpay_ccpay_id_seq
98310     START WITH 1
98311     INCREMENT BY 1
98312     NO MINVALUE
98313     NO MAXVALUE
98314     CACHE 1;
98315
98316
98317 ALTER TABLE public.ccpay_ccpay_id_seq OWNER TO admin;
98318
98319 --
98320 -- TOC entry 9627 (class 0 OID 0)
98321 -- Dependencies: 487
98322 -- Name: ccpay_ccpay_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98323 --
98324
98325 ALTER SEQUENCE ccpay_ccpay_id_seq OWNED BY ccpay.ccpay_id;
98326
98327
98328 --
98329 -- TOC entry 488 (class 1259 OID 146568640)
98330 -- Dependencies: 236 8
98331 -- Name: char_char_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98332 --
98333
98334 CREATE SEQUENCE char_char_id_seq
98335     START WITH 1
98336     INCREMENT BY 1
98337     NO MINVALUE
98338     NO MAXVALUE
98339     CACHE 1;
98340
98341
98342 ALTER TABLE public.char_char_id_seq OWNER TO admin;
98343
98344 --
98345 -- TOC entry 9629 (class 0 OID 0)
98346 -- Dependencies: 488
98347 -- Name: char_char_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98348 --
98349
98350 ALTER SEQUENCE char_char_id_seq OWNED BY "char".char_id;
98351
98352
98353 --
98354 -- TOC entry 489 (class 1259 OID 146568642)
98355 -- Dependencies: 237 8
98356 -- Name: charass_charass_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98357 --
98358
98359 CREATE SEQUENCE charass_charass_id_seq
98360     START WITH 1
98361     INCREMENT BY 1
98362     NO MINVALUE
98363     NO MAXVALUE
98364     CACHE 1;
98365
98366
98367 ALTER TABLE public.charass_charass_id_seq OWNER TO admin;
98368
98369 --
98370 -- TOC entry 9631 (class 0 OID 0)
98371 -- Dependencies: 489
98372 -- Name: charass_charass_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98373 --
98374
98375 ALTER SEQUENCE charass_charass_id_seq OWNED BY charass.charass_id;
98376
98377
98378 --
98379 -- TOC entry 490 (class 1259 OID 146568644)
98380 -- Dependencies: 6364 8
98381 -- Name: charopt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98382 --
98383
98384 CREATE TABLE charopt (
98385     charopt_id integer NOT NULL,
98386     charopt_char_id integer,
98387     charopt_value text NOT NULL,
98388     charopt_order integer DEFAULT 0 NOT NULL
98389 );
98390
98391
98392 ALTER TABLE public.charopt OWNER TO admin;
98393
98394 --
98395 -- TOC entry 9633 (class 0 OID 0)
98396 -- Dependencies: 490
98397 -- Name: TABLE charopt; Type: COMMENT; Schema: public; Owner: admin
98398 --
98399
98400 COMMENT ON TABLE charopt IS 'Stores list options for characteristics';
98401
98402
98403 --
98404 -- TOC entry 9634 (class 0 OID 0)
98405 -- Dependencies: 490
98406 -- Name: COLUMN charopt.charopt_id; Type: COMMENT; Schema: public; Owner: admin
98407 --
98408
98409 COMMENT ON COLUMN charopt.charopt_id IS 'Primary key';
98410
98411
98412 --
98413 -- TOC entry 9635 (class 0 OID 0)
98414 -- Dependencies: 490
98415 -- Name: COLUMN charopt.charopt_char_id; Type: COMMENT; Schema: public; Owner: admin
98416 --
98417
98418 COMMENT ON COLUMN charopt.charopt_char_id IS 'Reference to char table';
98419
98420
98421 --
98422 -- TOC entry 9636 (class 0 OID 0)
98423 -- Dependencies: 490
98424 -- Name: COLUMN charopt.charopt_value; Type: COMMENT; Schema: public; Owner: admin
98425 --
98426
98427 COMMENT ON COLUMN charopt.charopt_value IS 'Option value';
98428
98429
98430 --
98431 -- TOC entry 9637 (class 0 OID 0)
98432 -- Dependencies: 490
98433 -- Name: COLUMN charopt.charopt_order; Type: COMMENT; Schema: public; Owner: admin
98434 --
98435
98436 COMMENT ON COLUMN charopt.charopt_order IS 'Option sort order';
98437
98438
98439 --
98440 -- TOC entry 491 (class 1259 OID 146568651)
98441 -- Dependencies: 490 8
98442 -- Name: charopt_charopt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98443 --
98444
98445 CREATE SEQUENCE charopt_charopt_id_seq
98446     START WITH 1
98447     INCREMENT BY 1
98448     NO MINVALUE
98449     NO MAXVALUE
98450     CACHE 1;
98451
98452
98453 ALTER TABLE public.charopt_charopt_id_seq OWNER TO admin;
98454
98455 --
98456 -- TOC entry 9639 (class 0 OID 0)
98457 -- Dependencies: 491
98458 -- Name: charopt_charopt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98459 --
98460
98461 ALTER SEQUENCE charopt_charopt_id_seq OWNED BY charopt.charopt_id;
98462
98463
98464 --
98465 -- TOC entry 492 (class 1259 OID 146568653)
98466 -- Dependencies: 430 8
98467 -- Name: checkhead_checkhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98468 --
98469
98470 CREATE SEQUENCE checkhead_checkhead_id_seq
98471     START WITH 1
98472     INCREMENT BY 1
98473     NO MINVALUE
98474     NO MAXVALUE
98475     CACHE 1;
98476
98477
98478 ALTER TABLE public.checkhead_checkhead_id_seq OWNER TO admin;
98479
98480 --
98481 -- TOC entry 9641 (class 0 OID 0)
98482 -- Dependencies: 492
98483 -- Name: checkhead_checkhead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98484 --
98485
98486 ALTER SEQUENCE checkhead_checkhead_id_seq OWNED BY checkhead.checkhead_id;
98487
98488
98489 --
98490 -- TOC entry 493 (class 1259 OID 146568655)
98491 -- Dependencies: 432 8
98492 -- Name: checkitem_checkitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98493 --
98494
98495 CREATE SEQUENCE checkitem_checkitem_id_seq
98496     START WITH 1
98497     INCREMENT BY 1
98498     NO MINVALUE
98499     NO MAXVALUE
98500     CACHE 1;
98501
98502
98503 ALTER TABLE public.checkitem_checkitem_id_seq OWNER TO admin;
98504
98505 --
98506 -- TOC entry 9643 (class 0 OID 0)
98507 -- Dependencies: 493
98508 -- Name: checkitem_checkitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98509 --
98510
98511 ALTER SEQUENCE checkitem_checkitem_id_seq OWNED BY checkitem.checkitem_id;
98512
98513
98514 --
98515 -- TOC entry 494 (class 1259 OID 146568657)
98516 -- Dependencies: 8573 8
98517 -- Name: checkrecip; Type: VIEW; Schema: public; Owner: admin
98518 --
98519
98520 CREATE VIEW checkrecip AS
98521     (SELECT custinfo.cust_id AS checkrecip_id, 'C'::text AS checkrecip_type, custinfo.cust_number AS checkrecip_number, custinfo.cust_name AS checkrecip_name, 'A/R'::text AS checkrecip_gltrans_source, findaraccount(custinfo.cust_id) AS checkrecip_accnt_id, cntct.cntct_addr_id AS checkrecip_addr_id FROM (custinfo LEFT JOIN cntct ON ((custinfo.cust_cntct_id = cntct.cntct_id))) UNION ALL SELECT taxauth.taxauth_id AS checkrecip_id, 'T'::text AS checkrecip_type, taxauth.taxauth_code AS checkrecip_number, taxauth.taxauth_name AS checkrecip_name, 'G/L'::text AS checkrecip_gltrans_source, taxauth.taxauth_accnt_id AS checkrecip_accnt_id, taxauth.taxauth_addr_id AS checkrecip_addr_id FROM taxauth) UNION ALL SELECT vendinfo.vend_id AS checkrecip_id, 'V'::text AS checkrecip_type, vendinfo.vend_number AS checkrecip_number, vendinfo.vend_name AS checkrecip_name, 'A/P'::text AS checkrecip_gltrans_source, findapaccount(vendinfo.vend_id) AS checkrecip_accnt_id, vendaddrinfo.vendaddr_addr_id AS checkrecip_addr_id FROM (vendinfo LEFT JOIN vendaddrinfo ON (((vendinfo.vend_id = vendaddrinfo.vendaddr_vend_id) AND (upper(vendaddrinfo.vendaddr_code) = 'REMIT'::text))));
98522
98523
98524 ALTER TABLE public.checkrecip OWNER TO admin;
98525
98526 --
98527 -- TOC entry 495 (class 1259 OID 146568662)
98528 -- Dependencies: 8
98529 -- Name: classcode_classcode_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98530 --
98531
98532 CREATE SEQUENCE classcode_classcode_id_seq
98533     START WITH 1
98534     INCREMENT BY 1
98535     NO MINVALUE
98536     MAXVALUE 2147483647
98537     CACHE 1;
98538
98539
98540 ALTER TABLE public.classcode_classcode_id_seq OWNER TO admin;
98541
98542 --
98543 -- TOC entry 496 (class 1259 OID 146568664)
98544 -- Dependencies: 8
98545 -- Name: cmhead_cmhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98546 --
98547
98548 CREATE SEQUENCE cmhead_cmhead_id_seq
98549     START WITH 1
98550     INCREMENT BY 1
98551     NO MINVALUE
98552     MAXVALUE 2147483647
98553     CACHE 1;
98554
98555
98556 ALTER TABLE public.cmhead_cmhead_id_seq OWNER TO admin;
98557
98558 --
98559 -- TOC entry 497 (class 1259 OID 146568666)
98560 -- Dependencies: 377 8
98561 -- Name: cmheadtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98562 --
98563
98564 CREATE TABLE cmheadtax (
98565 )
98566 INHERITS (taxhist);
98567
98568
98569 ALTER TABLE public.cmheadtax OWNER TO admin;
98570
98571 --
98572 -- TOC entry 498 (class 1259 OID 146568672)
98573 -- Dependencies: 8
98574 -- Name: cmitem_cmitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98575 --
98576
98577 CREATE SEQUENCE cmitem_cmitem_id_seq
98578     START WITH 1
98579     INCREMENT BY 1
98580     NO MINVALUE
98581     MAXVALUE 2147483647
98582     CACHE 1;
98583
98584
98585 ALTER TABLE public.cmitem_cmitem_id_seq OWNER TO admin;
98586
98587 --
98588 -- TOC entry 499 (class 1259 OID 146568674)
98589 -- Dependencies: 377 8
98590 -- Name: cmitemtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98591 --
98592
98593 CREATE TABLE cmitemtax (
98594 )
98595 INHERITS (taxhist);
98596
98597
98598 ALTER TABLE public.cmitemtax OWNER TO admin;
98599
98600 --
98601 -- TOC entry 500 (class 1259 OID 146568680)
98602 -- Dependencies: 239 8
98603 -- Name: cmnttype_cmnttype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98604 --
98605
98606 CREATE SEQUENCE cmnttype_cmnttype_id_seq
98607     START WITH 1
98608     INCREMENT BY 1
98609     NO MINVALUE
98610     NO MAXVALUE
98611     CACHE 1;
98612
98613
98614 ALTER TABLE public.cmnttype_cmnttype_id_seq OWNER TO admin;
98615
98616 --
98617 -- TOC entry 9651 (class 0 OID 0)
98618 -- Dependencies: 500
98619 -- Name: cmnttype_cmnttype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98620 --
98621
98622 ALTER SEQUENCE cmnttype_cmnttype_id_seq OWNED BY cmnttype.cmnttype_id;
98623
98624
98625 --
98626 -- TOC entry 501 (class 1259 OID 146568682)
98627 -- Dependencies: 8
98628 -- Name: cmnttypesource; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98629 --
98630
98631 CREATE TABLE cmnttypesource (
98632     cmnttypesource_id integer NOT NULL,
98633     cmnttypesource_cmnttype_id integer,
98634     cmnttypesource_source_id integer
98635 );
98636
98637
98638 ALTER TABLE public.cmnttypesource OWNER TO admin;
98639
98640 --
98641 -- TOC entry 9653 (class 0 OID 0)
98642 -- Dependencies: 501
98643 -- Name: TABLE cmnttypesource; Type: COMMENT; Schema: public; Owner: admin
98644 --
98645
98646 COMMENT ON TABLE cmnttypesource IS 'Comment Type/Source association';
98647
98648
98649 --
98650 -- TOC entry 502 (class 1259 OID 146568685)
98651 -- Dependencies: 501 8
98652 -- Name: cmnttypesource_cmnttypesource_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98653 --
98654
98655 CREATE SEQUENCE cmnttypesource_cmnttypesource_id_seq
98656     START WITH 1
98657     INCREMENT BY 1
98658     NO MINVALUE
98659     NO MAXVALUE
98660     CACHE 1;
98661
98662
98663 ALTER TABLE public.cmnttypesource_cmnttypesource_id_seq OWNER TO admin;
98664
98665 --
98666 -- TOC entry 9655 (class 0 OID 0)
98667 -- Dependencies: 502
98668 -- Name: cmnttypesource_cmnttypesource_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98669 --
98670
98671 ALTER SEQUENCE cmnttypesource_cmnttypesource_id_seq OWNED BY cmnttypesource.cmnttypesource_id;
98672
98673
98674 --
98675 -- TOC entry 503 (class 1259 OID 146568687)
98676 -- Dependencies: 204 8
98677 -- Name: cntct_cntct_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98678 --
98679
98680 CREATE SEQUENCE cntct_cntct_id_seq
98681     START WITH 1
98682     INCREMENT BY 1
98683     NO MINVALUE
98684     NO MAXVALUE
98685     CACHE 1;
98686
98687
98688 ALTER TABLE public.cntct_cntct_id_seq OWNER TO admin;
98689
98690 --
98691 -- TOC entry 9657 (class 0 OID 0)
98692 -- Dependencies: 503
98693 -- Name: cntct_cntct_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98694 --
98695
98696 ALTER SEQUENCE cntct_cntct_id_seq OWNED BY cntct.cntct_id;
98697
98698
98699 --
98700 -- TOC entry 504 (class 1259 OID 146568689)
98701 -- Dependencies: 8
98702 -- Name: cntctaddr; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98703 --
98704
98705 CREATE TABLE cntctaddr (
98706     cntctaddr_id integer NOT NULL,
98707     cntctaddr_cntct_id integer,
98708     cntctaddr_primary boolean NOT NULL,
98709     cntctaddr_addr_id integer NOT NULL,
98710     cntctaddr_type character(2) NOT NULL
98711 );
98712
98713
98714 ALTER TABLE public.cntctaddr OWNER TO admin;
98715
98716 --
98717 -- TOC entry 505 (class 1259 OID 146568692)
98718 -- Dependencies: 504 8
98719 -- Name: cntctaddr_cntctaddr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98720 --
98721
98722 CREATE SEQUENCE cntctaddr_cntctaddr_id_seq
98723     START WITH 1
98724     INCREMENT BY 1
98725     NO MINVALUE
98726     NO MAXVALUE
98727     CACHE 1;
98728
98729
98730 ALTER TABLE public.cntctaddr_cntctaddr_id_seq OWNER TO admin;
98731
98732 --
98733 -- TOC entry 9660 (class 0 OID 0)
98734 -- Dependencies: 505
98735 -- Name: cntctaddr_cntctaddr_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98736 --
98737
98738 ALTER SEQUENCE cntctaddr_cntctaddr_id_seq OWNED BY cntctaddr.cntctaddr_id;
98739
98740
98741 --
98742 -- TOC entry 506 (class 1259 OID 146568694)
98743 -- Dependencies: 8
98744 -- Name: cntctdata; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98745 --
98746
98747 CREATE TABLE cntctdata (
98748     cntctdata_id integer NOT NULL,
98749     cntctdata_cntct_id integer,
98750     cntctdata_primary boolean NOT NULL,
98751     cntctdata_text text NOT NULL,
98752     cntctdata_type character(2) NOT NULL
98753 );
98754
98755
98756 ALTER TABLE public.cntctdata OWNER TO admin;
98757
98758 --
98759 -- TOC entry 507 (class 1259 OID 146568700)
98760 -- Dependencies: 506 8
98761 -- Name: cntctdata_cntctdata_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98762 --
98763
98764 CREATE SEQUENCE cntctdata_cntctdata_id_seq
98765     START WITH 1
98766     INCREMENT BY 1
98767     NO MINVALUE
98768     NO MAXVALUE
98769     CACHE 1;
98770
98771
98772 ALTER TABLE public.cntctdata_cntctdata_id_seq OWNER TO admin;
98773
98774 --
98775 -- TOC entry 9663 (class 0 OID 0)
98776 -- Dependencies: 507
98777 -- Name: cntctdata_cntctdata_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98778 --
98779
98780 ALTER SEQUENCE cntctdata_cntctdata_id_seq OWNED BY cntctdata.cntctdata_id;
98781
98782
98783 --
98784 -- TOC entry 508 (class 1259 OID 146568702)
98785 -- Dependencies: 6371 8
98786 -- Name: cntcteml; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98787 --
98788
98789 CREATE TABLE cntcteml (
98790     cntcteml_id integer NOT NULL,
98791     cntcteml_cntct_id integer,
98792     cntcteml_primary boolean DEFAULT false NOT NULL,
98793     cntcteml_email text NOT NULL
98794 );
98795
98796
98797 ALTER TABLE public.cntcteml OWNER TO admin;
98798
98799 --
98800 -- TOC entry 9665 (class 0 OID 0)
98801 -- Dependencies: 508
98802 -- Name: TABLE cntcteml; Type: COMMENT; Schema: public; Owner: admin
98803 --
98804
98805 COMMENT ON TABLE cntcteml IS 'Stores email addresses for contacts';
98806
98807
98808 --
98809 -- TOC entry 9666 (class 0 OID 0)
98810 -- Dependencies: 508
98811 -- Name: COLUMN cntcteml.cntcteml_id; Type: COMMENT; Schema: public; Owner: admin
98812 --
98813
98814 COMMENT ON COLUMN cntcteml.cntcteml_id IS 'Primary key';
98815
98816
98817 --
98818 -- TOC entry 9667 (class 0 OID 0)
98819 -- Dependencies: 508
98820 -- Name: COLUMN cntcteml.cntcteml_cntct_id; Type: COMMENT; Schema: public; Owner: admin
98821 --
98822
98823 COMMENT ON COLUMN cntcteml.cntcteml_cntct_id IS 'Reference to contact table';
98824
98825
98826 --
98827 -- TOC entry 9668 (class 0 OID 0)
98828 -- Dependencies: 508
98829 -- Name: COLUMN cntcteml.cntcteml_primary; Type: COMMENT; Schema: public; Owner: admin
98830 --
98831
98832 COMMENT ON COLUMN cntcteml.cntcteml_primary IS 'Flags whether this is the primary email address';
98833
98834
98835 --
98836 -- TOC entry 9669 (class 0 OID 0)
98837 -- Dependencies: 508
98838 -- Name: COLUMN cntcteml.cntcteml_email; Type: COMMENT; Schema: public; Owner: admin
98839 --
98840
98841 COMMENT ON COLUMN cntcteml.cntcteml_email IS 'Alternate information';
98842
98843
98844 --
98845 -- TOC entry 509 (class 1259 OID 146568709)
98846 -- Dependencies: 508 8
98847 -- Name: cntcteml_cntcteml_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98848 --
98849
98850 CREATE SEQUENCE cntcteml_cntcteml_id_seq
98851     START WITH 1
98852     INCREMENT BY 1
98853     NO MINVALUE
98854     NO MAXVALUE
98855     CACHE 1;
98856
98857
98858 ALTER TABLE public.cntcteml_cntcteml_id_seq OWNER TO admin;
98859
98860 --
98861 -- TOC entry 9671 (class 0 OID 0)
98862 -- Dependencies: 509
98863 -- Name: cntcteml_cntcteml_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
98864 --
98865
98866 ALTER SEQUENCE cntcteml_cntcteml_id_seq OWNED BY cntcteml.cntcteml_id;
98867
98868
98869 --
98870 -- TOC entry 510 (class 1259 OID 146568711)
98871 -- Dependencies: 6372 8
98872 -- Name: cntctmrgd; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98873 --
98874
98875 CREATE TABLE cntctmrgd (
98876     cntctmrgd_cntct_id integer NOT NULL,
98877     cntctmrgd_error boolean DEFAULT false
98878 );
98879
98880
98881 ALTER TABLE public.cntctmrgd OWNER TO admin;
98882
98883 --
98884 -- TOC entry 511 (class 1259 OID 146568715)
98885 -- Dependencies: 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 8
98886 -- Name: cntctsel; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98887 --
98888
98889 CREATE TABLE cntctsel (
98890     cntctsel_cntct_id integer NOT NULL,
98891     cntctsel_target boolean,
98892     cntctsel_mrg_crmacct_id boolean DEFAULT false,
98893     cntctsel_mrg_addr_id boolean DEFAULT false,
98894     cntctsel_mrg_first_name boolean DEFAULT false,
98895     cntctsel_mrg_last_name boolean DEFAULT false,
98896     cntctsel_mrg_honorific boolean DEFAULT false,
98897     cntctsel_mrg_initials boolean DEFAULT false,
98898     cntctsel_mrg_phone boolean DEFAULT false,
98899     cntctsel_mrg_phone2 boolean DEFAULT false,
98900     cntctsel_mrg_fax boolean DEFAULT false,
98901     cntctsel_mrg_email boolean DEFAULT false,
98902     cntctsel_mrg_webaddr boolean DEFAULT false,
98903     cntctsel_mrg_notes boolean DEFAULT false,
98904     cntctsel_mrg_title boolean DEFAULT false,
98905     cntctsel_mrg_middle boolean DEFAULT false,
98906     cntctsel_mrg_suffix boolean DEFAULT false,
98907     cntctsel_mrg_owner_username boolean DEFAULT false
98908 );
98909
98910
98911 ALTER TABLE public.cntctsel OWNER TO admin;
98912
98913 --
98914 -- TOC entry 512 (class 1259 OID 146568734)
98915 -- Dependencies: 8
98916 -- Name: cntslip_cntslip_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98917 --
98918
98919 CREATE SEQUENCE cntslip_cntslip_id_seq
98920     START WITH 1
98921     INCREMENT BY 1
98922     NO MINVALUE
98923     MAXVALUE 2147483647
98924     CACHE 1;
98925
98926
98927 ALTER TABLE public.cntslip_cntslip_id_seq OWNER TO admin;
98928
98929 --
98930 -- TOC entry 513 (class 1259 OID 146568736)
98931 -- Dependencies: 6389 8
98932 -- Name: cobill; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98933 --
98934
98935 CREATE TABLE cobill (
98936     cobill_id integer DEFAULT nextval(('cobill_cobill_id_seq'::text)::regclass) NOT NULL,
98937     cobill_coitem_id integer,
98938     cobill_selectdate timestamp with time zone,
98939     cobill_qty numeric(18,6),
98940     cobill_invcnum integer,
98941     cobill_toclose boolean,
98942     cobill_cobmisc_id integer,
98943     cobill_select_username text,
98944     cobill_invcitem_id integer,
98945     cobill_taxtype_id integer
98946 );
98947
98948
98949 ALTER TABLE public.cobill OWNER TO admin;
98950
98951 --
98952 -- TOC entry 9676 (class 0 OID 0)
98953 -- Dependencies: 513
98954 -- Name: TABLE cobill; Type: COMMENT; Schema: public; Owner: admin
98955 --
98956
98957 COMMENT ON TABLE cobill IS 'Billing Selection Line Item information';
98958
98959
98960 --
98961 -- TOC entry 514 (class 1259 OID 146568743)
98962 -- Dependencies: 8
98963 -- Name: cobill_cobill_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
98964 --
98965
98966 CREATE SEQUENCE cobill_cobill_id_seq
98967     START WITH 1
98968     INCREMENT BY 1
98969     NO MINVALUE
98970     MAXVALUE 2147483647
98971     CACHE 1;
98972
98973
98974 ALTER TABLE public.cobill_cobill_id_seq OWNER TO admin;
98975
98976 --
98977 -- TOC entry 515 (class 1259 OID 146568745)
98978 -- Dependencies: 377 8
98979 -- Name: cobilltax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98980 --
98981
98982 CREATE TABLE cobilltax (
98983 )
98984 INHERITS (taxhist);
98985
98986
98987 ALTER TABLE public.cobilltax OWNER TO admin;
98988
98989 --
98990 -- TOC entry 516 (class 1259 OID 146568751)
98991 -- Dependencies: 6391 6392 8
98992 -- Name: cobmisc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
98993 --
98994
98995 CREATE TABLE cobmisc (
98996     cobmisc_id integer DEFAULT nextval(('cobmisc_cobmisc_id_seq'::text)::regclass) NOT NULL,
98997     cobmisc_cohead_id integer,
98998     cobmisc_shipvia text,
98999     cobmisc_freight numeric(16,4),
99000     cobmisc_misc numeric(16,4),
99001     cobmisc_payment numeric(16,4),
99002     cobmisc_paymentref text,
99003     cobmisc_notes text,
99004     cobmisc_shipdate date,
99005     cobmisc_invcnumber integer,
99006     cobmisc_invcdate date,
99007     cobmisc_posted boolean,
99008     cobmisc_misc_accnt_id integer,
99009     cobmisc_misc_descrip text,
99010     cobmisc_closeorder boolean,
99011     cobmisc_curr_id integer DEFAULT basecurrid(),
99012     cobmisc_invchead_id integer,
99013     cobmisc_taxzone_id integer,
99014     cobmisc_taxtype_id integer
99015 );
99016
99017
99018 ALTER TABLE public.cobmisc OWNER TO admin;
99019
99020 --
99021 -- TOC entry 9680 (class 0 OID 0)
99022 -- Dependencies: 516
99023 -- Name: TABLE cobmisc; Type: COMMENT; Schema: public; Owner: admin
99024 --
99025
99026 COMMENT ON TABLE cobmisc IS 'General information about Billing Selections';
99027
99028
99029 --
99030 -- TOC entry 517 (class 1259 OID 146568759)
99031 -- Dependencies: 8
99032 -- Name: cobmisc_cobmisc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99033 --
99034
99035 CREATE SEQUENCE cobmisc_cobmisc_id_seq
99036     START WITH 1
99037     INCREMENT BY 1
99038     NO MINVALUE
99039     MAXVALUE 2147483647
99040     CACHE 1;
99041
99042
99043 ALTER TABLE public.cobmisc_cobmisc_id_seq OWNER TO admin;
99044
99045 --
99046 -- TOC entry 518 (class 1259 OID 146568761)
99047 -- Dependencies: 377 8
99048 -- Name: cobmisctax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99049 --
99050
99051 CREATE TABLE cobmisctax (
99052 )
99053 INHERITS (taxhist);
99054
99055
99056 ALTER TABLE public.cobmisctax OWNER TO admin;
99057
99058 --
99059 -- TOC entry 519 (class 1259 OID 146568767)
99060 -- Dependencies: 8
99061 -- Name: cohead_cohead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99062 --
99063
99064 CREATE SEQUENCE cohead_cohead_id_seq
99065     START WITH 1
99066     INCREMENT BY 1
99067     NO MINVALUE
99068     MAXVALUE 2147483647
99069     CACHE 1;
99070
99071
99072 ALTER TABLE public.cohead_cohead_id_seq OWNER TO admin;
99073
99074 --
99075 -- TOC entry 520 (class 1259 OID 146568769)
99076 -- Dependencies: 8
99077 -- Name: cohist_cohist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99078 --
99079
99080 CREATE SEQUENCE cohist_cohist_id_seq
99081     START WITH 1
99082     INCREMENT BY 1
99083     NO MINVALUE
99084     MAXVALUE 2147483647
99085     CACHE 1;
99086
99087
99088 ALTER TABLE public.cohist_cohist_id_seq OWNER TO admin;
99089
99090 --
99091 -- TOC entry 521 (class 1259 OID 146568771)
99092 -- Dependencies: 8
99093 -- Name: coitem_coitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99094 --
99095
99096 CREATE SEQUENCE coitem_coitem_id_seq
99097     START WITH 1
99098     INCREMENT BY 1
99099     NO MINVALUE
99100     MAXVALUE 2147483647
99101     CACHE 1;
99102
99103
99104 ALTER TABLE public.coitem_coitem_id_seq OWNER TO admin;
99105
99106 --
99107 -- TOC entry 522 (class 1259 OID 146568773)
99108 -- Dependencies: 8
99109 -- Name: comment_comment_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99110 --
99111
99112 CREATE SEQUENCE comment_comment_id_seq
99113     START WITH 1
99114     INCREMENT BY 1
99115     NO MINVALUE
99116     NO MAXVALUE
99117     CACHE 1;
99118
99119
99120 ALTER TABLE public.comment_comment_id_seq OWNER TO admin;
99121
99122 --
99123 -- TOC entry 523 (class 1259 OID 146568775)
99124 -- Dependencies: 6395 6396 8
99125 -- Name: company; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99126 --
99127
99128 CREATE TABLE company (
99129     company_id integer NOT NULL,
99130     company_number text NOT NULL,
99131     company_descrip text,
99132     company_external boolean DEFAULT false NOT NULL,
99133     company_server text,
99134     company_port integer,
99135     company_database text,
99136     company_curr_id integer,
99137     company_yearend_accnt_id integer,
99138     company_gainloss_accnt_id integer,
99139     company_dscrp_accnt_id integer,
99140     company_unrlzgainloss_accnt_id integer,
99141     CONSTRAINT company_company_number_check CHECK ((company_number <> ''::text))
99142 );
99143
99144
99145 ALTER TABLE public.company OWNER TO admin;
99146
99147 --
99148 -- TOC entry 9688 (class 0 OID 0)
99149 -- Dependencies: 523
99150 -- Name: TABLE company; Type: COMMENT; Schema: public; Owner: admin
99151 --
99152
99153 COMMENT ON TABLE company IS 'Company information';
99154
99155
99156 --
99157 -- TOC entry 524 (class 1259 OID 146568783)
99158 -- Dependencies: 523 8
99159 -- Name: company_company_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99160 --
99161
99162 CREATE SEQUENCE company_company_id_seq
99163     START WITH 1
99164     INCREMENT BY 1
99165     NO MINVALUE
99166     NO MAXVALUE
99167     CACHE 1;
99168
99169
99170 ALTER TABLE public.company_company_id_seq OWNER TO admin;
99171
99172 --
99173 -- TOC entry 9690 (class 0 OID 0)
99174 -- Dependencies: 524
99175 -- Name: company_company_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
99176 --
99177
99178 ALTER SEQUENCE company_company_id_seq OWNED BY company.company_id;
99179
99180
99181 --
99182 -- TOC entry 525 (class 1259 OID 146568785)
99183 -- Dependencies: 329 8
99184 -- Name: contrct_contrct_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99185 --
99186
99187 CREATE SEQUENCE contrct_contrct_id_seq
99188     START WITH 1
99189     INCREMENT BY 1
99190     NO MINVALUE
99191     NO MAXVALUE
99192     CACHE 1;
99193
99194
99195 ALTER TABLE public.contrct_contrct_id_seq OWNER TO admin;
99196
99197 --
99198 -- TOC entry 9692 (class 0 OID 0)
99199 -- Dependencies: 525
99200 -- Name: contrct_contrct_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
99201 --
99202
99203 ALTER SEQUENCE contrct_contrct_id_seq OWNED BY contrct.contrct_id;
99204
99205
99206 --
99207 -- TOC entry 526 (class 1259 OID 146568787)
99208 -- Dependencies: 6397 6398 6399 6401 6402 6403 8
99209 -- Name: shiphead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99210 --
99211
99212 CREATE TABLE shiphead (
99213     shiphead_id integer NOT NULL,
99214     shiphead_order_id integer NOT NULL,
99215     shiphead_order_type text NOT NULL,
99216     shiphead_number text NOT NULL,
99217     shiphead_shipvia text,
99218     shiphead_freight numeric(16,4) DEFAULT 0.0 NOT NULL,
99219     shiphead_freight_curr_id integer DEFAULT basecurrid() NOT NULL,
99220     shiphead_notes text,
99221     shiphead_shipped boolean DEFAULT false NOT NULL,
99222     shiphead_shipdate date,
99223     shiphead_shipchrg_id integer,
99224     shiphead_shipform_id integer,
99225     shiphead_sfstatus character(1) NOT NULL,
99226     shiphead_tracknum text,
99227     CONSTRAINT shiphead_shiphead_number_check CHECK ((shiphead_number <> ''::text)),
99228     CONSTRAINT shiphead_shiphead_order_type_check CHECK (((shiphead_order_type = 'SO'::text) OR (shiphead_order_type = 'TO'::text))),
99229     CONSTRAINT shiphead_shiphead_sfstatus_check CHECK ((((shiphead_sfstatus = 'D'::bpchar) OR (shiphead_sfstatus = 'N'::bpchar)) OR (shiphead_sfstatus = 'P'::bpchar)))
99230 );
99231
99232
99233 ALTER TABLE public.shiphead OWNER TO admin;
99234
99235 --
99236 -- TOC entry 9694 (class 0 OID 0)
99237 -- Dependencies: 526
99238 -- Name: TABLE shiphead; Type: COMMENT; Schema: public; Owner: admin
99239 --
99240
99241 COMMENT ON TABLE shiphead IS 'General information about Shipments';
99242
99243
99244 --
99245 -- TOC entry 527 (class 1259 OID 146568799)
99246 -- Dependencies: 6405 6406 8
99247 -- Name: shipitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99248 --
99249
99250 CREATE TABLE shipitem (
99251     shipitem_id integer NOT NULL,
99252     shipitem_orderitem_id integer NOT NULL,
99253     shipitem_shiphead_id integer NOT NULL,
99254     shipitem_qty numeric(18,6) NOT NULL,
99255     shipitem_shipped boolean DEFAULT false NOT NULL,
99256     shipitem_shipdate timestamp with time zone,
99257     shipitem_transdate timestamp with time zone,
99258     shipitem_trans_username text,
99259     shipitem_invoiced boolean DEFAULT false NOT NULL,
99260     shipitem_invcitem_id integer,
99261     shipitem_value numeric(18,6),
99262     shipitem_invhist_id integer
99263 );
99264
99265
99266 ALTER TABLE public.shipitem OWNER TO admin;
99267
99268 --
99269 -- TOC entry 9696 (class 0 OID 0)
99270 -- Dependencies: 527
99271 -- Name: TABLE shipitem; Type: COMMENT; Schema: public; Owner: admin
99272 --
99273
99274 COMMENT ON TABLE shipitem IS 'Information about Shipment Line Items';
99275
99276
99277 --
99278 -- TOC entry 528 (class 1259 OID 146568807)
99279 -- Dependencies: 8574 8
99280 -- Name: coship; Type: VIEW; Schema: public; Owner: admin
99281 --
99282
99283 CREATE VIEW coship AS
99284     SELECT shipitem.shipitem_id AS coship_id, shipitem.shipitem_orderitem_id AS coship_coitem_id, shipitem.shipitem_shipdate AS coship_shipdate, shipitem.shipitem_qty AS coship_qty, shipitem.shipitem_transdate AS coship_transdate, shipitem.shipitem_shipped AS coship_shipped, shipitem.shipitem_invoiced AS coship_invoiced, shipitem.shipitem_shiphead_id AS coship_cosmisc_id, shipitem.shipitem_trans_username AS coship_trans_username, shipitem.shipitem_invcitem_id AS coship_invcitem_id FROM shipitem, shiphead WHERE ((shipitem.shipitem_shiphead_id = shiphead.shiphead_id) AND (shiphead.shiphead_order_type = 'SO'::text));
99285
99286
99287 ALTER TABLE public.coship OWNER TO admin;
99288
99289 --
99290 -- TOC entry 529 (class 1259 OID 146568811)
99291 -- Dependencies: 8
99292 -- Name: coship_coship_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99293 --
99294
99295 CREATE SEQUENCE coship_coship_id_seq
99296     START WITH 1
99297     INCREMENT BY 1
99298     NO MINVALUE
99299     MAXVALUE 2147483647
99300     CACHE 1;
99301
99302
99303 ALTER TABLE public.coship_coship_id_seq OWNER TO admin;
99304
99305 --
99306 -- TOC entry 530 (class 1259 OID 146568813)
99307 -- Dependencies: 8575 8
99308 -- Name: cosmisc; Type: VIEW; Schema: public; Owner: admin
99309 --
99310
99311 CREATE VIEW cosmisc AS
99312     SELECT shiphead.shiphead_id AS cosmisc_id, shiphead.shiphead_order_id AS cosmisc_cohead_id, shiphead.shiphead_shipvia AS cosmisc_shipvia, shiphead.shiphead_freight AS cosmisc_freight, shiphead.shiphead_notes AS cosmisc_notes, shiphead.shiphead_shipdate AS cosmisc_shipdate, shiphead.shiphead_shipchrg_id AS cosmisc_shipchrg_id, shiphead.shiphead_shipform_id AS cosmisc_shipform_id, shiphead.shiphead_shipped AS cosmisc_shipped, shiphead.shiphead_sfstatus AS cosmisc_sfstatus, shiphead.shiphead_tracknum AS cosmisc_tracknum, shiphead.shiphead_number AS cosmisc_number FROM shiphead WHERE (shiphead.shiphead_order_type = 'SO'::text);
99313
99314
99315 ALTER TABLE public.cosmisc OWNER TO admin;
99316
99317 --
99318 -- TOC entry 531 (class 1259 OID 146568817)
99319 -- Dependencies: 8
99320 -- Name: cosmisc_cosmisc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99321 --
99322
99323 CREATE SEQUENCE cosmisc_cosmisc_id_seq
99324     START WITH 1
99325     INCREMENT BY 1
99326     NO MINVALUE
99327     MAXVALUE 2147483647
99328     CACHE 1;
99329
99330
99331 ALTER TABLE public.cosmisc_cosmisc_id_seq OWNER TO admin;
99332
99333 --
99334 -- TOC entry 532 (class 1259 OID 146568819)
99335 -- Dependencies: 8
99336 -- Name: cosrc_cosrc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99337 --
99338
99339 CREATE SEQUENCE cosrc_cosrc_id_seq
99340     START WITH 1
99341     INCREMENT BY 1
99342     NO MINVALUE
99343     MAXVALUE 2147483647
99344     CACHE 1;
99345
99346
99347 ALTER TABLE public.cosrc_cosrc_id_seq OWNER TO admin;
99348
99349 --
99350 -- TOC entry 533 (class 1259 OID 146568821)
99351 -- Dependencies: 8
99352 -- Name: costcat_costcat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99353 --
99354
99355 CREATE SEQUENCE costcat_costcat_id_seq
99356     START WITH 1
99357     INCREMENT BY 1
99358     NO MINVALUE
99359     MAXVALUE 2147483647
99360     CACHE 1;
99361
99362
99363 ALTER TABLE public.costcat_costcat_id_seq OWNER TO admin;
99364
99365 --
99366 -- TOC entry 534 (class 1259 OID 146568823)
99367 -- Dependencies: 8
99368 -- Name: costelem_costelem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99369 --
99370
99371 CREATE SEQUENCE costelem_costelem_id_seq
99372     START WITH 1
99373     INCREMENT BY 1
99374     NO MINVALUE
99375     MAXVALUE 2147483647
99376     CACHE 1;
99377
99378
99379 ALTER TABLE public.costelem_costelem_id_seq OWNER TO admin;
99380
99381 --
99382 -- TOC entry 535 (class 1259 OID 146568825)
99383 -- Dependencies: 6407 6408 6409 8
99384 -- Name: costhist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99385 --
99386
99387 CREATE TABLE costhist (
99388     costhist_id integer DEFAULT nextval(('"costhist_costhist_id_seq"'::text)::regclass) NOT NULL,
99389     costhist_item_id integer,
99390     costhist_costelem_id integer,
99391     costhist_type character(1),
99392     costhist_date timestamp with time zone,
99393     costhist_oldcost numeric(16,6),
99394     costhist_newcost numeric(16,6),
99395     costhist_lowlevel boolean,
99396     costhist_oldcurr_id integer DEFAULT basecurrid(),
99397     costhist_newcurr_id integer DEFAULT basecurrid(),
99398     costhist_username text
99399 );
99400
99401
99402 ALTER TABLE public.costhist OWNER TO admin;
99403
99404 --
99405 -- TOC entry 9705 (class 0 OID 0)
99406 -- Dependencies: 535
99407 -- Name: TABLE costhist; Type: COMMENT; Schema: public; Owner: admin
99408 --
99409
99410 COMMENT ON TABLE costhist IS 'Item Cost history';
99411
99412
99413 --
99414 -- TOC entry 536 (class 1259 OID 146568834)
99415 -- Dependencies: 8
99416 -- Name: costhist_costhist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99417 --
99418
99419 CREATE SEQUENCE costhist_costhist_id_seq
99420     START WITH 1
99421     INCREMENT BY 1
99422     NO MINVALUE
99423     NO MAXVALUE
99424     CACHE 1;
99425
99426
99427 ALTER TABLE public.costhist_costhist_id_seq OWNER TO admin;
99428
99429 --
99430 -- TOC entry 537 (class 1259 OID 146568836)
99431 -- Dependencies: 6410 8
99432 -- Name: costupdate; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99433 --
99434
99435 CREATE TABLE costupdate (
99436     costupdate_item_id integer,
99437     costupdate_lowlevel_code integer DEFAULT 1 NOT NULL,
99438     costupdate_item_type character(1)
99439 );
99440
99441
99442 ALTER TABLE public.costupdate OWNER TO admin;
99443
99444 --
99445 -- TOC entry 9708 (class 0 OID 0)
99446 -- Dependencies: 537
99447 -- Name: TABLE costupdate; Type: COMMENT; Schema: public; Owner: admin
99448 --
99449
99450 COMMENT ON TABLE costupdate IS 'Scratch area for sequencing the updating of item costs';
99451
99452
99453 --
99454 -- TOC entry 538 (class 1259 OID 146568840)
99455 -- Dependencies: 6412 6413 8
99456 -- Name: country; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99457 --
99458
99459 CREATE TABLE country (
99460     country_id integer NOT NULL,
99461     country_abbr character(2),
99462     country_name text,
99463     country_curr_abbr character(3),
99464     country_curr_name text,
99465     country_curr_number character(3),
99466     country_curr_symbol character varying(9),
99467     country_qt_number integer,
99468     CONSTRAINT country_country_abbr_check CHECK ((country_abbr <> ''::bpchar)),
99469     CONSTRAINT country_country_name_check CHECK ((country_name <> ''::text))
99470 );
99471
99472
99473 ALTER TABLE public.country OWNER TO admin;
99474
99475 --
99476 -- TOC entry 9710 (class 0 OID 0)
99477 -- Dependencies: 538
99478 -- Name: TABLE country; Type: COMMENT; Schema: public; Owner: admin
99479 --
99480
99481 COMMENT ON TABLE country IS 'Basic information and properties about countries.';
99482
99483
99484 --
99485 -- TOC entry 539 (class 1259 OID 146568848)
99486 -- Dependencies: 538 8
99487 -- Name: country_country_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99488 --
99489
99490 CREATE SEQUENCE country_country_id_seq
99491     START WITH 1
99492     INCREMENT BY 1
99493     NO MINVALUE
99494     NO MAXVALUE
99495     CACHE 1;
99496
99497
99498 ALTER TABLE public.country_country_id_seq OWNER TO admin;
99499
99500 --
99501 -- TOC entry 9712 (class 0 OID 0)
99502 -- Dependencies: 539
99503 -- Name: country_country_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
99504 --
99505
99506 ALTER SEQUENCE country_country_id_seq OWNED BY country.country_id;
99507
99508
99509 --
99510 -- TOC entry 540 (class 1259 OID 146568850)
99511 -- Dependencies: 6414 8
99512 -- Name: salesaccnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99513 --
99514
99515 CREATE TABLE salesaccnt (
99516     salesaccnt_id integer DEFAULT nextval(('"salesaccnt_salesaccnt_id_seq"'::text)::regclass) NOT NULL,
99517     salesaccnt_custtype_id integer,
99518     salesaccnt_prodcat_id integer,
99519     salesaccnt_warehous_id integer,
99520     salesaccnt_sales_accnt_id integer,
99521     salesaccnt_credit_accnt_id integer,
99522     salesaccnt_cos_accnt_id integer,
99523     salesaccnt_custtype text,
99524     salesaccnt_prodcat text,
99525     salesaccnt_returns_accnt_id integer,
99526     salesaccnt_cor_accnt_id integer,
99527     salesaccnt_cow_accnt_id integer,
99528     salesaccnt_saletype_id integer,
99529     salesaccnt_shipzone_id integer
99530 );
99531
99532
99533 ALTER TABLE public.salesaccnt OWNER TO admin;
99534
99535 --
99536 -- TOC entry 9714 (class 0 OID 0)
99537 -- Dependencies: 540
99538 -- Name: TABLE salesaccnt; Type: COMMENT; Schema: public; Owner: admin
99539 --
99540
99541 COMMENT ON TABLE salesaccnt IS 'Sales Account assignment information';
99542
99543
99544 --
99545 -- TOC entry 9715 (class 0 OID 0)
99546 -- Dependencies: 540
99547 -- Name: COLUMN salesaccnt.salesaccnt_saletype_id; Type: COMMENT; Schema: public; Owner: admin
99548 --
99549
99550 COMMENT ON COLUMN salesaccnt.salesaccnt_saletype_id IS 'Associated sale type for sales account.';
99551
99552
99553 --
99554 -- TOC entry 9716 (class 0 OID 0)
99555 -- Dependencies: 540
99556 -- Name: COLUMN salesaccnt.salesaccnt_shipzone_id; Type: COMMENT; Schema: public; Owner: admin
99557 --
99558
99559 COMMENT ON COLUMN salesaccnt.salesaccnt_shipzone_id IS 'Associated shipping zone for sales account.';
99560
99561
99562 --
99563 -- TOC entry 541 (class 1259 OID 146568857)
99564 -- Dependencies: 8576 8
99565 -- Name: creditmemoeditlist; Type: VIEW; Schema: public; Owner: admin
99566 --
99567
99568 CREATE VIEW creditmemoeditlist AS
99569     ((((SELECT cmhead.cmhead_id AS orderid, (-2) AS itemid, ('C/M-'::text || formatcreditmemonumber(cmhead.cmhead_id)) AS documentnumber, custinfo.cust_number, cmhead.cmhead_billtoname AS billtoname, cmhead.cmhead_number AS ordernumber, (-1) AS linenumber, ''::text AS item, ''::text AS itemdescrip, ''::text AS iteminvuom, ''::text AS qtytobill, ''::text AS price, formatmoney((((calccmheadamt(cmhead.cmhead_id) + cmhead.cmhead_freight) + cmhead.cmhead_misc) + calccmheadtax(cmhead.cmhead_id))) AS extprice, 'Credit'::text AS sence, COALESCE((SELECT formatglaccountlong(accnt.accnt_id) AS formatglaccountlong FROM accnt WHERE (accnt.accnt_id = findaraccount(custinfo.cust_id))), 'Not Assigned'::text) AS account FROM custinfo, cmhead WHERE ((((cmhead.cmhead_cust_id = custinfo.cust_id) AND (cmhead.cmhead_cust_id = custinfo.cust_id)) AND (NOT cmhead.cmhead_posted)) AND (NOT cmhead.cmhead_hold)) UNION SELECT cmhead.cmhead_id AS orderid, (-1) AS itemid, ''::text AS documentnumber, ''::text AS cust_number, ''::text AS billtoname, cmhead.cmhead_number AS ordernumber, (-1) AS linenumber, 'Freight'::text AS item, 'Freight Charge'::text AS itemdescrip, ''::text AS iteminvuom, ''::text AS qtytobill, formatmoney(cmhead.cmhead_freight) AS price, formatmoney(cmhead.cmhead_freight) AS extprice, 'Debit'::text AS sence, CASE WHEN (accnt.accnt_id IS NULL) THEN 'Not Assigned'::text ELSE formatglaccountlong(accnt.accnt_id) END AS account FROM (cmhead LEFT JOIN accnt ON ((accnt.accnt_id = findfreightaccount(cmhead.cmhead_cust_id)))) WHERE (((NOT cmhead.cmhead_posted) AND (NOT cmhead.cmhead_hold)) AND (cmhead.cmhead_freight <> (0)::numeric))) UNION SELECT cmhead.cmhead_id AS orderid, (-1) AS itemid, ''::text AS documentnumber, ''::text AS cust_number, ''::text AS billtoname, cmhead.cmhead_number AS ordernumber, (-1) AS linenumber, 'Misc. Charge'::text AS item, cmhead.cmhead_misc_descrip AS itemdescrip, ''::text AS iteminvuom, ''::text AS qtytobill, formatmoney(cmhead.cmhead_misc) AS price, formatmoney(cmhead.cmhead_misc) AS extprice, 'Debit'::text AS sence, formatglaccountlong(cmhead.cmhead_misc_accnt_id) AS account FROM cmhead WHERE (((NOT cmhead.cmhead_posted) AND (NOT cmhead.cmhead_hold)) AND (cmhead.cmhead_misc <> (0)::numeric))) UNION SELECT cmhead.cmhead_id AS orderid, (-1) AS itemid, ''::text AS documentnumber, ''::text AS cust_number, ''::text AS billtoname, cmhead.cmhead_number AS ordernumber, (-1) AS linenumber, 'Sales Tax'::text AS item, tax.tax_descrip AS itemdescrip, ''::text AS iteminvuom, ''::text AS qtytobill, formatmoney((cmheadtax.taxhist_tax * (-1.0))) AS price, formatmoney((cmheadtax.taxhist_tax * (-1.0))) AS extprice, 'Debit'::text AS sence, CASE WHEN (accnt.accnt_id IS NULL) THEN 'Not Assigned'::text ELSE ((formatglaccountlong(accnt.accnt_id) || ' - '::text) || accnt.accnt_descrip) END AS account FROM (((cmhead JOIN cmheadtax ON ((cmheadtax.taxhist_parent_id = cmhead.cmhead_id))) JOIN tax ON ((tax.tax_id = cmheadtax.taxhist_tax_id))) LEFT JOIN accnt ON ((accnt.accnt_id = tax.tax_sales_accnt_id))) WHERE ((NOT cmhead.cmhead_posted) AND (NOT cmhead.cmhead_hold))) UNION SELECT cmhead.cmhead_id AS orderid, (-1) AS itemid, ''::text AS documentnumber, ''::text AS cust_number, ''::text AS billtoname, cmhead.cmhead_number AS ordernumber, (-1) AS linenumber, 'Sales Tax'::text AS item, tax.tax_descrip AS itemdescrip, ''::text AS iteminvuom, ''::text AS qtytobill, formatmoney((cmitemtax.taxhist_tax * (-1.0))) AS price, formatmoney((cmitemtax.taxhist_tax * (-1.0))) AS extprice, 'Debit'::text AS sence, CASE WHEN (accnt.accnt_id IS NULL) THEN 'Not Assigned'::text ELSE ((formatglaccountlong(accnt.accnt_id) || ' - '::text) || accnt.accnt_descrip) END AS account FROM ((((cmhead JOIN cmitem ON ((cmitem.cmitem_cmhead_id = cmhead.cmhead_id))) JOIN cmitemtax ON ((cmitemtax.taxhist_parent_id = cmitem.cmitem_id))) JOIN tax ON ((tax.tax_id = cmitemtax.taxhist_tax_id))) LEFT JOIN accnt ON ((accnt.accnt_id = tax.tax_sales_accnt_id))) WHERE ((NOT cmhead.cmhead_posted) AND (NOT cmhead.cmhead_hold))) UNION SELECT cmhead.cmhead_id AS orderid, cmitem.cmitem_id AS itemid, ''::text AS documentnumber, ''::text AS cust_number, ''::text AS billtoname, cmhead.cmhead_number AS ordernumber, cmitem.cmitem_linenumber AS linenumber, item.item_number AS item, item.item_descrip1 AS itemdescrip, uom.uom_name AS iteminvuom, formatqty(COALESCE((cmitem.cmitem_qtycredit * cmitem.cmitem_qty_invuomratio), (0)::numeric)) AS qtytobill, formatprice(COALESCE((cmitem.cmitem_unitprice / cmitem.cmitem_price_invuomratio), (0)::numeric)) AS price, formatmoney(COALESCE(round(((cmitem.cmitem_qtycredit * cmitem.cmitem_qty_invuomratio) * (cmitem.cmitem_unitprice / cmitem.cmitem_price_invuomratio)), 2), (0)::numeric)) AS extprice, 'Debit'::text AS sence, COALESCE((SELECT formatglaccountlong(accnt.accnt_id) AS formatglaccountlong FROM accnt, salesaccnt WHERE ((salesaccnt.salesaccnt_sales_accnt_id = accnt.accnt_id) AND (salesaccnt.salesaccnt_id = findsalesaccnt(cmitem.cmitem_itemsite_id, 'IS'::text, cmhead.cmhead_cust_id, cmhead.cmhead_saletype_id, cmhead.cmhead_shipzone_id)))), 'Not Assigned'::text) AS account FROM item, itemsite, cmhead, cmitem, uom WHERE ((((((cmitem.cmitem_cmhead_id = cmhead.cmhead_id) AND (cmitem.cmitem_itemsite_id = itemsite.itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id)) AND (item.item_inv_uom_id = uom.uom_id)) AND (NOT cmhead.cmhead_posted)) AND (NOT cmhead.cmhead_hold)) ORDER BY 6, 7;
99570
99571
99572 ALTER TABLE public.creditmemoeditlist OWNER TO admin;
99573
99574 --
99575 -- TOC entry 542 (class 1259 OID 146568862)
99576 -- Dependencies: 8577 8
99577 -- Name: creditmemoitem; Type: VIEW; Schema: public; Owner: admin
99578 --
99579
99580 CREATE VIEW creditmemoitem AS
99581     SELECT cmitem.cmitem_id, cmitem.cmitem_cmhead_id, cmitem.cmitem_linenumber, cmitem.cmitem_itemsite_id, cmitem.cmitem_qtycredit, cmitem.cmitem_qtyreturned, cmitem.cmitem_unitprice, cmitem.cmitem_comments, cmitem.cmitem_rsncode_id, cmitem.cmitem_taxtype_id, cmitem.cmitem_qty_uom_id, cmitem.cmitem_qty_invuomratio, cmitem.cmitem_price_uom_id, cmitem.cmitem_price_invuomratio, cmitem.cmitem_raitem_id, cmitem.cmitem_updateinv, itemsite.itemsite_item_id AS item_id, COALESCE((cmitem.cmitem_qtycredit * cmitem.cmitem_qty_invuomratio), (0)::numeric) AS qty, COALESCE((cmitem.cmitem_unitprice / cmitem.cmitem_price_invuomratio), (0)::numeric) AS unitprice, COALESCE(round(((cmitem.cmitem_qtycredit * cmitem.cmitem_qty_invuomratio) * (cmitem.cmitem_unitprice / cmitem.cmitem_price_invuomratio)), 2), (0)::numeric) AS extprice, currtobase(cmhead.cmhead_curr_id, COALESCE(round(((cmitem.cmitem_qtycredit * cmitem.cmitem_qty_invuomratio) * (cmitem.cmitem_unitprice / cmitem.cmitem_price_invuomratio)), 2), (0)::numeric), cmhead.cmhead_docdate) AS baseextprice, (SELECT COALESCE(sum(cmitemtax.taxhist_tax), (0)::numeric) AS "coalesce" FROM cmitemtax WHERE (cmitemtax.taxhist_parent_id = cmitem.cmitem_id)) AS tax, CASE WHEN (itemsite.itemsite_costmethod = 'A'::bpchar) THEN avgcost(itemsite.itemsite_id) ELSE stdcost(itemsite.itemsite_item_id) END AS unitcost FROM ((cmitem JOIN cmhead ON ((cmhead.cmhead_id = cmitem.cmitem_cmhead_id))) LEFT JOIN itemsite ON ((itemsite.itemsite_id = cmitem.cmitem_itemsite_id)));
99582
99583
99584 ALTER TABLE public.creditmemoitem OWNER TO admin;
99585
99586 --
99587 -- TOC entry 9719 (class 0 OID 0)
99588 -- Dependencies: 542
99589 -- Name: VIEW creditmemoitem; Type: COMMENT; Schema: public; Owner: admin
99590 --
99591
99592 COMMENT ON VIEW creditmemoitem IS 'Single point for credit memo item (cmitem) calculations.';
99593
99594
99595 --
99596 -- TOC entry 543 (class 1259 OID 146568867)
99597 -- Dependencies: 205 8
99598 -- Name: crmacct_crmacct_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99599 --
99600
99601 CREATE SEQUENCE crmacct_crmacct_id_seq
99602     START WITH 1
99603     INCREMENT BY 1
99604     NO MINVALUE
99605     NO MAXVALUE
99606     CACHE 1;
99607
99608
99609 ALTER TABLE public.crmacct_crmacct_id_seq OWNER TO admin;
99610
99611 --
99612 -- TOC entry 9721 (class 0 OID 0)
99613 -- Dependencies: 543
99614 -- Name: crmacct_crmacct_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
99615 --
99616
99617 ALTER SEQUENCE crmacct_crmacct_id_seq OWNED BY crmacct.crmacct_id;
99618
99619
99620 --
99621 -- TOC entry 544 (class 1259 OID 146568869)
99622 -- Dependencies: 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 8
99623 -- Name: crmacctsel; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99624 --
99625
99626 CREATE TABLE crmacctsel (
99627     crmacctsel_src_crmacct_id integer NOT NULL,
99628     crmacctsel_dest_crmacct_id integer,
99629     crmacctsel_mrg_crmacct_active boolean DEFAULT false NOT NULL,
99630     crmacctsel_mrg_crmacct_cntct_id_1 boolean DEFAULT false NOT NULL,
99631     crmacctsel_mrg_crmacct_cntct_id_2 boolean DEFAULT false NOT NULL,
99632     crmacctsel_mrg_crmacct_competitor_id boolean DEFAULT false NOT NULL,
99633     crmacctsel_mrg_crmacct_cust_id boolean DEFAULT false NOT NULL,
99634     crmacctsel_mrg_crmacct_emp_id boolean DEFAULT false NOT NULL,
99635     crmacctsel_mrg_crmacct_name boolean DEFAULT false NOT NULL,
99636     crmacctsel_mrg_crmacct_notes boolean DEFAULT false NOT NULL,
99637     crmacctsel_mrg_crmacct_owner_username boolean DEFAULT false NOT NULL,
99638     crmacctsel_mrg_crmacct_parent_id boolean DEFAULT false NOT NULL,
99639     crmacctsel_mrg_crmacct_partner_id boolean DEFAULT false NOT NULL,
99640     crmacctsel_mrg_crmacct_prospect_id boolean DEFAULT false NOT NULL,
99641     crmacctsel_mrg_crmacct_salesrep_id boolean DEFAULT false NOT NULL,
99642     crmacctsel_mrg_crmacct_taxauth_id boolean DEFAULT false NOT NULL,
99643     crmacctsel_mrg_crmacct_type boolean DEFAULT false NOT NULL,
99644     crmacctsel_mrg_crmacct_usr_username boolean DEFAULT false NOT NULL,
99645     crmacctsel_mrg_crmacct_vend_id boolean DEFAULT false NOT NULL,
99646     crmacctsel_mrg_crmacct_number boolean DEFAULT false NOT NULL
99647 );
99648
99649
99650 ALTER TABLE public.crmacctsel OWNER TO admin;
99651
99652 --
99653 -- TOC entry 9723 (class 0 OID 0)
99654 -- Dependencies: 544
99655 -- Name: TABLE crmacctsel; Type: COMMENT; Schema: public; Owner: admin
99656 --
99657
99658 COMMENT ON TABLE crmacctsel IS 'This table records the proposed conditions of a CRM Account merge. When this merge is performed, the BOOLEAN columns in this table indicate which values in the crmacct table will be copied to the target record. Data in this table are temporary and will be removed by a purge.';
99659
99660
99661 --
99662 -- TOC entry 9724 (class 0 OID 0)
99663 -- Dependencies: 544
99664 -- Name: COLUMN crmacctsel.crmacctsel_src_crmacct_id; Type: COMMENT; Schema: public; Owner: admin
99665 --
99666
99667 COMMENT ON COLUMN crmacctsel.crmacctsel_src_crmacct_id IS 'This is the internal ID of the CRM Account record the data will come from during the merge.';
99668
99669
99670 --
99671 -- TOC entry 9725 (class 0 OID 0)
99672 -- Dependencies: 544
99673 -- Name: COLUMN crmacctsel.crmacctsel_dest_crmacct_id; Type: COMMENT; Schema: public; Owner: admin
99674 --
99675
99676 COMMENT ON COLUMN crmacctsel.crmacctsel_dest_crmacct_id IS 'This is the internal ID of the CRM Account record the data will go to during the merge. If crmacctsel_src_crmacct_id = crmacctsel_dest_crmacct_id, they indicate which crmacct record is the destination of the merge, meaning this is the record that will remain in the database after the merge has been completed and the intermediate data have been purged.';
99677
99678
99679 --
99680 -- TOC entry 545 (class 1259 OID 146568890)
99681 -- Dependencies: 6434 8
99682 -- Name: curr_rate; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99683 --
99684
99685 CREATE TABLE curr_rate (
99686     curr_rate_id integer NOT NULL,
99687     curr_id integer NOT NULL,
99688     curr_rate numeric(16,8) NOT NULL,
99689     curr_effective date NOT NULL,
99690     curr_expires date NOT NULL,
99691     CONSTRAINT curr_rate_curr_rate_check CHECK ((curr_rate > (0)::numeric))
99692 );
99693
99694
99695 ALTER TABLE public.curr_rate OWNER TO admin;
99696
99697 --
99698 -- TOC entry 9727 (class 0 OID 0)
99699 -- Dependencies: 545
99700 -- Name: TABLE curr_rate; Type: COMMENT; Schema: public; Owner: admin
99701 --
99702
99703 COMMENT ON TABLE curr_rate IS 'Exchange Rates Between Base and Foreign Currencies';
99704
99705
99706 --
99707 -- TOC entry 546 (class 1259 OID 146568894)
99708 -- Dependencies: 545 8
99709 -- Name: curr_rate_curr_rate_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99710 --
99711
99712 CREATE SEQUENCE curr_rate_curr_rate_id_seq
99713     START WITH 1
99714     INCREMENT BY 1
99715     NO MINVALUE
99716     NO MAXVALUE
99717     CACHE 1;
99718
99719
99720 ALTER TABLE public.curr_rate_curr_rate_id_seq OWNER TO admin;
99721
99722 --
99723 -- TOC entry 9729 (class 0 OID 0)
99724 -- Dependencies: 546
99725 -- Name: curr_rate_curr_rate_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
99726 --
99727
99728 ALTER SEQUENCE curr_rate_curr_rate_id_seq OWNED BY curr_rate.curr_rate_id;
99729
99730
99731 --
99732 -- TOC entry 547 (class 1259 OID 146568896)
99733 -- Dependencies: 208 8
99734 -- Name: curr_symbol_curr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99735 --
99736
99737 CREATE SEQUENCE curr_symbol_curr_id_seq
99738     START WITH 1
99739     INCREMENT BY 1
99740     NO MINVALUE
99741     NO MAXVALUE
99742     CACHE 1;
99743
99744
99745 ALTER TABLE public.curr_symbol_curr_id_seq OWNER TO admin;
99746
99747 --
99748 -- TOC entry 9731 (class 0 OID 0)
99749 -- Dependencies: 547
99750 -- Name: curr_symbol_curr_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
99751 --
99752
99753 ALTER SEQUENCE curr_symbol_curr_id_seq OWNED BY curr_symbol.curr_id;
99754
99755
99756 --
99757 -- TOC entry 548 (class 1259 OID 146568898)
99758 -- Dependencies: 8578 8
99759 -- Name: cust; Type: VIEW; Schema: public; Owner: admin
99760 --
99761
99762 CREATE VIEW cust AS
99763     SELECT custinfo.cust_id, custinfo.cust_active, custinfo.cust_custtype_id, custinfo.cust_salesrep_id, custinfo.cust_commprcnt, custinfo.cust_name, m.addr_line1 AS cust_address1, m.addr_line2 AS cust_address2, m.addr_line3 AS cust_address3, m.addr_city AS cust_city, m.addr_state AS cust_state, m.addr_postalcode AS cust_zipcode, btrim(((mc.cntct_first_name || ' '::text) || mc.cntct_last_name)) AS cust_contact, mc.cntct_phone AS cust_phone, mc.cntct_fax AS cust_fax, mc.cntct_email AS cust_email, c.addr_line1 AS cust_corraddress1, c.addr_line2 AS cust_corraddress2, c.addr_line3 AS cust_corraddress3, c.addr_city AS cust_corrcity, c.addr_state AS cust_corrstate, c.addr_postalcode AS cust_corrzipcode, btrim(((cc.cntct_first_name || ' '::text) || cc.cntct_last_name)) AS cust_corrcontact, cc.cntct_phone AS cust_corrphone, cc.cntct_fax AS cust_corrfax, cc.cntct_email AS cust_corremail, custinfo.cust_creditlmt, custinfo.cust_creditrating, custinfo.cust_financecharge, custinfo.cust_backorder, custinfo.cust_partialship, custinfo.cust_terms_id, custinfo.cust_discntprcnt, custinfo.cust_taxzone_id, custinfo.cust_balmethod, custinfo.cust_ffshipto, custinfo.cust_shipform_id, custinfo.cust_shipvia, custinfo.cust_blanketpos, custinfo.cust_shipchrg_id, custinfo.cust_creditstatus, custinfo.cust_comments, custinfo.cust_ffbillto, m.addr_country AS cust_country, c.addr_country AS cust_corrcountry, custinfo.cust_usespos, custinfo.cust_number, custinfo.cust_dateadded, custinfo.cust_exported, custinfo.cust_emaildelivery, custinfo.cust_ediemail, custinfo.cust_edisubject, custinfo.cust_edifilename, custinfo.cust_ediemailbody, custinfo.cust_autoupdatestatus, custinfo.cust_autoholdorders, custinfo.cust_edicc, custinfo.cust_ediprofile_id, custinfo.cust_preferred_warehous_id, custinfo.cust_curr_id, custinfo.cust_creditlmt_curr_id FROM ((((custinfo LEFT JOIN cntct mc ON ((custinfo.cust_cntct_id = mc.cntct_id))) LEFT JOIN addr m ON ((mc.cntct_addr_id = m.addr_id))) LEFT JOIN cntct cc ON ((custinfo.cust_corrcntct_id = cc.cntct_id))) LEFT JOIN addr c ON ((cc.cntct_addr_id = c.addr_id)));
99764
99765
99766 ALTER TABLE public.cust OWNER TO admin;
99767
99768 --
99769 -- TOC entry 549 (class 1259 OID 146568903)
99770 -- Dependencies: 8
99771 -- Name: cust_serial_seq; Type: SEQUENCE; Schema: public; Owner: admin
99772 --
99773
99774 CREATE SEQUENCE cust_serial_seq
99775     START WITH 1
99776     INCREMENT BY 1
99777     NO MINVALUE
99778     MAXVALUE 2147483647
99779     CACHE 1;
99780
99781
99782 ALTER TABLE public.cust_serial_seq OWNER TO admin;
99783
99784 --
99785 -- TOC entry 550 (class 1259 OID 146568905)
99786 -- Dependencies: 6435 8
99787 -- Name: custform; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99788 --
99789
99790 CREATE TABLE custform (
99791     custform_id integer DEFAULT nextval(('"custform_custform_id_seq"'::text)::regclass) NOT NULL,
99792     custform_custtype_id integer,
99793     custform_custtype text,
99794     custform_invoice_report_id integer,
99795     custform_creditmemo_report_id integer,
99796     custform_quote_report_id integer,
99797     custform_packinglist_report_id integer,
99798     custform_statement_report_id integer,
99799     custform_sopicklist_report_id integer,
99800     custform_invoice_report_name text,
99801     custform_creditmemo_report_name text,
99802     custform_quote_report_name text,
99803     custform_packinglist_report_name text,
99804     custform_statement_report_name text,
99805     custform_sopicklist_report_name text
99806 );
99807
99808
99809 ALTER TABLE public.custform OWNER TO admin;
99810
99811 --
99812 -- TOC entry 9735 (class 0 OID 0)
99813 -- Dependencies: 550
99814 -- Name: TABLE custform; Type: COMMENT; Schema: public; Owner: admin
99815 --
99816
99817 COMMENT ON TABLE custform IS 'Customer Form assignment information';
99818
99819
99820 --
99821 -- TOC entry 9736 (class 0 OID 0)
99822 -- Dependencies: 550
99823 -- Name: COLUMN custform.custform_invoice_report_id; Type: COMMENT; Schema: public; Owner: admin
99824 --
99825
99826 COMMENT ON COLUMN custform.custform_invoice_report_id IS 'Obsolete -- reference custform_invoice_report_name instead.';
99827
99828
99829 --
99830 -- TOC entry 9737 (class 0 OID 0)
99831 -- Dependencies: 550
99832 -- Name: COLUMN custform.custform_creditmemo_report_id; Type: COMMENT; Schema: public; Owner: admin
99833 --
99834
99835 COMMENT ON COLUMN custform.custform_creditmemo_report_id IS 'Obsolete -- reference custform_creditmemo_report_name instead.';
99836
99837
99838 --
99839 -- TOC entry 9738 (class 0 OID 0)
99840 -- Dependencies: 550
99841 -- Name: COLUMN custform.custform_quote_report_id; Type: COMMENT; Schema: public; Owner: admin
99842 --
99843
99844 COMMENT ON COLUMN custform.custform_quote_report_id IS 'Obsolete -- reference custform_quote_report_name instead.';
99845
99846
99847 --
99848 -- TOC entry 9739 (class 0 OID 0)
99849 -- Dependencies: 550
99850 -- Name: COLUMN custform.custform_packinglist_report_id; Type: COMMENT; Schema: public; Owner: admin
99851 --
99852
99853 COMMENT ON COLUMN custform.custform_packinglist_report_id IS 'Obsolete -- reference custform_packinglist_report_name instead.';
99854
99855
99856 --
99857 -- TOC entry 9740 (class 0 OID 0)
99858 -- Dependencies: 550
99859 -- Name: COLUMN custform.custform_statement_report_id; Type: COMMENT; Schema: public; Owner: admin
99860 --
99861
99862 COMMENT ON COLUMN custform.custform_statement_report_id IS 'Obsolete -- reference custform_statement_report_name instead.';
99863
99864
99865 --
99866 -- TOC entry 9741 (class 0 OID 0)
99867 -- Dependencies: 550
99868 -- Name: COLUMN custform.custform_sopicklist_report_id; Type: COMMENT; Schema: public; Owner: admin
99869 --
99870
99871 COMMENT ON COLUMN custform.custform_sopicklist_report_id IS 'Obsolete -- reference custform_sopicklist_report_name instead.';
99872
99873
99874 --
99875 -- TOC entry 551 (class 1259 OID 146568912)
99876 -- Dependencies: 8
99877 -- Name: custform_custform_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99878 --
99879
99880 CREATE SEQUENCE custform_custform_id_seq
99881     START WITH 1
99882     INCREMENT BY 1
99883     NO MINVALUE
99884     NO MAXVALUE
99885     CACHE 1;
99886
99887
99888 ALTER TABLE public.custform_custform_id_seq OWNER TO admin;
99889
99890 --
99891 -- TOC entry 552 (class 1259 OID 146568914)
99892 -- Dependencies: 6436 6437 8
99893 -- Name: custgrp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99894 --
99895
99896 CREATE TABLE custgrp (
99897     custgrp_id integer DEFAULT nextval(('"custgrp_custgrp_id_seq"'::text)::regclass) NOT NULL,
99898     custgrp_name text NOT NULL,
99899     custgrp_descrip text,
99900     CONSTRAINT custgrp_custgrp_name_check CHECK ((custgrp_name <> ''::text))
99901 );
99902
99903
99904 ALTER TABLE public.custgrp OWNER TO admin;
99905
99906 --
99907 -- TOC entry 9744 (class 0 OID 0)
99908 -- Dependencies: 552
99909 -- Name: TABLE custgrp; Type: COMMENT; Schema: public; Owner: admin
99910 --
99911
99912 COMMENT ON TABLE custgrp IS 'Customer Group information';
99913
99914
99915 --
99916 -- TOC entry 553 (class 1259 OID 146568922)
99917 -- Dependencies: 8
99918 -- Name: custgrp_custgrp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99919 --
99920
99921 CREATE SEQUENCE custgrp_custgrp_id_seq
99922     START WITH 1
99923     INCREMENT BY 1
99924     NO MINVALUE
99925     NO MAXVALUE
99926     CACHE 1;
99927
99928
99929 ALTER TABLE public.custgrp_custgrp_id_seq OWNER TO admin;
99930
99931 --
99932 -- TOC entry 554 (class 1259 OID 146568924)
99933 -- Dependencies: 6438 8
99934 -- Name: custgrpitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
99935 --
99936
99937 CREATE TABLE custgrpitem (
99938     custgrpitem_id integer DEFAULT nextval(('"custgrpitem_custgrpitem_id_seq"'::text)::regclass) NOT NULL,
99939     custgrpitem_custgrp_id integer,
99940     custgrpitem_cust_id integer
99941 );
99942
99943
99944 ALTER TABLE public.custgrpitem OWNER TO admin;
99945
99946 --
99947 -- TOC entry 9747 (class 0 OID 0)
99948 -- Dependencies: 554
99949 -- Name: TABLE custgrpitem; Type: COMMENT; Schema: public; Owner: admin
99950 --
99951
99952 COMMENT ON TABLE custgrpitem IS 'Customer Group Item information';
99953
99954
99955 --
99956 -- TOC entry 555 (class 1259 OID 146568928)
99957 -- Dependencies: 8
99958 -- Name: custgrpitem_custgrpitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99959 --
99960
99961 CREATE SEQUENCE custgrpitem_custgrpitem_id_seq
99962     START WITH 1
99963     INCREMENT BY 1
99964     NO MINVALUE
99965     NO MAXVALUE
99966     CACHE 1;
99967
99968
99969 ALTER TABLE public.custgrpitem_custgrpitem_id_seq OWNER TO admin;
99970
99971 --
99972 -- TOC entry 556 (class 1259 OID 146568930)
99973 -- Dependencies: 8
99974 -- Name: custtype_custtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99975 --
99976
99977 CREATE SEQUENCE custtype_custtype_id_seq
99978     START WITH 1
99979     INCREMENT BY 1
99980     NO MINVALUE
99981     MAXVALUE 2147483647
99982     CACHE 1;
99983
99984
99985 ALTER TABLE public.custtype_custtype_id_seq OWNER TO admin;
99986
99987 --
99988 -- TOC entry 557 (class 1259 OID 146568932)
99989 -- Dependencies: 291 8
99990 -- Name: dept_dept_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
99991 --
99992
99993 CREATE SEQUENCE dept_dept_id_seq
99994     START WITH 1
99995     INCREMENT BY 1
99996     NO MINVALUE
99997     NO MAXVALUE
99998     CACHE 1;
99999
100000
100001 ALTER TABLE public.dept_dept_id_seq OWNER TO admin;
100002
100003 --
100004 -- TOC entry 9751 (class 0 OID 0)
100005 -- Dependencies: 557
100006 -- Name: dept_dept_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100007 --
100008
100009 ALTER SEQUENCE dept_dept_id_seq OWNED BY dept.dept_id;
100010
100011
100012 --
100013 -- TOC entry 558 (class 1259 OID 146568934)
100014 -- Dependencies: 6439 8
100015 -- Name: destination; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100016 --
100017
100018 CREATE TABLE destination (
100019     destination_id integer DEFAULT nextval(('"destination_destination_id_seq"'::text)::regclass) NOT NULL,
100020     destination_name text,
100021     destination_city text,
100022     destination_state text,
100023     destination_comments text
100024 );
100025
100026
100027 ALTER TABLE public.destination OWNER TO admin;
100028
100029 --
100030 -- TOC entry 9753 (class 0 OID 0)
100031 -- Dependencies: 558
100032 -- Name: TABLE destination; Type: COMMENT; Schema: public; Owner: admin
100033 --
100034
100035 COMMENT ON TABLE destination IS 'Destination information';
100036
100037
100038 --
100039 -- TOC entry 559 (class 1259 OID 146568941)
100040 -- Dependencies: 8
100041 -- Name: destination_destination_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100042 --
100043
100044 CREATE SEQUENCE destination_destination_id_seq
100045     START WITH 1
100046     INCREMENT BY 1
100047     NO MINVALUE
100048     MAXVALUE 2147483647
100049     CACHE 1;
100050
100051
100052 ALTER TABLE public.destination_destination_id_seq OWNER TO admin;
100053
100054 --
100055 -- TOC entry 560 (class 1259 OID 146568943)
100056 -- Dependencies: 6440 6441 6442 6443 6444 6445 6446 6447 6448 8
100057 -- Name: wo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100058 --
100059
100060 CREATE TABLE wo (
100061     wo_id integer DEFAULT nextval(('wo_wo_id_seq'::text)::regclass) NOT NULL,
100062     wo_number integer,
100063     wo_subnumber integer,
100064     wo_status character(1),
100065     wo_itemsite_id integer,
100066     wo_startdate date,
100067     wo_duedate date,
100068     wo_ordtype character(1),
100069     wo_ordid integer,
100070     wo_qtyord numeric(18,6),
100071     wo_qtyrcv numeric(18,6),
100072     wo_adhoc boolean,
100073     wo_itemcfg_series integer,
100074     wo_imported boolean,
100075     wo_wipvalue numeric(16,6) DEFAULT 0,
100076     wo_postedvalue numeric(16,6) DEFAULT 0,
100077     wo_prodnotes text,
100078     wo_prj_id integer,
100079     wo_priority integer DEFAULT 1 NOT NULL,
100080     wo_brdvalue numeric(16,6) DEFAULT 0,
100081     wo_bom_rev_id integer DEFAULT (-1),
100082     wo_boo_rev_id integer DEFAULT (-1),
100083     wo_cosmethod character(1),
100084     wo_womatl_id integer,
100085     wo_username text DEFAULT geteffectivextuser(),
100086     CONSTRAINT chk_wo_cosmethod CHECK ((((wo_cosmethod = NULL::bpchar) OR (wo_cosmethod = 'D'::bpchar)) OR (wo_cosmethod = 'P'::bpchar)))
100087 );
100088
100089
100090 ALTER TABLE public.wo OWNER TO admin;
100091
100092 --
100093 -- TOC entry 9756 (class 0 OID 0)
100094 -- Dependencies: 560
100095 -- Name: TABLE wo; Type: COMMENT; Schema: public; Owner: admin
100096 --
100097
100098 COMMENT ON TABLE wo IS 'Work Order information';
100099
100100
100101 --
100102 -- TOC entry 561 (class 1259 OID 146568958)
100103 -- Dependencies: 8579 8
100104 -- Name: docinfo; Type: VIEW; Schema: public; Owner: admin
100105 --
100106
100107 CREATE VIEW docinfo AS
100108     (((((((((((((((((((((((((((((SELECT imageass.imageass_id AS id, (image.image_id)::text AS target_number, 'IMG'::text AS target_type, imageass.imageass_image_id AS target_id, imageass.imageass_source AS source_type, imageass.imageass_source_id AS source_id, image.image_name AS name, image.image_descrip AS description, imageass.imageass_purpose AS purpose FROM imageass, image WHERE (imageass.imageass_image_id = image.image_id) UNION ALL SELECT url.url_id AS id, (url.url_id)::text AS target_number, 'URL'::text AS target_type, url.url_id AS target_id, url.url_source AS source_type, url.url_source_id AS source_id, url.url_title AS name, url.url_url AS description, 'S'::bpchar AS purpose FROM url WHERE (url.url_stream IS NULL)) UNION ALL SELECT url.url_id AS id, (url.url_id)::text AS target_number, 'FILE'::text AS target_type, url.url_id AS target_id, url.url_source AS source_type, url.url_source_id AS source_id, url.url_title AS name, url.url_url AS description, 'S'::bpchar AS purpose FROM url WHERE (url.url_stream IS NOT NULL)) UNION ALL SELECT docass.docass_id AS id, (incdt.incdt_number)::text AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, incdt.incdt_summary AS name, firstline(incdt.incdt_descrip) AS description, docass.docass_purpose AS purpose FROM docass, incdt WHERE ((docass.docass_target_type = 'INCDT'::text) AND (docass.docass_target_id = incdt.incdt_id))) UNION ALL SELECT docass.docass_id AS id, (incdt.incdt_number)::text AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, incdt.incdt_summary AS name, firstline(incdt.incdt_descrip) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, incdt WHERE ((docass.docass_source_type = 'INCDT'::text) AND (docass.docass_source_id = incdt.incdt_id))) UNION ALL SELECT docass.docass_id AS id, (todoitem.todoitem_id)::text AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, todoitem.todoitem_name AS name, firstline(todoitem.todoitem_description) AS description, docass.docass_purpose AS purpose FROM docass, todoitem WHERE ((docass.docass_target_type = 'TODO'::text) AND (docass.docass_target_id = todoitem.todoitem_id))) UNION ALL SELECT docass.docass_id AS id, (todoitem.todoitem_id)::text AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, todoitem.todoitem_name AS name, firstline(todoitem.todoitem_description) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, todoitem WHERE ((docass.docass_source_type = 'TODO'::text) AND (docass.docass_source_id = todoitem.todoitem_id))) UNION ALL SELECT docass.docass_id AS id, prj.prj_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, prj.prj_name AS name, firstline(prj.prj_descrip) AS description, docass.docass_purpose AS purpose FROM docass, prj WHERE ((docass.docass_target_type = 'J'::text) AND (docass.docass_target_id = prj.prj_id))) UNION ALL SELECT docass.docass_id AS id, prj.prj_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, prj.prj_name AS name, firstline(prj.prj_descrip) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, prj WHERE ((docass.docass_source_type = 'J'::text) AND (docass.docass_source_id = prj.prj_id))) UNION ALL SELECT docass.docass_id AS id, item.item_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, firstline(item.item_descrip1) AS name, firstline(item.item_descrip2) AS description, docass.docass_purpose AS purpose FROM docass, item WHERE ((docass.docass_target_type = 'I'::text) AND (docass.docass_target_id = item.item_id))) UNION ALL SELECT docass.docass_id AS id, item.item_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, firstline(item.item_descrip1) AS name, firstline(item.item_descrip2) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, item WHERE ((docass.docass_source_type = 'I'::text) AND (docass.docass_source_id = item.item_id))) UNION ALL SELECT docass.docass_id AS id, crmacct.crmacct_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, crmacct.crmacct_name AS name, firstline(crmacct.crmacct_notes) AS description, docass.docass_purpose AS purpose FROM docass, crmacct WHERE ((docass.docass_target_type = 'CRMA'::text) AND (docass.docass_target_id = crmacct.crmacct_id))) UNION ALL SELECT docass.docass_id AS id, crmacct.crmacct_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, crmacct.crmacct_name AS name, firstline(crmacct.crmacct_notes) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, crmacct WHERE ((docass.docass_source_type = 'CRMA'::text) AND (docass.docass_source_id = crmacct.crmacct_id))) UNION SELECT docass.docass_id AS id, custinfo.cust_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, custinfo.cust_name AS name, firstline(custinfo.cust_comments) AS description, docass.docass_purpose AS purpose FROM docass, custinfo WHERE ((docass.docass_target_type = 'C'::text) AND (docass.docass_target_id = custinfo.cust_id))) UNION ALL SELECT docass.docass_id AS id, custinfo.cust_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, custinfo.cust_name AS name, firstline(custinfo.cust_comments) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, custinfo WHERE ((docass.docass_source_type = 'C'::text) AND (docass.docass_source_id = custinfo.cust_id))) UNION ALL SELECT docass.docass_id AS id, vendinfo.vend_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, vendinfo.vend_name AS name, firstline(vendinfo.vend_comments) AS description, docass.docass_purpose AS purpose FROM docass, vendinfo WHERE ((docass.docass_target_type = 'V'::text) AND (docass.docass_target_id = vendinfo.vend_id))) UNION ALL SELECT docass.docass_id AS id, vendinfo.vend_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, vendinfo.vend_name AS name, firstline(vendinfo.vend_comments) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, vendinfo WHERE ((docass.docass_source_type = 'V'::text) AND (docass.docass_source_id = vendinfo.vend_id))) UNION ALL SELECT docass.docass_id AS id, cntct.cntct_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, cntct.cntct_name AS name, cntct.cntct_title AS description, docass.docass_purpose AS purpose FROM docass, cntct WHERE ((docass.docass_target_type = 'T'::text) AND (docass.docass_target_id = cntct.cntct_id))) UNION ALL SELECT docass.docass_id AS id, cntct.cntct_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, cntct.cntct_name AS name, cntct.cntct_title AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, cntct WHERE ((docass.docass_source_type = 'T'::text) AND (docass.docass_source_id = cntct.cntct_id))) UNION ALL SELECT docass.docass_id AS id, (ophead.ophead_id)::text AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, ophead.ophead_name AS name, firstline(ophead.ophead_notes) AS description, docass.docass_purpose AS purpose FROM docass, ophead WHERE ((docass.docass_target_type = 'OPP'::text) AND (docass.docass_target_id = ophead.ophead_id))) UNION ALL SELECT docass.docass_id AS id, (ophead.ophead_id)::text AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, ophead.ophead_name AS name, firstline(ophead.ophead_notes) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, ophead WHERE ((docass.docass_source_type = 'OPP'::text) AND (docass.docass_source_id = ophead.ophead_id))) UNION ALL SELECT docass.docass_id AS id, quhead.quhead_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, custinfo.cust_name AS name, firstline(quhead.quhead_ordercomments) AS description, docass.docass_purpose AS purpose FROM docass, quhead, custinfo WHERE (((docass.docass_target_type = 'Q'::text) AND (docass.docass_target_id = quhead.quhead_id)) AND (custinfo.cust_id = quhead.quhead_cust_id))) UNION ALL SELECT docass.docass_id AS id, quhead.quhead_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, custinfo.cust_name AS name, firstline(quhead.quhead_ordercomments) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, quhead, custinfo WHERE (((docass.docass_source_type = 'Q'::text) AND (docass.docass_source_id = quhead.quhead_id)) AND (custinfo.cust_id = quhead.quhead_cust_id))) UNION ALL SELECT docass.docass_id AS id, cohead.cohead_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, custinfo.cust_name AS name, firstline(cohead.cohead_ordercomments) AS description, docass.docass_purpose AS purpose FROM docass, cohead, custinfo WHERE (((docass.docass_target_type = 'S'::text) AND (docass.docass_target_id = cohead.cohead_id)) AND (custinfo.cust_id = cohead.cohead_cust_id))) UNION ALL SELECT docass.docass_id AS id, cohead.cohead_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, custinfo.cust_name AS name, firstline(cohead.cohead_ordercomments) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, cohead, custinfo WHERE (((docass.docass_source_type = 'S'::text) AND (docass.docass_source_id = cohead.cohead_id)) AND (custinfo.cust_id = cohead.cohead_cust_id))) UNION ALL SELECT docass.docass_id AS id, pohead.pohead_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, vendinfo.vend_name AS name, firstline(pohead.pohead_comments) AS description, docass.docass_purpose AS purpose FROM docass, pohead, vendinfo WHERE (((docass.docass_target_type = 'P'::text) AND (docass.docass_target_id = pohead.pohead_id)) AND (vendinfo.vend_id = pohead.pohead_vend_id))) UNION ALL SELECT docass.docass_id AS id, pohead.pohead_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, vendinfo.vend_name AS name, firstline(pohead.pohead_comments) AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, pohead, vendinfo WHERE (((docass.docass_source_type = 'P'::text) AND (docass.docass_source_id = pohead.pohead_id)) AND (vendinfo.vend_id = pohead.pohead_vend_id))) UNION ALL SELECT docass.docass_id AS id, formatwonumber(wo.wo_id) AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, item.item_descrip1 AS name, item.item_descrip2 AS description, docass.docass_purpose AS purpose FROM docass, wo, itemsite, item WHERE ((((docass.docass_target_type = 'W'::text) AND (docass.docass_target_id = wo.wo_id)) AND (wo.wo_itemsite_id = itemsite.itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id))) UNION ALL SELECT docass.docass_id AS id, formatwonumber(wo.wo_id) AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, item.item_descrip1 AS name, item.item_descrip2 AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, wo, itemsite, item WHERE ((((docass.docass_source_type = 'W'::text) AND (docass.docass_source_id = wo.wo_id)) AND (wo.wo_itemsite_id = itemsite.itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id))) UNION ALL SELECT docass.docass_id AS id, emp.emp_number AS target_number, docass.docass_target_type AS target_type, docass.docass_target_id AS target_id, docass.docass_source_type AS source_type, docass.docass_source_id AS source_id, cntct.cntct_name AS name, cntct.cntct_title AS description, docass.docass_purpose AS purpose FROM docass, (emp LEFT JOIN cntct ON ((emp.emp_cntct_id = cntct.cntct_id))) WHERE ((docass.docass_target_type = 'EMP'::text) AND (docass.docass_target_id = emp.emp_id))) UNION ALL SELECT docass.docass_id AS id, emp.emp_number AS target_number, docass.docass_source_type AS target_type, docass.docass_source_id AS target_id, docass.docass_target_type AS source_type, docass.docass_target_id AS source_id, cntct.cntct_name AS name, cntct.cntct_title AS description, CASE WHEN (docass.docass_purpose = 'A'::bpchar) THEN 'C'::bpchar WHEN (docass.docass_purpose = 'C'::bpchar) THEN 'A'::bpchar ELSE docass.docass_purpose END AS purpose FROM docass, (emp LEFT JOIN cntct ON ((emp.emp_cntct_id = cntct.cntct_id))) WHERE ((docass.docass_source_type = 'EMP'::text) AND (docass.docass_source_id = emp.emp_id));
100109
100110
100111 ALTER TABLE public.docinfo OWNER TO admin;
100112
100113 --
100114 -- TOC entry 562 (class 1259 OID 146568963)
100115 -- Dependencies: 292 8
100116 -- Name: emp_emp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100117 --
100118
100119 CREATE SEQUENCE emp_emp_id_seq
100120     START WITH 1
100121     INCREMENT BY 1
100122     NO MINVALUE
100123     NO MAXVALUE
100124     CACHE 1;
100125
100126
100127 ALTER TABLE public.emp_emp_id_seq OWNER TO admin;
100128
100129 --
100130 -- TOC entry 9759 (class 0 OID 0)
100131 -- Dependencies: 562
100132 -- Name: emp_emp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100133 --
100134
100135 ALTER SEQUENCE emp_emp_id_seq OWNED BY emp.emp_id;
100136
100137
100138 --
100139 -- TOC entry 563 (class 1259 OID 146568965)
100140 -- Dependencies: 6450 8
100141 -- Name: empgrp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100142 --
100143
100144 CREATE TABLE empgrp (
100145     empgrp_id integer NOT NULL,
100146     empgrp_name text NOT NULL,
100147     empgrp_descrip text NOT NULL,
100148     CONSTRAINT empgrp_empgrp_name_check CHECK ((empgrp_name <> ''::text))
100149 );
100150
100151
100152 ALTER TABLE public.empgrp OWNER TO admin;
100153
100154 --
100155 -- TOC entry 564 (class 1259 OID 146568972)
100156 -- Dependencies: 563 8
100157 -- Name: empgrp_empgrp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100158 --
100159
100160 CREATE SEQUENCE empgrp_empgrp_id_seq
100161     START WITH 1
100162     INCREMENT BY 1
100163     NO MINVALUE
100164     NO MAXVALUE
100165     CACHE 1;
100166
100167
100168 ALTER TABLE public.empgrp_empgrp_id_seq OWNER TO admin;
100169
100170 --
100171 -- TOC entry 9762 (class 0 OID 0)
100172 -- Dependencies: 564
100173 -- Name: empgrp_empgrp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100174 --
100175
100176 ALTER SEQUENCE empgrp_empgrp_id_seq OWNED BY empgrp.empgrp_id;
100177
100178
100179 --
100180 -- TOC entry 565 (class 1259 OID 146568974)
100181 -- Dependencies: 8
100182 -- Name: empgrpitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100183 --
100184
100185 CREATE TABLE empgrpitem (
100186     empgrpitem_id integer NOT NULL,
100187     empgrpitem_empgrp_id integer NOT NULL,
100188     empgrpitem_emp_id integer NOT NULL
100189 );
100190
100191
100192 ALTER TABLE public.empgrpitem OWNER TO admin;
100193
100194 --
100195 -- TOC entry 566 (class 1259 OID 146568977)
100196 -- Dependencies: 565 8
100197 -- Name: empgrpitem_empgrpitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100198 --
100199
100200 CREATE SEQUENCE empgrpitem_empgrpitem_id_seq
100201     START WITH 1
100202     INCREMENT BY 1
100203     NO MINVALUE
100204     NO MAXVALUE
100205     CACHE 1;
100206
100207
100208 ALTER TABLE public.empgrpitem_empgrpitem_id_seq OWNER TO admin;
100209
100210 --
100211 -- TOC entry 9765 (class 0 OID 0)
100212 -- Dependencies: 566
100213 -- Name: empgrpitem_empgrpitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100214 --
100215
100216 ALTER SEQUENCE empgrpitem_empgrpitem_id_seq OWNED BY empgrpitem.empgrpitem_id;
100217
100218
100219 --
100220 -- TOC entry 567 (class 1259 OID 146568979)
100221 -- Dependencies: 6452 8
100222 -- Name: evntlog; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100223 --
100224
100225 CREATE TABLE evntlog (
100226     evntlog_id integer DEFAULT nextval(('evntlog_evntlog_id_seq'::text)::regclass) NOT NULL,
100227     evntlog_evnttime timestamp with time zone,
100228     evntlog_evnttype_id integer,
100229     evntlog_ord_id integer,
100230     evntlog_dispatched timestamp with time zone,
100231     evntlog_action text,
100232     evntlog_warehous_id integer,
100233     evntlog_number text,
100234     evntlog_newvalue numeric(20,10),
100235     evntlog_oldvalue numeric(20,10),
100236     evntlog_newdate date,
100237     evntlog_olddate date,
100238     evntlog_ordtype character(2),
100239     evntlog_username text
100240 );
100241
100242
100243 ALTER TABLE public.evntlog OWNER TO admin;
100244
100245 --
100246 -- TOC entry 9767 (class 0 OID 0)
100247 -- Dependencies: 567
100248 -- Name: TABLE evntlog; Type: COMMENT; Schema: public; Owner: admin
100249 --
100250
100251 COMMENT ON TABLE evntlog IS 'Event Notification history';
100252
100253
100254 --
100255 -- TOC entry 568 (class 1259 OID 146568986)
100256 -- Dependencies: 8
100257 -- Name: evntlog_evntlog_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100258 --
100259
100260 CREATE SEQUENCE evntlog_evntlog_id_seq
100261     START WITH 1
100262     INCREMENT BY 1
100263     NO MINVALUE
100264     MAXVALUE 2147483647
100265     CACHE 1;
100266
100267
100268 ALTER TABLE public.evntlog_evntlog_id_seq OWNER TO admin;
100269
100270 --
100271 -- TOC entry 569 (class 1259 OID 146568988)
100272 -- Dependencies: 6453 8
100273 -- Name: evntnot; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100274 --
100275
100276 CREATE TABLE evntnot (
100277     evntnot_id integer DEFAULT nextval(('evntnot_evntnot_id_seq'::text)::regclass) NOT NULL,
100278     evntnot_evnttype_id integer,
100279     evntnot_warehous_id integer,
100280     evntnot_username text
100281 );
100282
100283
100284 ALTER TABLE public.evntnot OWNER TO admin;
100285
100286 --
100287 -- TOC entry 9770 (class 0 OID 0)
100288 -- Dependencies: 569
100289 -- Name: TABLE evntnot; Type: COMMENT; Schema: public; Owner: admin
100290 --
100291
100292 COMMENT ON TABLE evntnot IS 'Temporary table for storing information about user Event Notification selections';
100293
100294
100295 --
100296 -- TOC entry 570 (class 1259 OID 146568995)
100297 -- Dependencies: 8
100298 -- Name: evntnot_evntnot_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100299 --
100300
100301 CREATE SEQUENCE evntnot_evntnot_id_seq
100302     START WITH 1
100303     INCREMENT BY 1
100304     NO MINVALUE
100305     MAXVALUE 2147483647
100306     CACHE 1;
100307
100308
100309 ALTER TABLE public.evntnot_evntnot_id_seq OWNER TO admin;
100310
100311 --
100312 -- TOC entry 571 (class 1259 OID 146568997)
100313 -- Dependencies: 6454 6455 8
100314 -- Name: evnttype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100315 --
100316
100317 CREATE TABLE evnttype (
100318     evnttype_id integer DEFAULT nextval(('evnttype_evnttype_id_seq'::text)::regclass) NOT NULL,
100319     evnttype_name text NOT NULL,
100320     evnttype_descrip text,
100321     evnttype_module text,
100322     CONSTRAINT evnttype_evnttype_name_check CHECK ((evnttype_name <> ''::text))
100323 );
100324
100325
100326 ALTER TABLE public.evnttype OWNER TO admin;
100327
100328 --
100329 -- TOC entry 9773 (class 0 OID 0)
100330 -- Dependencies: 571
100331 -- Name: TABLE evnttype; Type: COMMENT; Schema: public; Owner: admin
100332 --
100333
100334 COMMENT ON TABLE evnttype IS 'Event Type information';
100335
100336
100337 --
100338 -- TOC entry 572 (class 1259 OID 146569005)
100339 -- Dependencies: 8
100340 -- Name: evnttype_evnttype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100341 --
100342
100343 CREATE SEQUENCE evnttype_evnttype_id_seq
100344     START WITH 1
100345     INCREMENT BY 1
100346     NO MINVALUE
100347     MAXVALUE 2147483647
100348     CACHE 1;
100349
100350
100351 ALTER TABLE public.evnttype_evnttype_id_seq OWNER TO admin;
100352
100353 --
100354 -- TOC entry 573 (class 1259 OID 146569007)
100355 -- Dependencies: 358 8
100356 -- Name: expcat_expcat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100357 --
100358
100359 CREATE SEQUENCE expcat_expcat_id_seq
100360     START WITH 1
100361     INCREMENT BY 1
100362     NO MINVALUE
100363     NO MAXVALUE
100364     CACHE 1;
100365
100366
100367 ALTER TABLE public.expcat_expcat_id_seq OWNER TO admin;
100368
100369 --
100370 -- TOC entry 9776 (class 0 OID 0)
100371 -- Dependencies: 573
100372 -- Name: expcat_expcat_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100373 --
100374
100375 ALTER SEQUENCE expcat_expcat_id_seq OWNED BY expcat.expcat_id;
100376
100377
100378 --
100379 -- TOC entry 574 (class 1259 OID 146569009)
100380 -- Dependencies: 243 8
100381 -- Name: file_file_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100382 --
100383
100384 CREATE SEQUENCE file_file_id_seq
100385     START WITH 1
100386     INCREMENT BY 1
100387     NO MINVALUE
100388     NO MAXVALUE
100389     CACHE 1;
100390
100391
100392 ALTER TABLE public.file_file_id_seq OWNER TO admin;
100393
100394 --
100395 -- TOC entry 9778 (class 0 OID 0)
100396 -- Dependencies: 574
100397 -- Name: file_file_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100398 --
100399
100400 ALTER SEQUENCE file_file_id_seq OWNED BY file.file_id;
100401
100402
100403 --
100404 -- TOC entry 575 (class 1259 OID 146569011)
100405 -- Dependencies: 6457 8
100406 -- Name: filter; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100407 --
100408
100409 CREATE TABLE filter (
100410     filter_id integer NOT NULL,
100411     filter_screen text NOT NULL,
100412     filter_value text NOT NULL,
100413     filter_username text,
100414     filter_name text NOT NULL,
100415     filter_selected boolean DEFAULT false
100416 );
100417
100418
100419 ALTER TABLE public.filter OWNER TO admin;
100420
100421 --
100422 -- TOC entry 576 (class 1259 OID 146569018)
100423 -- Dependencies: 575 8
100424 -- Name: filter_filter_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100425 --
100426
100427 CREATE SEQUENCE filter_filter_id_seq
100428     START WITH 1
100429     INCREMENT BY 1
100430     NO MINVALUE
100431     NO MAXVALUE
100432     CACHE 1;
100433
100434
100435 ALTER TABLE public.filter_filter_id_seq OWNER TO admin;
100436
100437 --
100438 -- TOC entry 9781 (class 0 OID 0)
100439 -- Dependencies: 576
100440 -- Name: filter_filter_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100441 --
100442
100443 ALTER SEQUENCE filter_filter_id_seq OWNED BY filter.filter_id;
100444
100445
100446 --
100447 -- TOC entry 577 (class 1259 OID 146569020)
100448 -- Dependencies: 8
100449 -- Name: fincharg; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100450 --
100451
100452 CREATE TABLE fincharg (
100453     fincharg_id integer NOT NULL,
100454     fincharg_mincharg numeric NOT NULL,
100455     fincharg_graceperiod integer NOT NULL,
100456     fincharg_assessoverdue boolean NOT NULL,
100457     fincharg_calcfrom integer NOT NULL,
100458     fincharg_markoninvoice text NOT NULL,
100459     fincharg_air numeric NOT NULL,
100460     fincharg_accnt_id integer NOT NULL,
100461     fincharg_salescat_id integer NOT NULL,
100462     fincharg_lastfc_statementcyclefrom text,
100463     fincharg_lastfc_custidfrom text,
100464     fincharg_lastfc_custidto text,
100465     fincharg_lastfc_statementcycleto text
100466 );
100467
100468
100469 ALTER TABLE public.fincharg OWNER TO admin;
100470
100471 --
100472 -- TOC entry 9783 (class 0 OID 0)
100473 -- Dependencies: 577
100474 -- Name: TABLE fincharg; Type: COMMENT; Schema: public; Owner: admin
100475 --
100476
100477 COMMENT ON TABLE fincharg IS 'Finance Charge configuration information';
100478
100479
100480 --
100481 -- TOC entry 578 (class 1259 OID 146569026)
100482 -- Dependencies: 577 8
100483 -- Name: fincharg_fincharg_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100484 --
100485
100486 CREATE SEQUENCE fincharg_fincharg_id_seq
100487     START WITH 1
100488     INCREMENT BY 1
100489     NO MINVALUE
100490     NO MAXVALUE
100491     CACHE 1;
100492
100493
100494 ALTER TABLE public.fincharg_fincharg_id_seq OWNER TO admin;
100495
100496 --
100497 -- TOC entry 9785 (class 0 OID 0)
100498 -- Dependencies: 578
100499 -- Name: fincharg_fincharg_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100500 --
100501
100502 ALTER SEQUENCE fincharg_fincharg_id_seq OWNED BY fincharg.fincharg_id;
100503
100504
100505 --
100506 -- TOC entry 579 (class 1259 OID 146569028)
100507 -- Dependencies: 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6478 8
100508 -- Name: flhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100509 --
100510
100511 CREATE TABLE flhead (
100512     flhead_id integer NOT NULL,
100513     flhead_name text NOT NULL,
100514     flhead_descrip text,
100515     flhead_showtotal boolean DEFAULT false NOT NULL,
100516     flhead_showstart boolean DEFAULT true NOT NULL,
100517     flhead_showend boolean DEFAULT true NOT NULL,
100518     flhead_showdelta boolean DEFAULT true NOT NULL,
100519     flhead_showbudget boolean DEFAULT true NOT NULL,
100520     flhead_showdiff boolean DEFAULT false NOT NULL,
100521     flhead_showcustom boolean DEFAULT false NOT NULL,
100522     flhead_custom_label text,
100523     flhead_usealttotal boolean DEFAULT false NOT NULL,
100524     flhead_alttotal text,
100525     flhead_usealtbegin boolean DEFAULT false NOT NULL,
100526     flhead_altbegin text,
100527     flhead_usealtend boolean DEFAULT false NOT NULL,
100528     flhead_altend text,
100529     flhead_usealtdebits boolean DEFAULT false NOT NULL,
100530     flhead_altdebits text,
100531     flhead_usealtcredits boolean DEFAULT false NOT NULL,
100532     flhead_altcredits text,
100533     flhead_usealtbudget boolean DEFAULT false NOT NULL,
100534     flhead_altbudget text,
100535     flhead_usealtdiff boolean DEFAULT false NOT NULL,
100536     flhead_altdiff text,
100537     flhead_type character(1) DEFAULT 'A'::bpchar NOT NULL,
100538     flhead_active boolean DEFAULT true NOT NULL,
100539     flhead_sys boolean DEFAULT false,
100540     flhead_notes text DEFAULT ''::text,
100541     CONSTRAINT flhead_flhead_name_check CHECK ((flhead_name <> ''::text))
100542 );
100543
100544
100545 ALTER TABLE public.flhead OWNER TO admin;
100546
100547 --
100548 -- TOC entry 9787 (class 0 OID 0)
100549 -- Dependencies: 579
100550 -- Name: TABLE flhead; Type: COMMENT; Schema: public; Owner: admin
100551 --
100552
100553 COMMENT ON TABLE flhead IS 'Financial Layout header information';
100554
100555
100556 --
100557 -- TOC entry 580 (class 1259 OID 146569053)
100558 -- Dependencies: 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 8
100559 -- Name: flitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100560 --
100561
100562 CREATE TABLE flitem (
100563     flitem_id integer NOT NULL,
100564     flitem_flhead_id integer,
100565     flitem_flgrp_id integer,
100566     flitem_order integer,
100567     flitem_accnt_id integer,
100568     flitem_showstart boolean,
100569     flitem_showend boolean,
100570     flitem_showdelta boolean,
100571     flitem_showbudget boolean DEFAULT false NOT NULL,
100572     flitem_subtract boolean DEFAULT false NOT NULL,
100573     flitem_showstartprcnt boolean DEFAULT false NOT NULL,
100574     flitem_showendprcnt boolean DEFAULT false NOT NULL,
100575     flitem_showdeltaprcnt boolean DEFAULT false NOT NULL,
100576     flitem_showbudgetprcnt boolean DEFAULT false NOT NULL,
100577     flitem_prcnt_flgrp_id integer DEFAULT (-1) NOT NULL,
100578     flitem_showdiff boolean DEFAULT false NOT NULL,
100579     flitem_showdiffprcnt boolean DEFAULT false NOT NULL,
100580     flitem_showcustom boolean DEFAULT false NOT NULL,
100581     flitem_showcustomprcnt boolean DEFAULT false NOT NULL,
100582     flitem_custom_source character(1),
100583     flitem_company text,
100584     flitem_profit text,
100585     flitem_number text,
100586     flitem_sub text,
100587     flitem_type character(1),
100588     flitem_subaccnttype_code text
100589 );
100590
100591
100592 ALTER TABLE public.flitem OWNER TO admin;
100593
100594 --
100595 -- TOC entry 9789 (class 0 OID 0)
100596 -- Dependencies: 580
100597 -- Name: TABLE flitem; Type: COMMENT; Schema: public; Owner: admin
100598 --
100599
100600 COMMENT ON TABLE flitem IS 'Financial Layout Account information';
100601
100602
100603 --
100604 -- TOC entry 581 (class 1259 OID 146569070)
100605 -- Dependencies: 8580 8
100606 -- Name: flaccnt; Type: VIEW; Schema: public; Owner: admin
100607 --
100608
100609 CREATE VIEW flaccnt AS
100610     SELECT flhead.flhead_type, flitem.flitem_id, flitem.flitem_flhead_id, flitem.flitem_flgrp_id, flitem.flitem_order, flitem.flitem_accnt_id, flitem.flitem_showstart, flitem.flitem_showend, flitem.flitem_showdelta, flitem.flitem_showbudget, flitem.flitem_subtract, flitem.flitem_showstartprcnt, flitem.flitem_showendprcnt, flitem.flitem_showdeltaprcnt, flitem.flitem_showbudgetprcnt, flitem.flitem_prcnt_flgrp_id, flitem.flitem_showdiff, flitem.flitem_showdiffprcnt, flitem.flitem_showcustom, flitem.flitem_showcustomprcnt, flitem.flitem_custom_source, flitem.flitem_company, flitem.flitem_profit, flitem.flitem_number, flitem.flitem_sub, flitem.flitem_type, flitem.flitem_subaccnttype_code, accnt.accnt_id, accnt.accnt_type, accnt.accnt_company, accnt.accnt_profit, accnt.accnt_number, accnt.accnt_sub, (-1) AS prj_id FROM ((flhead JOIN flitem ON ((flhead.flhead_id = flitem.flitem_flhead_id))) JOIN accnt ON ((flitem.flitem_accnt_id = accnt.accnt_id))) UNION ALL SELECT flhead.flhead_type, flitem.flitem_id, flitem.flitem_flhead_id, flitem.flitem_flgrp_id, flitem.flitem_order, flitem.flitem_accnt_id, flitem.flitem_showstart, flitem.flitem_showend, flitem.flitem_showdelta, flitem.flitem_showbudget, flitem.flitem_subtract, flitem.flitem_showstartprcnt, flitem.flitem_showendprcnt, flitem.flitem_showdeltaprcnt, flitem.flitem_showbudgetprcnt, flitem.flitem_prcnt_flgrp_id, flitem.flitem_showdiff, flitem.flitem_showdiffprcnt, flitem.flitem_showcustom, flitem.flitem_showcustomprcnt, flitem.flitem_custom_source, flitem.flitem_company, flitem.flitem_profit, flitem.flitem_number, flitem.flitem_sub, flitem.flitem_type, flitem.flitem_subaccnttype_code, accnt.accnt_id, accnt.accnt_type, accnt.accnt_company, accnt.accnt_profit, accnt.accnt_number, accnt.accnt_sub, (-1) AS prj_id FROM (flhead JOIN flitem ON ((flhead.flhead_id = flitem.flitem_flhead_id))), accnt WHERE (((((((flitem.flitem_accnt_id = (-1)) AND ((flitem.flitem_type = ''::bpchar) OR (accnt.accnt_type = flitem.flitem_type))) AND ((flitem.flitem_company = 'All'::text) OR (accnt.accnt_company = flitem.flitem_company))) AND ((flitem.flitem_profit = 'All'::text) OR (accnt.accnt_profit = flitem.flitem_profit))) AND ((flitem.flitem_number = 'All'::text) OR (accnt.accnt_number = flitem.flitem_number))) AND ((flitem.flitem_sub = 'All'::text) OR (accnt.accnt_sub = flitem.flitem_sub))) AND ((flitem.flitem_subaccnttype_code = 'All'::text) OR (accnt.accnt_subaccnttype_code = flitem.flitem_subaccnttype_code))) ORDER BY 30, 31, 32, 33;
100611
100612
100613 ALTER TABLE public.flaccnt OWNER TO admin;
100614
100615 --
100616 -- TOC entry 582 (class 1259 OID 146569075)
100617 -- Dependencies: 8
100618 -- Name: flcol; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100619 --
100620
100621 CREATE TABLE flcol (
100622     flcol_id integer NOT NULL,
100623     flcol_flhead_id integer NOT NULL,
100624     flcol_name text,
100625     flcol_descrip text,
100626     flcol_report_id integer,
100627     flcol_month boolean,
100628     flcol_quarter boolean,
100629     flcol_year boolean,
100630     flcol_showdb boolean,
100631     flcol_prcnt boolean,
100632     flcol_priortype character(1),
100633     flcol_priormonth boolean,
100634     flcol_priorquarter boolean,
100635     flcol_prioryear character(1),
100636     flcol_priorprcnt boolean,
100637     flcol_priordiff boolean,
100638     flcol_priordiffprcnt boolean,
100639     flcol_budget boolean,
100640     flcol_budgetprcnt boolean,
100641     flcol_budgetdiff boolean,
100642     flcol_budgetdiffprcnt boolean
100643 );
100644
100645
100646 ALTER TABLE public.flcol OWNER TO admin;
100647
100648 --
100649 -- TOC entry 583 (class 1259 OID 146569081)
100650 -- Dependencies: 582 8
100651 -- Name: flcol_flcol_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100652 --
100653
100654 CREATE SEQUENCE flcol_flcol_id_seq
100655     START WITH 1
100656     INCREMENT BY 1
100657     NO MINVALUE
100658     NO MAXVALUE
100659     CACHE 1;
100660
100661
100662 ALTER TABLE public.flcol_flcol_id_seq OWNER TO admin;
100663
100664 --
100665 -- TOC entry 9793 (class 0 OID 0)
100666 -- Dependencies: 583
100667 -- Name: flcol_flcol_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100668 --
100669
100670 ALTER SEQUENCE flcol_flcol_id_seq OWNED BY flcol.flcol_id;
100671
100672
100673 --
100674 -- TOC entry 584 (class 1259 OID 146569083)
100675 -- Dependencies: 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 8
100676 -- Name: flgrp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100677 --
100678
100679 CREATE TABLE flgrp (
100680     flgrp_id integer NOT NULL,
100681     flgrp_flhead_id integer,
100682     flgrp_flgrp_id integer,
100683     flgrp_order integer,
100684     flgrp_name text,
100685     flgrp_descrip text,
100686     flgrp_subtotal boolean DEFAULT false NOT NULL,
100687     flgrp_summarize boolean DEFAULT false NOT NULL,
100688     flgrp_subtract boolean DEFAULT false NOT NULL,
100689     flgrp_showstart boolean DEFAULT true NOT NULL,
100690     flgrp_showend boolean DEFAULT true NOT NULL,
100691     flgrp_showdelta boolean DEFAULT true NOT NULL,
100692     flgrp_showbudget boolean DEFAULT true NOT NULL,
100693     flgrp_showstartprcnt boolean DEFAULT false NOT NULL,
100694     flgrp_showendprcnt boolean DEFAULT false NOT NULL,
100695     flgrp_showdeltaprcnt boolean DEFAULT false NOT NULL,
100696     flgrp_showbudgetprcnt boolean DEFAULT false NOT NULL,
100697     flgrp_prcnt_flgrp_id integer DEFAULT (-1) NOT NULL,
100698     flgrp_showdiff boolean DEFAULT false NOT NULL,
100699     flgrp_showdiffprcnt boolean DEFAULT false NOT NULL,
100700     flgrp_showcustom boolean DEFAULT false NOT NULL,
100701     flgrp_showcustomprcnt boolean DEFAULT false NOT NULL,
100702     flgrp_usealtsubtotal boolean DEFAULT false NOT NULL,
100703     flgrp_altsubtotal text
100704 );
100705
100706
100707 ALTER TABLE public.flgrp OWNER TO admin;
100708
100709 --
100710 -- TOC entry 9795 (class 0 OID 0)
100711 -- Dependencies: 584
100712 -- Name: TABLE flgrp; Type: COMMENT; Schema: public; Owner: admin
100713 --
100714
100715 COMMENT ON TABLE flgrp IS 'Financial Layout Group information';
100716
100717
100718 --
100719 -- TOC entry 585 (class 1259 OID 146569106)
100720 -- Dependencies: 584 8
100721 -- Name: flgrp_flgrp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100722 --
100723
100724 CREATE SEQUENCE flgrp_flgrp_id_seq
100725     START WITH 1
100726     INCREMENT BY 1
100727     NO MINVALUE
100728     NO MAXVALUE
100729     CACHE 1;
100730
100731
100732 ALTER TABLE public.flgrp_flgrp_id_seq OWNER TO admin;
100733
100734 --
100735 -- TOC entry 9797 (class 0 OID 0)
100736 -- Dependencies: 585
100737 -- Name: flgrp_flgrp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100738 --
100739
100740 ALTER SEQUENCE flgrp_flgrp_id_seq OWNED BY flgrp.flgrp_id;
100741
100742
100743 --
100744 -- TOC entry 586 (class 1259 OID 146569108)
100745 -- Dependencies: 579 8
100746 -- Name: flhead_flhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100747 --
100748
100749 CREATE SEQUENCE flhead_flhead_id_seq
100750     START WITH 1
100751     INCREMENT BY 1
100752     NO MINVALUE
100753     NO MAXVALUE
100754     CACHE 1;
100755
100756
100757 ALTER TABLE public.flhead_flhead_id_seq OWNER TO admin;
100758
100759 --
100760 -- TOC entry 9799 (class 0 OID 0)
100761 -- Dependencies: 586
100762 -- Name: flhead_flhead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100763 --
100764
100765 ALTER SEQUENCE flhead_flhead_id_seq OWNED BY flhead.flhead_id;
100766
100767
100768 --
100769 -- TOC entry 587 (class 1259 OID 146569110)
100770 -- Dependencies: 580 8
100771 -- Name: flitem_flitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100772 --
100773
100774 CREATE SEQUENCE flitem_flitem_id_seq
100775     START WITH 1
100776     INCREMENT BY 1
100777     NO MINVALUE
100778     NO MAXVALUE
100779     CACHE 1;
100780
100781
100782 ALTER TABLE public.flitem_flitem_id_seq OWNER TO admin;
100783
100784 --
100785 -- TOC entry 9801 (class 0 OID 0)
100786 -- Dependencies: 587
100787 -- Name: flitem_flitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100788 --
100789
100790 ALTER SEQUENCE flitem_flitem_id_seq OWNED BY flitem.flitem_id;
100791
100792
100793 --
100794 -- TOC entry 588 (class 1259 OID 146569112)
100795 -- Dependencies: 6511 8
100796 -- Name: flnotes; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100797 --
100798
100799 CREATE TABLE flnotes (
100800     flnotes_id integer NOT NULL,
100801     flnotes_flhead_id integer,
100802     flnotes_period_id integer,
100803     flnotes_notes text DEFAULT ''::text
100804 );
100805
100806
100807 ALTER TABLE public.flnotes OWNER TO admin;
100808
100809 --
100810 -- TOC entry 589 (class 1259 OID 146569119)
100811 -- Dependencies: 588 8
100812 -- Name: flnotes_flnotes_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100813 --
100814
100815 CREATE SEQUENCE flnotes_flnotes_id_seq
100816     START WITH 1
100817     INCREMENT BY 1
100818     NO MINVALUE
100819     NO MAXVALUE
100820     CACHE 1;
100821
100822
100823 ALTER TABLE public.flnotes_flnotes_id_seq OWNER TO admin;
100824
100825 --
100826 -- TOC entry 9804 (class 0 OID 0)
100827 -- Dependencies: 589
100828 -- Name: flnotes_flnotes_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100829 --
100830
100831 ALTER SEQUENCE flnotes_flnotes_id_seq OWNED BY flnotes.flnotes_id;
100832
100833
100834 --
100835 -- TOC entry 590 (class 1259 OID 146569121)
100836 -- Dependencies: 8
100837 -- Name: flrpt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100838 --
100839
100840 CREATE TABLE flrpt (
100841     flrpt_flhead_id integer NOT NULL,
100842     flrpt_period_id integer NOT NULL,
100843     flrpt_username text NOT NULL,
100844     flrpt_order integer NOT NULL,
100845     flrpt_level integer NOT NULL,
100846     flrpt_type text NOT NULL,
100847     flrpt_type_id integer NOT NULL,
100848     flrpt_beginning numeric,
100849     flrpt_ending numeric,
100850     flrpt_debits numeric,
100851     flrpt_credits numeric,
100852     flrpt_budget numeric,
100853     flrpt_beginningprcnt numeric,
100854     flrpt_endingprcnt numeric,
100855     flrpt_debitsprcnt numeric,
100856     flrpt_creditsprcnt numeric,
100857     flrpt_budgetprcnt numeric,
100858     flrpt_parent_id integer,
100859     flrpt_diff numeric,
100860     flrpt_diffprcnt numeric,
100861     flrpt_custom numeric,
100862     flrpt_customprcnt numeric,
100863     flrpt_altname text,
100864     flrpt_accnt_id integer,
100865     flrpt_interval character(1),
100866     flrpt_id integer NOT NULL
100867 );
100868
100869
100870 ALTER TABLE public.flrpt OWNER TO admin;
100871
100872 --
100873 -- TOC entry 9806 (class 0 OID 0)
100874 -- Dependencies: 590
100875 -- Name: TABLE flrpt; Type: COMMENT; Schema: public; Owner: admin
100876 --
100877
100878 COMMENT ON TABLE flrpt IS 'Scratch table where financial reporting information is processed before being displayed.';
100879
100880
100881 --
100882 -- TOC entry 591 (class 1259 OID 146569127)
100883 -- Dependencies: 590 8
100884 -- Name: flrpt_flrpt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100885 --
100886
100887 CREATE SEQUENCE flrpt_flrpt_id_seq
100888     START WITH 1
100889     INCREMENT BY 1
100890     NO MINVALUE
100891     NO MAXVALUE
100892     CACHE 1;
100893
100894
100895 ALTER TABLE public.flrpt_flrpt_id_seq OWNER TO admin;
100896
100897 --
100898 -- TOC entry 9808 (class 0 OID 0)
100899 -- Dependencies: 591
100900 -- Name: flrpt_flrpt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100901 --
100902
100903 ALTER SEQUENCE flrpt_flrpt_id_seq OWNED BY flrpt.flrpt_id;
100904
100905
100906 --
100907 -- TOC entry 592 (class 1259 OID 146569129)
100908 -- Dependencies: 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 8
100909 -- Name: flspec; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100910 --
100911
100912 CREATE TABLE flspec (
100913     flspec_id integer NOT NULL,
100914     flspec_flhead_id integer NOT NULL,
100915     flspec_flgrp_id integer NOT NULL,
100916     flspec_order integer NOT NULL,
100917     flspec_name text,
100918     flspec_type text,
100919     flspec_showstart boolean DEFAULT true NOT NULL,
100920     flspec_showend boolean DEFAULT true NOT NULL,
100921     flspec_showdelta boolean DEFAULT true NOT NULL,
100922     flspec_showbudget boolean DEFAULT false NOT NULL,
100923     flspec_subtract boolean DEFAULT false NOT NULL,
100924     flspec_showstartprcnt boolean DEFAULT false NOT NULL,
100925     flspec_showendprcnt boolean DEFAULT false NOT NULL,
100926     flspec_showdeltaprcnt boolean DEFAULT false NOT NULL,
100927     flspec_showbudgetprcnt boolean DEFAULT false NOT NULL,
100928     flspec_showdiff boolean DEFAULT false NOT NULL,
100929     flspec_showdiffprcnt boolean DEFAULT false NOT NULL,
100930     flspec_prcnt_flgrp_id integer DEFAULT (-1) NOT NULL,
100931     flspec_showcustom boolean DEFAULT false NOT NULL,
100932     flspec_showcustomprcnt boolean DEFAULT false NOT NULL,
100933     flspec_custom_source character(1)
100934 );
100935
100936
100937 ALTER TABLE public.flspec OWNER TO admin;
100938
100939 --
100940 -- TOC entry 9810 (class 0 OID 0)
100941 -- Dependencies: 592
100942 -- Name: TABLE flspec; Type: COMMENT; Schema: public; Owner: admin
100943 --
100944
100945 COMMENT ON TABLE flspec IS 'Financial Layout Special entries.';
100946
100947
100948 --
100949 -- TOC entry 593 (class 1259 OID 146569149)
100950 -- Dependencies: 592 8
100951 -- Name: flspec_flspec_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
100952 --
100953
100954 CREATE SEQUENCE flspec_flspec_id_seq
100955     START WITH 1
100956     INCREMENT BY 1
100957     NO MINVALUE
100958     NO MAXVALUE
100959     CACHE 1;
100960
100961
100962 ALTER TABLE public.flspec_flspec_id_seq OWNER TO admin;
100963
100964 --
100965 -- TOC entry 9812 (class 0 OID 0)
100966 -- Dependencies: 593
100967 -- Name: flspec_flspec_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
100968 --
100969
100970 ALTER SEQUENCE flspec_flspec_id_seq OWNED BY flspec.flspec_id;
100971
100972
100973 --
100974 -- TOC entry 594 (class 1259 OID 146569151)
100975 -- Dependencies: 6528 6529 8
100976 -- Name: form; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
100977 --
100978
100979 CREATE TABLE form (
100980     form_id integer DEFAULT nextval(('"form_form_id_seq"'::text)::regclass) NOT NULL,
100981     form_name text NOT NULL,
100982     form_descrip text,
100983     form_report_id integer,
100984     form_key character varying(4),
100985     form_report_name text,
100986     CONSTRAINT form_form_name_check CHECK ((form_name <> ''::text))
100987 );
100988
100989
100990 ALTER TABLE public.form OWNER TO admin;
100991
100992 --
100993 -- TOC entry 9814 (class 0 OID 0)
100994 -- Dependencies: 594
100995 -- Name: TABLE form; Type: COMMENT; Schema: public; Owner: admin
100996 --
100997
100998 COMMENT ON TABLE form IS 'Form information';
100999
101000
101001 --
101002 -- TOC entry 9815 (class 0 OID 0)
101003 -- Dependencies: 594
101004 -- Name: COLUMN form.form_report_id; Type: COMMENT; Schema: public; Owner: admin
101005 --
101006
101007 COMMENT ON COLUMN form.form_report_id IS 'Obsolete -- reference form_report_name instead.';
101008
101009
101010 --
101011 -- TOC entry 595 (class 1259 OID 146569159)
101012 -- Dependencies: 8
101013 -- Name: form_form_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101014 --
101015
101016 CREATE SEQUENCE form_form_id_seq
101017     START WITH 1
101018     INCREMENT BY 1
101019     NO MINVALUE
101020     MAXVALUE 2147483647
101021     CACHE 1;
101022
101023
101024 ALTER TABLE public.form_form_id_seq OWNER TO admin;
101025
101026 --
101027 -- TOC entry 596 (class 1259 OID 146569161)
101028 -- Dependencies: 299 8
101029 -- Name: freightclass_freightclass_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101030 --
101031
101032 CREATE SEQUENCE freightclass_freightclass_id_seq
101033     START WITH 1
101034     INCREMENT BY 1
101035     NO MINVALUE
101036     NO MAXVALUE
101037     CACHE 1;
101038
101039
101040 ALTER TABLE public.freightclass_freightclass_id_seq OWNER TO admin;
101041
101042 --
101043 -- TOC entry 9818 (class 0 OID 0)
101044 -- Dependencies: 596
101045 -- Name: freightclass_freightclass_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101046 --
101047
101048 ALTER SEQUENCE freightclass_freightclass_id_seq OWNED BY freightclass.freightclass_id;
101049
101050
101051 --
101052 -- TOC entry 597 (class 1259 OID 146569163)
101053 -- Dependencies: 6530 8
101054 -- Name: glseries; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101055 --
101056
101057 CREATE TABLE glseries (
101058     glseries_id integer DEFAULT nextval(('"glseries_glseries_id_seq"'::text)::regclass) NOT NULL,
101059     glseries_sequence integer,
101060     glseries_doctype character(2),
101061     glseries_docnumber text,
101062     glseries_accnt_id integer,
101063     glseries_amount numeric(20,2),
101064     glseries_source text,
101065     glseries_distdate date,
101066     glseries_notes text,
101067     glseries_misc_id integer
101068 );
101069
101070
101071 ALTER TABLE public.glseries OWNER TO admin;
101072
101073 --
101074 -- TOC entry 9820 (class 0 OID 0)
101075 -- Dependencies: 597
101076 -- Name: TABLE glseries; Type: COMMENT; Schema: public; Owner: admin
101077 --
101078
101079 COMMENT ON TABLE glseries IS 'Temporary table for storing information about General Ledger (G/L) Series Entries before Series Entries are posted';
101080
101081
101082 --
101083 -- TOC entry 598 (class 1259 OID 146569170)
101084 -- Dependencies: 8
101085 -- Name: glseries_glseries_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101086 --
101087
101088 CREATE SEQUENCE glseries_glseries_id_seq
101089     START WITH 1
101090     INCREMENT BY 1
101091     NO MINVALUE
101092     MAXVALUE 2147483647
101093     CACHE 1;
101094
101095
101096 ALTER TABLE public.glseries_glseries_id_seq OWNER TO admin;
101097
101098 --
101099 -- TOC entry 599 (class 1259 OID 146569172)
101100 -- Dependencies: 8
101101 -- Name: gltrans_gltrans_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101102 --
101103
101104 CREATE SEQUENCE gltrans_gltrans_id_seq
101105     START WITH 1
101106     INCREMENT BY 1
101107     NO MINVALUE
101108     MAXVALUE 2147483647
101109     CACHE 1;
101110
101111
101112 ALTER TABLE public.gltrans_gltrans_id_seq OWNER TO admin;
101113
101114 --
101115 -- TOC entry 600 (class 1259 OID 146569174)
101116 -- Dependencies: 8
101117 -- Name: gltrans_sequence_seq; Type: SEQUENCE; Schema: public; Owner: admin
101118 --
101119
101120 CREATE SEQUENCE gltrans_sequence_seq
101121     START WITH 1
101122     INCREMENT BY 1
101123     NO MINVALUE
101124     MAXVALUE 2147483647
101125     CACHE 1;
101126
101127
101128 ALTER TABLE public.gltrans_sequence_seq OWNER TO admin;
101129
101130 --
101131 -- TOC entry 601 (class 1259 OID 146569176)
101132 -- Dependencies: 6532 8
101133 -- Name: grp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101134 --
101135
101136 CREATE TABLE grp (
101137     grp_id integer NOT NULL,
101138     grp_name text NOT NULL,
101139     grp_descrip text,
101140     CONSTRAINT grp_grp_name_check CHECK ((grp_name <> ''::text))
101141 );
101142
101143
101144 ALTER TABLE public.grp OWNER TO admin;
101145
101146 --
101147 -- TOC entry 9825 (class 0 OID 0)
101148 -- Dependencies: 601
101149 -- Name: TABLE grp; Type: COMMENT; Schema: public; Owner: admin
101150 --
101151
101152 COMMENT ON TABLE grp IS 'This table is the basic group information.';
101153
101154
101155 --
101156 -- TOC entry 602 (class 1259 OID 146569183)
101157 -- Dependencies: 601 8
101158 -- Name: grp_grp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101159 --
101160
101161 CREATE SEQUENCE grp_grp_id_seq
101162     START WITH 1
101163     INCREMENT BY 1
101164     NO MINVALUE
101165     NO MAXVALUE
101166     CACHE 1;
101167
101168
101169 ALTER TABLE public.grp_grp_id_seq OWNER TO admin;
101170
101171 --
101172 -- TOC entry 9827 (class 0 OID 0)
101173 -- Dependencies: 602
101174 -- Name: grp_grp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101175 --
101176
101177 ALTER SEQUENCE grp_grp_id_seq OWNED BY grp.grp_id;
101178
101179
101180 --
101181 -- TOC entry 603 (class 1259 OID 146569185)
101182 -- Dependencies: 8
101183 -- Name: grppriv; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101184 --
101185
101186 CREATE TABLE grppriv (
101187     grppriv_id integer NOT NULL,
101188     grppriv_grp_id integer NOT NULL,
101189     grppriv_priv_id integer NOT NULL
101190 );
101191
101192
101193 ALTER TABLE public.grppriv OWNER TO admin;
101194
101195 --
101196 -- TOC entry 9829 (class 0 OID 0)
101197 -- Dependencies: 603
101198 -- Name: TABLE grppriv; Type: COMMENT; Schema: public; Owner: admin
101199 --
101200
101201 COMMENT ON TABLE grppriv IS 'This is a specific priv for a specific group.';
101202
101203
101204 --
101205 -- TOC entry 604 (class 1259 OID 146569188)
101206 -- Dependencies: 603 8
101207 -- Name: grppriv_grppriv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101208 --
101209
101210 CREATE SEQUENCE grppriv_grppriv_id_seq
101211     START WITH 1
101212     INCREMENT BY 1
101213     NO MINVALUE
101214     NO MAXVALUE
101215     CACHE 1;
101216
101217
101218 ALTER TABLE public.grppriv_grppriv_id_seq OWNER TO admin;
101219
101220 --
101221 -- TOC entry 9831 (class 0 OID 0)
101222 -- Dependencies: 604
101223 -- Name: grppriv_grppriv_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101224 --
101225
101226 ALTER SEQUENCE grppriv_grppriv_id_seq OWNED BY grppriv.grppriv_id;
101227
101228
101229 --
101230 -- TOC entry 605 (class 1259 OID 146569190)
101231 -- Dependencies: 6535 8
101232 -- Name: hnfc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101233 --
101234
101235 CREATE TABLE hnfc (
101236     hnfc_id integer NOT NULL,
101237     hnfc_code text NOT NULL,
101238     CONSTRAINT hnfc_hnfc_code_check CHECK ((hnfc_code <> ''::text))
101239 );
101240
101241
101242 ALTER TABLE public.hnfc OWNER TO admin;
101243
101244 --
101245 -- TOC entry 9833 (class 0 OID 0)
101246 -- Dependencies: 605
101247 -- Name: TABLE hnfc; Type: COMMENT; Schema: public; Owner: admin
101248 --
101249
101250 COMMENT ON TABLE hnfc IS 'List of personal titles/honorifics used in cntct table.';
101251
101252
101253 --
101254 -- TOC entry 606 (class 1259 OID 146569197)
101255 -- Dependencies: 605 8
101256 -- Name: hnfc_hnfc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101257 --
101258
101259 CREATE SEQUENCE hnfc_hnfc_id_seq
101260     START WITH 1
101261     INCREMENT BY 1
101262     NO MINVALUE
101263     NO MAXVALUE
101264     CACHE 1;
101265
101266
101267 ALTER TABLE public.hnfc_hnfc_id_seq OWNER TO admin;
101268
101269 --
101270 -- TOC entry 9835 (class 0 OID 0)
101271 -- Dependencies: 606
101272 -- Name: hnfc_hnfc_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101273 --
101274
101275 ALTER SEQUENCE hnfc_hnfc_id_seq OWNED BY hnfc.hnfc_id;
101276
101277
101278 --
101279 -- TOC entry 607 (class 1259 OID 146569199)
101280 -- Dependencies: 206 8
101281 -- Name: incdt_incdt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101282 --
101283
101284 CREATE SEQUENCE incdt_incdt_id_seq
101285     START WITH 1
101286     INCREMENT BY 1
101287     NO MINVALUE
101288     NO MAXVALUE
101289     CACHE 1;
101290
101291
101292 ALTER TABLE public.incdt_incdt_id_seq OWNER TO admin;
101293
101294 --
101295 -- TOC entry 9837 (class 0 OID 0)
101296 -- Dependencies: 607
101297 -- Name: incdt_incdt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101298 --
101299
101300 ALTER SEQUENCE incdt_incdt_id_seq OWNED BY incdt.incdt_id;
101301
101302
101303 --
101304 -- TOC entry 608 (class 1259 OID 146569201)
101305 -- Dependencies: 304 8
101306 -- Name: incdtcat_incdtcat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101307 --
101308
101309 CREATE SEQUENCE incdtcat_incdtcat_id_seq
101310     START WITH 1
101311     INCREMENT BY 1
101312     NO MINVALUE
101313     NO MAXVALUE
101314     CACHE 1;
101315
101316
101317 ALTER TABLE public.incdtcat_incdtcat_id_seq OWNER TO admin;
101318
101319 --
101320 -- TOC entry 9839 (class 0 OID 0)
101321 -- Dependencies: 608
101322 -- Name: incdtcat_incdtcat_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101323 --
101324
101325 ALTER SEQUENCE incdtcat_incdtcat_id_seq OWNED BY incdtcat.incdtcat_id;
101326
101327
101328 --
101329 -- TOC entry 609 (class 1259 OID 146569203)
101330 -- Dependencies: 6537 6538 8
101331 -- Name: incdthist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101332 --
101333
101334 CREATE TABLE incdthist (
101335     incdthist_id integer NOT NULL,
101336     incdthist_incdt_id integer NOT NULL,
101337     incdthist_change character(1),
101338     incdthist_target_id integer,
101339     incdthist_timestamp timestamp without time zone DEFAULT now() NOT NULL,
101340     incdthist_username text DEFAULT geteffectivextuser() NOT NULL,
101341     incdthist_descrip text
101342 );
101343
101344
101345 ALTER TABLE public.incdthist OWNER TO admin;
101346
101347 --
101348 -- TOC entry 9841 (class 0 OID 0)
101349 -- Dependencies: 609
101350 -- Name: TABLE incdthist; Type: COMMENT; Schema: public; Owner: admin
101351 --
101352
101353 COMMENT ON TABLE incdthist IS 'Incident history changes';
101354
101355
101356 --
101357 -- TOC entry 610 (class 1259 OID 146569211)
101358 -- Dependencies: 609 8
101359 -- Name: incdthist_incdthist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101360 --
101361
101362 CREATE SEQUENCE incdthist_incdthist_id_seq
101363     START WITH 1
101364     INCREMENT BY 1
101365     NO MINVALUE
101366     NO MAXVALUE
101367     CACHE 1;
101368
101369
101370 ALTER TABLE public.incdthist_incdthist_id_seq OWNER TO admin;
101371
101372 --
101373 -- TOC entry 9843 (class 0 OID 0)
101374 -- Dependencies: 610
101375 -- Name: incdthist_incdthist_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101376 --
101377
101378 ALTER SEQUENCE incdthist_incdthist_id_seq OWNED BY incdthist.incdthist_id;
101379
101380
101381 --
101382 -- TOC entry 611 (class 1259 OID 146569213)
101383 -- Dependencies: 305 8
101384 -- Name: incdtpriority_incdtpriority_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101385 --
101386
101387 CREATE SEQUENCE incdtpriority_incdtpriority_id_seq
101388     START WITH 1
101389     INCREMENT BY 1
101390     NO MINVALUE
101391     NO MAXVALUE
101392     CACHE 1;
101393
101394
101395 ALTER TABLE public.incdtpriority_incdtpriority_id_seq OWNER TO admin;
101396
101397 --
101398 -- TOC entry 9845 (class 0 OID 0)
101399 -- Dependencies: 611
101400 -- Name: incdtpriority_incdtpriority_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101401 --
101402
101403 ALTER SEQUENCE incdtpriority_incdtpriority_id_seq OWNED BY incdtpriority.incdtpriority_id;
101404
101405
101406 --
101407 -- TOC entry 612 (class 1259 OID 146569215)
101408 -- Dependencies: 306 8
101409 -- Name: incdtresolution_incdtresolution_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101410 --
101411
101412 CREATE SEQUENCE incdtresolution_incdtresolution_id_seq
101413     START WITH 1
101414     INCREMENT BY 1
101415     NO MINVALUE
101416     NO MAXVALUE
101417     CACHE 1;
101418
101419
101420 ALTER TABLE public.incdtresolution_incdtresolution_id_seq OWNER TO admin;
101421
101422 --
101423 -- TOC entry 9847 (class 0 OID 0)
101424 -- Dependencies: 612
101425 -- Name: incdtresolution_incdtresolution_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101426 --
101427
101428 ALTER SEQUENCE incdtresolution_incdtresolution_id_seq OWNED BY incdtresolution.incdtresolution_id;
101429
101430
101431 --
101432 -- TOC entry 613 (class 1259 OID 146569217)
101433 -- Dependencies: 307 8
101434 -- Name: incdtseverity_incdtseverity_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101435 --
101436
101437 CREATE SEQUENCE incdtseverity_incdtseverity_id_seq
101438     START WITH 1
101439     INCREMENT BY 1
101440     NO MINVALUE
101441     NO MAXVALUE
101442     CACHE 1;
101443
101444
101445 ALTER TABLE public.incdtseverity_incdtseverity_id_seq OWNER TO admin;
101446
101447 --
101448 -- TOC entry 9849 (class 0 OID 0)
101449 -- Dependencies: 613
101450 -- Name: incdtseverity_incdtseverity_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101451 --
101452
101453 ALTER SEQUENCE incdtseverity_incdtseverity_id_seq OWNED BY incdtseverity.incdtseverity_id;
101454
101455
101456 --
101457 -- TOC entry 614 (class 1259 OID 146569219)
101458 -- Dependencies: 202 8
101459 -- Name: invbal_invbal_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101460 --
101461
101462 CREATE SEQUENCE invbal_invbal_id_seq
101463     START WITH 1
101464     INCREMENT BY 1
101465     NO MINVALUE
101466     NO MAXVALUE
101467     CACHE 1;
101468
101469
101470 ALTER TABLE public.invbal_invbal_id_seq OWNER TO admin;
101471
101472 --
101473 -- TOC entry 9851 (class 0 OID 0)
101474 -- Dependencies: 614
101475 -- Name: invbal_invbal_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101476 --
101477
101478 ALTER SEQUENCE invbal_invbal_id_seq OWNED BY invbal.invbal_id;
101479
101480
101481 --
101482 -- TOC entry 615 (class 1259 OID 146569221)
101483 -- Dependencies: 8
101484 -- Name: invc_invc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101485 --
101486
101487 CREATE SEQUENCE invc_invc_id_seq
101488     START WITH 1
101489     INCREMENT BY 1
101490     NO MINVALUE
101491     MAXVALUE 2147483647
101492     CACHE 1;
101493
101494
101495 ALTER TABLE public.invc_invc_id_seq OWNER TO admin;
101496
101497 --
101498 -- TOC entry 616 (class 1259 OID 146569223)
101499 -- Dependencies: 224 8
101500 -- Name: invchead_invchead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101501 --
101502
101503 CREATE SEQUENCE invchead_invchead_id_seq
101504     START WITH 1
101505     INCREMENT BY 1
101506     NO MINVALUE
101507     NO MAXVALUE
101508     CACHE 1;
101509
101510
101511 ALTER TABLE public.invchead_invchead_id_seq OWNER TO admin;
101512
101513 --
101514 -- TOC entry 9854 (class 0 OID 0)
101515 -- Dependencies: 616
101516 -- Name: invchead_invchead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101517 --
101518
101519 ALTER SEQUENCE invchead_invchead_id_seq OWNED BY invchead.invchead_id;
101520
101521
101522 --
101523 -- TOC entry 617 (class 1259 OID 146569225)
101524 -- Dependencies: 377 8
101525 -- Name: invcheadtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101526 --
101527
101528 CREATE TABLE invcheadtax (
101529 )
101530 INHERITS (taxhist);
101531
101532
101533 ALTER TABLE public.invcheadtax OWNER TO admin;
101534
101535 --
101536 -- TOC entry 618 (class 1259 OID 146569231)
101537 -- Dependencies: 229 8
101538 -- Name: invcitem_invcitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101539 --
101540
101541 CREATE SEQUENCE invcitem_invcitem_id_seq
101542     START WITH 1
101543     INCREMENT BY 1
101544     NO MINVALUE
101545     NO MAXVALUE
101546     CACHE 1;
101547
101548
101549 ALTER TABLE public.invcitem_invcitem_id_seq OWNER TO admin;
101550
101551 --
101552 -- TOC entry 9857 (class 0 OID 0)
101553 -- Dependencies: 618
101554 -- Name: invcitem_invcitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101555 --
101556
101557 ALTER SEQUENCE invcitem_invcitem_id_seq OWNED BY invcitem.invcitem_id;
101558
101559
101560 --
101561 -- TOC entry 619 (class 1259 OID 146569233)
101562 -- Dependencies: 377 8
101563 -- Name: invcitemtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101564 --
101565
101566 CREATE TABLE invcitemtax (
101567 )
101568 INHERITS (taxhist);
101569
101570
101571 ALTER TABLE public.invcitemtax OWNER TO admin;
101572
101573 --
101574 -- TOC entry 620 (class 1259 OID 146569239)
101575 -- Dependencies: 8
101576 -- Name: invcnt_invcnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101577 --
101578
101579 CREATE SEQUENCE invcnt_invcnt_id_seq
101580     START WITH 1
101581     INCREMENT BY 1
101582     NO MINVALUE
101583     MAXVALUE 2147483647
101584     CACHE 1;
101585
101586
101587 ALTER TABLE public.invcnt_invcnt_id_seq OWNER TO admin;
101588
101589 --
101590 -- TOC entry 621 (class 1259 OID 146569241)
101591 -- Dependencies: 6541 8
101592 -- Name: invdetail; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101593 --
101594
101595 CREATE TABLE invdetail (
101596     invdetail_id integer DEFAULT nextval(('"invdetail_invdetail_id_seq"'::text)::regclass) NOT NULL,
101597     invdetail_transtype character(2),
101598     invdetail_invhist_id integer,
101599     invdetail_location_id integer,
101600     invdetail_qty numeric(18,6),
101601     invdetail_comments text,
101602     invdetail_qty_before numeric(18,6),
101603     invdetail_qty_after numeric(18,6),
101604     invdetail_invcitem_id integer,
101605     invdetail_expiration date,
101606     invdetail_warrpurc date,
101607     invdetail_ls_id integer
101608 );
101609
101610
101611 ALTER TABLE public.invdetail OWNER TO admin;
101612
101613 --
101614 -- TOC entry 9861 (class 0 OID 0)
101615 -- Dependencies: 621
101616 -- Name: TABLE invdetail; Type: COMMENT; Schema: public; Owner: admin
101617 --
101618
101619 COMMENT ON TABLE invdetail IS 'Detailed Inventory transaction information for Lot/Serial and Multiple Location Control (MLC) Items';
101620
101621
101622 --
101623 -- TOC entry 622 (class 1259 OID 146569248)
101624 -- Dependencies: 8
101625 -- Name: invdetail_invdetail_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101626 --
101627
101628 CREATE SEQUENCE invdetail_invdetail_id_seq
101629     START WITH 1
101630     INCREMENT BY 1
101631     NO MINVALUE
101632     MAXVALUE 2147483647
101633     CACHE 1;
101634
101635
101636 ALTER TABLE public.invdetail_invdetail_id_seq OWNER TO admin;
101637
101638 --
101639 -- TOC entry 623 (class 1259 OID 146569250)
101640 -- Dependencies: 6542 6543 6544 6545 6546 6547 6548 8
101641 -- Name: invhist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101642 --
101643
101644 CREATE TABLE invhist (
101645     invhist_id integer DEFAULT nextval(('invhist_invhist_id_seq'::text)::regclass) NOT NULL,
101646     invhist_itemsite_id integer,
101647     invhist_transdate timestamp with time zone DEFAULT ('now'::text)::timestamp(6) with time zone,
101648     invhist_transtype character(2),
101649     invhist_invqty numeric(18,6),
101650     invhist_invuom text,
101651     invhist_ordnumber text,
101652     invhist_docnumber text,
101653     invhist_qoh_before numeric(18,6),
101654     invhist_qoh_after numeric(18,6),
101655     invhist_unitcost numeric(16,6),
101656     invhist_acct_id integer,
101657     invhist_xfer_warehous_id integer,
101658     invhist_comments text,
101659     invhist_posted boolean DEFAULT true,
101660     invhist_imported boolean,
101661     invhist_hasdetail boolean DEFAULT false,
101662     invhist_ordtype text,
101663     invhist_analyze boolean DEFAULT true,
101664     invhist_user text DEFAULT geteffectivextuser(),
101665     invhist_created timestamp with time zone DEFAULT now() NOT NULL,
101666     invhist_costmethod character(1) NOT NULL,
101667     invhist_value_before numeric(12,2) NOT NULL,
101668     invhist_value_after numeric(12,2) NOT NULL,
101669     invhist_series integer
101670 );
101671
101672
101673 ALTER TABLE public.invhist OWNER TO admin;
101674
101675 --
101676 -- TOC entry 9864 (class 0 OID 0)
101677 -- Dependencies: 623
101678 -- Name: TABLE invhist; Type: COMMENT; Schema: public; Owner: admin
101679 --
101680
101681 COMMENT ON TABLE invhist IS 'Inventory transaction history';
101682
101683
101684 --
101685 -- TOC entry 624 (class 1259 OID 146569263)
101686 -- Dependencies: 8
101687 -- Name: invhist_invhist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101688 --
101689
101690 CREATE SEQUENCE invhist_invhist_id_seq
101691     START WITH 1
101692     INCREMENT BY 1
101693     NO MINVALUE
101694     MAXVALUE 2147483647
101695     CACHE 1;
101696
101697
101698 ALTER TABLE public.invhist_invhist_id_seq OWNER TO admin;
101699
101700 --
101701 -- TOC entry 625 (class 1259 OID 146569265)
101702 -- Dependencies: 8
101703 -- Name: invhistexpcat; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101704 --
101705
101706 CREATE TABLE invhistexpcat (
101707     invhistexpcat_id integer NOT NULL,
101708     invhistexpcat_invhist_id integer NOT NULL,
101709     invhistexpcat_expcat_id integer NOT NULL
101710 );
101711
101712
101713 ALTER TABLE public.invhistexpcat OWNER TO admin;
101714
101715 --
101716 -- TOC entry 9867 (class 0 OID 0)
101717 -- Dependencies: 625
101718 -- Name: TABLE invhistexpcat; Type: COMMENT; Schema: public; Owner: admin
101719 --
101720
101721 COMMENT ON TABLE invhistexpcat IS 'Track the relationship between an EX transaction in the invhist table and the corresponding Expense Category.';
101722
101723
101724 --
101725 -- TOC entry 626 (class 1259 OID 146569268)
101726 -- Dependencies: 625 8
101727 -- Name: invhistexpcat_invhistexpcat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101728 --
101729
101730 CREATE SEQUENCE invhistexpcat_invhistexpcat_id_seq
101731     START WITH 1
101732     INCREMENT BY 1
101733     NO MINVALUE
101734     NO MAXVALUE
101735     CACHE 1;
101736
101737
101738 ALTER TABLE public.invhistexpcat_invhistexpcat_id_seq OWNER TO admin;
101739
101740 --
101741 -- TOC entry 9869 (class 0 OID 0)
101742 -- Dependencies: 626
101743 -- Name: invhistexpcat_invhistexpcat_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101744 --
101745
101746 ALTER SEQUENCE invhistexpcat_invhistexpcat_id_seq OWNED BY invhistexpcat.invhistexpcat_id;
101747
101748
101749 --
101750 -- TOC entry 627 (class 1259 OID 146569270)
101751 -- Dependencies: 8581 8
101752 -- Name: invoiceitem; Type: VIEW; Schema: public; Owner: admin
101753 --
101754
101755 CREATE VIEW invoiceitem AS
101756     SELECT invcitem.invcitem_id, invcitem.invcitem_invchead_id, invcitem.invcitem_linenumber, invcitem.invcitem_item_id, invcitem.invcitem_warehous_id, invcitem.invcitem_custpn, invcitem.invcitem_number, invcitem.invcitem_descrip, invcitem.invcitem_ordered, invcitem.invcitem_billed, invcitem.invcitem_custprice, invcitem.invcitem_price, invcitem.invcitem_notes, invcitem.invcitem_salescat_id, invcitem.invcitem_taxtype_id, invcitem.invcitem_qty_uom_id, invcitem.invcitem_qty_invuomratio, invcitem.invcitem_price_uom_id, invcitem.invcitem_price_invuomratio, invcitem.invcitem_coitem_id, invcitem.invcitem_updateinv, invcitem.invcitem_rev_accnt_id, itemsite.itemsite_id, cohead.cohead_number, COALESCE((invcitem.invcitem_billed * invcitem.invcitem_qty_invuomratio), (0)::numeric) AS qty, COALESCE((invcitem.invcitem_price / invcitem.invcitem_price_invuomratio), (0)::numeric) AS unitprice, COALESCE(round(((invcitem.invcitem_billed * invcitem.invcitem_qty_invuomratio) * (invcitem.invcitem_price / invcitem.invcitem_price_invuomratio)), 2), (0)::numeric) AS extprice, currtobase(invchead.invchead_curr_id, COALESCE(round(((invcitem.invcitem_billed * invcitem.invcitem_qty_invuomratio) * (invcitem.invcitem_price / invcitem.invcitem_price_invuomratio)), 2), (0)::numeric), invchead.invchead_invcdate) AS baseextprice, (SELECT COALESCE(sum(invcitemtax.taxhist_tax), (0)::numeric) AS "coalesce" FROM invcitemtax WHERE (invcitemtax.taxhist_parent_id = invcitem.invcitem_id)) AS tax, ((SELECT COALESCE(sum(shipitem.shipitem_value), (itemcost(itemsite.itemsite_id) * invcitem.invcitem_billed), (0)::numeric) AS "coalesce" FROM shipitem WHERE (shipitem.shipitem_invcitem_id = invcitem.invcitem_id)) / CASE WHEN (invcitem.invcitem_billed <> (0)::numeric) THEN (invcitem.invcitem_billed * invcitem.invcitem_qty_invuomratio) ELSE (1)::numeric END) AS unitcost FROM ((((invcitem JOIN invchead ON ((invchead.invchead_id = invcitem.invcitem_invchead_id))) LEFT JOIN coitem ON ((coitem.coitem_id = invcitem.invcitem_coitem_id))) LEFT JOIN cohead ON ((cohead.cohead_id = coitem.coitem_cohead_id))) LEFT JOIN itemsite ON (((itemsite.itemsite_item_id = invcitem.invcitem_item_id) AND (itemsite.itemsite_warehous_id = invcitem.invcitem_warehous_id))));
101757
101758
101759 ALTER TABLE public.invoiceitem OWNER TO admin;
101760
101761 --
101762 -- TOC entry 9871 (class 0 OID 0)
101763 -- Dependencies: 627
101764 -- Name: VIEW invoiceitem; Type: COMMENT; Schema: public; Owner: admin
101765 --
101766
101767 COMMENT ON VIEW invoiceitem IS 'Single point for invoice item (invcitem) calculations.';
101768
101769
101770 --
101771 -- TOC entry 628 (class 1259 OID 146569275)
101772 -- Dependencies: 347 8
101773 -- Name: ipsass_ipsass_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101774 --
101775
101776 CREATE SEQUENCE ipsass_ipsass_id_seq
101777     START WITH 1
101778     INCREMENT BY 1
101779     NO MINVALUE
101780     NO MAXVALUE
101781     CACHE 1;
101782
101783
101784 ALTER TABLE public.ipsass_ipsass_id_seq OWNER TO admin;
101785
101786 --
101787 -- TOC entry 9873 (class 0 OID 0)
101788 -- Dependencies: 628
101789 -- Name: ipsass_ipsass_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101790 --
101791
101792 ALTER SEQUENCE ipsass_ipsass_id_seq OWNED BY ipsass.ipsass_id;
101793
101794
101795 --
101796 -- TOC entry 629 (class 1259 OID 146569277)
101797 -- Dependencies: 8
101798 -- Name: ipsctyp_ipsctyp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101799 --
101800
101801 CREATE SEQUENCE ipsctyp_ipsctyp_id_seq
101802     START WITH 1
101803     INCREMENT BY 1
101804     NO MINVALUE
101805     NO MAXVALUE
101806     CACHE 1;
101807
101808
101809 ALTER TABLE public.ipsctyp_ipsctyp_id_seq OWNER TO admin;
101810
101811 --
101812 -- TOC entry 630 (class 1259 OID 146569279)
101813 -- Dependencies: 8
101814 -- Name: ipscust_ipscust_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101815 --
101816
101817 CREATE SEQUENCE ipscust_ipscust_id_seq
101818     START WITH 1
101819     INCREMENT BY 1
101820     NO MINVALUE
101821     NO MAXVALUE
101822     CACHE 1;
101823
101824
101825 ALTER TABLE public.ipscust_ipscust_id_seq OWNER TO admin;
101826
101827 --
101828 -- TOC entry 631 (class 1259 OID 146569281)
101829 -- Dependencies: 300 8
101830 -- Name: ipsfreight_ipsfreight_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101831 --
101832
101833 CREATE SEQUENCE ipsfreight_ipsfreight_id_seq
101834     START WITH 1
101835     INCREMENT BY 1
101836     NO MINVALUE
101837     NO MAXVALUE
101838     CACHE 1;
101839
101840
101841 ALTER TABLE public.ipsfreight_ipsfreight_id_seq OWNER TO admin;
101842
101843 --
101844 -- TOC entry 9877 (class 0 OID 0)
101845 -- Dependencies: 631
101846 -- Name: ipsfreight_ipsfreight_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101847 --
101848
101849 ALTER SEQUENCE ipsfreight_ipsfreight_id_seq OWNED BY ipsfreight.ipsfreight_id;
101850
101851
101852 --
101853 -- TOC entry 632 (class 1259 OID 146569283)
101854 -- Dependencies: 8
101855 -- Name: ipshead_ipshead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101856 --
101857
101858 CREATE SEQUENCE ipshead_ipshead_id_seq
101859     START WITH 1
101860     INCREMENT BY 1
101861     NO MINVALUE
101862     NO MAXVALUE
101863     CACHE 1;
101864
101865
101866 ALTER TABLE public.ipshead_ipshead_id_seq OWNER TO admin;
101867
101868 --
101869 -- TOC entry 633 (class 1259 OID 146569285)
101870 -- Dependencies: 8
101871 -- Name: ipsitem_ipsitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101872 --
101873
101874 CREATE SEQUENCE ipsitem_ipsitem_id_seq
101875     START WITH 1
101876     INCREMENT BY 1
101877     NO MINVALUE
101878     NO MAXVALUE
101879     CACHE 1;
101880
101881
101882 ALTER TABLE public.ipsitem_ipsitem_id_seq OWNER TO admin;
101883
101884 --
101885 -- TOC entry 634 (class 1259 OID 146569287)
101886 -- Dependencies: 351 8
101887 -- Name: ipsitemchar_ipsitemchar_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101888 --
101889
101890 CREATE SEQUENCE ipsitemchar_ipsitemchar_id_seq
101891     START WITH 1
101892     INCREMENT BY 1
101893     NO MINVALUE
101894     NO MAXVALUE
101895     CACHE 1;
101896
101897
101898 ALTER TABLE public.ipsitemchar_ipsitemchar_id_seq OWNER TO admin;
101899
101900 --
101901 -- TOC entry 9881 (class 0 OID 0)
101902 -- Dependencies: 634
101903 -- Name: ipsitemchar_ipsitemchar_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101904 --
101905
101906 ALTER SEQUENCE ipsitemchar_ipsitemchar_id_seq OWNED BY ipsitemchar.ipsitemchar_id;
101907
101908
101909 --
101910 -- TOC entry 635 (class 1259 OID 146569289)
101911 -- Dependencies: 8582 8
101912 -- Name: ipsprice; Type: VIEW; Schema: public; Owner: admin
101913 --
101914
101915 CREATE VIEW ipsprice AS
101916     SELECT ipsiteminfo.ipsitem_id AS ipsprice_id, 'I'::text AS ipsprice_source, ipsiteminfo.ipsitem_ipshead_id AS ipsprice_ipshead_id, ipsiteminfo.ipsitem_item_id AS ipsprice_item_id, itemuomtouom(ipsiteminfo.ipsitem_item_id, ipsiteminfo.ipsitem_qty_uom_id, NULL::integer, ipsiteminfo.ipsitem_qtybreak) AS ipsprice_qtybreak, CASE WHEN (ipsiteminfo.ipsitem_type = 'N'::bpchar) THEN ((ipsiteminfo.ipsitem_price * itemuomtouomratio(ipsiteminfo.ipsitem_item_id, NULL::integer, ipsiteminfo.ipsitem_price_uom_id)) * iteminvpricerat(ipsiteminfo.ipsitem_item_id)) WHEN (ipsiteminfo.ipsitem_type = 'D'::bpchar) THEN ((item.item_listprice - (item.item_listprice * ipsiteminfo.ipsitem_discntprcnt)) - ipsiteminfo.ipsitem_fixedamtdiscount) WHEN ((ipsiteminfo.ipsitem_type = 'M'::bpchar) AND fetchmetricbool('Long30Markups'::text)) THEN ((stdcost(item.item_id) / (1.0 - ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) WHEN (ipsiteminfo.ipsitem_type = 'M'::bpchar) THEN ((item.item_listcost + (item.item_listcost * ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) ELSE NULL::numeric END AS ipsprice_price, ipsiteminfo.ipsitem_qtybreak AS ipsprice_uomqtybreak, ipsiteminfo.ipsitem_qty_uom_id AS ipsprice_uomqtybreak_uom_id, CASE WHEN (ipsiteminfo.ipsitem_type = 'N'::bpchar) THEN ipsiteminfo.ipsitem_price WHEN (ipsiteminfo.ipsitem_type = 'D'::bpchar) THEN ((item.item_listprice - (item.item_listprice * ipsiteminfo.ipsitem_discntprcnt)) - ipsiteminfo.ipsitem_fixedamtdiscount) WHEN ((ipsiteminfo.ipsitem_type = 'M'::bpchar) AND fetchmetricbool('Long30Markups'::text)) THEN ((stdcost(item.item_id) / (1.0 - ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) WHEN (ipsiteminfo.ipsitem_type = 'M'::bpchar) THEN ((item.item_listcost + (item.item_listcost * ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) ELSE NULL::numeric END AS ipsprice_uomprice, ipsiteminfo.ipsitem_price_uom_id AS ipsprice_uomprice_uom_id, ipsiteminfo.ipsitem_discntprcnt AS ipsprice_discountpercent, ipsiteminfo.ipsitem_fixedamtdiscount AS ipsprice_discountfixed, ipsiteminfo.ipsitem_type AS ipsprice_type FROM (ipsiteminfo JOIN item ON ((item.item_id = ipsiteminfo.ipsitem_item_id))) UNION SELECT ipsiteminfo.ipsitem_id AS ipsprice_id, 'P'::text AS ipsprice_source, ipsiteminfo.ipsitem_ipshead_id AS ipsprice_ipshead_id, item.item_id AS ipsprice_item_id, ipsiteminfo.ipsitem_qtybreak AS ipsprice_qtybreak, CASE WHEN (ipsiteminfo.ipsitem_type = 'D'::bpchar) THEN ((item.item_listprice - (item.item_listprice * ipsiteminfo.ipsitem_discntprcnt)) - ipsiteminfo.ipsitem_fixedamtdiscount) WHEN ((ipsiteminfo.ipsitem_type = 'M'::bpchar) AND fetchmetricbool('Long30Markups'::text)) THEN ((stdcost(item.item_id) / (1.0 - ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) WHEN (ipsiteminfo.ipsitem_type = 'M'::bpchar) THEN ((item.item_listcost + (item.item_listcost * ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) ELSE NULL::numeric END AS ipsprice_price, ipsiteminfo.ipsitem_qtybreak AS ipsprice_uomqtybreak, item.item_inv_uom_id AS ipsprice_uomqtybreak_uom_id, CASE WHEN (ipsiteminfo.ipsitem_type = 'D'::bpchar) THEN ((item.item_listprice - (item.item_listprice * ipsiteminfo.ipsitem_discntprcnt)) - ipsiteminfo.ipsitem_fixedamtdiscount) WHEN ((ipsiteminfo.ipsitem_type = 'M'::bpchar) AND fetchmetricbool('Long30Markups'::text)) THEN ((stdcost(item.item_id) / (1.0 - ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) WHEN (ipsiteminfo.ipsitem_type = 'M'::bpchar) THEN ((item.item_listcost + (item.item_listcost * ipsiteminfo.ipsitem_discntprcnt)) + ipsiteminfo.ipsitem_fixedamtdiscount) ELSE NULL::numeric END AS ipsprice_uomprice, item.item_price_uom_id AS ipsprice_uomprice_uom_id, ipsiteminfo.ipsitem_discntprcnt AS ipsprice_discountpercent, ipsiteminfo.ipsitem_fixedamtdiscount AS ipsprice_discountfixed, ipsiteminfo.ipsitem_type AS ipsprice_type FROM (ipsiteminfo JOIN item ON ((ipsiteminfo.ipsitem_prodcat_id = item.item_prodcat_id)));
101917
101918
101919 ALTER TABLE public.ipsprice OWNER TO admin;
101920
101921 --
101922 -- TOC entry 636 (class 1259 OID 146569294)
101923 -- Dependencies: 6551 8
101924 -- Name: ipsprodcat_bak; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
101925 --
101926
101927 CREATE TABLE ipsprodcat_bak (
101928     ipsprodcat_id integer NOT NULL,
101929     ipsprodcat_ipshead_id integer NOT NULL,
101930     ipsprodcat_prodcat_id integer NOT NULL,
101931     ipsprodcat_qtybreak numeric(18,6) NOT NULL,
101932     ipsprodcat_discntprcnt numeric(10,6) NOT NULL,
101933     ipsprodcat_fixedamtdiscount numeric(16,4) DEFAULT 0.00 NOT NULL
101934 );
101935
101936
101937 ALTER TABLE public.ipsprodcat_bak OWNER TO admin;
101938
101939 --
101940 -- TOC entry 9884 (class 0 OID 0)
101941 -- Dependencies: 636
101942 -- Name: TABLE ipsprodcat_bak; Type: COMMENT; Schema: public; Owner: admin
101943 --
101944
101945 COMMENT ON TABLE ipsprodcat_bak IS 'Pricing Schedule Product Category information.';
101946
101947
101948 --
101949 -- TOC entry 637 (class 1259 OID 146569298)
101950 -- Dependencies: 636 8
101951 -- Name: ipsprodcat_ipsprodcat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101952 --
101953
101954 CREATE SEQUENCE ipsprodcat_ipsprodcat_id_seq
101955     START WITH 1
101956     INCREMENT BY 1
101957     NO MINVALUE
101958     NO MAXVALUE
101959     CACHE 1;
101960
101961
101962 ALTER TABLE public.ipsprodcat_ipsprodcat_id_seq OWNER TO admin;
101963
101964 --
101965 -- TOC entry 9886 (class 0 OID 0)
101966 -- Dependencies: 637
101967 -- Name: ipsprodcat_ipsprodcat_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
101968 --
101969
101970 ALTER SEQUENCE ipsprodcat_ipsprodcat_id_seq OWNED BY ipsprodcat_bak.ipsprodcat_id;
101971
101972
101973 --
101974 -- TOC entry 638 (class 1259 OID 146569300)
101975 -- Dependencies: 8
101976 -- Name: item_item_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101977 --
101978
101979 CREATE SEQUENCE item_item_id_seq
101980     START WITH 1
101981     INCREMENT BY 1
101982     NO MINVALUE
101983     MAXVALUE 2147483647
101984     CACHE 1;
101985
101986
101987 ALTER TABLE public.item_item_id_seq OWNER TO admin;
101988
101989 --
101990 -- TOC entry 639 (class 1259 OID 146569302)
101991 -- Dependencies: 8
101992 -- Name: itemalias_itemalias_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
101993 --
101994
101995 CREATE SEQUENCE itemalias_itemalias_id_seq
101996     START WITH 1
101997     INCREMENT BY 1
101998     NO MINVALUE
101999     MAXVALUE 2147483647
102000     CACHE 1;
102001
102002
102003 ALTER TABLE public.itemalias_itemalias_id_seq OWNER TO admin;
102004
102005 --
102006 -- TOC entry 640 (class 1259 OID 146569304)
102007 -- Dependencies: 8
102008 -- Name: itematr_itematr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102009 --
102010
102011 CREATE SEQUENCE itematr_itematr_id_seq
102012     START WITH 1
102013     INCREMENT BY 1
102014     NO MINVALUE
102015     MAXVALUE 2147483647
102016     CACHE 1;
102017
102018
102019 ALTER TABLE public.itematr_itematr_id_seq OWNER TO admin;
102020
102021 --
102022 -- TOC entry 641 (class 1259 OID 146569306)
102023 -- Dependencies: 8
102024 -- Name: itemcost_itemcost_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102025 --
102026
102027 CREATE SEQUENCE itemcost_itemcost_id_seq
102028     START WITH 1
102029     INCREMENT BY 1
102030     NO MINVALUE
102031     MAXVALUE 2147483647
102032     CACHE 1;
102033
102034
102035 ALTER TABLE public.itemcost_itemcost_id_seq OWNER TO admin;
102036
102037 --
102038 -- TOC entry 642 (class 1259 OID 146569308)
102039 -- Dependencies: 8
102040 -- Name: itemfrez_itemfrez_seq; Type: SEQUENCE; Schema: public; Owner: admin
102041 --
102042
102043 CREATE SEQUENCE itemfrez_itemfrez_seq
102044     START WITH 1
102045     INCREMENT BY 1
102046     NO MINVALUE
102047     MAXVALUE 2147483647
102048     CACHE 1;
102049
102050
102051 ALTER TABLE public.itemfrez_itemfrez_seq OWNER TO admin;
102052
102053 --
102054 -- TOC entry 643 (class 1259 OID 146569310)
102055 -- Dependencies: 6552 6553 6554 8
102056 -- Name: itemgrp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102057 --
102058
102059 CREATE TABLE itemgrp (
102060     itemgrp_id integer DEFAULT nextval(('"itemgrp_itemgrp_id_seq"'::text)::regclass) NOT NULL,
102061     itemgrp_name text NOT NULL,
102062     itemgrp_descrip text,
102063     itemgrp_catalog boolean DEFAULT false NOT NULL,
102064     CONSTRAINT itemgrp_itemgrp_name_check CHECK ((itemgrp_name <> ''::text))
102065 );
102066
102067
102068 ALTER TABLE public.itemgrp OWNER TO admin;
102069
102070 --
102071 -- TOC entry 9893 (class 0 OID 0)
102072 -- Dependencies: 643
102073 -- Name: TABLE itemgrp; Type: COMMENT; Schema: public; Owner: admin
102074 --
102075
102076 COMMENT ON TABLE itemgrp IS 'Item Group information';
102077
102078
102079 --
102080 -- TOC entry 644 (class 1259 OID 146569319)
102081 -- Dependencies: 8
102082 -- Name: itemgrp_itemgrp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102083 --
102084
102085 CREATE SEQUENCE itemgrp_itemgrp_id_seq
102086     START WITH 1
102087     INCREMENT BY 1
102088     NO MINVALUE
102089     MAXVALUE 2147483647
102090     CACHE 1;
102091
102092
102093 ALTER TABLE public.itemgrp_itemgrp_id_seq OWNER TO admin;
102094
102095 --
102096 -- TOC entry 645 (class 1259 OID 146569321)
102097 -- Dependencies: 6555 6556 6557 8
102098 -- Name: itemgrpitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102099 --
102100
102101 CREATE TABLE itemgrpitem (
102102     itemgrpitem_id integer DEFAULT nextval(('"itemgrpitem_itemgrpitem_id_seq"'::text)::regclass) NOT NULL,
102103     itemgrpitem_itemgrp_id integer,
102104     itemgrpitem_item_id integer,
102105     itemgrpitem_item_type character(1) DEFAULT 'I'::bpchar NOT NULL,
102106     CONSTRAINT itemgrpitem_valid_item_type CHECK ((itemgrpitem_item_type = ANY (ARRAY['I'::bpchar, 'G'::bpchar])))
102107 );
102108
102109
102110 ALTER TABLE public.itemgrpitem OWNER TO admin;
102111
102112 --
102113 -- TOC entry 9896 (class 0 OID 0)
102114 -- Dependencies: 645
102115 -- Name: TABLE itemgrpitem; Type: COMMENT; Schema: public; Owner: admin
102116 --
102117
102118 COMMENT ON TABLE itemgrpitem IS 'Item Group Item information';
102119
102120
102121 --
102122 -- TOC entry 646 (class 1259 OID 146569327)
102123 -- Dependencies: 8
102124 -- Name: itemgrpitem_itemgrpitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102125 --
102126
102127 CREATE SEQUENCE itemgrpitem_itemgrpitem_id_seq
102128     START WITH 1
102129     INCREMENT BY 1
102130     NO MINVALUE
102131     MAXVALUE 2147483647
102132     CACHE 1;
102133
102134
102135 ALTER TABLE public.itemgrpitem_itemgrpitem_id_seq OWNER TO admin;
102136
102137 --
102138 -- TOC entry 647 (class 1259 OID 146569329)
102139 -- Dependencies: 8583 8
102140 -- Name: itemimage; Type: VIEW; Schema: public; Owner: admin
102141 --
102142
102143 CREATE VIEW itemimage AS
102144     SELECT imageass.imageass_id AS itemimage_id, imageass.imageass_source_id AS itemimage_item_id, imageass.imageass_image_id AS itemimage_image_id, imageass.imageass_purpose AS itemimage_purpose FROM imageass WHERE (imageass.imageass_source = 'I'::text);
102145
102146
102147 ALTER TABLE public.itemimage OWNER TO admin;
102148
102149 --
102150 -- TOC entry 9899 (class 0 OID 0)
102151 -- Dependencies: 647
102152 -- Name: VIEW itemimage; Type: COMMENT; Schema: public; Owner: admin
102153 --
102154
102155 COMMENT ON VIEW itemimage IS 'Itemimage view for legacy support. Use of itemimage is deprecated. Use imageass table for future development';
102156
102157
102158 --
102159 -- TOC entry 648 (class 1259 OID 146569333)
102160 -- Dependencies: 8
102161 -- Name: itemimage_itemimage_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102162 --
102163
102164 CREATE SEQUENCE itemimage_itemimage_id_seq
102165     START WITH 1
102166     INCREMENT BY 1
102167     NO MINVALUE
102168     NO MAXVALUE
102169     CACHE 1;
102170
102171
102172 ALTER TABLE public.itemimage_itemimage_id_seq OWNER TO admin;
102173
102174 --
102175 -- TOC entry 649 (class 1259 OID 146569335)
102176 -- Dependencies: 6558 8
102177 -- Name: itemloc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102178 --
102179
102180 CREATE TABLE itemloc (
102181     itemloc_id integer DEFAULT nextval(('"itemloc_itemloc_id_seq"'::text)::regclass) NOT NULL,
102182     itemloc_itemsite_id integer NOT NULL,
102183     itemloc_location_id integer NOT NULL,
102184     itemloc_qty numeric(18,6) NOT NULL,
102185     itemloc_expiration date NOT NULL,
102186     itemloc_consolflag boolean,
102187     itemloc_ls_id integer,
102188     itemloc_warrpurc date
102189 );
102190
102191
102192 ALTER TABLE public.itemloc OWNER TO admin;
102193
102194 --
102195 -- TOC entry 9902 (class 0 OID 0)
102196 -- Dependencies: 649
102197 -- Name: TABLE itemloc; Type: COMMENT; Schema: public; Owner: admin
102198 --
102199
102200 COMMENT ON TABLE itemloc IS 'Detailed Location information for Lot/Serial and Multiple Location Control (MLC) Items';
102201
102202
102203 --
102204 -- TOC entry 650 (class 1259 OID 146569339)
102205 -- Dependencies: 8
102206 -- Name: itemloc_itemloc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102207 --
102208
102209 CREATE SEQUENCE itemloc_itemloc_id_seq
102210     START WITH 1
102211     INCREMENT BY 1
102212     NO MINVALUE
102213     NO MAXVALUE
102214     CACHE 1;
102215
102216
102217 ALTER TABLE public.itemloc_itemloc_id_seq OWNER TO admin;
102218
102219 --
102220 -- TOC entry 651 (class 1259 OID 146569341)
102221 -- Dependencies: 8
102222 -- Name: itemloc_series_seq; Type: SEQUENCE; Schema: public; Owner: admin
102223 --
102224
102225 CREATE SEQUENCE itemloc_series_seq
102226     START WITH 1
102227     INCREMENT BY 1
102228     NO MINVALUE
102229     MAXVALUE 2147483647
102230     CACHE 1;
102231
102232
102233 ALTER TABLE public.itemloc_series_seq OWNER TO admin;
102234
102235 --
102236 -- TOC entry 652 (class 1259 OID 146569343)
102237 -- Dependencies: 6559 6560 6561 8
102238 -- Name: itemlocdist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102239 --
102240
102241 CREATE TABLE itemlocdist (
102242     itemlocdist_id integer DEFAULT nextval(('"itemlocdist_itemlocdist_id_seq"'::text)::regclass) NOT NULL,
102243     itemlocdist_itemlocdist_id integer,
102244     itemlocdist_source_type character(1),
102245     itemlocdist_source_id integer,
102246     itemlocdist_qty numeric(18,6),
102247     itemlocdist_series integer,
102248     itemlocdist_invhist_id integer,
102249     itemlocdist_itemsite_id integer,
102250     itemlocdist_reqlotserial boolean DEFAULT false,
102251     itemlocdist_flush boolean DEFAULT false,
102252     itemlocdist_expiration date,
102253     itemlocdist_distlotserial boolean,
102254     itemlocdist_warranty date,
102255     itemlocdist_ls_id integer,
102256     itemlocdist_order_type text,
102257     itemlocdist_order_id integer
102258 );
102259
102260
102261 ALTER TABLE public.itemlocdist OWNER TO admin;
102262
102263 --
102264 -- TOC entry 9906 (class 0 OID 0)
102265 -- Dependencies: 652
102266 -- Name: TABLE itemlocdist; Type: COMMENT; Schema: public; Owner: admin
102267 --
102268
102269 COMMENT ON TABLE itemlocdist IS 'Temporary table for storing information about Inventory distributions involving Lot/Serial and Multiple Location Control (MLC) Items';
102270
102271
102272 --
102273 -- TOC entry 653 (class 1259 OID 146569352)
102274 -- Dependencies: 8
102275 -- Name: itemlocdist_itemlocdist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102276 --
102277
102278 CREATE SEQUENCE itemlocdist_itemlocdist_id_seq
102279     START WITH 1
102280     INCREMENT BY 1
102281     NO MINVALUE
102282     NO MAXVALUE
102283     CACHE 1;
102284
102285
102286 ALTER TABLE public.itemlocdist_itemlocdist_id_seq OWNER TO admin;
102287
102288 --
102289 -- TOC entry 654 (class 1259 OID 146569354)
102290 -- Dependencies: 8
102291 -- Name: itemlocpost; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102292 --
102293
102294 CREATE TABLE itemlocpost (
102295     itemlocpost_id integer NOT NULL,
102296     itemlocpost_itemlocseries integer,
102297     itemlocpost_glseq integer
102298 );
102299
102300
102301 ALTER TABLE public.itemlocpost OWNER TO admin;
102302
102303 --
102304 -- TOC entry 9909 (class 0 OID 0)
102305 -- Dependencies: 654
102306 -- Name: TABLE itemlocpost; Type: COMMENT; Schema: public; Owner: admin
102307 --
102308
102309 COMMENT ON TABLE itemlocpost IS 'Temporary table for storing information about Inventory distribution G/L postings involving Lot/Serial and Multiple Location Control (MLC) Items';
102310
102311
102312 --
102313 -- TOC entry 655 (class 1259 OID 146569357)
102314 -- Dependencies: 654 8
102315 -- Name: itemlocpost_itemlocpost_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102316 --
102317
102318 CREATE SEQUENCE itemlocpost_itemlocpost_id_seq
102319     START WITH 1
102320     INCREMENT BY 1
102321     NO MINVALUE
102322     NO MAXVALUE
102323     CACHE 1;
102324
102325
102326 ALTER TABLE public.itemlocpost_itemlocpost_id_seq OWNER TO admin;
102327
102328 --
102329 -- TOC entry 9911 (class 0 OID 0)
102330 -- Dependencies: 655
102331 -- Name: itemlocpost_itemlocpost_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102332 --
102333
102334 ALTER SEQUENCE itemlocpost_itemlocpost_id_seq OWNED BY itemlocpost.itemlocpost_id;
102335
102336
102337 --
102338 -- TOC entry 656 (class 1259 OID 146569359)
102339 -- Dependencies: 8
102340 -- Name: itemopn_itemopn_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102341 --
102342
102343 CREATE SEQUENCE itemopn_itemopn_id_seq
102344     START WITH 1
102345     INCREMENT BY 1
102346     NO MINVALUE
102347     MAXVALUE 2147483647
102348     CACHE 1;
102349
102350
102351 ALTER TABLE public.itemopn_itemopn_id_seq OWNER TO admin;
102352
102353 --
102354 -- TOC entry 657 (class 1259 OID 146569361)
102355 -- Dependencies: 8
102356 -- Name: itemsite_itemsite_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102357 --
102358
102359 CREATE SEQUENCE itemsite_itemsite_id_seq
102360     START WITH 1
102361     INCREMENT BY 1
102362     NO MINVALUE
102363     MAXVALUE 2147483647
102364     CACHE 1;
102365
102366
102367 ALTER TABLE public.itemsite_itemsite_id_seq OWNER TO admin;
102368
102369 --
102370 -- TOC entry 658 (class 1259 OID 146569363)
102371 -- Dependencies: 8
102372 -- Name: itemsrc_itemsrc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102373 --
102374
102375 CREATE SEQUENCE itemsrc_itemsrc_id_seq
102376     START WITH 1
102377     INCREMENT BY 1
102378     NO MINVALUE
102379     MAXVALUE 2147483647
102380     CACHE 1;
102381
102382
102383 ALTER TABLE public.itemsrc_itemsrc_id_seq OWNER TO admin;
102384
102385 --
102386 -- TOC entry 659 (class 1259 OID 146569365)
102387 -- Dependencies: 8
102388 -- Name: itemsrcp_itemsrcp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102389 --
102390
102391 CREATE SEQUENCE itemsrcp_itemsrcp_id_seq
102392     START WITH 1
102393     INCREMENT BY 1
102394     NO MINVALUE
102395     MAXVALUE 2147483647
102396     CACHE 1;
102397
102398
102399 ALTER TABLE public.itemsrcp_itemsrcp_id_seq OWNER TO admin;
102400
102401 --
102402 -- TOC entry 660 (class 1259 OID 146569367)
102403 -- Dependencies: 8
102404 -- Name: itemsub_itemsub_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102405 --
102406
102407 CREATE SEQUENCE itemsub_itemsub_id_seq
102408     START WITH 1
102409     INCREMENT BY 1
102410     NO MINVALUE
102411     MAXVALUE 2147483647
102412     CACHE 1;
102413
102414
102415 ALTER TABLE public.itemsub_itemsub_id_seq OWNER TO admin;
102416
102417 --
102418 -- TOC entry 661 (class 1259 OID 146569369)
102419 -- Dependencies: 336 8
102420 -- Name: itemtax_itemtax_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102421 --
102422
102423 CREATE SEQUENCE itemtax_itemtax_id_seq
102424     START WITH 1
102425     INCREMENT BY 1
102426     NO MINVALUE
102427     NO MAXVALUE
102428     CACHE 1;
102429
102430
102431 ALTER TABLE public.itemtax_itemtax_id_seq OWNER TO admin;
102432
102433 --
102434 -- TOC entry 9918 (class 0 OID 0)
102435 -- Dependencies: 661
102436 -- Name: itemtax_itemtax_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102437 --
102438
102439 ALTER SEQUENCE itemtax_itemtax_id_seq OWNED BY itemtax.itemtax_id;
102440
102441
102442 --
102443 -- TOC entry 662 (class 1259 OID 146569371)
102444 -- Dependencies: 8
102445 -- Name: itemtrans; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102446 --
102447
102448 CREATE TABLE itemtrans (
102449     itemtrans_id integer NOT NULL,
102450     itemtrans_source_item_id integer,
102451     itemtrans_target_item_id integer
102452 );
102453
102454
102455 ALTER TABLE public.itemtrans OWNER TO admin;
102456
102457 --
102458 -- TOC entry 9920 (class 0 OID 0)
102459 -- Dependencies: 662
102460 -- Name: TABLE itemtrans; Type: COMMENT; Schema: public; Owner: admin
102461 --
102462
102463 COMMENT ON TABLE itemtrans IS 'Item Transformation information';
102464
102465
102466 --
102467 -- TOC entry 663 (class 1259 OID 146569374)
102468 -- Dependencies: 662 8
102469 -- Name: itemtrans_itemtrans_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102470 --
102471
102472 CREATE SEQUENCE itemtrans_itemtrans_id_seq
102473     START WITH 1
102474     INCREMENT BY 1
102475     NO MINVALUE
102476     NO MAXVALUE
102477     CACHE 1;
102478
102479
102480 ALTER TABLE public.itemtrans_itemtrans_id_seq OWNER TO admin;
102481
102482 --
102483 -- TOC entry 9922 (class 0 OID 0)
102484 -- Dependencies: 663
102485 -- Name: itemtrans_itemtrans_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102486 --
102487
102488 ALTER SEQUENCE itemtrans_itemtrans_id_seq OWNED BY itemtrans.itemtrans_id;
102489
102490
102491 --
102492 -- TOC entry 664 (class 1259 OID 146569376)
102493 -- Dependencies: 8
102494 -- Name: itemuom; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102495 --
102496
102497 CREATE TABLE itemuom (
102498     itemuom_id integer NOT NULL,
102499     itemuom_itemuomconv_id integer NOT NULL,
102500     itemuom_uomtype_id integer NOT NULL
102501 );
102502
102503
102504 ALTER TABLE public.itemuom OWNER TO admin;
102505
102506 --
102507 -- TOC entry 9924 (class 0 OID 0)
102508 -- Dependencies: 664
102509 -- Name: TABLE itemuom; Type: COMMENT; Schema: public; Owner: admin
102510 --
102511
102512 COMMENT ON TABLE itemuom IS 'A UOM type relation for a specific conversion.';
102513
102514
102515 --
102516 -- TOC entry 665 (class 1259 OID 146569379)
102517 -- Dependencies: 664 8
102518 -- Name: itemuom_itemuom_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102519 --
102520
102521 CREATE SEQUENCE itemuom_itemuom_id_seq
102522     START WITH 1
102523     INCREMENT BY 1
102524     NO MINVALUE
102525     NO MAXVALUE
102526     CACHE 1;
102527
102528
102529 ALTER TABLE public.itemuom_itemuom_id_seq OWNER TO admin;
102530
102531 --
102532 -- TOC entry 9926 (class 0 OID 0)
102533 -- Dependencies: 665
102534 -- Name: itemuom_itemuom_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102535 --
102536
102537 ALTER SEQUENCE itemuom_itemuom_id_seq OWNED BY itemuom.itemuom_id;
102538
102539
102540 --
102541 -- TOC entry 666 (class 1259 OID 146569381)
102542 -- Dependencies: 338 8
102543 -- Name: itemuomconv_itemuomconv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102544 --
102545
102546 CREATE SEQUENCE itemuomconv_itemuomconv_id_seq
102547     START WITH 1
102548     INCREMENT BY 1
102549     NO MINVALUE
102550     NO MAXVALUE
102551     CACHE 1;
102552
102553
102554 ALTER TABLE public.itemuomconv_itemuomconv_id_seq OWNER TO admin;
102555
102556 --
102557 -- TOC entry 9928 (class 0 OID 0)
102558 -- Dependencies: 666
102559 -- Name: itemuomconv_itemuomconv_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102560 --
102561
102562 ALTER SEQUENCE itemuomconv_itemuomconv_id_seq OWNED BY itemuomconv.itemuomconv_id;
102563
102564
102565 --
102566 -- TOC entry 667 (class 1259 OID 146569383)
102567 -- Dependencies: 8
102568 -- Name: journal_number_seq; Type: SEQUENCE; Schema: public; Owner: admin
102569 --
102570
102571 CREATE SEQUENCE journal_number_seq
102572     START WITH 1
102573     INCREMENT BY 1
102574     NO MINVALUE
102575     NO MAXVALUE
102576     CACHE 1;
102577
102578
102579 ALTER TABLE public.journal_number_seq OWNER TO admin;
102580
102581 --
102582 -- TOC entry 668 (class 1259 OID 146569385)
102583 -- Dependencies: 6565 8
102584 -- Name: jrnluse; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102585 --
102586
102587 CREATE TABLE jrnluse (
102588     jrnluse_id integer DEFAULT nextval(('"jrnluse_jrnluse_id_seq"'::text)::regclass) NOT NULL,
102589     jrnluse_date timestamp without time zone,
102590     jrnluse_number integer,
102591     jrnluse_use text
102592 );
102593
102594
102595 ALTER TABLE public.jrnluse OWNER TO admin;
102596
102597 --
102598 -- TOC entry 9931 (class 0 OID 0)
102599 -- Dependencies: 668
102600 -- Name: TABLE jrnluse; Type: COMMENT; Schema: public; Owner: admin
102601 --
102602
102603 COMMENT ON TABLE jrnluse IS 'Journal entry and use information';
102604
102605
102606 --
102607 -- TOC entry 669 (class 1259 OID 146569392)
102608 -- Dependencies: 8
102609 -- Name: jrnluse_jrnluse_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102610 --
102611
102612 CREATE SEQUENCE jrnluse_jrnluse_id_seq
102613     START WITH 1
102614     INCREMENT BY 1
102615     NO MINVALUE
102616     NO MAXVALUE
102617     CACHE 1;
102618
102619
102620 ALTER TABLE public.jrnluse_jrnluse_id_seq OWNER TO admin;
102621
102622 --
102623 -- TOC entry 670 (class 1259 OID 146569394)
102624 -- Dependencies: 8
102625 -- Name: labeldef; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102626 --
102627
102628 CREATE TABLE labeldef (
102629     labeldef_id integer NOT NULL,
102630     labeldef_name text NOT NULL,
102631     labeldef_papersize text NOT NULL,
102632     labeldef_columns integer NOT NULL,
102633     labeldef_rows integer NOT NULL,
102634     labeldef_width integer NOT NULL,
102635     labeldef_height integer NOT NULL,
102636     labeldef_start_offset_x integer NOT NULL,
102637     labeldef_start_offset_y integer NOT NULL,
102638     labeldef_horizontal_gap integer NOT NULL,
102639     labeldef_vertical_gap integer NOT NULL
102640 );
102641
102642
102643 ALTER TABLE public.labeldef OWNER TO admin;
102644
102645 --
102646 -- TOC entry 671 (class 1259 OID 146569400)
102647 -- Dependencies: 670 8
102648 -- Name: labeldef_labeldef_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102649 --
102650
102651 CREATE SEQUENCE labeldef_labeldef_id_seq
102652     START WITH 1
102653     INCREMENT BY 1
102654     NO MINVALUE
102655     NO MAXVALUE
102656     CACHE 1;
102657
102658
102659 ALTER TABLE public.labeldef_labeldef_id_seq OWNER TO admin;
102660
102661 --
102662 -- TOC entry 9935 (class 0 OID 0)
102663 -- Dependencies: 671
102664 -- Name: labeldef_labeldef_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102665 --
102666
102667 ALTER SEQUENCE labeldef_labeldef_id_seq OWNED BY labeldef.labeldef_id;
102668
102669
102670 --
102671 -- TOC entry 672 (class 1259 OID 146569402)
102672 -- Dependencies: 6567 6568 8
102673 -- Name: labelform; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102674 --
102675
102676 CREATE TABLE labelform (
102677     labelform_id integer DEFAULT nextval(('"labelform_labelform_id_seq"'::text)::regclass) NOT NULL,
102678     labelform_name text NOT NULL,
102679     labelform_report_id integer,
102680     labelform_perpage integer,
102681     labelform_report_name text,
102682     CONSTRAINT labelform_labelform_name_check CHECK ((labelform_name <> ''::text))
102683 );
102684
102685
102686 ALTER TABLE public.labelform OWNER TO admin;
102687
102688 --
102689 -- TOC entry 9937 (class 0 OID 0)
102690 -- Dependencies: 672
102691 -- Name: TABLE labelform; Type: COMMENT; Schema: public; Owner: admin
102692 --
102693
102694 COMMENT ON TABLE labelform IS 'Label Form information';
102695
102696
102697 --
102698 -- TOC entry 9938 (class 0 OID 0)
102699 -- Dependencies: 672
102700 -- Name: COLUMN labelform.labelform_report_id; Type: COMMENT; Schema: public; Owner: admin
102701 --
102702
102703 COMMENT ON COLUMN labelform.labelform_report_id IS 'Obsolete -- reference labelform_report_name instead.';
102704
102705
102706 --
102707 -- TOC entry 673 (class 1259 OID 146569410)
102708 -- Dependencies: 8
102709 -- Name: labelform_labelform_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102710 --
102711
102712 CREATE SEQUENCE labelform_labelform_id_seq
102713     START WITH 1
102714     INCREMENT BY 1
102715     NO MINVALUE
102716     NO MAXVALUE
102717     CACHE 1;
102718
102719
102720 ALTER TABLE public.labelform_labelform_id_seq OWNER TO admin;
102721
102722 --
102723 -- TOC entry 674 (class 1259 OID 146569412)
102724 -- Dependencies: 8
102725 -- Name: lang; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102726 --
102727
102728 CREATE TABLE lang (
102729     lang_id integer NOT NULL,
102730     lang_qt_number integer,
102731     lang_abbr3 text,
102732     lang_abbr2 text,
102733     lang_name text NOT NULL
102734 );
102735
102736
102737 ALTER TABLE public.lang OWNER TO admin;
102738
102739 --
102740 -- TOC entry 9941 (class 0 OID 0)
102741 -- Dependencies: 674
102742 -- Name: TABLE lang; Type: COMMENT; Schema: public; Owner: admin
102743 --
102744
102745 COMMENT ON TABLE lang IS 'Table mapping ISO 639-1 and 639-2 language codes to Qt''s enum QLocale::Language integer values. See http://www.loc.gov/standards/iso639-2/php/code_list.php and the QLocale documentation..';
102746
102747
102748 --
102749 -- TOC entry 9942 (class 0 OID 0)
102750 -- Dependencies: 674
102751 -- Name: COLUMN lang.lang_abbr3; Type: COMMENT; Schema: public; Owner: admin
102752 --
102753
102754 COMMENT ON COLUMN lang.lang_abbr3 IS 'ISO 639-2 code for language. Where there is a choice between bibliographic (B) and terminology (T) usage, this value is the T code';
102755
102756
102757 --
102758 -- TOC entry 9943 (class 0 OID 0)
102759 -- Dependencies: 674
102760 -- Name: COLUMN lang.lang_abbr2; Type: COMMENT; Schema: public; Owner: admin
102761 --
102762
102763 COMMENT ON COLUMN lang.lang_abbr2 IS 'ISO 639-1 code for language';
102764
102765
102766 --
102767 -- TOC entry 9944 (class 0 OID 0)
102768 -- Dependencies: 674
102769 -- Name: COLUMN lang.lang_name; Type: COMMENT; Schema: public; Owner: admin
102770 --
102771
102772 COMMENT ON COLUMN lang.lang_name IS 'Name of a human language, taken from the ISO 639-2 documentation';
102773
102774
102775 --
102776 -- TOC entry 675 (class 1259 OID 146569418)
102777 -- Dependencies: 674 8
102778 -- Name: lang_lang_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
102779 --
102780
102781 CREATE SEQUENCE lang_lang_id_seq
102782     START WITH 1
102783     INCREMENT BY 1
102784     NO MINVALUE
102785     NO MAXVALUE
102786     CACHE 1;
102787
102788
102789 ALTER TABLE public.lang_lang_id_seq OWNER TO admin;
102790
102791 --
102792 -- TOC entry 9946 (class 0 OID 0)
102793 -- Dependencies: 675
102794 -- Name: lang_lang_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
102795 --
102796
102797 ALTER SEQUENCE lang_lang_id_seq OWNED BY lang.lang_id;
102798
102799
102800 --
102801 -- TOC entry 676 (class 1259 OID 146569420)
102802 -- Dependencies: 6570 6571 6572 6573 8
102803 -- Name: locale; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
102804 --
102805
102806 CREATE TABLE locale (
102807     locale_id integer DEFAULT nextval(('locale_locale_id_seq'::text)::regclass) NOT NULL,
102808     locale_code text NOT NULL,
102809     locale_descrip text,
102810     locale_lang_file text,
102811     locale_dateformat text,
102812     locale_currformat text,
102813     locale_qtyformat text,
102814     locale_comments text,
102815     locale_qtyperformat text,
102816     locale_salespriceformat text,
102817     locale_extpriceformat text,
102818     locale_timeformat text,
102819     locale_timestampformat text,
102820     local_costformat text,
102821     locale_costformat text,
102822     locale_purchpriceformat text,
102823     locale_uomratioformat text,
102824     locale_intervalformat text,
102825     locale_lang_id integer,
102826     locale_country_id integer,
102827     locale_error_color text,
102828     locale_warning_color text,
102829     locale_emphasis_color text,
102830     locale_altemphasis_color text,
102831     locale_expired_color text,
102832     locale_future_color text,
102833     locale_curr_scale integer,
102834     locale_salesprice_scale integer,
102835     locale_purchprice_scale integer,
102836     locale_extprice_scale integer,
102837     locale_cost_scale integer,
102838     locale_qty_scale integer,
102839     locale_qtyper_scale integer,
102840     locale_uomratio_scale integer,
102841     locale_percent_scale integer DEFAULT 2,
102842     locale_weight_scale integer DEFAULT 2 NOT NULL,
102843     CONSTRAINT locale_locale_code_check CHECK ((locale_code <> ''::text))
102844 );
102845
102846
102847 ALTER TABLE public.locale OWNER TO admin;
102848
102849 --
102850 -- TOC entry 9948 (class 0 OID 0)
102851 -- Dependencies: 676
102852 -- Name: TABLE locale; Type: COMMENT; Schema: public; Owner: admin
102853 --
102854
102855 COMMENT ON TABLE locale IS 'The locale table holds information required to show data to the user in a localized format. Colors are either names documented by the WWW Consortium or RGB colors. Format for RGB colors is #RGB, #RRGGBB, or #RRRGGGBBB, where the letters R, G, and B stand for hexidecimal digits.';
102856
102857
102858 --
102859 -- TOC entry 9949 (class 0 OID 0)
102860 -- Dependencies: 676
102861 -- Name: COLUMN locale.locale_lang_file; Type: COMMENT; Schema: public; Owner: admin
102862 --
102863
102864 COMMENT ON COLUMN locale.locale_lang_file IS 'Deprecated';
102865
102866
102867 --
102868 -- TOC entry 9950 (class 0 OID 0)
102869 -- Dependencies: 676
102870 -- Name: COLUMN locale.locale_dateformat; Type: COMMENT; Schema: public; Owner: admin
102871 --
102872
102873 COMMENT ON COLUMN locale.locale_dateformat IS 'Deprecated';
102874
102875
102876 --
102877 -- TOC entry 9951 (class 0 OID 0)
102878 -- Dependencies: 676
102879 -- Name: COLUMN locale.locale_currformat; Type: COMMENT; Schema: public; Owner: admin
102880 --
102881
102882 COMMENT ON COLUMN locale.locale_currformat IS 'Deprecated';
102883
102884
102885 --
102886 -- TOC entry 9952 (class 0 OID 0)
102887 -- Dependencies: 676
102888 -- Name: COLUMN locale.locale_qtyformat; Type: COMMENT; Schema: public; Owner: admin
102889 --
102890
102891 COMMENT ON COLUMN locale.locale_qtyformat IS 'Deprecated';
102892
102893
102894 --
102895 -- TOC entry 9953 (class 0 OID 0)
102896 -- Dependencies: 676
102897 -- Name: COLUMN locale.locale_qtyperformat; Type: COMMENT; Schema: public; Owner: admin
102898 --
102899
102900 COMMENT ON COLUMN locale.locale_qtyperformat IS 'Deprecated';
102901
102902
102903 --
102904 -- TOC entry 9954 (class 0 OID 0)
102905 -- Dependencies: 676
102906 -- Name: COLUMN locale.locale_salespriceformat; Type: COMMENT; Schema: public; Owner: admin
102907 --
102908
102909 COMMENT ON COLUMN locale.locale_salespriceformat IS 'Deprecated';
102910
102911
102912 --
102913 -- TOC entry 9955 (class 0 OID 0)
102914 -- Dependencies: 676
102915 -- Name: COLUMN locale.locale_extpriceformat; Type: COMMENT; Schema: public; Owner: admin
102916 --
102917
102918 COMMENT ON COLUMN locale.locale_extpriceformat IS 'Deprecated';
102919
102920
102921 --
102922 -- TOC entry 9956 (class 0 OID 0)
102923 -- Dependencies: 676
102924 -- Name: COLUMN locale.locale_timeformat; Type: COMMENT; Schema: public; Owner: admin
102925 --
102926
102927 COMMENT ON COLUMN locale.locale_timeformat IS 'Deprecated';
102928
102929
102930 --
102931 -- TOC entry 9957 (class 0 OID 0)
102932 -- Dependencies: 676
102933 -- Name: COLUMN locale.locale_timestampformat; Type: COMMENT; Schema: public; Owner: admin
102934 --
102935
102936 COMMENT ON COLUMN locale.locale_timestampformat IS 'Deprecated';
102937
102938
102939 --
102940 -- TOC entry 9958 (class 0 OID 0)
102941 -- Dependencies: 676
102942 -- Name: COLUMN locale.local_costformat; Type: COMMENT; Schema: public; Owner: admin
102943 --
102944
102945 COMMENT ON COLUMN locale.local_costformat IS 'Deprecated';
102946
102947
102948 --
102949 -- TOC entry 9959 (class 0 OID 0)
102950 -- Dependencies: 676
102951 -- Name: COLUMN locale.locale_costformat; Type: COMMENT; Schema: public; Owner: admin
102952 --
102953
102954 COMMENT ON COLUMN locale.locale_costformat IS 'Deprecated';
102955
102956
102957 --
102958 -- TOC entry 9960 (class 0 OID 0)
102959 -- Dependencies: 676
102960 -- Name: COLUMN locale.locale_purchpriceformat; Type: COMMENT; Schema: public; Owner: admin
102961 --
102962
102963 COMMENT ON COLUMN locale.locale_purchpriceformat IS 'Deprecated';
102964
102965
102966 --
102967 -- TOC entry 9961 (class 0 OID 0)
102968 -- Dependencies: 676
102969 -- Name: COLUMN locale.locale_uomratioformat; Type: COMMENT; Schema: public; Owner: admin
102970 --
102971
102972 COMMENT ON COLUMN locale.locale_uomratioformat IS 'Deprecated';
102973
102974
102975 --
102976 -- TOC entry 9962 (class 0 OID 0)
102977 -- Dependencies: 676
102978 -- Name: COLUMN locale.locale_intervalformat; Type: COMMENT; Schema: public; Owner: admin
102979 --
102980
102981 COMMENT ON COLUMN locale.locale_intervalformat IS 'Deprecated';
102982
102983
102984 --
102985 -- TOC entry 9963 (class 0 OID 0)
102986 -- Dependencies: 676
102987 -- Name: COLUMN locale.locale_error_color; Type: COMMENT; Schema: public; Owner: admin
102988 --
102989
102990 COMMENT ON COLUMN locale.locale_error_color IS 'Color to use to mark data that require immediate attention.';
102991
102992
102993 --
102994 -- TOC entry 9964 (class 0 OID 0)
102995 -- Dependencies: 676
102996 -- Name: COLUMN locale.locale_warning_color; Type: COMMENT; Schema: public; Owner: admin
102997 --
102998
102999 COMMENT ON COLUMN locale.locale_warning_color IS 'Color to use to mark data that require attention soon.';
103000
103001
103002 --
103003 -- TOC entry 9965 (class 0 OID 0)
103004 -- Dependencies: 676
103005 -- Name: COLUMN locale.locale_emphasis_color; Type: COMMENT; Schema: public; Owner: admin
103006 --
103007
103008 COMMENT ON COLUMN locale.locale_emphasis_color IS 'Color to use to mark data that need to stand out but are not in error.';
103009
103010
103011 --
103012 -- TOC entry 9966 (class 0 OID 0)
103013 -- Dependencies: 676
103014 -- Name: COLUMN locale.locale_altemphasis_color; Type: COMMENT; Schema: public; Owner: admin
103015 --
103016
103017 COMMENT ON COLUMN locale.locale_altemphasis_color IS 'Color to use to mark data that need to stand out and be differentiated from other emphasized data.';
103018
103019
103020 --
103021 -- TOC entry 9967 (class 0 OID 0)
103022 -- Dependencies: 676
103023 -- Name: COLUMN locale.locale_expired_color; Type: COMMENT; Schema: public; Owner: admin
103024 --
103025
103026 COMMENT ON COLUMN locale.locale_expired_color IS 'Color to use to mark data that are no longer current.';
103027
103028
103029 --
103030 -- TOC entry 9968 (class 0 OID 0)
103031 -- Dependencies: 676
103032 -- Name: COLUMN locale.locale_future_color; Type: COMMENT; Schema: public; Owner: admin
103033 --
103034
103035 COMMENT ON COLUMN locale.locale_future_color IS 'Color to use to mark data that will not be effective until some point in the future.';
103036
103037
103038 --
103039 -- TOC entry 9969 (class 0 OID 0)
103040 -- Dependencies: 676
103041 -- Name: COLUMN locale.locale_curr_scale; Type: COMMENT; Schema: public; Owner: admin
103042 --
103043
103044 COMMENT ON COLUMN locale.locale_curr_scale IS 'Number of decimal places to show when displaying Currency values.';
103045
103046
103047 --
103048 -- TOC entry 9970 (class 0 OID 0)
103049 -- Dependencies: 676
103050 -- Name: COLUMN locale.locale_salesprice_scale; Type: COMMENT; Schema: public; Owner: admin
103051 --
103052
103053 COMMENT ON COLUMN locale.locale_salesprice_scale IS 'Number of decimal places to show when displaying Sales Prices.';
103054
103055
103056 --
103057 -- TOC entry 9971 (class 0 OID 0)
103058 -- Dependencies: 676
103059 -- Name: COLUMN locale.locale_purchprice_scale; Type: COMMENT; Schema: public; Owner: admin
103060 --
103061
103062 COMMENT ON COLUMN locale.locale_purchprice_scale IS 'Number of decimal places to show when displaying Purchase Prices.';
103063
103064
103065 --
103066 -- TOC entry 9972 (class 0 OID 0)
103067 -- Dependencies: 676
103068 -- Name: COLUMN locale.locale_extprice_scale; Type: COMMENT; Schema: public; Owner: admin
103069 --
103070
103071 COMMENT ON COLUMN locale.locale_extprice_scale IS 'Number of decimal places to show when displaying Extended Prices.';
103072
103073
103074 --
103075 -- TOC entry 9973 (class 0 OID 0)
103076 -- Dependencies: 676
103077 -- Name: COLUMN locale.locale_cost_scale; Type: COMMENT; Schema: public; Owner: admin
103078 --
103079
103080 COMMENT ON COLUMN locale.locale_cost_scale IS 'Number of decimal places to show when displaying Costs.';
103081
103082
103083 --
103084 -- TOC entry 9974 (class 0 OID 0)
103085 -- Dependencies: 676
103086 -- Name: COLUMN locale.locale_qty_scale; Type: COMMENT; Schema: public; Owner: admin
103087 --
103088
103089 COMMENT ON COLUMN locale.locale_qty_scale IS 'Number of decimal places to show when displaying Quantities.';
103090
103091
103092 --
103093 -- TOC entry 9975 (class 0 OID 0)
103094 -- Dependencies: 676
103095 -- Name: COLUMN locale.locale_qtyper_scale; Type: COMMENT; Schema: public; Owner: admin
103096 --
103097
103098 COMMENT ON COLUMN locale.locale_qtyper_scale IS 'Number of decimal places to show when displaying Quantities Per.';
103099
103100
103101 --
103102 -- TOC entry 9976 (class 0 OID 0)
103103 -- Dependencies: 676
103104 -- Name: COLUMN locale.locale_uomratio_scale; Type: COMMENT; Schema: public; Owner: admin
103105 --
103106
103107 COMMENT ON COLUMN locale.locale_uomratio_scale IS 'Number of decimal places to show when displaying UOM Ratios.';
103108
103109
103110 --
103111 -- TOC entry 677 (class 1259 OID 146569430)
103112 -- Dependencies: 8
103113 -- Name: locale_locale_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103114 --
103115
103116 CREATE SEQUENCE locale_locale_id_seq
103117     START WITH 1
103118     INCREMENT BY 1
103119     NO MINVALUE
103120     MAXVALUE 2147483647
103121     CACHE 1;
103122
103123
103124 ALTER TABLE public.locale_locale_id_seq OWNER TO admin;
103125
103126 --
103127 -- TOC entry 678 (class 1259 OID 146569432)
103128 -- Dependencies: 8
103129 -- Name: location_location_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103130 --
103131
103132 CREATE SEQUENCE location_location_id_seq
103133     START WITH 1
103134     INCREMENT BY 1
103135     NO MINVALUE
103136     MAXVALUE 2147483647
103137     CACHE 1;
103138
103139
103140 ALTER TABLE public.location_location_id_seq OWNER TO admin;
103141
103142 --
103143 -- TOC entry 679 (class 1259 OID 146569434)
103144 -- Dependencies: 6574 8
103145 -- Name: locitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103146 --
103147
103148 CREATE TABLE locitem (
103149     locitem_id integer DEFAULT nextval(('"locitem_locitem_id_seq"'::text)::regclass) NOT NULL,
103150     locitem_location_id integer,
103151     locitem_item_id integer
103152 );
103153
103154
103155 ALTER TABLE public.locitem OWNER TO admin;
103156
103157 --
103158 -- TOC entry 9980 (class 0 OID 0)
103159 -- Dependencies: 679
103160 -- Name: TABLE locitem; Type: COMMENT; Schema: public; Owner: admin
103161 --
103162
103163 COMMENT ON TABLE locitem IS 'Restricted Warehouse Location Allowable Items information';
103164
103165
103166 --
103167 -- TOC entry 680 (class 1259 OID 146569438)
103168 -- Dependencies: 8
103169 -- Name: locitem_locitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103170 --
103171
103172 CREATE SEQUENCE locitem_locitem_id_seq
103173     START WITH 1
103174     INCREMENT BY 1
103175     NO MINVALUE
103176     MAXVALUE 2147483647
103177     CACHE 1;
103178
103179
103180 ALTER TABLE public.locitem_locitem_id_seq OWNER TO admin;
103181
103182 --
103183 -- TOC entry 681 (class 1259 OID 146569440)
103184 -- Dependencies: 8
103185 -- Name: log_log_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103186 --
103187
103188 CREATE SEQUENCE log_log_id_seq
103189     START WITH 1
103190     INCREMENT BY 1
103191     NO MINVALUE
103192     MAXVALUE 2147483647
103193     CACHE 1;
103194
103195
103196 ALTER TABLE public.log_log_id_seq OWNER TO admin;
103197
103198 --
103199 -- TOC entry 682 (class 1259 OID 146569442)
103200 -- Dependencies: 6575 6576 8
103201 -- Name: metric; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103202 --
103203
103204 CREATE TABLE metric (
103205     metric_id integer DEFAULT nextval(('metric_metric_id_seq'::text)::regclass) NOT NULL,
103206     metric_name text NOT NULL,
103207     metric_value text,
103208     metric_module text,
103209     CONSTRAINT metric_metric_name_check CHECK ((metric_name <> ''::text))
103210 );
103211
103212
103213 ALTER TABLE public.metric OWNER TO admin;
103214
103215 --
103216 -- TOC entry 9984 (class 0 OID 0)
103217 -- Dependencies: 682
103218 -- Name: TABLE metric; Type: COMMENT; Schema: public; Owner: admin
103219 --
103220
103221 COMMENT ON TABLE metric IS 'Application-wide settings information';
103222
103223
103224 --
103225 -- TOC entry 683 (class 1259 OID 146569450)
103226 -- Dependencies: 8
103227 -- Name: metric_metric_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103228 --
103229
103230 CREATE SEQUENCE metric_metric_id_seq
103231     START WITH 1
103232     INCREMENT BY 1
103233     NO MINVALUE
103234     MAXVALUE 2147483647
103235     CACHE 1;
103236
103237
103238 ALTER TABLE public.metric_metric_id_seq OWNER TO admin;
103239
103240 --
103241 -- TOC entry 684 (class 1259 OID 146569452)
103242 -- Dependencies: 6578 8
103243 -- Name: metricenc; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103244 --
103245
103246 CREATE TABLE metricenc (
103247     metricenc_id integer NOT NULL,
103248     metricenc_name text NOT NULL,
103249     metricenc_value bytea,
103250     metricenc_module text,
103251     CONSTRAINT metricenc_metricenc_name_check CHECK ((metricenc_name <> ''::text))
103252 );
103253
103254
103255 ALTER TABLE public.metricenc OWNER TO admin;
103256
103257 --
103258 -- TOC entry 9987 (class 0 OID 0)
103259 -- Dependencies: 684
103260 -- Name: TABLE metricenc; Type: COMMENT; Schema: public; Owner: admin
103261 --
103262
103263 COMMENT ON TABLE metricenc IS 'Application-wide settings information encrypted data';
103264
103265
103266 --
103267 -- TOC entry 685 (class 1259 OID 146569459)
103268 -- Dependencies: 684 8
103269 -- Name: metricenc_metricenc_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103270 --
103271
103272 CREATE SEQUENCE metricenc_metricenc_id_seq
103273     START WITH 1
103274     INCREMENT BY 1
103275     NO MINVALUE
103276     NO MAXVALUE
103277     CACHE 1;
103278
103279
103280 ALTER TABLE public.metricenc_metricenc_id_seq OWNER TO admin;
103281
103282 --
103283 -- TOC entry 9989 (class 0 OID 0)
103284 -- Dependencies: 685
103285 -- Name: metricenc_metricenc_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103286 --
103287
103288 ALTER SEQUENCE metricenc_metricenc_id_seq OWNED BY metricenc.metricenc_id;
103289
103290
103291 --
103292 -- TOC entry 686 (class 1259 OID 146569461)
103293 -- Dependencies: 8
103294 -- Name: misc_index_seq; Type: SEQUENCE; Schema: public; Owner: admin
103295 --
103296
103297 CREATE SEQUENCE misc_index_seq
103298     START WITH 1
103299     INCREMENT BY 1
103300     NO MINVALUE
103301     MAXVALUE 2147483647
103302     CACHE 1;
103303
103304
103305 ALTER TABLE public.misc_index_seq OWNER TO admin;
103306
103307 --
103308 -- TOC entry 687 (class 1259 OID 146569463)
103309 -- Dependencies: 8
103310 -- Name: mrghist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103311 --
103312
103313 CREATE TABLE mrghist (
103314     mrghist_cntct_id integer NOT NULL,
103315     mrghist_table text NOT NULL,
103316     mrghist_pkey_col text NOT NULL,
103317     mrghist_pkey_id integer NOT NULL,
103318     mrghist_cntct_col text NOT NULL
103319 );
103320
103321
103322 ALTER TABLE public.mrghist OWNER TO admin;
103323
103324 --
103325 -- TOC entry 688 (class 1259 OID 146569469)
103326 -- Dependencies: 8
103327 -- Name: mrgundo; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103328 --
103329
103330 CREATE TABLE mrgundo (
103331     mrgundo_base_schema text,
103332     mrgundo_base_table text,
103333     mrgundo_base_id integer,
103334     mrgundo_schema text,
103335     mrgundo_table text,
103336     mrgundo_pkey_col text,
103337     mrgundo_pkey_id integer,
103338     mrgundo_col text,
103339     mrgundo_value text,
103340     mrgundo_type text
103341 );
103342
103343
103344 ALTER TABLE public.mrgundo OWNER TO admin;
103345
103346 --
103347 -- TOC entry 9993 (class 0 OID 0)
103348 -- Dependencies: 688
103349 -- Name: TABLE mrgundo; Type: COMMENT; Schema: public; Owner: admin
103350 --
103351
103352 COMMENT ON TABLE mrgundo IS 'This table keeps track of the original values of changes made while merging two records. It is a generalization of mrghist and trgthist, which are specific to merging contacts. The schema, table, and pkey_id columns uniquely identify the record that was changed while the _base_ columns identify the merge target. The _base_ columns are required to allow finding all of the records that pertain to a particular merge (e.g. find changes to the comment table that pertain to a crmacct merge).';
103353
103354
103355 --
103356 -- TOC entry 9994 (class 0 OID 0)
103357 -- Dependencies: 688
103358 -- Name: COLUMN mrgundo.mrgundo_base_schema; Type: COMMENT; Schema: public; Owner: admin
103359 --
103360
103361 COMMENT ON COLUMN mrgundo.mrgundo_base_schema IS 'The schema in which the merge target resides.';
103362
103363
103364 --
103365 -- TOC entry 9995 (class 0 OID 0)
103366 -- Dependencies: 688
103367 -- Name: COLUMN mrgundo.mrgundo_base_table; Type: COMMENT; Schema: public; Owner: admin
103368 --
103369
103370 COMMENT ON COLUMN mrgundo.mrgundo_base_table IS 'The table in which the merge target resides.';
103371
103372
103373 --
103374 -- TOC entry 9996 (class 0 OID 0)
103375 -- Dependencies: 688
103376 -- Name: COLUMN mrgundo.mrgundo_base_id; Type: COMMENT; Schema: public; Owner: admin
103377 --
103378
103379 COMMENT ON COLUMN mrgundo.mrgundo_base_id IS 'The internal id of the merge target record.';
103380
103381
103382 --
103383 -- TOC entry 9997 (class 0 OID 0)
103384 -- Dependencies: 688
103385 -- Name: COLUMN mrgundo.mrgundo_schema; Type: COMMENT; Schema: public; Owner: admin
103386 --
103387
103388 COMMENT ON COLUMN mrgundo.mrgundo_schema IS 'The name of the schema in which the modified table resides.';
103389
103390
103391 --
103392 -- TOC entry 9998 (class 0 OID 0)
103393 -- Dependencies: 688
103394 -- Name: COLUMN mrgundo.mrgundo_table; Type: COMMENT; Schema: public; Owner: admin
103395 --
103396
103397 COMMENT ON COLUMN mrgundo.mrgundo_table IS 'The name of the table that was modified during a merge.';
103398
103399
103400 --
103401 -- TOC entry 9999 (class 0 OID 0)
103402 -- Dependencies: 688
103403 -- Name: COLUMN mrgundo.mrgundo_pkey_col; Type: COMMENT; Schema: public; Owner: admin
103404 --
103405
103406 COMMENT ON COLUMN mrgundo.mrgundo_pkey_col IS 'The name of the primary key column in the modified table. This could be derived during the undo processing but it is simpler just to store it during the merge.';
103407
103408
103409 --
103410 -- TOC entry 10000 (class 0 OID 0)
103411 -- Dependencies: 688
103412 -- Name: COLUMN mrgundo.mrgundo_pkey_id; Type: COMMENT; Schema: public; Owner: admin
103413 --
103414
103415 COMMENT ON COLUMN mrgundo.mrgundo_pkey_id IS 'The primary key of the modified record.';
103416
103417
103418 --
103419 -- TOC entry 10001 (class 0 OID 0)
103420 -- Dependencies: 688
103421 -- Name: COLUMN mrgundo.mrgundo_col; Type: COMMENT; Schema: public; Owner: admin
103422 --
103423
103424 COMMENT ON COLUMN mrgundo.mrgundo_col IS 'The column that was modified.';
103425
103426
103427 --
103428 -- TOC entry 10002 (class 0 OID 0)
103429 -- Dependencies: 688
103430 -- Name: COLUMN mrgundo.mrgundo_value; Type: COMMENT; Schema: public; Owner: admin
103431 --
103432
103433 COMMENT ON COLUMN mrgundo.mrgundo_value IS 'The value of the column before the change.';
103434
103435
103436 --
103437 -- TOC entry 10003 (class 0 OID 0)
103438 -- Dependencies: 688
103439 -- Name: COLUMN mrgundo.mrgundo_type; Type: COMMENT; Schema: public; Owner: admin
103440 --
103441
103442 COMMENT ON COLUMN mrgundo.mrgundo_type IS 'The data type of the modified column. This could be derived during the undo processing but it is simpler just to store it during the merge.';
103443
103444
103445 --
103446 -- TOC entry 689 (class 1259 OID 146569475)
103447 -- Dependencies: 6579 8
103448 -- Name: msg; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103449 --
103450
103451 CREATE TABLE msg (
103452     msg_id integer DEFAULT nextval(('"msg_msg_id_seq"'::text)::regclass) NOT NULL,
103453     msg_posted timestamp with time zone,
103454     msg_scheduled timestamp with time zone,
103455     msg_text text,
103456     msg_expires timestamp with time zone,
103457     msg_username text
103458 );
103459
103460
103461 ALTER TABLE public.msg OWNER TO admin;
103462
103463 --
103464 -- TOC entry 10005 (class 0 OID 0)
103465 -- Dependencies: 689
103466 -- Name: TABLE msg; Type: COMMENT; Schema: public; Owner: admin
103467 --
103468
103469 COMMENT ON TABLE msg IS 'System Message information';
103470
103471
103472 --
103473 -- TOC entry 690 (class 1259 OID 146569482)
103474 -- Dependencies: 8
103475 -- Name: msg_msg_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103476 --
103477
103478 CREATE SEQUENCE msg_msg_id_seq
103479     START WITH 1
103480     INCREMENT BY 1
103481     NO MINVALUE
103482     MAXVALUE 2147483647
103483     CACHE 1;
103484
103485
103486 ALTER TABLE public.msg_msg_id_seq OWNER TO admin;
103487
103488 --
103489 -- TOC entry 691 (class 1259 OID 146569484)
103490 -- Dependencies: 6580 8
103491 -- Name: msguser; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103492 --
103493
103494 CREATE TABLE msguser (
103495     msguser_id integer DEFAULT nextval(('"msguser_msguser_id_seq"'::text)::regclass) NOT NULL,
103496     msguser_msg_id integer,
103497     msguser_viewed timestamp with time zone,
103498     msguser_username text
103499 );
103500
103501
103502 ALTER TABLE public.msguser OWNER TO admin;
103503
103504 --
103505 -- TOC entry 10008 (class 0 OID 0)
103506 -- Dependencies: 691
103507 -- Name: TABLE msguser; Type: COMMENT; Schema: public; Owner: admin
103508 --
103509
103510 COMMENT ON TABLE msguser IS 'System Message user information';
103511
103512
103513 --
103514 -- TOC entry 692 (class 1259 OID 146569491)
103515 -- Dependencies: 8
103516 -- Name: msguser_msguser_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103517 --
103518
103519 CREATE SEQUENCE msguser_msguser_id_seq
103520     START WITH 1
103521     INCREMENT BY 1
103522     NO MINVALUE
103523     MAXVALUE 2147483647
103524     CACHE 1;
103525
103526
103527 ALTER TABLE public.msguser_msguser_id_seq OWNER TO admin;
103528
103529 --
103530 -- TOC entry 693 (class 1259 OID 146569493)
103531 -- Dependencies: 8
103532 -- Name: nvend_nvend_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103533 --
103534
103535 CREATE SEQUENCE nvend_nvend_id_seq
103536     START WITH 1
103537     INCREMENT BY 1
103538     NO MINVALUE
103539     MAXVALUE 2147483647
103540     CACHE 1;
103541
103542
103543 ALTER TABLE public.nvend_nvend_id_seq OWNER TO admin;
103544
103545 --
103546 -- TOC entry 694 (class 1259 OID 146569495)
103547 -- Dependencies: 6581 6582 6583 8
103548 -- Name: obsolete_tax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103549 --
103550
103551 CREATE TABLE obsolete_tax (
103552     tax_id integer DEFAULT nextval(('"tax_tax_id_seq"'::text)::regclass) NOT NULL,
103553     tax_code text,
103554     tax_descrip text,
103555     tax_ratea numeric(8,4),
103556     tax_sales_accnt_id integer,
103557     tax_freight boolean DEFAULT false NOT NULL,
103558     tax_cumulative boolean DEFAULT false NOT NULL,
103559     tax_rateb numeric(8,4),
103560     tax_salesb_accnt_id integer,
103561     tax_ratec numeric(8,4),
103562     tax_salesc_accnt_id integer
103563 );
103564
103565
103566 ALTER TABLE public.obsolete_tax OWNER TO admin;
103567
103568 --
103569 -- TOC entry 10012 (class 0 OID 0)
103570 -- Dependencies: 694
103571 -- Name: TABLE obsolete_tax; Type: COMMENT; Schema: public; Owner: admin
103572 --
103573
103574 COMMENT ON TABLE obsolete_tax IS 'Tax information. Obsolete table structure.';
103575
103576
103577 --
103578 -- TOC entry 10013 (class 0 OID 0)
103579 -- Dependencies: 694
103580 -- Name: COLUMN obsolete_tax.tax_freight; Type: COMMENT; Schema: public; Owner: admin
103581 --
103582
103583 COMMENT ON COLUMN obsolete_tax.tax_freight IS 'Deprecated in 2.1 and moved to taxsel table where taxtype is the system defined Freight.';
103584
103585
103586 --
103587 -- TOC entry 695 (class 1259 OID 146569504)
103588 -- Dependencies: 231 8
103589 -- Name: ophead_ophead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103590 --
103591
103592 CREATE SEQUENCE ophead_ophead_id_seq
103593     START WITH 1
103594     INCREMENT BY 1
103595     NO MINVALUE
103596     NO MAXVALUE
103597     CACHE 1;
103598
103599
103600 ALTER TABLE public.ophead_ophead_id_seq OWNER TO admin;
103601
103602 --
103603 -- TOC entry 10015 (class 0 OID 0)
103604 -- Dependencies: 695
103605 -- Name: ophead_ophead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103606 --
103607
103608 ALTER SEQUENCE ophead_ophead_id_seq OWNED BY ophead.ophead_id;
103609
103610
103611 --
103612 -- TOC entry 696 (class 1259 OID 146569506)
103613 -- Dependencies: 6585 8
103614 -- Name: opsource; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103615 --
103616
103617 CREATE TABLE opsource (
103618     opsource_id integer NOT NULL,
103619     opsource_name text NOT NULL,
103620     opsource_descrip text,
103621     CONSTRAINT opsource_opsource_name_check CHECK ((opsource_name <> ''::text))
103622 );
103623
103624
103625 ALTER TABLE public.opsource OWNER TO admin;
103626
103627 --
103628 -- TOC entry 10017 (class 0 OID 0)
103629 -- Dependencies: 696
103630 -- Name: TABLE opsource; Type: COMMENT; Schema: public; Owner: admin
103631 --
103632
103633 COMMENT ON TABLE opsource IS 'Opportunity Lead Source values.';
103634
103635
103636 --
103637 -- TOC entry 697 (class 1259 OID 146569513)
103638 -- Dependencies: 696 8
103639 -- Name: opsource_opsource_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103640 --
103641
103642 CREATE SEQUENCE opsource_opsource_id_seq
103643     START WITH 1
103644     INCREMENT BY 1
103645     NO MINVALUE
103646     NO MAXVALUE
103647     CACHE 1;
103648
103649
103650 ALTER TABLE public.opsource_opsource_id_seq OWNER TO admin;
103651
103652 --
103653 -- TOC entry 10019 (class 0 OID 0)
103654 -- Dependencies: 697
103655 -- Name: opsource_opsource_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103656 --
103657
103658 ALTER SEQUENCE opsource_opsource_id_seq OWNED BY opsource.opsource_id;
103659
103660
103661 --
103662 -- TOC entry 698 (class 1259 OID 146569515)
103663 -- Dependencies: 6587 6588 6589 8
103664 -- Name: opstage; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103665 --
103666
103667 CREATE TABLE opstage (
103668     opstage_id integer NOT NULL,
103669     opstage_name text NOT NULL,
103670     opstage_descrip text,
103671     opstage_order integer DEFAULT 0 NOT NULL,
103672     opstage_opinactive boolean DEFAULT false,
103673     CONSTRAINT opstage_opstage_name_check CHECK ((opstage_name <> ''::text))
103674 );
103675
103676
103677 ALTER TABLE public.opstage OWNER TO admin;
103678
103679 --
103680 -- TOC entry 10021 (class 0 OID 0)
103681 -- Dependencies: 698
103682 -- Name: TABLE opstage; Type: COMMENT; Schema: public; Owner: admin
103683 --
103684
103685 COMMENT ON TABLE opstage IS 'Opportunity stage values.';
103686
103687
103688 --
103689 -- TOC entry 699 (class 1259 OID 146569524)
103690 -- Dependencies: 698 8
103691 -- Name: opstage_opstage_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103692 --
103693
103694 CREATE SEQUENCE opstage_opstage_id_seq
103695     START WITH 1
103696     INCREMENT BY 1
103697     NO MINVALUE
103698     NO MAXVALUE
103699     CACHE 1;
103700
103701
103702 ALTER TABLE public.opstage_opstage_id_seq OWNER TO admin;
103703
103704 --
103705 -- TOC entry 10023 (class 0 OID 0)
103706 -- Dependencies: 699
103707 -- Name: opstage_opstage_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103708 --
103709
103710 ALTER SEQUENCE opstage_opstage_id_seq OWNED BY opstage.opstage_id;
103711
103712
103713 --
103714 -- TOC entry 700 (class 1259 OID 146569526)
103715 -- Dependencies: 6591 8
103716 -- Name: optype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103717 --
103718
103719 CREATE TABLE optype (
103720     optype_id integer NOT NULL,
103721     optype_name text NOT NULL,
103722     optype_descrip text,
103723     CONSTRAINT optype_optype_name_check CHECK ((optype_name <> ''::text))
103724 );
103725
103726
103727 ALTER TABLE public.optype OWNER TO admin;
103728
103729 --
103730 -- TOC entry 10025 (class 0 OID 0)
103731 -- Dependencies: 700
103732 -- Name: TABLE optype; Type: COMMENT; Schema: public; Owner: admin
103733 --
103734
103735 COMMENT ON TABLE optype IS 'Opportunity Type values.';
103736
103737
103738 --
103739 -- TOC entry 701 (class 1259 OID 146569533)
103740 -- Dependencies: 700 8
103741 -- Name: optype_optype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103742 --
103743
103744 CREATE SEQUENCE optype_optype_id_seq
103745     START WITH 1
103746     INCREMENT BY 1
103747     NO MINVALUE
103748     NO MAXVALUE
103749     CACHE 1;
103750
103751
103752 ALTER TABLE public.optype_optype_id_seq OWNER TO admin;
103753
103754 --
103755 -- TOC entry 10027 (class 0 OID 0)
103756 -- Dependencies: 701
103757 -- Name: optype_optype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103758 --
103759
103760 ALTER SEQUENCE optype_optype_id_seq OWNED BY optype.optype_id;
103761
103762
103763 --
103764 -- TOC entry 702 (class 1259 OID 146569535)
103765 -- Dependencies: 8584 8
103766 -- Name: orderhead; Type: VIEW; Schema: public; Owner: admin
103767 --
103768
103769 CREATE VIEW orderhead AS
103770     SELECT DISTINCT data.orderhead_id, data.orderhead_type, data.orderhead_number, data.orderhead_status, data.orderhead_orderdate, data.orderhead_linecount, data.orderhead_from_id, data.orderhead_from, data.orderhead_to_id, data.orderhead_to, data.orderhead_curr_id, data.orderhead_agent_username, data.orderhead_shipvia FROM (SELECT pohead.pohead_id AS orderhead_id, 'PO'::text AS orderhead_type, pohead.pohead_number AS orderhead_number, pohead.pohead_status AS orderhead_status, pohead.pohead_orderdate AS orderhead_orderdate, (SELECT count(*) AS count FROM poitem WHERE (poitem.poitem_pohead_id = pohead.pohead_id)) AS orderhead_linecount, pohead.pohead_vend_id AS orderhead_from_id, vendinfo.vend_name AS orderhead_from, NULL::integer AS orderhead_to_id, ''::text AS orderhead_to, pohead.pohead_curr_id AS orderhead_curr_id, pohead.pohead_agent_username AS orderhead_agent_username, pohead.pohead_shipvia AS orderhead_shipvia FROM (pohead LEFT JOIN vendinfo ON ((pohead.pohead_vend_id = vendinfo.vend_id))) UNION ALL SELECT cohead.cohead_id AS orderhead_id, 'SO'::text AS orderhead_type, cohead.cohead_number AS orderhead_number, cohead.cohead_status AS orderhead_status, cohead.cohead_orderdate AS orderhead_orderdate, (SELECT count(*) AS count FROM coitem WHERE (coitem.coitem_cohead_id = cohead.cohead_id)) AS orderhead_linecount, NULL::integer AS orderhead_from_id, ''::text AS orderhead_from, cohead.cohead_cust_id AS orderhead_to_id, CASE WHEN (length(cohead.cohead_shiptoname) > 0) THEN cohead.cohead_shiptoname ELSE cohead.cohead_billtoname END AS orderhead_to, cohead.cohead_curr_id AS orderhead_curr_id, ''::text AS orderhead_agent_username, cohead.cohead_shipvia AS orderhead_shipvia FROM cohead) data;
103771
103772
103773 ALTER TABLE public.orderhead OWNER TO admin;
103774
103775 --
103776 -- TOC entry 10029 (class 0 OID 0)
103777 -- Dependencies: 702
103778 -- Name: VIEW orderhead; Type: COMMENT; Schema: public; Owner: admin
103779 --
103780
103781 COMMENT ON VIEW orderhead IS 'Union of all orders for use by widgets and stored procedures which process multiple types of order';
103782
103783
103784 --
103785 -- TOC entry 703 (class 1259 OID 146569540)
103786 -- Dependencies: 8585 8
103787 -- Name: orderitem; Type: VIEW; Schema: public; Owner: admin
103788 --
103789
103790 CREATE VIEW orderitem AS
103791     (SELECT poitem.poitem_id AS orderitem_id, 'PO'::text AS orderitem_orderhead_type, poitem.poitem_pohead_id AS orderitem_orderhead_id, poitem.poitem_linenumber AS orderitem_linenumber, poitem.poitem_status AS orderitem_status, poitem.poitem_itemsite_id AS orderitem_itemsite_id, poitem.poitem_duedate AS orderitem_scheddate, poitem.poitem_qty_ordered AS orderitem_qty_ordered, poitem.poitem_qty_returned AS orderitem_qty_shipped, poitem.poitem_qty_received AS orderitem_qty_received, uom.uom_id AS orderitem_qty_uom_id, poitem.poitem_invvenduomratio AS orderitem_qty_invuomratio, poitem.poitem_unitprice AS orderitem_unitcost, pohead.pohead_curr_id AS orderitem_unitcost_curr_id, poitem.poitem_freight AS orderitem_freight, poitem.poitem_freight_received AS orderitem_freight_received, pohead.pohead_curr_id AS orderitem_freight_curr_id FROM ((poitem LEFT JOIN pohead ON ((poitem.poitem_pohead_id = pohead.pohead_id))) LEFT JOIN uom ON ((uom.uom_name = poitem.poitem_vend_uom))) UNION ALL SELECT coitem.coitem_id AS orderitem_id, 'SO'::text AS orderitem_orderhead_type, coitem.coitem_cohead_id AS orderitem_orderhead_id, coitem.coitem_linenumber AS orderitem_linenumber, coitem.coitem_status AS orderitem_status, coitem.coitem_itemsite_id AS orderitem_itemsite_id, coitem.coitem_scheddate AS orderitem_scheddate, coitem.coitem_qtyord AS orderitem_qty_ordered, coitem.coitem_qtyshipped AS orderitem_qty_shipped, coitem.coitem_qtyreturned AS orderitem_qty_received, coitem.coitem_qty_uom_id AS orderitem_qty_uom_id, coitem.coitem_qty_invuomratio AS orderitem_qty_invuomratio, coitem.coitem_unitcost AS orderitem_unitcost, basecurrid() AS orderitem_unitcost_curr_id, NULL::numeric AS orderitem_freight, NULL::numeric AS orderitem_freight_received, basecurrid() AS orderitem_freight_curr_id FROM coitem) UNION ALL SELECT quitem.quitem_id AS orderitem_id, 'QU'::text AS orderitem_orderhead_type, quitem.quitem_quhead_id AS orderitem_orderhead_id, quitem.quitem_linenumber AS orderitem_linenumber, 'O'::bpchar AS orderitem_status, quitem.quitem_itemsite_id AS orderitem_itemsite_id, quitem.quitem_scheddate AS orderitem_scheddate, quitem.quitem_qtyord AS orderitem_qty_ordered, 0 AS orderitem_qty_shipped, 0 AS orderitem_qty_received, quitem.quitem_qty_uom_id AS orderitem_qty_uom_id, quitem.quitem_qty_invuomratio AS orderitem_qty_invuomratio, quitem.quitem_unitcost AS orderitem_unitcost, basecurrid() AS orderitem_unitcost_curr_id, NULL::numeric AS orderitem_freight, NULL::numeric AS orderitem_freight_received, basecurrid() AS orderitem_freight_curr_id FROM quitem;
103792
103793
103794 ALTER TABLE public.orderitem OWNER TO admin;
103795
103796 --
103797 -- TOC entry 10031 (class 0 OID 0)
103798 -- Dependencies: 703
103799 -- Name: VIEW orderitem; Type: COMMENT; Schema: public; Owner: admin
103800 --
103801
103802 COMMENT ON VIEW orderitem IS 'Union of all order line items for use by widgets and stored procedures which process multiple types of order';
103803
103804
103805 --
103806 -- TOC entry 704 (class 1259 OID 146569545)
103807 -- Dependencies: 6592 6593 8 2700
103808 -- Name: orderseq; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103809 --
103810
103811 CREATE TABLE orderseq (
103812     orderseq_id integer DEFAULT nextval(('orderseq_orderseq_id_seq'::text)::regclass) NOT NULL,
103813     orderseq_name text NOT NULL,
103814     orderseq_number integer,
103815     orderseq_table text,
103816     orderseq_numcol text,
103817     orderseq_seqiss seqiss[],
103818     CONSTRAINT orderseq_orderseq_name_check CHECK ((orderseq_name <> ''::text))
103819 );
103820
103821
103822 ALTER TABLE public.orderseq OWNER TO admin;
103823
103824 --
103825 -- TOC entry 10033 (class 0 OID 0)
103826 -- Dependencies: 704
103827 -- Name: TABLE orderseq; Type: COMMENT; Schema: public; Owner: admin
103828 --
103829
103830 COMMENT ON TABLE orderseq IS 'Configuration information for common numbering sequences';
103831
103832
103833 --
103834 -- TOC entry 705 (class 1259 OID 146569553)
103835 -- Dependencies: 8
103836 -- Name: orderseq_orderseq_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103837 --
103838
103839 CREATE SEQUENCE orderseq_orderseq_id_seq
103840     START WITH 1
103841     INCREMENT BY 1
103842     NO MINVALUE
103843     MAXVALUE 2147483647
103844     CACHE 1;
103845
103846
103847 ALTER TABLE public.orderseq_orderseq_id_seq OWNER TO admin;
103848
103849 --
103850 -- TOC entry 706 (class 1259 OID 146569555)
103851 -- Dependencies: 6595 6596 8
103852 -- Name: pack; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103853 --
103854
103855 CREATE TABLE pack (
103856     pack_id integer NOT NULL,
103857     pack_head_id integer NOT NULL,
103858     pack_head_type text NOT NULL,
103859     pack_shiphead_id integer,
103860     pack_printed boolean DEFAULT false NOT NULL,
103861     CONSTRAINT pack_pack_head_type_check CHECK (((pack_head_type = 'SO'::text) OR (pack_head_type = 'TO'::text)))
103862 );
103863
103864
103865 ALTER TABLE public.pack OWNER TO admin;
103866
103867 --
103868 -- TOC entry 10036 (class 0 OID 0)
103869 -- Dependencies: 706
103870 -- Name: TABLE pack; Type: COMMENT; Schema: public; Owner: admin
103871 --
103872
103873 COMMENT ON TABLE pack IS 'Temporary table for storing information about Orders added to the Packing List Batch';
103874
103875
103876 --
103877 -- TOC entry 707 (class 1259 OID 146569563)
103878 -- Dependencies: 706 8
103879 -- Name: pack_pack_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103880 --
103881
103882 CREATE SEQUENCE pack_pack_id_seq
103883     START WITH 1
103884     INCREMENT BY 1
103885     NO MINVALUE
103886     NO MAXVALUE
103887     CACHE 1;
103888
103889
103890 ALTER TABLE public.pack_pack_id_seq OWNER TO admin;
103891
103892 --
103893 -- TOC entry 10038 (class 0 OID 0)
103894 -- Dependencies: 707
103895 -- Name: pack_pack_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103896 --
103897
103898 ALTER SEQUENCE pack_pack_id_seq OWNED BY pack.pack_id;
103899
103900
103901 --
103902 -- TOC entry 708 (class 1259 OID 146569565)
103903 -- Dependencies: 6597 6598 8
103904 -- Name: payaropen; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103905 --
103906
103907 CREATE TABLE payaropen (
103908     payaropen_ccpay_id integer NOT NULL,
103909     payaropen_aropen_id integer NOT NULL,
103910     payaropen_amount numeric(20,2) DEFAULT 0.00 NOT NULL,
103911     payaropen_curr_id integer DEFAULT basecurrid()
103912 );
103913
103914
103915 ALTER TABLE public.payaropen OWNER TO admin;
103916
103917 --
103918 -- TOC entry 10040 (class 0 OID 0)
103919 -- Dependencies: 708
103920 -- Name: TABLE payaropen; Type: COMMENT; Schema: public; Owner: admin
103921 --
103922
103923 COMMENT ON TABLE payaropen IS 'Credit Card payment to credit memo join table';
103924
103925
103926 --
103927 -- TOC entry 709 (class 1259 OID 146569570)
103928 -- Dependencies: 6599 6600 8
103929 -- Name: payco; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103930 --
103931
103932 CREATE TABLE payco (
103933     payco_ccpay_id integer NOT NULL,
103934     payco_cohead_id integer NOT NULL,
103935     payco_amount numeric(20,2) DEFAULT 0.00 NOT NULL,
103936     payco_curr_id integer DEFAULT basecurrid()
103937 );
103938
103939
103940 ALTER TABLE public.payco OWNER TO admin;
103941
103942 --
103943 -- TOC entry 10042 (class 0 OID 0)
103944 -- Dependencies: 709
103945 -- Name: TABLE payco; Type: COMMENT; Schema: public; Owner: admin
103946 --
103947
103948 COMMENT ON TABLE payco IS 'Credit Card payment to sales order join table';
103949
103950
103951 --
103952 -- TOC entry 710 (class 1259 OID 146569575)
103953 -- Dependencies: 264 8
103954 -- Name: period_period_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
103955 --
103956
103957 CREATE SEQUENCE period_period_id_seq
103958     START WITH 1
103959     INCREMENT BY 1
103960     NO MINVALUE
103961     NO MAXVALUE
103962     CACHE 1;
103963
103964
103965 ALTER TABLE public.period_period_id_seq OWNER TO admin;
103966
103967 --
103968 -- TOC entry 10044 (class 0 OID 0)
103969 -- Dependencies: 710
103970 -- Name: period_period_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
103971 --
103972
103973 ALTER SEQUENCE period_period_id_seq OWNED BY period.period_id;
103974
103975
103976 --
103977 -- TOC entry 711 (class 1259 OID 146569577)
103978 -- Dependencies: 8
103979 -- Name: pkgdep; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
103980 --
103981
103982 CREATE TABLE pkgdep (
103983     pkgdep_id integer NOT NULL,
103984     pkgdep_pkghead_id integer NOT NULL,
103985     pkgdep_parent_pkghead_id integer NOT NULL
103986 );
103987
103988
103989 ALTER TABLE public.pkgdep OWNER TO admin;
103990
103991 --
103992 -- TOC entry 10046 (class 0 OID 0)
103993 -- Dependencies: 711
103994 -- Name: TABLE pkgdep; Type: COMMENT; Schema: public; Owner: admin
103995 --
103996
103997 COMMENT ON TABLE pkgdep IS 'Package Dependencies list describing which packages are dependent on which other packages.';
103998
103999
104000 --
104001 -- TOC entry 10047 (class 0 OID 0)
104002 -- Dependencies: 711
104003 -- Name: COLUMN pkgdep.pkgdep_pkghead_id; Type: COMMENT; Schema: public; Owner: admin
104004 --
104005
104006 COMMENT ON COLUMN pkgdep.pkgdep_pkghead_id IS 'This is the internal ID of a package which requires at least one other package to be installed first to operate successfully';
104007
104008
104009 --
104010 -- TOC entry 10048 (class 0 OID 0)
104011 -- Dependencies: 711
104012 -- Name: COLUMN pkgdep.pkgdep_parent_pkghead_id; Type: COMMENT; Schema: public; Owner: admin
104013 --
104014
104015 COMMENT ON COLUMN pkgdep.pkgdep_parent_pkghead_id IS 'This is the internal ID of a package which must be installed for the package pointed to by pkgdep_pkghead_id to operate successfully.';
104016
104017
104018 --
104019 -- TOC entry 712 (class 1259 OID 146569580)
104020 -- Dependencies: 711 8
104021 -- Name: pkgdep_pkgdep_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104022 --
104023
104024 CREATE SEQUENCE pkgdep_pkgdep_id_seq
104025     START WITH 1
104026     INCREMENT BY 1
104027     NO MINVALUE
104028     NO MAXVALUE
104029     CACHE 1;
104030
104031
104032 ALTER TABLE public.pkgdep_pkgdep_id_seq OWNER TO admin;
104033
104034 --
104035 -- TOC entry 10050 (class 0 OID 0)
104036 -- Dependencies: 712
104037 -- Name: pkgdep_pkgdep_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104038 --
104039
104040 ALTER SEQUENCE pkgdep_pkgdep_id_seq OWNED BY pkgdep.pkgdep_id;
104041
104042
104043 --
104044 -- TOC entry 713 (class 1259 OID 146569582)
104045 -- Dependencies: 6603 6604 8
104046 -- Name: pkghead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104047 --
104048
104049 CREATE TABLE pkghead (
104050     pkghead_id integer NOT NULL,
104051     pkghead_name text NOT NULL,
104052     pkghead_descrip text,
104053     pkghead_version text NOT NULL,
104054     pkghead_developer text NOT NULL,
104055     pkghead_notes text,
104056     pkghead_created timestamp with time zone,
104057     pkghead_updated timestamp with time zone,
104058     pkghead_indev boolean DEFAULT false NOT NULL,
104059     CONSTRAINT pkghead_pkghead_name_check CHECK ((pkghead_name <> ''::text))
104060 );
104061
104062
104063 ALTER TABLE public.pkghead OWNER TO admin;
104064
104065 --
104066 -- TOC entry 10052 (class 0 OID 0)
104067 -- Dependencies: 713
104068 -- Name: TABLE pkghead; Type: COMMENT; Schema: public; Owner: admin
104069 --
104070
104071 COMMENT ON TABLE pkghead IS 'Information about non-core Packages added to the database';
104072
104073
104074 --
104075 -- TOC entry 10053 (class 0 OID 0)
104076 -- Dependencies: 713
104077 -- Name: COLUMN pkghead.pkghead_indev; Type: COMMENT; Schema: public; Owner: admin
104078 --
104079
104080 COMMENT ON COLUMN pkghead.pkghead_indev IS 'Flag indicating whether the contents of this package may be modified in-place - this package is /in dev/elopment.';
104081
104082
104083 --
104084 -- TOC entry 714 (class 1259 OID 146569590)
104085 -- Dependencies: 713 8
104086 -- Name: pkghead_pkghead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104087 --
104088
104089 CREATE SEQUENCE pkghead_pkghead_id_seq
104090     START WITH 1
104091     INCREMENT BY 1
104092     NO MINVALUE
104093     NO MAXVALUE
104094     CACHE 1;
104095
104096
104097 ALTER TABLE public.pkghead_pkghead_id_seq OWNER TO admin;
104098
104099 --
104100 -- TOC entry 10055 (class 0 OID 0)
104101 -- Dependencies: 714
104102 -- Name: pkghead_pkghead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104103 --
104104
104105 ALTER SEQUENCE pkghead_pkghead_id_seq OWNED BY pkghead.pkghead_id;
104106
104107
104108 --
104109 -- TOC entry 715 (class 1259 OID 146569592)
104110 -- Dependencies: 6606 8
104111 -- Name: pkgitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104112 --
104113
104114 CREATE TABLE pkgitem (
104115     pkgitem_id integer NOT NULL,
104116     pkgitem_pkghead_id integer,
104117     pkgitem_type text,
104118     pkgitem_item_id integer NOT NULL,
104119     pkgitem_name text NOT NULL,
104120     pkgitem_descrip text,
104121     CONSTRAINT pkgitem_pkgitem_type_check CHECK (((((((((((((pkgitem_type = 'C'::text) OR (pkgitem_type = 'D'::text)) OR (pkgitem_type = 'F'::text)) OR (pkgitem_type = 'G'::text)) OR (pkgitem_type = 'I'::text)) OR (pkgitem_type = 'M'::text)) OR (pkgitem_type = 'P'::text)) OR (pkgitem_type = 'R'::text)) OR (pkgitem_type = 'S'::text)) OR (pkgitem_type = 'T'::text)) OR (pkgitem_type = 'U'::text)) OR (pkgitem_type = 'V'::text)))
104122 );
104123
104124
104125 ALTER TABLE public.pkgitem OWNER TO admin;
104126
104127 --
104128 -- TOC entry 10057 (class 0 OID 0)
104129 -- Dependencies: 715
104130 -- Name: TABLE pkgitem; Type: COMMENT; Schema: public; Owner: admin
104131 --
104132
104133 COMMENT ON TABLE pkgitem IS 'Deprecated - the pkgitem table is no longer used to track package contents. It has been replaced by direct queries to the database schema and component tables. This table will be removed when all users have switched to Updater 2.2.0 or later.';
104134
104135
104136 --
104137 -- TOC entry 716 (class 1259 OID 146569599)
104138 -- Dependencies: 715 8
104139 -- Name: pkgitem_pkgitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104140 --
104141
104142 CREATE SEQUENCE pkgitem_pkgitem_id_seq
104143     START WITH 1
104144     INCREMENT BY 1
104145     NO MINVALUE
104146     NO MAXVALUE
104147     CACHE 1;
104148
104149
104150 ALTER TABLE public.pkgitem_pkgitem_id_seq OWNER TO admin;
104151
104152 --
104153 -- TOC entry 10059 (class 0 OID 0)
104154 -- Dependencies: 716
104155 -- Name: pkgitem_pkgitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104156 --
104157
104158 ALTER SEQUENCE pkgitem_pkgitem_id_seq OWNED BY pkgitem.pkgitem_id;
104159
104160
104161 --
104162 -- TOC entry 717 (class 1259 OID 146569601)
104163 -- Dependencies: 8
104164 -- Name: plancode_plancode_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104165 --
104166
104167 CREATE SEQUENCE plancode_plancode_id_seq
104168     START WITH 1
104169     INCREMENT BY 1
104170     NO MINVALUE
104171     NO MAXVALUE
104172     CACHE 1;
104173
104174
104175 ALTER TABLE public.plancode_plancode_id_seq OWNER TO admin;
104176
104177 --
104178 -- TOC entry 718 (class 1259 OID 146569603)
104179 -- Dependencies: 8
104180 -- Name: planord_planord_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104181 --
104182
104183 CREATE SEQUENCE planord_planord_id_seq
104184     START WITH 1
104185     INCREMENT BY 1
104186     NO MINVALUE
104187     MAXVALUE 2147483647
104188     CACHE 1;
104189
104190
104191 ALTER TABLE public.planord_planord_id_seq OWNER TO admin;
104192
104193 --
104194 -- TOC entry 719 (class 1259 OID 146569605)
104195 -- Dependencies: 8
104196 -- Name: pohead_pohead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104197 --
104198
104199 CREATE SEQUENCE pohead_pohead_id_seq
104200     START WITH 1
104201     INCREMENT BY 1
104202     NO MINVALUE
104203     MAXVALUE 2147483647
104204     CACHE 1;
104205
104206
104207 ALTER TABLE public.pohead_pohead_id_seq OWNER TO admin;
104208
104209 --
104210 -- TOC entry 720 (class 1259 OID 146569607)
104211 -- Dependencies: 8
104212 -- Name: poitem_poitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104213 --
104214
104215 CREATE SEQUENCE poitem_poitem_id_seq
104216     START WITH 1
104217     INCREMENT BY 1
104218     NO MINVALUE
104219     MAXVALUE 2147483647
104220     CACHE 1;
104221
104222
104223 ALTER TABLE public.poitem_poitem_id_seq OWNER TO admin;
104224
104225 --
104226 -- TOC entry 721 (class 1259 OID 146569609)
104227 -- Dependencies: 6607 6608 6609 6611 8
104228 -- Name: recv; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104229 --
104230
104231 CREATE TABLE recv (
104232     recv_id integer NOT NULL,
104233     recv_order_type text NOT NULL,
104234     recv_order_number text NOT NULL,
104235     recv_orderitem_id integer NOT NULL,
104236     recv_agent_username text,
104237     recv_itemsite_id integer,
104238     recv_vend_id integer,
104239     recv_vend_item_number text,
104240     recv_vend_item_descrip text,
104241     recv_vend_uom text,
104242     recv_purchcost numeric(16,6),
104243     recv_purchcost_curr_id integer,
104244     recv_duedate date,
104245     recv_qty numeric(18,6),
104246     recv_recvcost numeric(16,6),
104247     recv_recvcost_curr_id integer,
104248     recv_freight numeric(16,4),
104249     recv_freight_curr_id integer,
104250     recv_date timestamp with time zone,
104251     recv_value numeric(18,6),
104252     recv_posted boolean DEFAULT false NOT NULL,
104253     recv_invoiced boolean DEFAULT false NOT NULL,
104254     recv_vohead_id integer,
104255     recv_voitem_id integer,
104256     recv_trans_usr_name text DEFAULT geteffectivextuser() NOT NULL,
104257     recv_notes text,
104258     recv_gldistdate date,
104259     recv_splitfrom_id integer,
104260     recv_rlsd_duedate date,
104261     CONSTRAINT recv_recv_order_type_check CHECK ((((recv_order_type = 'PO'::text) OR (recv_order_type = 'RA'::text)) OR (recv_order_type = 'TO'::text)))
104262 );
104263
104264
104265 ALTER TABLE public.recv OWNER TO admin;
104266
104267 --
104268 -- TOC entry 10065 (class 0 OID 0)
104269 -- Dependencies: 721
104270 -- Name: TABLE recv; Type: COMMENT; Schema: public; Owner: admin
104271 --
104272
104273 COMMENT ON TABLE recv IS 'Information about Received Orders.';
104274
104275
104276 --
104277 -- TOC entry 722 (class 1259 OID 146569619)
104278 -- Dependencies: 8586 8
104279 -- Name: porecv; Type: VIEW; Schema: public; Owner: admin
104280 --
104281
104282 CREATE VIEW porecv AS
104283     SELECT recv.recv_id AS porecv_id, recv.recv_date AS porecv_date, recv.recv_rlsd_duedate AS porecv_rlsd_duedate, pohead.pohead_orderdate AS porecv_orderdate, pohead.pohead_released AS porecv_released, recv.recv_order_number AS porecv_ponumber, recv.recv_itemsite_id AS porecv_itemsite_id, recv.recv_vend_id AS porecv_vend_id, item.item_number AS porecv_item_number, recv.recv_vend_item_number AS porecv_vend_item_number, COALESCE(item.item_descrip1, recv.recv_vend_item_descrip) AS porecv_vend_item_descrip, recv.recv_vend_uom AS porecv_vend_uom, recv.recv_qty AS porecv_qty, recv.recv_posted AS porecv_posted, recv.recv_invoiced AS porecv_invoiced, (pg_user.usesysid)::integer AS porecv_trans_usr_id, recv.recv_orderitem_id AS porecv_poitem_id, NULL::integer AS porecv_linenumber, recv.recv_purchcost AS porecv_purchcost, recv.recv_vohead_id AS porecv_vohead_id, recv.recv_recvcost AS porecv_recvcost, recv.recv_duedate AS porecv_duedate, recv.recv_agent_username AS porecv_agent_username, recv.recv_notes AS porecv_notes, recv.recv_freight AS porecv_freight, recv.recv_freight_curr_id AS porecv_curr_id, recv.recv_gldistdate AS porecv_gldistdate, recv.recv_voitem_id AS porecv_voitem_id, recv.recv_value AS porecv_value FROM ((((recv LEFT JOIN pg_user ON ((recv.recv_trans_usr_name = (pg_user.usename)::text))) LEFT JOIN pohead ON ((recv.recv_order_number = pohead.pohead_number))) LEFT JOIN itemsite ON ((recv.recv_itemsite_id = itemsite.itemsite_id))) LEFT JOIN item ON ((itemsite.itemsite_item_id = item.item_id))) WHERE (recv.recv_order_type = 'PO'::text);
104284
104285
104286 ALTER TABLE public.porecv OWNER TO admin;
104287
104288 --
104289 -- TOC entry 723 (class 1259 OID 146569624)
104290 -- Dependencies: 8
104291 -- Name: porecv_porecv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104292 --
104293
104294 CREATE SEQUENCE porecv_porecv_id_seq
104295     START WITH 1
104296     INCREMENT BY 1
104297     NO MINVALUE
104298     MAXVALUE 2147483647
104299     CACHE 1;
104300
104301
104302 ALTER TABLE public.porecv_porecv_id_seq OWNER TO admin;
104303
104304 --
104305 -- TOC entry 724 (class 1259 OID 146569626)
104306 -- Dependencies: 6612 8
104307 -- Name: poreject; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104308 --
104309
104310 CREATE TABLE poreject (
104311     poreject_id integer DEFAULT nextval(('"poreject_poreject_id_seq"'::text)::regclass) NOT NULL,
104312     poreject_date timestamp with time zone,
104313     poreject_ponumber text,
104314     poreject_itemsite_id integer,
104315     poreject_vend_id integer,
104316     poreject_vend_item_number text,
104317     poreject_vend_item_descrip text,
104318     poreject_vend_uom text,
104319     poreject_qty numeric(18,6),
104320     poreject_posted boolean,
104321     poreject_rjctcode_id integer,
104322     poreject_poitem_id integer,
104323     poreject_invoiced boolean,
104324     poreject_vohead_id integer,
104325     poreject_agent_username text,
104326     poreject_voitem_id integer,
104327     poreject_value numeric(18,6),
104328     poreject_trans_username text,
104329     poreject_recv_id integer
104330 );
104331
104332
104333 ALTER TABLE public.poreject OWNER TO admin;
104334
104335 --
104336 -- TOC entry 10069 (class 0 OID 0)
104337 -- Dependencies: 724
104338 -- Name: TABLE poreject; Type: COMMENT; Schema: public; Owner: admin
104339 --
104340
104341 COMMENT ON TABLE poreject IS 'The poreject table describes Purchase Order Items that were returned to Vendors.';
104342
104343
104344 --
104345 -- TOC entry 10070 (class 0 OID 0)
104346 -- Dependencies: 724
104347 -- Name: COLUMN poreject.poreject_id; Type: COMMENT; Schema: public; Owner: admin
104348 --
104349
104350 COMMENT ON COLUMN poreject.poreject_id IS 'This is the internal id of this poreject record';
104351
104352
104353 --
104354 -- TOC entry 10071 (class 0 OID 0)
104355 -- Dependencies: 724
104356 -- Name: COLUMN poreject.poreject_date; Type: COMMENT; Schema: public; Owner: admin
104357 --
104358
104359 COMMENT ON COLUMN poreject.poreject_date IS 'This is the date and time the return was entered into the database';
104360
104361
104362 --
104363 -- TOC entry 10072 (class 0 OID 0)
104364 -- Dependencies: 724
104365 -- Name: COLUMN poreject.poreject_ponumber; Type: COMMENT; Schema: public; Owner: admin
104366 --
104367
104368 COMMENT ON COLUMN poreject.poreject_ponumber IS 'This is the number of the original Purchase Order of this item';
104369
104370
104371 --
104372 -- TOC entry 10073 (class 0 OID 0)
104373 -- Dependencies: 724
104374 -- Name: COLUMN poreject.poreject_itemsite_id; Type: COMMENT; Schema: public; Owner: admin
104375 --
104376
104377 COMMENT ON COLUMN poreject.poreject_itemsite_id IS 'This is the Item Site into which the item had been received';
104378
104379
104380 --
104381 -- TOC entry 10074 (class 0 OID 0)
104382 -- Dependencies: 724
104383 -- Name: COLUMN poreject.poreject_vend_id; Type: COMMENT; Schema: public; Owner: admin
104384 --
104385
104386 COMMENT ON COLUMN poreject.poreject_vend_id IS 'This is the Vendor from which the item had been purchased';
104387
104388
104389 --
104390 -- TOC entry 10075 (class 0 OID 0)
104391 -- Dependencies: 724
104392 -- Name: COLUMN poreject.poreject_vend_item_number; Type: COMMENT; Schema: public; Owner: admin
104393 --
104394
104395 COMMENT ON COLUMN poreject.poreject_vend_item_number IS 'This is the Vendor''s item number for this item';
104396
104397
104398 --
104399 -- TOC entry 10076 (class 0 OID 0)
104400 -- Dependencies: 724
104401 -- Name: COLUMN poreject.poreject_vend_item_descrip; Type: COMMENT; Schema: public; Owner: admin
104402 --
104403
104404 COMMENT ON COLUMN poreject.poreject_vend_item_descrip IS 'This is the Vendor''s description of this item';
104405
104406
104407 --
104408 -- TOC entry 10077 (class 0 OID 0)
104409 -- Dependencies: 724
104410 -- Name: COLUMN poreject.poreject_vend_uom; Type: COMMENT; Schema: public; Owner: admin
104411 --
104412
104413 COMMENT ON COLUMN poreject.poreject_vend_uom IS 'This is the Unit of Measure in which the Vendor sold this item';
104414
104415
104416 --
104417 -- TOC entry 10078 (class 0 OID 0)
104418 -- Dependencies: 724
104419 -- Name: COLUMN poreject.poreject_qty; Type: COMMENT; Schema: public; Owner: admin
104420 --
104421
104422 COMMENT ON COLUMN poreject.poreject_qty IS 'This is the quantity of the item that was returned';
104423
104424
104425 --
104426 -- TOC entry 10079 (class 0 OID 0)
104427 -- Dependencies: 724
104428 -- Name: COLUMN poreject.poreject_posted; Type: COMMENT; Schema: public; Owner: admin
104429 --
104430
104431 COMMENT ON COLUMN poreject.poreject_posted IS 'This indicates whether or not the return has been recorded in the General Ledger, Inventory History, and Purchase Order Item';
104432
104433
104434 --
104435 -- TOC entry 10080 (class 0 OID 0)
104436 -- Dependencies: 724
104437 -- Name: COLUMN poreject.poreject_rjctcode_id; Type: COMMENT; Schema: public; Owner: admin
104438 --
104439
104440 COMMENT ON COLUMN poreject.poreject_rjctcode_id IS 'This indicates the reason for the return';
104441
104442
104443 --
104444 -- TOC entry 10081 (class 0 OID 0)
104445 -- Dependencies: 724
104446 -- Name: COLUMN poreject.poreject_poitem_id; Type: COMMENT; Schema: public; Owner: admin
104447 --
104448
104449 COMMENT ON COLUMN poreject.poreject_poitem_id IS 'This is the internal id of the original Purchase Order Item';
104450
104451
104452 --
104453 -- TOC entry 10082 (class 0 OID 0)
104454 -- Dependencies: 724
104455 -- Name: COLUMN poreject.poreject_invoiced; Type: COMMENT; Schema: public; Owner: admin
104456 --
104457
104458 COMMENT ON COLUMN poreject.poreject_invoiced IS 'This indicates whether the Credit Memo associated with the return has been posted';
104459
104460
104461 --
104462 -- TOC entry 10083 (class 0 OID 0)
104463 -- Dependencies: 724
104464 -- Name: COLUMN poreject.poreject_vohead_id; Type: COMMENT; Schema: public; Owner: admin
104465 --
104466
104467 COMMENT ON COLUMN poreject.poreject_vohead_id IS 'This is the Voucher associated with the Purchase Order Item';
104468
104469
104470 --
104471 -- TOC entry 10084 (class 0 OID 0)
104472 -- Dependencies: 724
104473 -- Name: COLUMN poreject.poreject_agent_username; Type: COMMENT; Schema: public; Owner: admin
104474 --
104475
104476 COMMENT ON COLUMN poreject.poreject_agent_username IS 'This is the Purchase Order Agent responsible for the original Purchase Order';
104477
104478
104479 --
104480 -- TOC entry 10085 (class 0 OID 0)
104481 -- Dependencies: 724
104482 -- Name: COLUMN poreject.poreject_voitem_id; Type: COMMENT; Schema: public; Owner: admin
104483 --
104484
104485 COMMENT ON COLUMN poreject.poreject_voitem_id IS 'This is the Voucher Item associated with the Purchase Order Item';
104486
104487
104488 --
104489 -- TOC entry 10086 (class 0 OID 0)
104490 -- Dependencies: 724
104491 -- Name: COLUMN poreject.poreject_value; Type: COMMENT; Schema: public; Owner: admin
104492 --
104493
104494 COMMENT ON COLUMN poreject.poreject_value IS 'This is the value (in base currency) of the return at the time it was posted to the General Ledger';
104495
104496
104497 --
104498 -- TOC entry 10087 (class 0 OID 0)
104499 -- Dependencies: 724
104500 -- Name: COLUMN poreject.poreject_trans_username; Type: COMMENT; Schema: public; Owner: admin
104501 --
104502
104503 COMMENT ON COLUMN poreject.poreject_trans_username IS 'This is the user who recorded the return';
104504
104505
104506 --
104507 -- TOC entry 725 (class 1259 OID 146569633)
104508 -- Dependencies: 8
104509 -- Name: poreject_poreject_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104510 --
104511
104512 CREATE SEQUENCE poreject_poreject_id_seq
104513     START WITH 1
104514     INCREMENT BY 1
104515     NO MINVALUE
104516     MAXVALUE 2147483647
104517     CACHE 1;
104518
104519
104520 ALTER TABLE public.poreject_poreject_id_seq OWNER TO admin;
104521
104522 --
104523 -- TOC entry 726 (class 1259 OID 146569635)
104524 -- Dependencies: 8
104525 -- Name: potype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104526 --
104527
104528 CREATE TABLE potype (
104529     potype_id integer NOT NULL,
104530     potype_name text,
104531     potype_descrip text
104532 );
104533
104534
104535 ALTER TABLE public.potype OWNER TO admin;
104536
104537 --
104538 -- TOC entry 10090 (class 0 OID 0)
104539 -- Dependencies: 726
104540 -- Name: TABLE potype; Type: COMMENT; Schema: public; Owner: admin
104541 --
104542
104543 COMMENT ON TABLE potype IS 'Purchase Order Type information';
104544
104545
104546 --
104547 -- TOC entry 727 (class 1259 OID 146569641)
104548 -- Dependencies: 726 8
104549 -- Name: potype_potype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104550 --
104551
104552 CREATE SEQUENCE potype_potype_id_seq
104553     START WITH 1
104554     INCREMENT BY 1
104555     NO MINVALUE
104556     NO MAXVALUE
104557     CACHE 1;
104558
104559
104560 ALTER TABLE public.potype_potype_id_seq OWNER TO admin;
104561
104562 --
104563 -- TOC entry 10092 (class 0 OID 0)
104564 -- Dependencies: 727
104565 -- Name: potype_potype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104566 --
104567
104568 ALTER SEQUENCE potype_potype_id_seq OWNED BY potype.potype_id;
104569
104570
104571 --
104572 -- TOC entry 728 (class 1259 OID 146569643)
104573 -- Dependencies: 6614 6615 8
104574 -- Name: pr; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104575 --
104576
104577 CREATE TABLE pr (
104578     pr_id integer DEFAULT nextval(('"pr_pr_id_seq"'::text)::regclass) NOT NULL,
104579     pr_number integer,
104580     pr_subnumber integer,
104581     pr_status character(1),
104582     pr_order_type character(1),
104583     pr_order_id integer,
104584     pr_poitem_id integer,
104585     pr_duedate date,
104586     pr_itemsite_id integer,
104587     pr_qtyreq numeric(18,6),
104588     pr_prj_id integer,
104589     pr_releasenote text,
104590     pr_createdate timestamp without time zone DEFAULT now()
104591 );
104592
104593
104594 ALTER TABLE public.pr OWNER TO admin;
104595
104596 --
104597 -- TOC entry 10094 (class 0 OID 0)
104598 -- Dependencies: 728
104599 -- Name: TABLE pr; Type: COMMENT; Schema: public; Owner: admin
104600 --
104601
104602 COMMENT ON TABLE pr IS 'Purchase Request information';
104603
104604
104605 --
104606 -- TOC entry 729 (class 1259 OID 146569651)
104607 -- Dependencies: 8
104608 -- Name: pr_pr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104609 --
104610
104611 CREATE SEQUENCE pr_pr_id_seq
104612     START WITH 1
104613     INCREMENT BY 1
104614     NO MINVALUE
104615     NO MAXVALUE
104616     CACHE 1;
104617
104618
104619 ALTER TABLE public.pr_pr_id_seq OWNER TO admin;
104620
104621 --
104622 -- TOC entry 730 (class 1259 OID 146569653)
104623 -- Dependencies: 6617 8
104624 -- Name: prftcntr; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104625 --
104626
104627 CREATE TABLE prftcntr (
104628     prftcntr_id integer NOT NULL,
104629     prftcntr_number text NOT NULL,
104630     prftcntr_descrip text,
104631     CONSTRAINT prftcntr_prftcntr_number_check CHECK ((prftcntr_number <> ''::text))
104632 );
104633
104634
104635 ALTER TABLE public.prftcntr OWNER TO admin;
104636
104637 --
104638 -- TOC entry 10097 (class 0 OID 0)
104639 -- Dependencies: 730
104640 -- Name: TABLE prftcntr; Type: COMMENT; Schema: public; Owner: admin
104641 --
104642
104643 COMMENT ON TABLE prftcntr IS 'Profit Center information';
104644
104645
104646 --
104647 -- TOC entry 731 (class 1259 OID 146569660)
104648 -- Dependencies: 730 8
104649 -- Name: prftcntr_prftcntr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104650 --
104651
104652 CREATE SEQUENCE prftcntr_prftcntr_id_seq
104653     START WITH 1
104654     INCREMENT BY 1
104655     NO MINVALUE
104656     NO MAXVALUE
104657     CACHE 1;
104658
104659
104660 ALTER TABLE public.prftcntr_prftcntr_id_seq OWNER TO admin;
104661
104662 --
104663 -- TOC entry 10099 (class 0 OID 0)
104664 -- Dependencies: 731
104665 -- Name: prftcntr_prftcntr_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104666 --
104667
104668 ALTER SEQUENCE prftcntr_prftcntr_id_seq OWNED BY prftcntr.prftcntr_id;
104669
104670
104671 --
104672 -- TOC entry 732 (class 1259 OID 146569662)
104673 -- Dependencies: 8
104674 -- Name: usrgrp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104675 --
104676
104677 CREATE TABLE usrgrp (
104678     usrgrp_id integer NOT NULL,
104679     usrgrp_grp_id integer NOT NULL,
104680     usrgrp_username text NOT NULL
104681 );
104682
104683
104684 ALTER TABLE public.usrgrp OWNER TO admin;
104685
104686 --
104687 -- TOC entry 10101 (class 0 OID 0)
104688 -- Dependencies: 732
104689 -- Name: TABLE usrgrp; Type: COMMENT; Schema: public; Owner: admin
104690 --
104691
104692 COMMENT ON TABLE usrgrp IS 'This is which group a user belongs to.';
104693
104694
104695 --
104696 -- TOC entry 733 (class 1259 OID 146569668)
104697 -- Dependencies: 6619 8
104698 -- Name: usrpriv; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104699 --
104700
104701 CREATE TABLE usrpriv (
104702     usrpriv_id integer DEFAULT nextval(('usrpriv_usrpriv_id_seq'::text)::regclass) NOT NULL,
104703     usrpriv_priv_id integer,
104704     usrpriv_username text
104705 );
104706
104707
104708 ALTER TABLE public.usrpriv OWNER TO admin;
104709
104710 --
104711 -- TOC entry 10103 (class 0 OID 0)
104712 -- Dependencies: 733
104713 -- Name: TABLE usrpriv; Type: COMMENT; Schema: public; Owner: admin
104714 --
104715
104716 COMMENT ON TABLE usrpriv IS 'User Privileges information';
104717
104718
104719 --
104720 -- TOC entry 734 (class 1259 OID 146569675)
104721 -- Dependencies: 8587 8
104722 -- Name: privgranted; Type: VIEW; Schema: public; Owner: admin
104723 --
104724
104725 CREATE VIEW privgranted AS
104726     SELECT priv.priv_name AS privilege, (COALESCE(usrpriv.usrpriv_priv_id, grppriv.grppriv_priv_id, (-1)) > 0) AS granted, priv.priv_seq AS sequence FROM ((priv LEFT JOIN usrpriv ON (((priv.priv_id = usrpriv.usrpriv_priv_id) AND (usrpriv.usrpriv_username = geteffectivextuser())))) LEFT JOIN (SELECT DISTINCT grppriv.grppriv_priv_id FROM (grppriv JOIN usrgrp ON (((grppriv.grppriv_grp_id = usrgrp.usrgrp_grp_id) AND (usrgrp.usrgrp_username = geteffectivextuser()))))) grppriv ON ((grppriv.grppriv_priv_id = priv.priv_id)));
104727
104728
104729 ALTER TABLE public.privgranted OWNER TO admin;
104730
104731 --
104732 -- TOC entry 735 (class 1259 OID 146569680)
104733 -- Dependencies: 225 8
104734 -- Name: prj_prj_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104735 --
104736
104737 CREATE SEQUENCE prj_prj_id_seq
104738     START WITH 1
104739     INCREMENT BY 1
104740     NO MINVALUE
104741     NO MAXVALUE
104742     CACHE 1;
104743
104744
104745 ALTER TABLE public.prj_prj_id_seq OWNER TO admin;
104746
104747 --
104748 -- TOC entry 10106 (class 0 OID 0)
104749 -- Dependencies: 735
104750 -- Name: prj_prj_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104751 --
104752
104753 ALTER SEQUENCE prj_prj_id_seq OWNED BY prj.prj_id;
104754
104755
104756 --
104757 -- TOC entry 736 (class 1259 OID 146569682)
104758 -- Dependencies: 232 8
104759 -- Name: prjtask_prjtask_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104760 --
104761
104762 CREATE SEQUENCE prjtask_prjtask_id_seq
104763     START WITH 1
104764     INCREMENT BY 1
104765     NO MINVALUE
104766     NO MAXVALUE
104767     CACHE 1;
104768
104769
104770 ALTER TABLE public.prjtask_prjtask_id_seq OWNER TO admin;
104771
104772 --
104773 -- TOC entry 10108 (class 0 OID 0)
104774 -- Dependencies: 736
104775 -- Name: prjtask_prjtask_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104776 --
104777
104778 ALTER SEQUENCE prjtask_prjtask_id_seq OWNED BY prjtask.prjtask_id;
104779
104780
104781 --
104782 -- TOC entry 737 (class 1259 OID 146569684)
104783 -- Dependencies: 8
104784 -- Name: prjtaskuser; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104785 --
104786
104787 CREATE TABLE prjtaskuser (
104788     prjtaskuser_id integer NOT NULL,
104789     prjtaskuser_prjtask_id integer,
104790     prjtaskuser_username text
104791 );
104792
104793
104794 ALTER TABLE public.prjtaskuser OWNER TO admin;
104795
104796 --
104797 -- TOC entry 10110 (class 0 OID 0)
104798 -- Dependencies: 737
104799 -- Name: TABLE prjtaskuser; Type: COMMENT; Schema: public; Owner: admin
104800 --
104801
104802 COMMENT ON TABLE prjtaskuser IS 'Project Task user information';
104803
104804
104805 --
104806 -- TOC entry 738 (class 1259 OID 146569690)
104807 -- Dependencies: 737 8
104808 -- Name: prjtaskuser_prjtaskuser_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104809 --
104810
104811 CREATE SEQUENCE prjtaskuser_prjtaskuser_id_seq
104812     START WITH 1
104813     INCREMENT BY 1
104814     NO MINVALUE
104815     NO MAXVALUE
104816     CACHE 1;
104817
104818
104819 ALTER TABLE public.prjtaskuser_prjtaskuser_id_seq OWNER TO admin;
104820
104821 --
104822 -- TOC entry 10112 (class 0 OID 0)
104823 -- Dependencies: 738
104824 -- Name: prjtaskuser_prjtaskuser_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104825 --
104826
104827 ALTER SEQUENCE prjtaskuser_prjtaskuser_id_seq OWNED BY prjtaskuser.prjtaskuser_id;
104828
104829
104830 --
104831 -- TOC entry 739 (class 1259 OID 146569692)
104832 -- Dependencies: 6622 8
104833 -- Name: prjtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104834 --
104835
104836 CREATE TABLE prjtype (
104837     prjtype_id integer NOT NULL,
104838     prjtype_code text,
104839     prjtype_descr text,
104840     prjtype_active boolean DEFAULT true
104841 );
104842
104843
104844 ALTER TABLE public.prjtype OWNER TO admin;
104845
104846 --
104847 -- TOC entry 740 (class 1259 OID 146569699)
104848 -- Dependencies: 739 8
104849 -- Name: prjtype_prjtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104850 --
104851
104852 CREATE SEQUENCE prjtype_prjtype_id_seq
104853     START WITH 1
104854     INCREMENT BY 1
104855     NO MINVALUE
104856     NO MAXVALUE
104857     CACHE 1;
104858
104859
104860 ALTER TABLE public.prjtype_prjtype_id_seq OWNER TO admin;
104861
104862 --
104863 -- TOC entry 10115 (class 0 OID 0)
104864 -- Dependencies: 740
104865 -- Name: prjtype_prjtype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104866 --
104867
104868 ALTER SEQUENCE prjtype_prjtype_id_seq OWNED BY prjtype.prjtype_id;
104869
104870
104871 --
104872 -- TOC entry 741 (class 1259 OID 146569701)
104873 -- Dependencies: 8
104874 -- Name: prodcat_prodcat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104875 --
104876
104877 CREATE SEQUENCE prodcat_prodcat_id_seq
104878     START WITH 1
104879     INCREMENT BY 1
104880     NO MINVALUE
104881     MAXVALUE 2147483647
104882     CACHE 1;
104883
104884
104885 ALTER TABLE public.prodcat_prodcat_id_seq OWNER TO admin;
104886
104887 --
104888 -- TOC entry 742 (class 1259 OID 146569703)
104889 -- Dependencies: 6624 6625 6626 8
104890 -- Name: qryhead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104891 --
104892
104893 CREATE TABLE qryhead (
104894     qryhead_id integer NOT NULL,
104895     qryhead_name text NOT NULL,
104896     qryhead_descrip text,
104897     qryhead_notes text,
104898     qryhead_username text DEFAULT geteffectivextuser() NOT NULL,
104899     qryhead_updated date DEFAULT ('now'::text)::date NOT NULL,
104900     CONSTRAINT qryhead_qryhead_name_check CHECK ((qryhead_name <> ''::text))
104901 );
104902
104903
104904 ALTER TABLE public.qryhead OWNER TO admin;
104905
104906 --
104907 -- TOC entry 10117 (class 0 OID 0)
104908 -- Dependencies: 742
104909 -- Name: TABLE qryhead; Type: COMMENT; Schema: public; Owner: admin
104910 --
104911
104912 COMMENT ON TABLE qryhead IS 'A header record for a set of queries to be run sequentially. One use is for data export.';
104913
104914
104915 --
104916 -- TOC entry 10118 (class 0 OID 0)
104917 -- Dependencies: 742
104918 -- Name: COLUMN qryhead.qryhead_id; Type: COMMENT; Schema: public; Owner: admin
104919 --
104920
104921 COMMENT ON COLUMN qryhead.qryhead_id IS 'The primary key, holding an internal value used to cross-reference this table.';
104922
104923
104924 --
104925 -- TOC entry 10119 (class 0 OID 0)
104926 -- Dependencies: 742
104927 -- Name: COLUMN qryhead.qryhead_name; Type: COMMENT; Schema: public; Owner: admin
104928 --
104929
104930 COMMENT ON COLUMN qryhead.qryhead_name IS 'The user-assigned short name for this set of queries.';
104931
104932
104933 --
104934 -- TOC entry 10120 (class 0 OID 0)
104935 -- Dependencies: 742
104936 -- Name: COLUMN qryhead.qryhead_descrip; Type: COMMENT; Schema: public; Owner: admin
104937 --
104938
104939 COMMENT ON COLUMN qryhead.qryhead_descrip IS 'A long description of the purpose of this set of queries.';
104940
104941
104942 --
104943 -- TOC entry 10121 (class 0 OID 0)
104944 -- Dependencies: 742
104945 -- Name: COLUMN qryhead.qryhead_notes; Type: COMMENT; Schema: public; Owner: admin
104946 --
104947
104948 COMMENT ON COLUMN qryhead.qryhead_notes IS 'General information about this queryset.';
104949
104950
104951 --
104952 -- TOC entry 10122 (class 0 OID 0)
104953 -- Dependencies: 742
104954 -- Name: COLUMN qryhead.qryhead_username; Type: COMMENT; Schema: public; Owner: admin
104955 --
104956
104957 COMMENT ON COLUMN qryhead.qryhead_username IS 'The name of the user who last modified this qryhead record.';
104958
104959
104960 --
104961 -- TOC entry 10123 (class 0 OID 0)
104962 -- Dependencies: 742
104963 -- Name: COLUMN qryhead.qryhead_updated; Type: COMMENT; Schema: public; Owner: admin
104964 --
104965
104966 COMMENT ON COLUMN qryhead.qryhead_updated IS 'The date this qryhead was last modified.';
104967
104968
104969 --
104970 -- TOC entry 743 (class 1259 OID 146569712)
104971 -- Dependencies: 742 8
104972 -- Name: qryhead_qryhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
104973 --
104974
104975 CREATE SEQUENCE qryhead_qryhead_id_seq
104976     START WITH 1
104977     INCREMENT BY 1
104978     NO MINVALUE
104979     NO MAXVALUE
104980     CACHE 1;
104981
104982
104983 ALTER TABLE public.qryhead_qryhead_id_seq OWNER TO admin;
104984
104985 --
104986 -- TOC entry 10125 (class 0 OID 0)
104987 -- Dependencies: 743
104988 -- Name: qryhead_qryhead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
104989 --
104990
104991 ALTER SEQUENCE qryhead_qryhead_id_seq OWNED BY qryhead.qryhead_id;
104992
104993
104994 --
104995 -- TOC entry 744 (class 1259 OID 146569714)
104996 -- Dependencies: 6627 6628 6629 6631 6632 8
104997 -- Name: qryitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
104998 --
104999
105000 CREATE TABLE qryitem (
105001     qryitem_id integer NOT NULL,
105002     qryitem_qryhead_id integer NOT NULL,
105003     qryitem_name text NOT NULL,
105004     qryitem_order integer NOT NULL,
105005     qryitem_src text NOT NULL,
105006     qryitem_group text,
105007     qryitem_detail text NOT NULL,
105008     qryitem_notes text DEFAULT ''::text NOT NULL,
105009     qryitem_username text DEFAULT geteffectivextuser() NOT NULL,
105010     qryitem_updated date DEFAULT ('now'::text)::date NOT NULL,
105011     CONSTRAINT qryitem_qryitem_detail_check CHECK ((btrim(qryitem_detail) <> ''::text)),
105012     CONSTRAINT qryitem_qryitem_src_check CHECK ((qryitem_src = ANY (ARRAY['REL'::text, 'MQL'::text, 'CUSTOM'::text])))
105013 );
105014
105015
105016 ALTER TABLE public.qryitem OWNER TO admin;
105017
105018 --
105019 -- TOC entry 10127 (class 0 OID 0)
105020 -- Dependencies: 744
105021 -- Name: TABLE qryitem; Type: COMMENT; Schema: public; Owner: admin
105022 --
105023
105024 COMMENT ON TABLE qryitem IS 'The description of a query to be run as part of a set (see qryhead).';
105025
105026
105027 --
105028 -- TOC entry 10128 (class 0 OID 0)
105029 -- Dependencies: 744
105030 -- Name: COLUMN qryitem.qryitem_id; Type: COMMENT; Schema: public; Owner: admin
105031 --
105032
105033 COMMENT ON COLUMN qryitem.qryitem_id IS 'The primary key, holding an internal value used to cross-reference this table.';
105034
105035
105036 --
105037 -- TOC entry 10129 (class 0 OID 0)
105038 -- Dependencies: 744
105039 -- Name: COLUMN qryitem.qryitem_qryhead_id; Type: COMMENT; Schema: public; Owner: admin
105040 --
105041
105042 COMMENT ON COLUMN qryitem.qryitem_qryhead_id IS 'The primary key of the query set to which this individual query belongs.';
105043
105044
105045 --
105046 -- TOC entry 10130 (class 0 OID 0)
105047 -- Dependencies: 744
105048 -- Name: COLUMN qryitem.qryitem_order; Type: COMMENT; Schema: public; Owner: admin
105049 --
105050
105051 COMMENT ON COLUMN qryitem.qryitem_order IS 'The order in which query items within a query set should be run.';
105052
105053
105054 --
105055 -- TOC entry 10131 (class 0 OID 0)
105056 -- Dependencies: 744
105057 -- Name: COLUMN qryitem.qryitem_src; Type: COMMENT; Schema: public; Owner: admin
105058 --
105059
105060 COMMENT ON COLUMN qryitem.qryitem_src IS 'The source of the query. If the qryitem_src is "REL" then the qryitem_group and _detail name a particular table or view and all rows will be returned. If the source is "MQL" then the qryitem_group and _detail name a pre-defined MetaSQL query in the metasql table. If the source is "CUSTOM" then the qryitem_detail contains the full MetaSQL text of the query to run.';
105061
105062
105063 --
105064 -- TOC entry 10132 (class 0 OID 0)
105065 -- Dependencies: 744
105066 -- Name: COLUMN qryitem.qryitem_group; Type: COMMENT; Schema: public; Owner: admin
105067 --
105068
105069 COMMENT ON COLUMN qryitem.qryitem_group IS 'Information to help find the query to run. If the qryitem_src is "REL" then this is the schema in which to find the table or view to query and all rows will be returned (the qryitem_detail names the table or view). If the qryitem_src is "MQL" then this is the group of the query in the metasql table to run (the name is in qryitem_detail). If the qryitem_src IS "CUSTOM" then this ignored.';
105070
105071
105072 --
105073 -- TOC entry 10133 (class 0 OID 0)
105074 -- Dependencies: 744
105075 -- Name: COLUMN qryitem.qryitem_detail; Type: COMMENT; Schema: public; Owner: admin
105076 --
105077
105078 COMMENT ON COLUMN qryitem.qryitem_detail IS 'The particular query to run. If the qryitem_src is "REL" then this is the name of the table or view to query and all rows will be returned. If the qryitem_src is "MQL" then this is the name of the query in the metasql table to run. If the qryitem_src IS "CUSTOM" then this is the actual MetaSQL query text to be parsed and run.';
105079
105080
105081 --
105082 -- TOC entry 10134 (class 0 OID 0)
105083 -- Dependencies: 744
105084 -- Name: COLUMN qryitem.qryitem_notes; Type: COMMENT; Schema: public; Owner: admin
105085 --
105086
105087 COMMENT ON COLUMN qryitem.qryitem_notes IS 'General information about this query.';
105088
105089
105090 --
105091 -- TOC entry 10135 (class 0 OID 0)
105092 -- Dependencies: 744
105093 -- Name: COLUMN qryitem.qryitem_username; Type: COMMENT; Schema: public; Owner: admin
105094 --
105095
105096 COMMENT ON COLUMN qryitem.qryitem_username IS 'The name of the user who last modified this qryitem record.';
105097
105098
105099 --
105100 -- TOC entry 10136 (class 0 OID 0)
105101 -- Dependencies: 744
105102 -- Name: COLUMN qryitem.qryitem_updated; Type: COMMENT; Schema: public; Owner: admin
105103 --
105104
105105 COMMENT ON COLUMN qryitem.qryitem_updated IS 'The date this qryitem was last modified.';
105106
105107
105108 --
105109 -- TOC entry 745 (class 1259 OID 146569725)
105110 -- Dependencies: 744 8
105111 -- Name: qryitem_qryitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105112 --
105113
105114 CREATE SEQUENCE qryitem_qryitem_id_seq
105115     START WITH 1
105116     INCREMENT BY 1
105117     NO MINVALUE
105118     NO MAXVALUE
105119     CACHE 1;
105120
105121
105122 ALTER TABLE public.qryitem_qryitem_id_seq OWNER TO admin;
105123
105124 --
105125 -- TOC entry 10138 (class 0 OID 0)
105126 -- Dependencies: 745
105127 -- Name: qryitem_qryitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105128 --
105129
105130 ALTER SEQUENCE qryitem_qryitem_id_seq OWNED BY qryitem.qryitem_id;
105131
105132
105133 --
105134 -- TOC entry 746 (class 1259 OID 146569727)
105135 -- Dependencies: 8
105136 -- Name: quhead_quhead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105137 --
105138
105139 CREATE SEQUENCE quhead_quhead_id_seq
105140     START WITH 1
105141     INCREMENT BY 1
105142     NO MINVALUE
105143     NO MAXVALUE
105144     CACHE 1;
105145
105146
105147 ALTER TABLE public.quhead_quhead_id_seq OWNER TO admin;
105148
105149 --
105150 -- TOC entry 747 (class 1259 OID 146569729)
105151 -- Dependencies: 8
105152 -- Name: quitem_quitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105153 --
105154
105155 CREATE SEQUENCE quitem_quitem_id_seq
105156     START WITH 1
105157     INCREMENT BY 1
105158     NO MINVALUE
105159     NO MAXVALUE
105160     CACHE 1;
105161
105162
105163 ALTER TABLE public.quitem_quitem_id_seq OWNER TO admin;
105164
105165 --
105166 -- TOC entry 748 (class 1259 OID 146569731)
105167 -- Dependencies: 6633 8
105168 -- Name: rcalitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105169 --
105170
105171 CREATE TABLE rcalitem (
105172     rcalitem_id integer DEFAULT nextval(('"xcalitem_xcalitem_id_seq"'::text)::regclass) NOT NULL,
105173     rcalitem_calhead_id integer,
105174     rcalitem_offsettype character(1),
105175     rcalitem_offsetcount integer,
105176     rcalitem_periodtype character(1),
105177     rcalitem_periodcount integer,
105178     rcalitem_name text
105179 );
105180
105181
105182 ALTER TABLE public.rcalitem OWNER TO admin;
105183
105184 --
105185 -- TOC entry 10142 (class 0 OID 0)
105186 -- Dependencies: 748
105187 -- Name: TABLE rcalitem; Type: COMMENT; Schema: public; Owner: admin
105188 --
105189
105190 COMMENT ON TABLE rcalitem IS 'Relative Calendar Item information';
105191
105192
105193 --
105194 -- TOC entry 749 (class 1259 OID 146569738)
105195 -- Dependencies: 6635 6636 6637 8
105196 -- Name: recur; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105197 --
105198
105199 CREATE TABLE recur (
105200     recur_id integer NOT NULL,
105201     recur_parent_id integer NOT NULL,
105202     recur_parent_type text NOT NULL,
105203     recur_period text NOT NULL,
105204     recur_freq integer DEFAULT 1 NOT NULL,
105205     recur_start timestamp with time zone DEFAULT now(),
105206     recur_end timestamp with time zone,
105207     recur_max integer,
105208     recur_data text,
105209     CONSTRAINT recur_recur_period_check CHECK ((recur_period = ANY (ARRAY['m'::text, 'H'::text, 'D'::text, 'W'::text, 'M'::text, 'Y'::text, 'C'::text])))
105210 );
105211
105212
105213 ALTER TABLE public.recur OWNER TO admin;
105214
105215 --
105216 -- TOC entry 10144 (class 0 OID 0)
105217 -- Dependencies: 749
105218 -- Name: TABLE recur; Type: COMMENT; Schema: public; Owner: admin
105219 --
105220
105221 COMMENT ON TABLE recur IS 'Track recurring events and objects.';
105222
105223
105224 --
105225 -- TOC entry 10145 (class 0 OID 0)
105226 -- Dependencies: 749
105227 -- Name: COLUMN recur.recur_id; Type: COMMENT; Schema: public; Owner: admin
105228 --
105229
105230 COMMENT ON COLUMN recur.recur_id IS 'Internal ID of this recurrence record.';
105231
105232
105233 --
105234 -- TOC entry 10146 (class 0 OID 0)
105235 -- Dependencies: 749
105236 -- Name: COLUMN recur.recur_parent_id; Type: COMMENT; Schema: public; Owner: admin
105237 --
105238
105239 COMMENT ON COLUMN recur.recur_parent_id IS 'The internal ID of the event/object that recurs.';
105240
105241
105242 --
105243 -- TOC entry 10147 (class 0 OID 0)
105244 -- Dependencies: 749
105245 -- Name: COLUMN recur.recur_parent_type; Type: COMMENT; Schema: public; Owner: admin
105246 --
105247
105248 COMMENT ON COLUMN recur.recur_parent_type IS 'The table in which the parent event or object is stored.';
105249
105250
105251 --
105252 -- TOC entry 10148 (class 0 OID 0)
105253 -- Dependencies: 749
105254 -- Name: COLUMN recur.recur_period; Type: COMMENT; Schema: public; Owner: admin
105255 --
105256
105257 COMMENT ON COLUMN recur.recur_period IS 'With recur_freq, how often this event recurs. Values are "m" for every minute, "H" for every hour, "D" for daily, "W" for weekly, "M" for monthly, "Y" for yearly, and "C" for customized or complex.';
105258
105259
105260 --
105261 -- TOC entry 10149 (class 0 OID 0)
105262 -- Dependencies: 749
105263 -- Name: COLUMN recur.recur_freq; Type: COMMENT; Schema: public; Owner: admin
105264 --
105265
105266 COMMENT ON COLUMN recur.recur_freq IS 'With recur_period, how often this event recurs. Values are integers counts of recur_periods. For example, if recur_freq = 2 and recur_period = w then the event recurs every 2 weeks.';
105267
105268
105269 --
105270 -- TOC entry 10150 (class 0 OID 0)
105271 -- Dependencies: 749
105272 -- Name: COLUMN recur.recur_start; Type: COMMENT; Schema: public; Owner: admin
105273 --
105274
105275 COMMENT ON COLUMN recur.recur_start IS 'The first date/time when the event should occur.';
105276
105277
105278 --
105279 -- TOC entry 10151 (class 0 OID 0)
105280 -- Dependencies: 749
105281 -- Name: COLUMN recur.recur_end; Type: COMMENT; Schema: public; Owner: admin
105282 --
105283
105284 COMMENT ON COLUMN recur.recur_end IS 'The last date/time when the event should occur. NULL means there is no end date/time and the event should recur forever.';
105285
105286
105287 --
105288 -- TOC entry 10152 (class 0 OID 0)
105289 -- Dependencies: 749
105290 -- Name: COLUMN recur.recur_max; Type: COMMENT; Schema: public; Owner: admin
105291 --
105292
105293 COMMENT ON COLUMN recur.recur_max IS 'The maximum number of recurrence events to create at one time. If this is NULL then when new events are created, a system-wide default will limit the number.';
105294
105295
105296 --
105297 -- TOC entry 10153 (class 0 OID 0)
105298 -- Dependencies: 749
105299 -- Name: COLUMN recur.recur_data; Type: COMMENT; Schema: public; Owner: admin
105300 --
105301
105302 COMMENT ON COLUMN recur.recur_data IS 'Not yet used and format still undetermined. Additional data to describe how to apply the period and frequency, particularly when period = "C".';
105303
105304
105305 --
105306 -- TOC entry 750 (class 1259 OID 146569747)
105307 -- Dependencies: 749 8
105308 -- Name: recur_recur_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105309 --
105310
105311 CREATE SEQUENCE recur_recur_id_seq
105312     START WITH 1
105313     INCREMENT BY 1
105314     NO MINVALUE
105315     NO MAXVALUE
105316     CACHE 1;
105317
105318
105319 ALTER TABLE public.recur_recur_id_seq OWNER TO admin;
105320
105321 --
105322 -- TOC entry 10155 (class 0 OID 0)
105323 -- Dependencies: 750
105324 -- Name: recur_recur_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105325 --
105326
105327 ALTER SEQUENCE recur_recur_id_seq OWNED BY recur.recur_id;
105328
105329
105330 --
105331 -- TOC entry 751 (class 1259 OID 146569749)
105332 -- Dependencies: 8
105333 -- Name: recurtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105334 --
105335
105336 CREATE TABLE recurtype (
105337     recurtype_id integer NOT NULL,
105338     recurtype_type text NOT NULL,
105339     recurtype_table text NOT NULL,
105340     recurtype_donecheck text NOT NULL,
105341     recurtype_schedcol text NOT NULL,
105342     recurtype_limit text,
105343     recurtype_copyfunc text NOT NULL,
105344     recurtype_copyargs text[] NOT NULL,
105345     recurtype_delfunc text
105346 );
105347
105348
105349 ALTER TABLE public.recurtype OWNER TO admin;
105350
105351 --
105352 -- TOC entry 10157 (class 0 OID 0)
105353 -- Dependencies: 751
105354 -- Name: TABLE recurtype; Type: COMMENT; Schema: public; Owner: admin
105355 --
105356
105357 COMMENT ON TABLE recurtype IS 'Describes the properties of recurring items/events in way that can be used by stored procedures to maintain the recurrence.';
105358
105359
105360 --
105361 -- TOC entry 10158 (class 0 OID 0)
105362 -- Dependencies: 751
105363 -- Name: COLUMN recurtype.recurtype_id; Type: COMMENT; Schema: public; Owner: admin
105364 --
105365
105366 COMMENT ON COLUMN recurtype.recurtype_id IS 'The internal id of this recurrence description.';
105367
105368
105369 --
105370 -- TOC entry 10159 (class 0 OID 0)
105371 -- Dependencies: 751
105372 -- Name: COLUMN recurtype.recurtype_type; Type: COMMENT; Schema: public; Owner: admin
105373 --
105374
105375 COMMENT ON COLUMN recurtype.recurtype_type IS 'A code value used by the RecurrenceWidget and the code that uses it to describe the item/event that will recur. Examples include "INCDT" for CRM Incidents and "J" for Projects.';
105376
105377
105378 --
105379 -- TOC entry 10160 (class 0 OID 0)
105380 -- Dependencies: 751
105381 -- Name: COLUMN recurtype.recurtype_table; Type: COMMENT; Schema: public; Owner: admin
105382 --
105383
105384 COMMENT ON COLUMN recurtype.recurtype_table IS 'The table that holds the item/event that will recur.';
105385
105386
105387 --
105388 -- TOC entry 10161 (class 0 OID 0)
105389 -- Dependencies: 751
105390 -- Name: COLUMN recurtype.recurtype_donecheck; Type: COMMENT; Schema: public; Owner: admin
105391 --
105392
105393 COMMENT ON COLUMN recurtype.recurtype_donecheck IS 'A boolean expression that returns TRUE if an individual item/event record in the recurtype_table has already been completed.';
105394
105395
105396 --
105397 -- TOC entry 10162 (class 0 OID 0)
105398 -- Dependencies: 751
105399 -- Name: COLUMN recurtype.recurtype_schedcol; Type: COMMENT; Schema: public; Owner: admin
105400 --
105401
105402 COMMENT ON COLUMN recurtype.recurtype_schedcol IS 'The name of the column in the recurtype_table holding the date or timestamp by which the item is scheduled to be completed or at which the event is supposed to occur.';
105403
105404
105405 --
105406 -- TOC entry 10163 (class 0 OID 0)
105407 -- Dependencies: 751
105408 -- Name: COLUMN recurtype.recurtype_limit; Type: COMMENT; Schema: public; Owner: admin
105409 --
105410
105411 COMMENT ON COLUMN recurtype.recurtype_limit IS 'A boolean expression that returns TRUE if the current user should see the row in the recurtype_table. NULL indicates there is no specific limitation. For example, the maintainance of recurring TODO items should restricted to those items belonging to the user unless s/he has been granted the privilege to modify other people''s todo lists.';
105412
105413
105414 --
105415 -- TOC entry 10164 (class 0 OID 0)
105416 -- Dependencies: 751
105417 -- Name: COLUMN recurtype.recurtype_copyfunc; Type: COMMENT; Schema: public; Owner: admin
105418 --
105419
105420 COMMENT ON COLUMN recurtype.recurtype_copyfunc IS 'The name of the function to copy an existing item/event record. The copy function is expected to take at least 2 arguments: the id of the item to copy and the new date/timestamp. If the function accepts more than 2, it must be able to accept NULL values for the 3rd and following arguments.';
105421
105422
105423 --
105424 -- TOC entry 10165 (class 0 OID 0)
105425 -- Dependencies: 751
105426 -- Name: COLUMN recurtype.recurtype_copyargs; Type: COMMENT; Schema: public; Owner: admin
105427 --
105428
105429 COMMENT ON COLUMN recurtype.recurtype_copyargs IS 'An abbreviated argument list for the copy function. This is used to determine whether the second argument must be cast to a date or a timestamp, and to figure out how many additional arguments to pass.';
105430
105431
105432 --
105433 -- TOC entry 10166 (class 0 OID 0)
105434 -- Dependencies: 751
105435 -- Name: COLUMN recurtype.recurtype_delfunc; Type: COMMENT; Schema: public; Owner: admin
105436 --
105437
105438 COMMENT ON COLUMN recurtype.recurtype_delfunc IS 'The name of the function to delete an existing item/event record. The function is expected to take exactly one argument: the id of the item to delete. NULL indicates there is no delete function and that an SQL DELETE statement can be used. In this case, the id column name will be built as the recurtype_table concatenated with the "_id" suffix.';
105439
105440
105441 --
105442 -- TOC entry 752 (class 1259 OID 146569755)
105443 -- Dependencies: 751 8
105444 -- Name: recurtype_recurtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105445 --
105446
105447 CREATE SEQUENCE recurtype_recurtype_id_seq
105448     START WITH 1
105449     INCREMENT BY 1
105450     NO MINVALUE
105451     NO MAXVALUE
105452     CACHE 1;
105453
105454
105455 ALTER TABLE public.recurtype_recurtype_id_seq OWNER TO admin;
105456
105457 --
105458 -- TOC entry 10168 (class 0 OID 0)
105459 -- Dependencies: 752
105460 -- Name: recurtype_recurtype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105461 --
105462
105463 ALTER SEQUENCE recurtype_recurtype_id_seq OWNED BY recurtype.recurtype_id;
105464
105465
105466 --
105467 -- TOC entry 753 (class 1259 OID 146569757)
105468 -- Dependencies: 721 8
105469 -- Name: recv_recv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105470 --
105471
105472 CREATE SEQUENCE recv_recv_id_seq
105473     START WITH 1
105474     INCREMENT BY 1
105475     NO MINVALUE
105476     NO MAXVALUE
105477     CACHE 1;
105478
105479
105480 ALTER TABLE public.recv_recv_id_seq OWNER TO admin;
105481
105482 --
105483 -- TOC entry 10170 (class 0 OID 0)
105484 -- Dependencies: 753
105485 -- Name: recv_recv_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105486 --
105487
105488 ALTER SEQUENCE recv_recv_id_seq OWNED BY recv.recv_id;
105489
105490
105491 --
105492 -- TOC entry 754 (class 1259 OID 146569759)
105493 -- Dependencies: 8588 8
105494 -- Name: remitto; Type: VIEW; Schema: public; Owner: admin
105495 --
105496
105497 CREATE VIEW remitto AS
105498     SELECT (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_name'::text)) AS remitto_name, (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_address1'::text)) AS remitto_address1, (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_address2'::text)) AS remitto_address2, (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_address3'::text)) AS remitto_address3, (((((SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_city'::text)) || '  '::text) || (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_state'::text))) || '  '::text) || (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_zipcode'::text))) AS remitto_citystatezip, (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_country'::text)) AS remitto_country, (SELECT metric.metric_value FROM metric WHERE (metric.metric_name = 'remitto_phone'::text)) AS remitto_phone;
105499
105500
105501 ALTER TABLE public.remitto OWNER TO admin;
105502
105503 --
105504 -- TOC entry 755 (class 1259 OID 146569763)
105505 -- Dependencies: 6639 6640 8
105506 -- Name: rjctcode; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105507 --
105508
105509 CREATE TABLE rjctcode (
105510     rjctcode_id integer DEFAULT nextval(('"rjctcode_rjctcode_id_seq"'::text)::regclass) NOT NULL,
105511     rjctcode_code text NOT NULL,
105512     rjctcode_descrip text,
105513     CONSTRAINT rjctcode_rjctcode_code_check CHECK ((rjctcode_code <> ''::text))
105514 );
105515
105516
105517 ALTER TABLE public.rjctcode OWNER TO admin;
105518
105519 --
105520 -- TOC entry 10173 (class 0 OID 0)
105521 -- Dependencies: 755
105522 -- Name: TABLE rjctcode; Type: COMMENT; Schema: public; Owner: admin
105523 --
105524
105525 COMMENT ON TABLE rjctcode IS 'Reject Code information';
105526
105527
105528 --
105529 -- TOC entry 756 (class 1259 OID 146569771)
105530 -- Dependencies: 8
105531 -- Name: rjctcode_rjctcode_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105532 --
105533
105534 CREATE SEQUENCE rjctcode_rjctcode_id_seq
105535     START WITH 1
105536     INCREMENT BY 1
105537     NO MINVALUE
105538     MAXVALUE 2147483647
105539     CACHE 1;
105540
105541
105542 ALTER TABLE public.rjctcode_rjctcode_id_seq OWNER TO admin;
105543
105544 --
105545 -- TOC entry 757 (class 1259 OID 146569773)
105546 -- Dependencies: 214 8
105547 -- Name: rsncode_rsncode_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105548 --
105549
105550 CREATE SEQUENCE rsncode_rsncode_id_seq
105551     START WITH 1
105552     INCREMENT BY 1
105553     NO MINVALUE
105554     NO MAXVALUE
105555     CACHE 1;
105556
105557
105558 ALTER TABLE public.rsncode_rsncode_id_seq OWNER TO admin;
105559
105560 --
105561 -- TOC entry 10176 (class 0 OID 0)
105562 -- Dependencies: 757
105563 -- Name: rsncode_rsncode_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105564 --
105565
105566 ALTER SEQUENCE rsncode_rsncode_id_seq OWNED BY rsncode.rsncode_id;
105567
105568
105569 --
105570 -- TOC entry 758 (class 1259 OID 146569775)
105571 -- Dependencies: 6641 6642 8
105572 -- Name: sale; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105573 --
105574
105575 CREATE TABLE sale (
105576     sale_id integer DEFAULT nextval(('"sale_sale_id_seq"'::text)::regclass) NOT NULL,
105577     sale_name text NOT NULL,
105578     sale_descrip text,
105579     sale_ipshead_id integer,
105580     sale_startdate date,
105581     sale_enddate date,
105582     CONSTRAINT sale_sale_name_check CHECK ((sale_name <> ''::text))
105583 );
105584
105585
105586 ALTER TABLE public.sale OWNER TO admin;
105587
105588 --
105589 -- TOC entry 10178 (class 0 OID 0)
105590 -- Dependencies: 758
105591 -- Name: TABLE sale; Type: COMMENT; Schema: public; Owner: admin
105592 --
105593
105594 COMMENT ON TABLE sale IS 'Sale information';
105595
105596
105597 --
105598 -- TOC entry 759 (class 1259 OID 146569783)
105599 -- Dependencies: 8
105600 -- Name: sale_sale_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105601 --
105602
105603 CREATE SEQUENCE sale_sale_id_seq
105604     START WITH 1
105605     INCREMENT BY 1
105606     NO MINVALUE
105607     NO MAXVALUE
105608     CACHE 1;
105609
105610
105611 ALTER TABLE public.sale_sale_id_seq OWNER TO admin;
105612
105613 --
105614 -- TOC entry 760 (class 1259 OID 146569785)
105615 -- Dependencies: 8
105616 -- Name: salesaccnt_salesaccnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105617 --
105618
105619 CREATE SEQUENCE salesaccnt_salesaccnt_id_seq
105620     START WITH 1
105621     INCREMENT BY 1
105622     NO MINVALUE
105623     MAXVALUE 2147483647
105624     CACHE 1;
105625
105626
105627 ALTER TABLE public.salesaccnt_salesaccnt_id_seq OWNER TO admin;
105628
105629 --
105630 -- TOC entry 761 (class 1259 OID 146569787)
105631 -- Dependencies: 215 8
105632 -- Name: salescat_salescat_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105633 --
105634
105635 CREATE SEQUENCE salescat_salescat_id_seq
105636     START WITH 1
105637     INCREMENT BY 1
105638     NO MINVALUE
105639     NO MAXVALUE
105640     CACHE 1;
105641
105642
105643 ALTER TABLE public.salescat_salescat_id_seq OWNER TO admin;
105644
105645 --
105646 -- TOC entry 10182 (class 0 OID 0)
105647 -- Dependencies: 761
105648 -- Name: salescat_salescat_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105649 --
105650
105651 ALTER SEQUENCE salescat_salescat_id_seq OWNED BY salescat.salescat_id;
105652
105653
105654 --
105655 -- TOC entry 762 (class 1259 OID 146569789)
105656 -- Dependencies: 8589 8
105657 -- Name: saleshistory; Type: VIEW; Schema: public; Owner: admin
105658 --
105659
105660 CREATE VIEW saleshistory AS
105661     SELECT cohist.cohist_id, cohist.cohist_cust_id, cohist.cohist_itemsite_id, cohist.cohist_shipdate, cohist.cohist_shipvia, cohist.cohist_ordernumber, cohist.cohist_orderdate, cohist.cohist_invcnumber, cohist.cohist_invcdate, cohist.cohist_qtyshipped, cohist.cohist_unitprice, cohist.cohist_shipto_id, cohist.cohist_salesrep_id, cohist.cohist_duedate, cohist.cohist_imported, cohist.cohist_billtoname, cohist.cohist_billtoaddress1, cohist.cohist_billtoaddress2, cohist.cohist_billtoaddress3, cohist.cohist_billtocity, cohist.cohist_billtostate, cohist.cohist_billtozip, cohist.cohist_shiptoname, cohist.cohist_shiptoaddress1, cohist.cohist_shiptoaddress2, cohist.cohist_shiptoaddress3, cohist.cohist_shiptocity, cohist.cohist_shiptostate, cohist.cohist_shiptozip, cohist.cohist_commission, cohist.cohist_commissionpaid, cohist.cohist_unitcost, cohist.cohist_misc_type, cohist.cohist_misc_descrip, cohist.cohist_misc_id, cohist.cohist_doctype, cohist.cohist_promisedate, cohist.cohist_ponumber, cohist.cohist_curr_id, cohist.cohist_sequence, cohist.cohist_taxtype_id, cohist.cohist_taxzone_id, cohist.cohist_cohead_ccpay_id, cohist.cohist_saletype_id, cohist.cohist_shipzone_id, CASE WHEN (cohist.cohist_invcnumber = '-1'::text) THEN 'Credit'::text ELSE cohist.cohist_invcnumber END AS invoicenumber, custinfo.cust_id, custinfo.cust_number, custinfo.cust_name, custinfo.cust_curr_id, custinfo.cust_custtype_id, custtype.custtype_code, custtype.custtype_descrip, salesrep.salesrep_number, salesrep.salesrep_name, shipzone.shipzone_id, shipzone.shipzone_name, shipzone.shipzone_descrip, itemsite.itemsite_warehous_id, itemsite.itemsite_item_id, item.item_id, item.item_number, item.item_descrip1, ((item.item_descrip1 || ' '::text) || item.item_descrip2) AS itemdescription, item.item_prodcat_id, site.warehous_code, site.warehous_descrip, prodcat.prodcat_code, currtobase(cohist.cohist_curr_id, cohist.cohist_commission, cohist.cohist_invcdate) AS basecommission, currtobase(cohist.cohist_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate) AS baseunitprice, currtocurr(cohist.cohist_curr_id, custinfo.cust_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate) AS custunitprice, round((cohist.cohist_qtyshipped * cohist.cohist_unitprice), 2) AS extprice, round((cohist.cohist_qtyshipped * currtobase(cohist.cohist_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate)), 2) AS baseextprice, round((cohist.cohist_qtyshipped * currtocurr(cohist.cohist_curr_id, custinfo.cust_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate)), 2) AS custextprice, round((cohist.cohist_qtyshipped * cohist.cohist_unitcost), 4) AS extcost, currconcat(cohist.cohist_curr_id) AS currabbr, 'Return'::text AS cohist_invcdate_xtnullrole, 'qty'::text AS cohist_qtyshipped_xtnumericrole, 'salesprice'::text AS cohist_unitprice_xtnumericrole, 'salesprice'::text AS baseunitprice_xtnumericrole, 'curr'::text AS custunitprice_xtnumericrole, 'curr'::text AS custextprice_xtnumericrole, 'curr'::text AS extprice_xtnumericrole, 'curr'::text AS baseextprice_xtnumericrole, 'cost'::text AS cohist_unitcost_xtnumericrole, 'curr'::text AS extcost_xtnumericrole, 'curr'::text AS cohist_commission_xtnumericrole, 'curr'::text AS basecommission_xtnumericrole, 0 AS cohist_qtyshipped_xttotalrole, 0 AS custextprice_xttotalrole, 0 AS baseextprice_xttotalrole, 0 AS extcost_xttotalrole, 0 AS basecommission_xttotalrole FROM (((((((((cohist JOIN custinfo ON ((custinfo.cust_id = cohist.cohist_cust_id))) JOIN custtype ON ((custtype.custtype_id = custinfo.cust_custtype_id))) JOIN salesrep ON ((salesrep.salesrep_id = cohist.cohist_salesrep_id))) JOIN itemsite ON ((itemsite.itemsite_id = cohist.cohist_itemsite_id))) JOIN site() site(warehous_id, warehous_code, warehous_descrip, warehous_fob, warehous_active, warehous_counttag_prefix, warehous_counttag_number, warehous_bol_prefix, warehous_bol_number, warehous_shipping, warehous_useslips, warehous_usezones, warehous_aislesize, warehous_aislealpha, warehous_racksize, warehous_rackalpha, warehous_binsize, warehous_binalpha, warehous_locationsize, warehous_locationalpha, warehous_enforcearbl, warehous_default_accnt_id, warehous_shipping_commission, warehous_cntct_id, warehous_addr_id, warehous_transit, warehous_shipform_id, warehous_shipvia_id, warehous_shipcomments, warehous_costcat_id, warehous_sitetype_id, warehous_taxzone_id, warehous_sequence) ON ((site.warehous_id = itemsite.itemsite_warehous_id))) JOIN item ON ((item.item_id = itemsite.itemsite_item_id))) JOIN prodcat ON ((prodcat.prodcat_id = item.item_prodcat_id))) LEFT JOIN shiptoinfo ON ((shiptoinfo.shipto_id = cohist.cohist_shipto_id))) LEFT JOIN shipzone ON ((shipzone.shipzone_id = shiptoinfo.shipto_shipzone_id)));
105662
105663
105664 ALTER TABLE public.saleshistory OWNER TO admin;
105665
105666 --
105667 -- TOC entry 10184 (class 0 OID 0)
105668 -- Dependencies: 762
105669 -- Name: VIEW saleshistory; Type: COMMENT; Schema: public; Owner: admin
105670 --
105671
105672 COMMENT ON VIEW saleshistory IS 'Single point for sales history calculations.';
105673
105674
105675 --
105676 -- TOC entry 763 (class 1259 OID 146569794)
105677 -- Dependencies: 8590 8
105678 -- Name: saleshistorymisc; Type: VIEW; Schema: public; Owner: admin
105679 --
105680
105681 CREATE VIEW saleshistorymisc AS
105682     SELECT cohist.cohist_id, cohist.cohist_cust_id, cohist.cohist_itemsite_id, cohist.cohist_shipdate, cohist.cohist_shipvia, cohist.cohist_ordernumber, cohist.cohist_orderdate, cohist.cohist_invcnumber, cohist.cohist_invcdate, cohist.cohist_qtyshipped, cohist.cohist_unitprice, cohist.cohist_shipto_id, cohist.cohist_salesrep_id, cohist.cohist_duedate, cohist.cohist_imported, cohist.cohist_billtoname, cohist.cohist_billtoaddress1, cohist.cohist_billtoaddress2, cohist.cohist_billtoaddress3, cohist.cohist_billtocity, cohist.cohist_billtostate, cohist.cohist_billtozip, cohist.cohist_shiptoname, cohist.cohist_shiptoaddress1, cohist.cohist_shiptoaddress2, cohist.cohist_shiptoaddress3, cohist.cohist_shiptocity, cohist.cohist_shiptostate, cohist.cohist_shiptozip, cohist.cohist_commission, cohist.cohist_commissionpaid, cohist.cohist_unitcost, cohist.cohist_misc_type, cohist.cohist_misc_descrip, cohist.cohist_misc_id, cohist.cohist_doctype, cohist.cohist_promisedate, cohist.cohist_ponumber, cohist.cohist_curr_id, cohist.cohist_sequence, cohist.cohist_taxtype_id, cohist.cohist_taxzone_id, cohist.cohist_cohead_ccpay_id, cohist.cohist_saletype_id, cohist.cohist_shipzone_id, CASE WHEN (cohist.cohist_invcnumber = '-1'::text) THEN 'Credit'::text ELSE cohist.cohist_invcnumber END AS invoicenumber, custinfo.cust_id, custinfo.cust_number, custinfo.cust_name, custinfo.cust_curr_id, custinfo.cust_custtype_id, custtype.custtype_code, salesrep.salesrep_number, salesrep.salesrep_name, shipzone.shipzone_id, shipzone.shipzone_name, itemsite.itemsite_warehous_id, itemsite.itemsite_item_id, item.item_number, item.item_descrip1, ((item.item_descrip1 || ' '::text) || item.item_descrip2) AS itemdescription, item.item_prodcat_id, site.warehous_code, prodcat.prodcat_code, currtobase(cohist.cohist_curr_id, cohist.cohist_commission, cohist.cohist_invcdate) AS basecommission, currtobase(cohist.cohist_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate) AS baseunitprice, currtocurr(cohist.cohist_curr_id, custinfo.cust_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate) AS custunitprice, round((cohist.cohist_qtyshipped * cohist.cohist_unitprice), 2) AS extprice, round((cohist.cohist_qtyshipped * currtobase(cohist.cohist_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate)), 2) AS baseextprice, round((cohist.cohist_qtyshipped * currtocurr(cohist.cohist_curr_id, custinfo.cust_curr_id, cohist.cohist_unitprice, cohist.cohist_invcdate)), 2) AS custextprice, round((cohist.cohist_qtyshipped * cohist.cohist_unitcost), 4) AS extcost, currconcat(cohist.cohist_curr_id) AS currabbr, 'Return'::text AS cohist_invcdate_xtnullrole, 'qty'::text AS cohist_qtyshipped_xtnumericrole, 'salesprice'::text AS cohist_unitprice_xtnumericrole, 'salesprice'::text AS baseunitprice_xtnumericrole, 'curr'::text AS custunitprice_xtnumericrole, 'curr'::text AS custextprice_xtnumericrole, 'curr'::text AS extprice_xtnumericrole, 'curr'::text AS baseextprice_xtnumericrole, 'cost'::text AS cohist_unitcost_xtnumericrole, 'curr'::text AS extcost_xtnumericrole, 'curr'::text AS cohist_commission_xtnumericrole, 'curr'::text AS basecommission_xtnumericrole, 0 AS cohist_qtyshipped_xttotalrole, 0 AS custextprice_xttotalrole, 0 AS baseextprice_xttotalrole, 0 AS extcost_xttotalrole, 0 AS basecommission_xttotalrole FROM (((((((((cohist JOIN custinfo ON ((custinfo.cust_id = cohist.cohist_cust_id))) JOIN custtype ON ((custtype.custtype_id = custinfo.cust_custtype_id))) JOIN salesrep ON ((salesrep.salesrep_id = cohist.cohist_salesrep_id))) LEFT JOIN itemsite ON ((itemsite.itemsite_id = cohist.cohist_itemsite_id))) LEFT JOIN site() site(warehous_id, warehous_code, warehous_descrip, warehous_fob, warehous_active, warehous_counttag_prefix, warehous_counttag_number, warehous_bol_prefix, warehous_bol_number, warehous_shipping, warehous_useslips, warehous_usezones, warehous_aislesize, warehous_aislealpha, warehous_racksize, warehous_rackalpha, warehous_binsize, warehous_binalpha, warehous_locationsize, warehous_locationalpha, warehous_enforcearbl, warehous_default_accnt_id, warehous_shipping_commission, warehous_cntct_id, warehous_addr_id, warehous_transit, warehous_shipform_id, warehous_shipvia_id, warehous_shipcomments, warehous_costcat_id, warehous_sitetype_id, warehous_taxzone_id, warehous_sequence) ON ((site.warehous_id = itemsite.itemsite_warehous_id))) LEFT JOIN item ON ((item.item_id = itemsite.itemsite_item_id))) LEFT JOIN prodcat ON ((prodcat.prodcat_id = item.item_prodcat_id))) LEFT JOIN shiptoinfo ON ((shiptoinfo.shipto_id = cohist.cohist_shipto_id))) LEFT JOIN shipzone ON ((shipzone.shipzone_id = shiptoinfo.shipto_shipzone_id)));
105683
105684
105685 ALTER TABLE public.saleshistorymisc OWNER TO admin;
105686
105687 --
105688 -- TOC entry 10186 (class 0 OID 0)
105689 -- Dependencies: 763
105690 -- Name: VIEW saleshistorymisc; Type: COMMENT; Schema: public; Owner: admin
105691 --
105692
105693 COMMENT ON VIEW saleshistorymisc IS 'Single point for sales history (including misc. items) calculations.';
105694
105695
105696 --
105697 -- TOC entry 764 (class 1259 OID 146569799)
105698 -- Dependencies: 8
105699 -- Name: salesrep_salesrep_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105700 --
105701
105702 CREATE SEQUENCE salesrep_salesrep_id_seq
105703     START WITH 1
105704     INCREMENT BY 1
105705     NO MINVALUE
105706     NO MAXVALUE
105707     CACHE 1;
105708
105709
105710 ALTER TABLE public.salesrep_salesrep_id_seq OWNER TO admin;
105711
105712 --
105713 -- TOC entry 765 (class 1259 OID 146569801)
105714 -- Dependencies: 226 8
105715 -- Name: saletype_saletype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105716 --
105717
105718 CREATE SEQUENCE saletype_saletype_id_seq
105719     START WITH 1
105720     INCREMENT BY 1
105721     NO MINVALUE
105722     NO MAXVALUE
105723     CACHE 1;
105724
105725
105726 ALTER TABLE public.saletype_saletype_id_seq OWNER TO admin;
105727
105728 --
105729 -- TOC entry 10189 (class 0 OID 0)
105730 -- Dependencies: 765
105731 -- Name: saletype_saletype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105732 --
105733
105734 ALTER SEQUENCE saletype_saletype_id_seq OWNED BY saletype.saletype_id;
105735
105736
105737 --
105738 -- TOC entry 766 (class 1259 OID 146569803)
105739 -- Dependencies: 6644 6645 8
105740 -- Name: schemaord; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105741 --
105742
105743 CREATE TABLE schemaord (
105744     schemaord_id integer NOT NULL,
105745     schemaord_name text NOT NULL,
105746     schemaord_order integer NOT NULL,
105747     CONSTRAINT schemaord_schemaord_name_check CHECK ((length(schemaord_name) > 0)),
105748     CONSTRAINT schemaord_schemaord_name_check1 CHECK ((schemaord_name <> ''::text))
105749 );
105750
105751
105752 ALTER TABLE public.schemaord OWNER TO admin;
105753
105754 --
105755 -- TOC entry 10191 (class 0 OID 0)
105756 -- Dependencies: 766
105757 -- Name: TABLE schemaord; Type: COMMENT; Schema: public; Owner: admin
105758 --
105759
105760 COMMENT ON TABLE schemaord IS 'Set the order in which db schemas will appear in the search path after login';
105761
105762
105763 --
105764 -- TOC entry 767 (class 1259 OID 146569811)
105765 -- Dependencies: 766 8
105766 -- Name: schemaord_schemaord_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105767 --
105768
105769 CREATE SEQUENCE schemaord_schemaord_id_seq
105770     START WITH 1
105771     INCREMENT BY 1
105772     NO MINVALUE
105773     NO MAXVALUE
105774     CACHE 1;
105775
105776
105777 ALTER TABLE public.schemaord_schemaord_id_seq OWNER TO admin;
105778
105779 --
105780 -- TOC entry 10193 (class 0 OID 0)
105781 -- Dependencies: 767
105782 -- Name: schemaord_schemaord_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105783 --
105784
105785 ALTER SEQUENCE schemaord_schemaord_id_seq OWNED BY schemaord.schemaord_id;
105786
105787
105788 --
105789 -- TOC entry 768 (class 1259 OID 146569813)
105790 -- Dependencies: 8
105791 -- Name: sequence; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105792 --
105793
105794 CREATE TABLE sequence (
105795     sequence_value integer
105796 );
105797
105798
105799 ALTER TABLE public.sequence OWNER TO admin;
105800
105801 --
105802 -- TOC entry 10195 (class 0 OID 0)
105803 -- Dependencies: 768
105804 -- Name: TABLE sequence; Type: COMMENT; Schema: public; Owner: admin
105805 --
105806
105807 COMMENT ON TABLE sequence IS 'Pre-populated list of sequence numbers (1-1000) used for printing Labels and other uses';
105808
105809
105810 --
105811 -- TOC entry 769 (class 1259 OID 146569816)
105812 -- Dependencies: 293 8
105813 -- Name: shift_shift_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105814 --
105815
105816 CREATE SEQUENCE shift_shift_id_seq
105817     START WITH 1
105818     INCREMENT BY 1
105819     NO MINVALUE
105820     NO MAXVALUE
105821     CACHE 1;
105822
105823
105824 ALTER TABLE public.shift_shift_id_seq OWNER TO admin;
105825
105826 --
105827 -- TOC entry 10197 (class 0 OID 0)
105828 -- Dependencies: 769
105829 -- Name: shift_shift_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105830 --
105831
105832 ALTER SEQUENCE shift_shift_id_seq OWNED BY shift.shift_id;
105833
105834
105835 --
105836 -- TOC entry 770 (class 1259 OID 146569818)
105837 -- Dependencies: 281 8
105838 -- Name: shipchrg_shipchrg_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105839 --
105840
105841 CREATE SEQUENCE shipchrg_shipchrg_id_seq
105842     START WITH 1
105843     INCREMENT BY 1
105844     NO MINVALUE
105845     NO MAXVALUE
105846     CACHE 1;
105847
105848
105849 ALTER TABLE public.shipchrg_shipchrg_id_seq OWNER TO admin;
105850
105851 --
105852 -- TOC entry 10199 (class 0 OID 0)
105853 -- Dependencies: 770
105854 -- Name: shipchrg_shipchrg_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105855 --
105856
105857 ALTER SEQUENCE shipchrg_shipchrg_id_seq OWNED BY shipchrg.shipchrg_id;
105858
105859
105860 --
105861 -- TOC entry 771 (class 1259 OID 146569820)
105862 -- Dependencies: 6646 6647 6648 6649 6650 8
105863 -- Name: shipdatasum; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
105864 --
105865
105866 CREATE TABLE shipdatasum (
105867     shipdatasum_cohead_number text NOT NULL,
105868     shipdatasum_cosmisc_tracknum text NOT NULL,
105869     shipdatasum_cosmisc_packnum_tracknum text NOT NULL,
105870     shipdatasum_weight numeric(16,4),
105871     shipdatasum_base_freight numeric(16,4),
105872     shipdatasum_total_freight numeric(16,4),
105873     shipdatasum_shipper text DEFAULT 'UPS'::text,
105874     shipdatasum_billing_option text,
105875     shipdatasum_package_type text,
105876     shipdatasum_lastupdated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
105877     shipdatasum_shipped boolean DEFAULT false,
105878     shipdatasum_shiphead_number text,
105879     shipdatasum_base_freight_curr_id integer DEFAULT basecurrid(),
105880     shipdatasum_total_freight_curr_id integer DEFAULT basecurrid()
105881 );
105882
105883
105884 ALTER TABLE public.shipdatasum OWNER TO admin;
105885
105886 --
105887 -- TOC entry 10201 (class 0 OID 0)
105888 -- Dependencies: 771
105889 -- Name: TABLE shipdatasum; Type: COMMENT; Schema: public; Owner: admin
105890 --
105891
105892 COMMENT ON TABLE shipdatasum IS 'Shipping Interface information.';
105893
105894
105895 --
105896 -- TOC entry 772 (class 1259 OID 146569831)
105897 -- Dependencies: 8
105898 -- Name: shipform_shipform_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105899 --
105900
105901 CREATE SEQUENCE shipform_shipform_id_seq
105902     START WITH 1
105903     INCREMENT BY 1
105904     NO MINVALUE
105905     MAXVALUE 2147483647
105906     CACHE 1;
105907
105908
105909 ALTER TABLE public.shipform_shipform_id_seq OWNER TO admin;
105910
105911 --
105912 -- TOC entry 773 (class 1259 OID 146569833)
105913 -- Dependencies: 526 8
105914 -- Name: shiphead_shiphead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105915 --
105916
105917 CREATE SEQUENCE shiphead_shiphead_id_seq
105918     START WITH 1
105919     INCREMENT BY 1
105920     NO MINVALUE
105921     NO MAXVALUE
105922     CACHE 1;
105923
105924
105925 ALTER TABLE public.shiphead_shiphead_id_seq OWNER TO admin;
105926
105927 --
105928 -- TOC entry 10204 (class 0 OID 0)
105929 -- Dependencies: 773
105930 -- Name: shiphead_shiphead_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105931 --
105932
105933 ALTER SEQUENCE shiphead_shiphead_id_seq OWNED BY shiphead.shiphead_id;
105934
105935
105936 --
105937 -- TOC entry 774 (class 1259 OID 146569835)
105938 -- Dependencies: 527 8
105939 -- Name: shipitem_shipitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105940 --
105941
105942 CREATE SEQUENCE shipitem_shipitem_id_seq
105943     START WITH 1
105944     INCREMENT BY 1
105945     NO MINVALUE
105946     NO MAXVALUE
105947     CACHE 1;
105948
105949
105950 ALTER TABLE public.shipitem_shipitem_id_seq OWNER TO admin;
105951
105952 --
105953 -- TOC entry 10206 (class 0 OID 0)
105954 -- Dependencies: 774
105955 -- Name: shipitem_shipitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
105956 --
105957
105958 ALTER SEQUENCE shipitem_shipitem_id_seq OWNED BY shipitem.shipitem_id;
105959
105960
105961 --
105962 -- TOC entry 775 (class 1259 OID 146569837)
105963 -- Dependencies: 8
105964 -- Name: shipment_number_seq; Type: SEQUENCE; Schema: public; Owner: admin
105965 --
105966
105967 CREATE SEQUENCE shipment_number_seq
105968     START WITH 1
105969     INCREMENT BY 1
105970     NO MINVALUE
105971     NO MAXVALUE
105972     CACHE 1;
105973
105974
105975 ALTER TABLE public.shipment_number_seq OWNER TO admin;
105976
105977 --
105978 -- TOC entry 776 (class 1259 OID 146569839)
105979 -- Dependencies: 8591 8
105980 -- Name: shipto; Type: VIEW; Schema: public; Owner: admin
105981 --
105982
105983 CREATE VIEW shipto AS
105984     SELECT shiptoinfo.shipto_id, shiptoinfo.shipto_cust_id, shiptoinfo.shipto_name, m.addr_line1 AS shipto_address1, m.addr_line2 AS shipto_address2, m.addr_line3 AS shipto_address3, m.addr_city AS shipto_city, m.addr_state AS shipto_state, m.addr_postalcode AS shipto_zipcode, shiptoinfo.shipto_taxzone_id, shiptoinfo.shipto_salesrep_id, c1.cntct_phone AS shipto_phone, shiptoinfo.shipto_comments, shiptoinfo.shipto_shipcomments, btrim(((c1.cntct_first_name || ' '::text) || c1.cntct_last_name)) AS shipto_contact, c1.cntct_fax AS shipto_fax, c1.cntct_email AS shipto_email, shiptoinfo.shipto_shipzone_id, shiptoinfo.shipto_shipvia, shiptoinfo.shipto_commission, shiptoinfo.shipto_shipform_id, shiptoinfo.shipto_shipchrg_id, shiptoinfo.shipto_active, shiptoinfo.shipto_default, shiptoinfo.shipto_num, shiptoinfo.shipto_ediprofile_id, m.addr_country AS shipto_country FROM ((shiptoinfo LEFT JOIN cntct c1 ON ((shiptoinfo.shipto_cntct_id = c1.cntct_id))) LEFT JOIN addr m ON ((shiptoinfo.shipto_addr_id = m.addr_id)));
105985
105986
105987 ALTER TABLE public.shipto OWNER TO admin;
105988
105989 --
105990 -- TOC entry 777 (class 1259 OID 146569844)
105991 -- Dependencies: 8
105992 -- Name: shipto_shipto_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
105993 --
105994
105995 CREATE SEQUENCE shipto_shipto_id_seq
105996     START WITH 1
105997     INCREMENT BY 1
105998     NO MINVALUE
105999     MAXVALUE 2147483647
106000     CACHE 1;
106001
106002
106003 ALTER TABLE public.shipto_shipto_id_seq OWNER TO admin;
106004
106005 --
106006 -- TOC entry 778 (class 1259 OID 146569846)
106007 -- Dependencies: 8
106008 -- Name: shipvia_shipvia_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106009 --
106010
106011 CREATE SEQUENCE shipvia_shipvia_id_seq
106012     START WITH 1
106013     INCREMENT BY 1
106014     NO MINVALUE
106015     MAXVALUE 2147483647
106016     CACHE 1;
106017
106018
106019 ALTER TABLE public.shipvia_shipvia_id_seq OWNER TO admin;
106020
106021 --
106022 -- TOC entry 779 (class 1259 OID 146569848)
106023 -- Dependencies: 8
106024 -- Name: shipzone_shipzone_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106025 --
106026
106027 CREATE SEQUENCE shipzone_shipzone_id_seq
106028     START WITH 1
106029     INCREMENT BY 1
106030     NO MINVALUE
106031     MAXVALUE 2147483647
106032     CACHE 1;
106033
106034
106035 ALTER TABLE public.shipzone_shipzone_id_seq OWNER TO admin;
106036
106037 --
106038 -- TOC entry 780 (class 1259 OID 146569850)
106039 -- Dependencies: 387 8
106040 -- Name: sitetype_sitetype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106041 --
106042
106043 CREATE SEQUENCE sitetype_sitetype_id_seq
106044     START WITH 1
106045     INCREMENT BY 1
106046     NO MINVALUE
106047     NO MAXVALUE
106048     CACHE 1;
106049
106050
106051 ALTER TABLE public.sitetype_sitetype_id_seq OWNER TO admin;
106052
106053 --
106054 -- TOC entry 10213 (class 0 OID 0)
106055 -- Dependencies: 780
106056 -- Name: sitetype_sitetype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106057 --
106058
106059 ALTER SEQUENCE sitetype_sitetype_id_seq OWNED BY sitetype.sitetype_id;
106060
106061
106062 --
106063 -- TOC entry 781 (class 1259 OID 146569852)
106064 -- Dependencies: 6651 6652 6653 8
106065 -- Name: sltrans; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106066 --
106067
106068 CREATE TABLE sltrans (
106069     sltrans_id integer DEFAULT nextval('gltrans_gltrans_id_seq'::regclass) NOT NULL,
106070     sltrans_created timestamp with time zone,
106071     sltrans_date date NOT NULL,
106072     sltrans_sequence integer,
106073     sltrans_accnt_id integer NOT NULL,
106074     sltrans_source text,
106075     sltrans_docnumber text,
106076     sltrans_misc_id integer,
106077     sltrans_amount numeric(20,2) NOT NULL,
106078     sltrans_notes text,
106079     sltrans_journalnumber integer,
106080     sltrans_posted boolean NOT NULL,
106081     sltrans_doctype text,
106082     sltrans_username text DEFAULT geteffectivextuser() NOT NULL,
106083     sltrans_gltrans_journalnumber integer,
106084     sltrans_rec boolean DEFAULT false NOT NULL
106085 );
106086
106087
106088 ALTER TABLE public.sltrans OWNER TO admin;
106089
106090 --
106091 -- TOC entry 10215 (class 0 OID 0)
106092 -- Dependencies: 781
106093 -- Name: TABLE sltrans; Type: COMMENT; Schema: public; Owner: admin
106094 --
106095
106096 COMMENT ON TABLE sltrans IS 'Journal transaction information';
106097
106098
106099 --
106100 -- TOC entry 782 (class 1259 OID 146569861)
106101 -- Dependencies: 8
106102 -- Name: sltrans_backup; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106103 --
106104
106105 CREATE TABLE sltrans_backup (
106106     sltrans_old_id integer,
106107     sltrans_new_id integer
106108 );
106109
106110
106111 ALTER TABLE public.sltrans_backup OWNER TO admin;
106112
106113 --
106114 -- TOC entry 10217 (class 0 OID 0)
106115 -- Dependencies: 782
106116 -- Name: TABLE sltrans_backup; Type: COMMENT; Schema: public; Owner: admin
106117 --
106118
106119 COMMENT ON TABLE sltrans_backup IS 'backup cross references of old and new ids for sltrans 4.0 upgrade.';
106120
106121
106122 --
106123 -- TOC entry 783 (class 1259 OID 146569864)
106124 -- Dependencies: 8592 8
106125 -- Name: sopack; Type: VIEW; Schema: public; Owner: admin
106126 --
106127
106128 CREATE VIEW sopack AS
106129     SELECT pack.pack_id AS sopack_id, pack.pack_head_id AS sopack_sohead_id, pack.pack_printed AS sopack_printed, pack.pack_shiphead_id AS sopack_cosmisc_id FROM pack WHERE (pack.pack_head_type = 'SO'::text);
106130
106131
106132 ALTER TABLE public.sopack OWNER TO admin;
106133
106134 --
106135 -- TOC entry 784 (class 1259 OID 146569868)
106136 -- Dependencies: 8
106137 -- Name: sopack_sopack_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106138 --
106139
106140 CREATE SEQUENCE sopack_sopack_id_seq
106141     START WITH 1
106142     INCREMENT BY 1
106143     NO MINVALUE
106144     NO MAXVALUE
106145     CACHE 1;
106146
106147
106148 ALTER TABLE public.sopack_sopack_id_seq OWNER TO admin;
106149
106150 --
106151 -- TOC entry 785 (class 1259 OID 146569870)
106152 -- Dependencies: 6655 8
106153 -- Name: source; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106154 --
106155
106156 CREATE TABLE source (
106157     source_id integer NOT NULL,
106158     source_module text,
106159     source_name text NOT NULL,
106160     source_descrip text,
106161     CONSTRAINT source_source_name_check CHECK ((source_name <> ''::text))
106162 );
106163
106164
106165 ALTER TABLE public.source OWNER TO admin;
106166
106167 --
106168 -- TOC entry 10220 (class 0 OID 0)
106169 -- Dependencies: 785
106170 -- Name: TABLE source; Type: COMMENT; Schema: public; Owner: admin
106171 --
106172
106173 COMMENT ON TABLE source IS 'Tax class information';
106174
106175
106176 --
106177 -- TOC entry 10221 (class 0 OID 0)
106178 -- Dependencies: 785
106179 -- Name: COLUMN source.source_id; Type: COMMENT; Schema: public; Owner: admin
106180 --
106181
106182 COMMENT ON COLUMN source.source_id IS 'Primary key';
106183
106184
106185 --
106186 -- TOC entry 10222 (class 0 OID 0)
106187 -- Dependencies: 785
106188 -- Name: COLUMN source.source_module; Type: COMMENT; Schema: public; Owner: admin
106189 --
106190
106191 COMMENT ON COLUMN source.source_module IS 'Application module';
106192
106193
106194 --
106195 -- TOC entry 10223 (class 0 OID 0)
106196 -- Dependencies: 785
106197 -- Name: COLUMN source.source_name; Type: COMMENT; Schema: public; Owner: admin
106198 --
106199
106200 COMMENT ON COLUMN source.source_name IS 'Name';
106201
106202
106203 --
106204 -- TOC entry 10224 (class 0 OID 0)
106205 -- Dependencies: 785
106206 -- Name: COLUMN source.source_descrip; Type: COMMENT; Schema: public; Owner: admin
106207 --
106208
106209 COMMENT ON COLUMN source.source_descrip IS 'Description';
106210
106211
106212 --
106213 -- TOC entry 786 (class 1259 OID 146569877)
106214 -- Dependencies: 785 8
106215 -- Name: source_source_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106216 --
106217
106218 CREATE SEQUENCE source_source_id_seq
106219     START WITH 1
106220     INCREMENT BY 1
106221     NO MINVALUE
106222     NO MAXVALUE
106223     CACHE 1;
106224
106225
106226 ALTER TABLE public.source_source_id_seq OWNER TO admin;
106227
106228 --
106229 -- TOC entry 10226 (class 0 OID 0)
106230 -- Dependencies: 786
106231 -- Name: source_source_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106232 --
106233
106234 ALTER SEQUENCE source_source_id_seq OWNED BY source.source_id;
106235
106236
106237 --
106238 -- TOC entry 787 (class 1259 OID 146569879)
106239 -- Dependencies: 6657 8
106240 -- Name: state; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106241 --
106242
106243 CREATE TABLE state (
106244     state_id integer NOT NULL,
106245     state_name text NOT NULL,
106246     state_abbr text,
106247     state_country_id integer,
106248     CONSTRAINT state_state_name_check CHECK ((state_name <> ''::text))
106249 );
106250
106251
106252 ALTER TABLE public.state OWNER TO admin;
106253
106254 --
106255 -- TOC entry 10228 (class 0 OID 0)
106256 -- Dependencies: 787
106257 -- Name: TABLE state; Type: COMMENT; Schema: public; Owner: admin
106258 --
106259
106260 COMMENT ON TABLE state IS 'List of states, provinces, and territories associated with various countries.';
106261
106262
106263 --
106264 -- TOC entry 788 (class 1259 OID 146569886)
106265 -- Dependencies: 787 8
106266 -- Name: state_state_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106267 --
106268
106269 CREATE SEQUENCE state_state_id_seq
106270     START WITH 1
106271     INCREMENT BY 1
106272     NO MINVALUE
106273     NO MAXVALUE
106274     CACHE 1;
106275
106276
106277 ALTER TABLE public.state_state_id_seq OWNER TO admin;
106278
106279 --
106280 -- TOC entry 10230 (class 0 OID 0)
106281 -- Dependencies: 788
106282 -- Name: state_state_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106283 --
106284
106285 ALTER SEQUENCE state_state_id_seq OWNED BY state.state_id;
106286
106287
106288 --
106289 -- TOC entry 789 (class 1259 OID 146569888)
106290 -- Dependencies: 6659 8
106291 -- Name: status; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106292 --
106293
106294 CREATE TABLE status (
106295     status_id integer NOT NULL,
106296     status_type text NOT NULL,
106297     status_code character(1) NOT NULL,
106298     status_name text,
106299     status_seq integer,
106300     status_color text DEFAULT 'white'::text
106301 );
106302
106303
106304 ALTER TABLE public.status OWNER TO admin;
106305
106306 --
106307 -- TOC entry 790 (class 1259 OID 146569895)
106308 -- Dependencies: 789 8
106309 -- Name: status_status_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106310 --
106311
106312 CREATE SEQUENCE status_status_id_seq
106313     START WITH 1
106314     INCREMENT BY 1
106315     NO MINVALUE
106316     NO MAXVALUE
106317     CACHE 1;
106318
106319
106320 ALTER TABLE public.status_status_id_seq OWNER TO admin;
106321
106322 --
106323 -- TOC entry 10233 (class 0 OID 0)
106324 -- Dependencies: 790
106325 -- Name: status_status_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106326 --
106327
106328 ALTER SEQUENCE status_status_id_seq OWNED BY status.status_id;
106329
106330
106331 --
106332 -- TOC entry 791 (class 1259 OID 146569897)
106333 -- Dependencies: 6661 8
106334 -- Name: stdjrnl; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106335 --
106336
106337 CREATE TABLE stdjrnl (
106338     stdjrnl_id integer NOT NULL,
106339     stdjrnl_name text NOT NULL,
106340     stdjrnl_descrip text,
106341     stdjrnl_notes text,
106342     CONSTRAINT stdjrnl_stdjrnl_name_check CHECK ((stdjrnl_name <> ''::text))
106343 );
106344
106345
106346 ALTER TABLE public.stdjrnl OWNER TO admin;
106347
106348 --
106349 -- TOC entry 10235 (class 0 OID 0)
106350 -- Dependencies: 791
106351 -- Name: TABLE stdjrnl; Type: COMMENT; Schema: public; Owner: admin
106352 --
106353
106354 COMMENT ON TABLE stdjrnl IS 'Standard Journal information';
106355
106356
106357 --
106358 -- TOC entry 792 (class 1259 OID 146569904)
106359 -- Dependencies: 791 8
106360 -- Name: stdjrnl_stdjrnl_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106361 --
106362
106363 CREATE SEQUENCE stdjrnl_stdjrnl_id_seq
106364     START WITH 1
106365     INCREMENT BY 1
106366     NO MINVALUE
106367     NO MAXVALUE
106368     CACHE 1;
106369
106370
106371 ALTER TABLE public.stdjrnl_stdjrnl_id_seq OWNER TO admin;
106372
106373 --
106374 -- TOC entry 10237 (class 0 OID 0)
106375 -- Dependencies: 792
106376 -- Name: stdjrnl_stdjrnl_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106377 --
106378
106379 ALTER SEQUENCE stdjrnl_stdjrnl_id_seq OWNED BY stdjrnl.stdjrnl_id;
106380
106381
106382 --
106383 -- TOC entry 793 (class 1259 OID 146569906)
106384 -- Dependencies: 6663 8
106385 -- Name: stdjrnlgrp; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106386 --
106387
106388 CREATE TABLE stdjrnlgrp (
106389     stdjrnlgrp_id integer NOT NULL,
106390     stdjrnlgrp_name text NOT NULL,
106391     stdjrnlgrp_descrip text,
106392     CONSTRAINT stdjrnlgrp_stdjrnlgrp_name_check CHECK ((stdjrnlgrp_name <> ''::text))
106393 );
106394
106395
106396 ALTER TABLE public.stdjrnlgrp OWNER TO admin;
106397
106398 --
106399 -- TOC entry 10239 (class 0 OID 0)
106400 -- Dependencies: 793
106401 -- Name: TABLE stdjrnlgrp; Type: COMMENT; Schema: public; Owner: admin
106402 --
106403
106404 COMMENT ON TABLE stdjrnlgrp IS 'Standard Journal Group information';
106405
106406
106407 --
106408 -- TOC entry 794 (class 1259 OID 146569913)
106409 -- Dependencies: 793 8
106410 -- Name: stdjrnlgrp_stdjrnlgrp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106411 --
106412
106413 CREATE SEQUENCE stdjrnlgrp_stdjrnlgrp_id_seq
106414     START WITH 1
106415     INCREMENT BY 1
106416     NO MINVALUE
106417     NO MAXVALUE
106418     CACHE 1;
106419
106420
106421 ALTER TABLE public.stdjrnlgrp_stdjrnlgrp_id_seq OWNER TO admin;
106422
106423 --
106424 -- TOC entry 10241 (class 0 OID 0)
106425 -- Dependencies: 794
106426 -- Name: stdjrnlgrp_stdjrnlgrp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106427 --
106428
106429 ALTER SEQUENCE stdjrnlgrp_stdjrnlgrp_id_seq OWNED BY stdjrnlgrp.stdjrnlgrp_id;
106430
106431
106432 --
106433 -- TOC entry 795 (class 1259 OID 146569915)
106434 -- Dependencies: 8
106435 -- Name: stdjrnlgrpitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106436 --
106437
106438 CREATE TABLE stdjrnlgrpitem (
106439     stdjrnlgrpitem_id integer NOT NULL,
106440     stdjrnlgrpitem_stdjrnl_id integer,
106441     stdjrnlgrpitem_toapply integer,
106442     stdjrnlgrpitem_applied integer,
106443     stdjrnlgrpitem_effective date,
106444     stdjrnlgrpitem_expires date,
106445     stdjrnlgrpitem_stdjrnlgrp_id integer
106446 );
106447
106448
106449 ALTER TABLE public.stdjrnlgrpitem OWNER TO admin;
106450
106451 --
106452 -- TOC entry 10243 (class 0 OID 0)
106453 -- Dependencies: 795
106454 -- Name: TABLE stdjrnlgrpitem; Type: COMMENT; Schema: public; Owner: admin
106455 --
106456
106457 COMMENT ON TABLE stdjrnlgrpitem IS 'Standard Journal Group Item information';
106458
106459
106460 --
106461 -- TOC entry 796 (class 1259 OID 146569918)
106462 -- Dependencies: 795 8
106463 -- Name: stdjrnlgrpitem_stdjrnlgrpitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106464 --
106465
106466 CREATE SEQUENCE stdjrnlgrpitem_stdjrnlgrpitem_id_seq
106467     START WITH 1
106468     INCREMENT BY 1
106469     NO MINVALUE
106470     NO MAXVALUE
106471     CACHE 1;
106472
106473
106474 ALTER TABLE public.stdjrnlgrpitem_stdjrnlgrpitem_id_seq OWNER TO admin;
106475
106476 --
106477 -- TOC entry 10245 (class 0 OID 0)
106478 -- Dependencies: 796
106479 -- Name: stdjrnlgrpitem_stdjrnlgrpitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106480 --
106481
106482 ALTER SEQUENCE stdjrnlgrpitem_stdjrnlgrpitem_id_seq OWNED BY stdjrnlgrpitem.stdjrnlgrpitem_id;
106483
106484
106485 --
106486 -- TOC entry 797 (class 1259 OID 146569920)
106487 -- Dependencies: 8
106488 -- Name: stdjrnlitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106489 --
106490
106491 CREATE TABLE stdjrnlitem (
106492     stdjrnlitem_id integer NOT NULL,
106493     stdjrnlitem_stdjrnl_id integer NOT NULL,
106494     stdjrnlitem_accnt_id integer NOT NULL,
106495     stdjrnlitem_amount numeric(20,2) NOT NULL,
106496     stdjrnlitem_notes text
106497 );
106498
106499
106500 ALTER TABLE public.stdjrnlitem OWNER TO admin;
106501
106502 --
106503 -- TOC entry 10247 (class 0 OID 0)
106504 -- Dependencies: 797
106505 -- Name: TABLE stdjrnlitem; Type: COMMENT; Schema: public; Owner: admin
106506 --
106507
106508 COMMENT ON TABLE stdjrnlitem IS 'Standard Journal Item information';
106509
106510
106511 --
106512 -- TOC entry 798 (class 1259 OID 146569926)
106513 -- Dependencies: 797 8
106514 -- Name: stdjrnlitem_stdjrnlitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106515 --
106516
106517 CREATE SEQUENCE stdjrnlitem_stdjrnlitem_id_seq
106518     START WITH 1
106519     INCREMENT BY 1
106520     NO MINVALUE
106521     NO MAXVALUE
106522     CACHE 1;
106523
106524
106525 ALTER TABLE public.stdjrnlitem_stdjrnlitem_id_seq OWNER TO admin;
106526
106527 --
106528 -- TOC entry 10249 (class 0 OID 0)
106529 -- Dependencies: 798
106530 -- Name: stdjrnlitem_stdjrnlitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106531 --
106532
106533 ALTER SEQUENCE stdjrnlitem_stdjrnlitem_id_seq OWNED BY stdjrnlitem.stdjrnlitem_id;
106534
106535
106536 --
106537 -- TOC entry 799 (class 1259 OID 146569928)
106538 -- Dependencies: 6667 8
106539 -- Name: subaccnt; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106540 --
106541
106542 CREATE TABLE subaccnt (
106543     subaccnt_id integer NOT NULL,
106544     subaccnt_number text NOT NULL,
106545     subaccnt_descrip text,
106546     CONSTRAINT subaccnt_subaccnt_number_check CHECK ((subaccnt_number <> ''::text))
106547 );
106548
106549
106550 ALTER TABLE public.subaccnt OWNER TO admin;
106551
106552 --
106553 -- TOC entry 10251 (class 0 OID 0)
106554 -- Dependencies: 799
106555 -- Name: TABLE subaccnt; Type: COMMENT; Schema: public; Owner: admin
106556 --
106557
106558 COMMENT ON TABLE subaccnt IS 'Subaccount information';
106559
106560
106561 --
106562 -- TOC entry 800 (class 1259 OID 146569935)
106563 -- Dependencies: 799 8
106564 -- Name: subaccnt_subaccnt_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106565 --
106566
106567 CREATE SEQUENCE subaccnt_subaccnt_id_seq
106568     START WITH 1
106569     INCREMENT BY 1
106570     NO MINVALUE
106571     NO MAXVALUE
106572     CACHE 1;
106573
106574
106575 ALTER TABLE public.subaccnt_subaccnt_id_seq OWNER TO admin;
106576
106577 --
106578 -- TOC entry 10253 (class 0 OID 0)
106579 -- Dependencies: 800
106580 -- Name: subaccnt_subaccnt_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106581 --
106582
106583 ALTER SEQUENCE subaccnt_subaccnt_id_seq OWNED BY subaccnt.subaccnt_id;
106584
106585
106586 --
106587 -- TOC entry 801 (class 1259 OID 146569937)
106588 -- Dependencies: 8
106589 -- Name: subaccnttype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106590 --
106591
106592 CREATE TABLE subaccnttype (
106593     subaccnttype_id integer NOT NULL,
106594     subaccnttype_accnt_type character(1) NOT NULL,
106595     subaccnttype_code text NOT NULL,
106596     subaccnttype_descrip text
106597 );
106598
106599
106600 ALTER TABLE public.subaccnttype OWNER TO admin;
106601
106602 --
106603 -- TOC entry 10255 (class 0 OID 0)
106604 -- Dependencies: 801
106605 -- Name: TABLE subaccnttype; Type: COMMENT; Schema: public; Owner: admin
106606 --
106607
106608 COMMENT ON TABLE subaccnttype IS 'User defined Sub Account Types.';
106609
106610
106611 --
106612 -- TOC entry 802 (class 1259 OID 146569943)
106613 -- Dependencies: 801 8
106614 -- Name: subaccnttype_subaccnttype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106615 --
106616
106617 CREATE SEQUENCE subaccnttype_subaccnttype_id_seq
106618     START WITH 1
106619     INCREMENT BY 1
106620     NO MINVALUE
106621     NO MAXVALUE
106622     CACHE 1;
106623
106624
106625 ALTER TABLE public.subaccnttype_subaccnttype_id_seq OWNER TO admin;
106626
106627 --
106628 -- TOC entry 10257 (class 0 OID 0)
106629 -- Dependencies: 802
106630 -- Name: subaccnttype_subaccnttype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106631 --
106632
106633 ALTER SEQUENCE subaccnttype_subaccnttype_id_seq OWNED BY subaccnttype.subaccnttype_id;
106634
106635
106636 --
106637 -- TOC entry 803 (class 1259 OID 146569945)
106638 -- Dependencies: 8
106639 -- Name: tax_tax_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106640 --
106641
106642 CREATE SEQUENCE tax_tax_id_seq
106643     START WITH 1
106644     INCREMENT BY 1
106645     NO MINVALUE
106646     NO MAXVALUE
106647     CACHE 1;
106648
106649
106650 ALTER TABLE public.tax_tax_id_seq OWNER TO admin;
106651
106652 --
106653 -- TOC entry 804 (class 1259 OID 146569947)
106654 -- Dependencies: 8
106655 -- Name: taxass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106656 --
106657
106658 CREATE TABLE taxass (
106659     taxass_id integer NOT NULL,
106660     taxass_taxzone_id integer,
106661     taxass_taxtype_id integer,
106662     taxass_tax_id integer NOT NULL
106663 );
106664
106665
106666 ALTER TABLE public.taxass OWNER TO admin;
106667
106668 --
106669 -- TOC entry 10260 (class 0 OID 0)
106670 -- Dependencies: 804
106671 -- Name: TABLE taxass; Type: COMMENT; Schema: public; Owner: admin
106672 --
106673
106674 COMMENT ON TABLE taxass IS 'The tax assignment table associates different tax zones and tax types to a given set of tax codes.';
106675
106676
106677 --
106678 -- TOC entry 10261 (class 0 OID 0)
106679 -- Dependencies: 804
106680 -- Name: COLUMN taxass.taxass_taxzone_id; Type: COMMENT; Schema: public; Owner: admin
106681 --
106682
106683 COMMENT ON COLUMN taxass.taxass_taxzone_id IS 'The id of the tax zone. If NULL any tax zone will apply.';
106684
106685
106686 --
106687 -- TOC entry 10262 (class 0 OID 0)
106688 -- Dependencies: 804
106689 -- Name: COLUMN taxass.taxass_taxtype_id; Type: COMMENT; Schema: public; Owner: admin
106690 --
106691
106692 COMMENT ON COLUMN taxass.taxass_taxtype_id IS 'The id of the tax type. If NULL any tax type will apply.';
106693
106694
106695 --
106696 -- TOC entry 10263 (class 0 OID 0)
106697 -- Dependencies: 804
106698 -- Name: COLUMN taxass.taxass_tax_id; Type: COMMENT; Schema: public; Owner: admin
106699 --
106700
106701 COMMENT ON COLUMN taxass.taxass_tax_id IS 'The id of the tax code.';
106702
106703
106704 --
106705 -- TOC entry 805 (class 1259 OID 146569950)
106706 -- Dependencies: 804 8
106707 -- Name: taxass_taxass_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106708 --
106709
106710 CREATE SEQUENCE taxass_taxass_id_seq
106711     START WITH 1
106712     INCREMENT BY 1
106713     NO MINVALUE
106714     NO MAXVALUE
106715     CACHE 1;
106716
106717
106718 ALTER TABLE public.taxass_taxass_id_seq OWNER TO admin;
106719
106720 --
106721 -- TOC entry 10265 (class 0 OID 0)
106722 -- Dependencies: 805
106723 -- Name: taxass_taxass_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106724 --
106725
106726 ALTER SEQUENCE taxass_taxass_id_seq OWNED BY taxass.taxass_id;
106727
106728
106729 --
106730 -- TOC entry 806 (class 1259 OID 146569952)
106731 -- Dependencies: 284 8
106732 -- Name: taxauth_taxauth_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106733 --
106734
106735 CREATE SEQUENCE taxauth_taxauth_id_seq
106736     START WITH 1
106737     INCREMENT BY 1
106738     NO MINVALUE
106739     NO MAXVALUE
106740     CACHE 1;
106741
106742
106743 ALTER TABLE public.taxauth_taxauth_id_seq OWNER TO admin;
106744
106745 --
106746 -- TOC entry 10267 (class 0 OID 0)
106747 -- Dependencies: 806
106748 -- Name: taxauth_taxauth_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106749 --
106750
106751 ALTER SEQUENCE taxauth_taxauth_id_seq OWNED BY taxauth.taxauth_id;
106752
106753
106754 --
106755 -- TOC entry 807 (class 1259 OID 146569954)
106756 -- Dependencies: 6671 8
106757 -- Name: taxclass; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106758 --
106759
106760 CREATE TABLE taxclass (
106761     taxclass_id integer NOT NULL,
106762     taxclass_code text NOT NULL,
106763     taxclass_descrip text,
106764     taxclass_sequence integer,
106765     CONSTRAINT taxclass_taxclass_code_check CHECK ((taxclass_code <> ''::text))
106766 );
106767
106768
106769 ALTER TABLE public.taxclass OWNER TO admin;
106770
106771 --
106772 -- TOC entry 10269 (class 0 OID 0)
106773 -- Dependencies: 807
106774 -- Name: TABLE taxclass; Type: COMMENT; Schema: public; Owner: admin
106775 --
106776
106777 COMMENT ON TABLE taxclass IS 'Tax class information';
106778
106779
106780 --
106781 -- TOC entry 10270 (class 0 OID 0)
106782 -- Dependencies: 807
106783 -- Name: COLUMN taxclass.taxclass_id; Type: COMMENT; Schema: public; Owner: admin
106784 --
106785
106786 COMMENT ON COLUMN taxclass.taxclass_id IS 'Primary key';
106787
106788
106789 --
106790 -- TOC entry 10271 (class 0 OID 0)
106791 -- Dependencies: 807
106792 -- Name: COLUMN taxclass.taxclass_code; Type: COMMENT; Schema: public; Owner: admin
106793 --
106794
106795 COMMENT ON COLUMN taxclass.taxclass_code IS 'Code';
106796
106797
106798 --
106799 -- TOC entry 10272 (class 0 OID 0)
106800 -- Dependencies: 807
106801 -- Name: COLUMN taxclass.taxclass_descrip; Type: COMMENT; Schema: public; Owner: admin
106802 --
106803
106804 COMMENT ON COLUMN taxclass.taxclass_descrip IS 'Description';
106805
106806
106807 --
106808 -- TOC entry 10273 (class 0 OID 0)
106809 -- Dependencies: 807
106810 -- Name: COLUMN taxclass.taxclass_sequence; Type: COMMENT; Schema: public; Owner: admin
106811 --
106812
106813 COMMENT ON COLUMN taxclass.taxclass_sequence IS 'Group sequence';
106814
106815
106816 --
106817 -- TOC entry 808 (class 1259 OID 146569961)
106818 -- Dependencies: 807 8
106819 -- Name: taxclass_taxclass_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106820 --
106821
106822 CREATE SEQUENCE taxclass_taxclass_id_seq
106823     START WITH 1
106824     INCREMENT BY 1
106825     NO MINVALUE
106826     NO MAXVALUE
106827     CACHE 1;
106828
106829
106830 ALTER TABLE public.taxclass_taxclass_id_seq OWNER TO admin;
106831
106832 --
106833 -- TOC entry 10275 (class 0 OID 0)
106834 -- Dependencies: 808
106835 -- Name: taxclass_taxclass_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106836 --
106837
106838 ALTER SEQUENCE taxclass_taxclass_id_seq OWNED BY taxclass.taxclass_id;
106839
106840
106841 --
106842 -- TOC entry 378 (class 1259 OID 146568112)
106843 -- Dependencies: 377 8
106844 -- Name: taxhist_taxhist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106845 --
106846
106847 CREATE SEQUENCE taxhist_taxhist_id_seq
106848     START WITH 1
106849     INCREMENT BY 1
106850     NO MINVALUE
106851     NO MAXVALUE
106852     CACHE 1;
106853
106854
106855 ALTER TABLE public.taxhist_taxhist_id_seq OWNER TO admin;
106856
106857 --
106858 -- TOC entry 10277 (class 0 OID 0)
106859 -- Dependencies: 378
106860 -- Name: taxhist_taxhist_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106861 --
106862
106863 ALTER SEQUENCE taxhist_taxhist_id_seq OWNED BY taxhist.taxhist_id;
106864
106865
106866 --
106867 -- TOC entry 809 (class 1259 OID 146569963)
106868 -- Dependencies: 8
106869 -- Name: taxrate; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
106870 --
106871
106872 CREATE TABLE taxrate (
106873     taxrate_id integer NOT NULL,
106874     taxrate_tax_id integer NOT NULL,
106875     taxrate_percent numeric(10,6) NOT NULL,
106876     taxrate_curr_id integer,
106877     taxrate_amount numeric(16,2) NOT NULL,
106878     taxrate_effective date,
106879     taxrate_expires date
106880 );
106881
106882
106883 ALTER TABLE public.taxrate OWNER TO admin;
106884
106885 --
106886 -- TOC entry 10279 (class 0 OID 0)
106887 -- Dependencies: 809
106888 -- Name: TABLE taxrate; Type: COMMENT; Schema: public; Owner: admin
106889 --
106890
106891 COMMENT ON TABLE taxrate IS 'Tax rates.';
106892
106893
106894 --
106895 -- TOC entry 10280 (class 0 OID 0)
106896 -- Dependencies: 809
106897 -- Name: COLUMN taxrate.taxrate_id; Type: COMMENT; Schema: public; Owner: admin
106898 --
106899
106900 COMMENT ON COLUMN taxrate.taxrate_id IS 'Primary key.';
106901
106902
106903 --
106904 -- TOC entry 10281 (class 0 OID 0)
106905 -- Dependencies: 809
106906 -- Name: COLUMN taxrate.taxrate_tax_id; Type: COMMENT; Schema: public; Owner: admin
106907 --
106908
106909 COMMENT ON COLUMN taxrate.taxrate_tax_id IS 'The id of the parent tax code.';
106910
106911
106912 --
106913 -- TOC entry 10282 (class 0 OID 0)
106914 -- Dependencies: 809
106915 -- Name: COLUMN taxrate.taxrate_percent; Type: COMMENT; Schema: public; Owner: admin
106916 --
106917
106918 COMMENT ON COLUMN taxrate.taxrate_percent IS 'Tax rate percentage.';
106919
106920
106921 --
106922 -- TOC entry 10283 (class 0 OID 0)
106923 -- Dependencies: 809
106924 -- Name: COLUMN taxrate.taxrate_curr_id; Type: COMMENT; Schema: public; Owner: admin
106925 --
106926
106927 COMMENT ON COLUMN taxrate.taxrate_curr_id IS 'The currency id of the flat rate amount.';
106928
106929
106930 --
106931 -- TOC entry 10284 (class 0 OID 0)
106932 -- Dependencies: 809
106933 -- Name: COLUMN taxrate.taxrate_amount; Type: COMMENT; Schema: public; Owner: admin
106934 --
106935
106936 COMMENT ON COLUMN taxrate.taxrate_amount IS 'Flat tax rate amount.';
106937
106938
106939 --
106940 -- TOC entry 10285 (class 0 OID 0)
106941 -- Dependencies: 809
106942 -- Name: COLUMN taxrate.taxrate_effective; Type: COMMENT; Schema: public; Owner: admin
106943 --
106944
106945 COMMENT ON COLUMN taxrate.taxrate_effective IS 'The effective date of the tax rate.  NULL value means always.';
106946
106947
106948 --
106949 -- TOC entry 10286 (class 0 OID 0)
106950 -- Dependencies: 809
106951 -- Name: COLUMN taxrate.taxrate_expires; Type: COMMENT; Schema: public; Owner: admin
106952 --
106953
106954 COMMENT ON COLUMN taxrate.taxrate_expires IS 'The expire date of the tax rate.  NULL value means never.';
106955
106956
106957 --
106958 -- TOC entry 810 (class 1259 OID 146569966)
106959 -- Dependencies: 809 8
106960 -- Name: taxrate_taxrate_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106961 --
106962
106963 CREATE SEQUENCE taxrate_taxrate_id_seq
106964     START WITH 1
106965     INCREMENT BY 1
106966     NO MINVALUE
106967     NO MAXVALUE
106968     CACHE 1;
106969
106970
106971 ALTER TABLE public.taxrate_taxrate_id_seq OWNER TO admin;
106972
106973 --
106974 -- TOC entry 10288 (class 0 OID 0)
106975 -- Dependencies: 810
106976 -- Name: taxrate_taxrate_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
106977 --
106978
106979 ALTER SEQUENCE taxrate_taxrate_id_seq OWNED BY taxrate.taxrate_id;
106980
106981
106982 --
106983 -- TOC entry 811 (class 1259 OID 146569968)
106984 -- Dependencies: 285 8
106985 -- Name: taxreg_taxreg_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
106986 --
106987
106988 CREATE SEQUENCE taxreg_taxreg_id_seq
106989     START WITH 1
106990     INCREMENT BY 1
106991     NO MINVALUE
106992     NO MAXVALUE
106993     CACHE 1;
106994
106995
106996 ALTER TABLE public.taxreg_taxreg_id_seq OWNER TO admin;
106997
106998 --
106999 -- TOC entry 10290 (class 0 OID 0)
107000 -- Dependencies: 811
107001 -- Name: taxreg_taxreg_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107002 --
107003
107004 ALTER SEQUENCE taxreg_taxreg_id_seq OWNED BY taxreg.taxreg_id;
107005
107006
107007 --
107008 -- TOC entry 812 (class 1259 OID 146569970)
107009 -- Dependencies: 199 8
107010 -- Name: taxtype_taxtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107011 --
107012
107013 CREATE SEQUENCE taxtype_taxtype_id_seq
107014     START WITH 1
107015     INCREMENT BY 1
107016     NO MINVALUE
107017     NO MAXVALUE
107018     CACHE 1;
107019
107020
107021 ALTER TABLE public.taxtype_taxtype_id_seq OWNER TO admin;
107022
107023 --
107024 -- TOC entry 10292 (class 0 OID 0)
107025 -- Dependencies: 812
107026 -- Name: taxtype_taxtype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107027 --
107028
107029 ALTER SEQUENCE taxtype_taxtype_id_seq OWNED BY taxtype.taxtype_id;
107030
107031
107032 --
107033 -- TOC entry 813 (class 1259 OID 146569972)
107034 -- Dependencies: 220 8
107035 -- Name: taxzone_taxzone_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107036 --
107037
107038 CREATE SEQUENCE taxzone_taxzone_id_seq
107039     START WITH 1
107040     INCREMENT BY 1
107041     NO MINVALUE
107042     NO MAXVALUE
107043     CACHE 1;
107044
107045
107046 ALTER TABLE public.taxzone_taxzone_id_seq OWNER TO admin;
107047
107048 --
107049 -- TOC entry 10294 (class 0 OID 0)
107050 -- Dependencies: 813
107051 -- Name: taxzone_taxzone_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107052 --
107053
107054 ALTER SEQUENCE taxzone_taxzone_id_seq OWNED BY taxzone.taxzone_id;
107055
107056
107057 --
107058 -- TOC entry 814 (class 1259 OID 146569974)
107059 -- Dependencies: 8
107060 -- Name: terms_terms_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107061 --
107062
107063 CREATE SEQUENCE terms_terms_id_seq
107064     START WITH 1
107065     INCREMENT BY 1
107066     NO MINVALUE
107067     MAXVALUE 2147483647
107068     CACHE 1;
107069
107070
107071 ALTER TABLE public.terms_terms_id_seq OWNER TO admin;
107072
107073 --
107074 -- TOC entry 815 (class 1259 OID 146569976)
107075 -- Dependencies: 233 8
107076 -- Name: todoitem_todoitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107077 --
107078
107079 CREATE SEQUENCE todoitem_todoitem_id_seq
107080     START WITH 1
107081     INCREMENT BY 1
107082     NO MINVALUE
107083     NO MAXVALUE
107084     CACHE 1;
107085
107086
107087 ALTER TABLE public.todoitem_todoitem_id_seq OWNER TO admin;
107088
107089 --
107090 -- TOC entry 10297 (class 0 OID 0)
107091 -- Dependencies: 815
107092 -- Name: todoitem_todoitem_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107093 --
107094
107095 ALTER SEQUENCE todoitem_todoitem_id_seq OWNED BY todoitem.todoitem_id;
107096
107097
107098 --
107099 -- TOC entry 816 (class 1259 OID 146569978)
107100 -- Dependencies: 8
107101 -- Name: trgthist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107102 --
107103
107104 CREATE TABLE trgthist (
107105     trgthist_src_cntct_id integer NOT NULL,
107106     trgthist_trgt_cntct_id integer NOT NULL,
107107     trgthist_col text NOT NULL,
107108     trgthist_value text NOT NULL
107109 );
107110
107111
107112 ALTER TABLE public.trgthist OWNER TO admin;
107113
107114 --
107115 -- TOC entry 817 (class 1259 OID 146569984)
107116 -- Dependencies: 6674 8
107117 -- Name: trialbal; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107118 --
107119
107120 CREATE TABLE trialbal (
107121     trialbal_id integer NOT NULL,
107122     trialbal_period_id integer,
107123     trialbal_accnt_id integer,
107124     trialbal_beginning numeric(20,2),
107125     trialbal_ending numeric(20,2),
107126     trialbal_credits numeric(20,2),
107127     trialbal_debits numeric(20,2),
107128     trialbal_dirty boolean,
107129     trialbal_yearend numeric(20,2) DEFAULT 0.00 NOT NULL
107130 );
107131
107132
107133 ALTER TABLE public.trialbal OWNER TO admin;
107134
107135 --
107136 -- TOC entry 10300 (class 0 OID 0)
107137 -- Dependencies: 817
107138 -- Name: TABLE trialbal; Type: COMMENT; Schema: public; Owner: admin
107139 --
107140
107141 COMMENT ON TABLE trialbal IS 'Trial Balance information';
107142
107143
107144 --
107145 -- TOC entry 818 (class 1259 OID 146569988)
107146 -- Dependencies: 817 8
107147 -- Name: trialbal_trialbal_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107148 --
107149
107150 CREATE SEQUENCE trialbal_trialbal_id_seq
107151     START WITH 1
107152     INCREMENT BY 1
107153     NO MINVALUE
107154     NO MAXVALUE
107155     CACHE 1;
107156
107157
107158 ALTER TABLE public.trialbal_trialbal_id_seq OWNER TO admin;
107159
107160 --
107161 -- TOC entry 10302 (class 0 OID 0)
107162 -- Dependencies: 818
107163 -- Name: trialbal_trialbal_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107164 --
107165
107166 ALTER SEQUENCE trialbal_trialbal_id_seq OWNED BY trialbal.trialbal_id;
107167
107168
107169 --
107170 -- TOC entry 819 (class 1259 OID 146569990)
107171 -- Dependencies: 200 8
107172 -- Name: uom_uom_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107173 --
107174
107175 CREATE SEQUENCE uom_uom_id_seq
107176     START WITH 1
107177     INCREMENT BY 1
107178     NO MINVALUE
107179     NO MAXVALUE
107180     CACHE 1;
107181
107182
107183 ALTER TABLE public.uom_uom_id_seq OWNER TO admin;
107184
107185 --
107186 -- TOC entry 10304 (class 0 OID 0)
107187 -- Dependencies: 819
107188 -- Name: uom_uom_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107189 --
107190
107191 ALTER SEQUENCE uom_uom_id_seq OWNED BY uom.uom_id;
107192
107193
107194 --
107195 -- TOC entry 820 (class 1259 OID 146569992)
107196 -- Dependencies: 6676 8
107197 -- Name: uomconv; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107198 --
107199
107200 CREATE TABLE uomconv (
107201     uomconv_id integer NOT NULL,
107202     uomconv_from_uom_id integer NOT NULL,
107203     uomconv_from_value numeric(20,10) NOT NULL,
107204     uomconv_to_uom_id integer NOT NULL,
107205     uomconv_to_value numeric(20,10) NOT NULL,
107206     uomconv_fractional boolean DEFAULT false NOT NULL
107207 );
107208
107209
107210 ALTER TABLE public.uomconv OWNER TO admin;
107211
107212 --
107213 -- TOC entry 10306 (class 0 OID 0)
107214 -- Dependencies: 820
107215 -- Name: TABLE uomconv; Type: COMMENT; Schema: public; Owner: admin
107216 --
107217
107218 COMMENT ON TABLE uomconv IS 'UOM conversion information. From Unit to To Unit with a value per ratio.';
107219
107220
107221 --
107222 -- TOC entry 821 (class 1259 OID 146569996)
107223 -- Dependencies: 820 8
107224 -- Name: uomconv_uomconv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107225 --
107226
107227 CREATE SEQUENCE uomconv_uomconv_id_seq
107228     START WITH 1
107229     INCREMENT BY 1
107230     NO MINVALUE
107231     NO MAXVALUE
107232     CACHE 1;
107233
107234
107235 ALTER TABLE public.uomconv_uomconv_id_seq OWNER TO admin;
107236
107237 --
107238 -- TOC entry 10308 (class 0 OID 0)
107239 -- Dependencies: 821
107240 -- Name: uomconv_uomconv_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107241 --
107242
107243 ALTER SEQUENCE uomconv_uomconv_id_seq OWNED BY uomconv.uomconv_id;
107244
107245
107246 --
107247 -- TOC entry 822 (class 1259 OID 146569998)
107248 -- Dependencies: 6678 6679 8
107249 -- Name: uomtype; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107250 --
107251
107252 CREATE TABLE uomtype (
107253     uomtype_id integer NOT NULL,
107254     uomtype_name text NOT NULL,
107255     uomtype_descrip text,
107256     uomtype_multiple boolean DEFAULT false NOT NULL,
107257     CONSTRAINT uomtype_uomtype_name_check CHECK ((uomtype_name <> ''::text))
107258 );
107259
107260
107261 ALTER TABLE public.uomtype OWNER TO admin;
107262
107263 --
107264 -- TOC entry 10310 (class 0 OID 0)
107265 -- Dependencies: 822
107266 -- Name: TABLE uomtype; Type: COMMENT; Schema: public; Owner: admin
107267 --
107268
107269 COMMENT ON TABLE uomtype IS 'UOM Type values.';
107270
107271
107272 --
107273 -- TOC entry 823 (class 1259 OID 146570006)
107274 -- Dependencies: 822 8
107275 -- Name: uomtype_uomtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107276 --
107277
107278 CREATE SEQUENCE uomtype_uomtype_id_seq
107279     START WITH 1
107280     INCREMENT BY 1
107281     NO MINVALUE
107282     NO MAXVALUE
107283     CACHE 1;
107284
107285
107286 ALTER TABLE public.uomtype_uomtype_id_seq OWNER TO admin;
107287
107288 --
107289 -- TOC entry 10312 (class 0 OID 0)
107290 -- Dependencies: 823
107291 -- Name: uomtype_uomtype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107292 --
107293
107294 ALTER SEQUENCE uomtype_uomtype_id_seq OWNED BY uomtype.uomtype_id;
107295
107296
107297 --
107298 -- TOC entry 824 (class 1259 OID 146570008)
107299 -- Dependencies: 244 8
107300 -- Name: urlinfo_url_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107301 --
107302
107303 CREATE SEQUENCE urlinfo_url_id_seq
107304     START WITH 1
107305     INCREMENT BY 1
107306     NO MINVALUE
107307     NO MAXVALUE
107308     CACHE 1;
107309
107310
107311 ALTER TABLE public.urlinfo_url_id_seq OWNER TO admin;
107312
107313 --
107314 -- TOC entry 10314 (class 0 OID 0)
107315 -- Dependencies: 824
107316 -- Name: urlinfo_url_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107317 --
107318
107319 ALTER SEQUENCE urlinfo_url_id_seq OWNED BY urlinfo.url_id;
107320
107321
107322 --
107323 -- TOC entry 825 (class 1259 OID 146570010)
107324 -- Dependencies: 6680 8
107325 -- Name: usrpref; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107326 --
107327
107328 CREATE TABLE usrpref (
107329     usrpref_id integer DEFAULT nextval(('usrpref_usrpref_id_seq'::text)::regclass) NOT NULL,
107330     usrpref_name text,
107331     usrpref_value text,
107332     usrpref_username text
107333 );
107334
107335
107336 ALTER TABLE public.usrpref OWNER TO admin;
107337
107338 --
107339 -- TOC entry 10316 (class 0 OID 0)
107340 -- Dependencies: 825
107341 -- Name: TABLE usrpref; Type: COMMENT; Schema: public; Owner: admin
107342 --
107343
107344 COMMENT ON TABLE usrpref IS 'User Preferences information';
107345
107346
107347 --
107348 -- TOC entry 826 (class 1259 OID 146570017)
107349 -- Dependencies: 8593 8
107350 -- Name: usr; Type: VIEW; Schema: public; Owner: admin
107351 --
107352
107353 CREATE VIEW usr AS
107354     SELECT (pg_user.usesysid)::integer AS usr_id, (pg_user.usename)::text AS usr_username, COALESCE((SELECT usrpref.usrpref_value FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'propername'::text))), ''::text) AS usr_propername, NULL::text AS usr_passwd, COALESCE((SELECT (usrpref.usrpref_value)::integer AS usrpref_value FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'locale_id'::text))), COALESCE((SELECT locale.locale_id FROM locale WHERE (lower(locale.locale_code) = 'default'::text) LIMIT 1), (SELECT locale.locale_id FROM locale ORDER BY locale.locale_id LIMIT 1))) AS usr_locale_id, COALESCE((SELECT usrpref.usrpref_value FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'initials'::text))), ''::text) AS usr_initials, COALESCE((SELECT CASE WHEN (usrpref.usrpref_value = 't'::text) THEN true ELSE false END AS "case" FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'agent'::text))), false) AS usr_agent, COALESCE((SELECT CASE WHEN (usrpref.usrpref_value = 't'::text) THEN true ELSE false END AS "case" FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'active'::text))), usercanlogin((pg_user.usename)::text)) AS usr_active, COALESCE((SELECT usrpref.usrpref_value FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'email'::text))), ''::text) AS usr_email, COALESCE((SELECT usrpref.usrpref_value FROM usrpref WHERE ((usrpref.usrpref_username = (pg_user.usename)::text) AND (usrpref.usrpref_name = 'window'::text))), ''::text) AS usr_window FROM pg_user;
107355
107356
107357 ALTER TABLE public.usr OWNER TO admin;
107358
107359 --
107360 -- TOC entry 827 (class 1259 OID 146570022)
107361 -- Dependencies: 6681 8
107362 -- Name: usr_bak; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107363 --
107364
107365 CREATE TABLE usr_bak (
107366     usr_id integer DEFAULT nextval(('usr_usr_id_seq'::text)::regclass) NOT NULL,
107367     usr_username text NOT NULL,
107368     usr_propername text,
107369     usr_passwd text,
107370     usr_locale_id integer NOT NULL,
107371     usr_initials text,
107372     usr_agent boolean NOT NULL,
107373     usr_active boolean NOT NULL,
107374     usr_email text,
107375     usr_window text
107376 );
107377
107378
107379 ALTER TABLE public.usr_bak OWNER TO admin;
107380
107381 --
107382 -- TOC entry 10319 (class 0 OID 0)
107383 -- Dependencies: 827
107384 -- Name: TABLE usr_bak; Type: COMMENT; Schema: public; Owner: admin
107385 --
107386
107387 COMMENT ON TABLE usr_bak IS 'User information';
107388
107389
107390 --
107391 -- TOC entry 828 (class 1259 OID 146570029)
107392 -- Dependencies: 8
107393 -- Name: usr_usr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107394 --
107395
107396 CREATE SEQUENCE usr_usr_id_seq
107397     START WITH 1
107398     INCREMENT BY 1
107399     NO MINVALUE
107400     MAXVALUE 2147483647
107401     CACHE 1;
107402
107403
107404 ALTER TABLE public.usr_usr_id_seq OWNER TO admin;
107405
107406 --
107407 -- TOC entry 829 (class 1259 OID 146570031)
107408 -- Dependencies: 732 8
107409 -- Name: usrgrp_usrgrp_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107410 --
107411
107412 CREATE SEQUENCE usrgrp_usrgrp_id_seq
107413     START WITH 1
107414     INCREMENT BY 1
107415     NO MINVALUE
107416     NO MAXVALUE
107417     CACHE 1;
107418
107419
107420 ALTER TABLE public.usrgrp_usrgrp_id_seq OWNER TO admin;
107421
107422 --
107423 -- TOC entry 10322 (class 0 OID 0)
107424 -- Dependencies: 829
107425 -- Name: usrgrp_usrgrp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107426 --
107427
107428 ALTER SEQUENCE usrgrp_usrgrp_id_seq OWNED BY usrgrp.usrgrp_id;
107429
107430
107431 --
107432 -- TOC entry 830 (class 1259 OID 146570033)
107433 -- Dependencies: 8
107434 -- Name: usrpref_usrpref_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107435 --
107436
107437 CREATE SEQUENCE usrpref_usrpref_id_seq
107438     START WITH 1
107439     INCREMENT BY 1
107440     NO MINVALUE
107441     MAXVALUE 2147483647
107442     CACHE 1;
107443
107444
107445 ALTER TABLE public.usrpref_usrpref_id_seq OWNER TO admin;
107446
107447 --
107448 -- TOC entry 831 (class 1259 OID 146570035)
107449 -- Dependencies: 8
107450 -- Name: usrpriv_usrpriv_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107451 --
107452
107453 CREATE SEQUENCE usrpriv_usrpriv_id_seq
107454     START WITH 1
107455     INCREMENT BY 1
107456     NO MINVALUE
107457     MAXVALUE 2147483647
107458     CACHE 1;
107459
107460
107461 ALTER TABLE public.usrpriv_usrpriv_id_seq OWNER TO admin;
107462
107463 --
107464 -- TOC entry 832 (class 1259 OID 146570037)
107465 -- Dependencies: 8594 8
107466 -- Name: vend; Type: VIEW; Schema: public; Owner: admin
107467 --
107468
107469 CREATE VIEW vend AS
107470     SELECT vendinfo.vend_id, vendinfo.vend_name, m.addr_line1 AS vend_address1, m.addr_line2 AS vend_address2, m.addr_line3 AS vend_address3, m.addr_city AS vend_city, m.addr_state AS vend_state, m.addr_postalcode AS vend_zip, btrim(((c1.cntct_first_name || ' '::text) || c1.cntct_last_name)) AS vend_contact1, c1.cntct_phone AS vend_phone1, btrim(((c2.cntct_first_name || ' '::text) || c2.cntct_last_name)) AS vend_contact2, c2.cntct_phone AS vend_phone2, vendinfo.vend_lastpurchdate, vendinfo.vend_active, vendinfo.vend_po, vendinfo.vend_comments, vendinfo.vend_pocomments, vendinfo.vend_number, c1.cntct_fax AS vend_fax1, c2.cntct_fax AS vend_fax2, c1.cntct_email AS vend_email1, c2.cntct_email AS vend_email2, vendinfo.vend_1099, vendinfo.vend_exported, vendinfo.vend_fobsource, vendinfo.vend_fob, vendinfo.vend_terms_id, vendinfo.vend_shipvia, vendinfo.vend_vendtype_id, vendinfo.vend_qualified, vendinfo.vend_ediemail, vendinfo.vend_ediemailbody, vendinfo.vend_edisubject, vendinfo.vend_edifilename, vendinfo.vend_accntnum, vendinfo.vend_emailpodelivery, vendinfo.vend_restrictpurch, vendinfo.vend_edicc, m.addr_country AS vend_country, vendinfo.vend_curr_id, vendinfo.vend_taxzone_id FROM (((vendinfo LEFT JOIN cntct c1 ON ((vendinfo.vend_cntct1_id = c1.cntct_id))) LEFT JOIN addr m ON ((vendinfo.vend_addr_id = m.addr_id))) LEFT JOIN cntct c2 ON ((vendinfo.vend_cntct2_id = c2.cntct_id)));
107471
107472
107473 ALTER TABLE public.vend OWNER TO admin;
107474
107475 --
107476 -- TOC entry 833 (class 1259 OID 146570042)
107477 -- Dependencies: 8
107478 -- Name: vend_vend_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107479 --
107480
107481 CREATE SEQUENCE vend_vend_id_seq
107482     START WITH 1
107483     INCREMENT BY 1
107484     NO MINVALUE
107485     MAXVALUE 2147483647
107486     CACHE 1;
107487
107488
107489 ALTER TABLE public.vend_vend_id_seq OWNER TO admin;
107490
107491 --
107492 -- TOC entry 834 (class 1259 OID 146570044)
107493 -- Dependencies: 8595 8
107494 -- Name: vendaddr; Type: VIEW; Schema: public; Owner: admin
107495 --
107496
107497 CREATE VIEW vendaddr AS
107498     SELECT vendaddrinfo.vendaddr_id, vendaddrinfo.vendaddr_vend_id, vendaddrinfo.vendaddr_code, vendaddrinfo.vendaddr_name, m.addr_line1 AS vendaddr_address1, m.addr_line2 AS vendaddr_address2, m.addr_line3 AS vendaddr_address3, btrim(((c1.cntct_first_name || ' '::text) || c1.cntct_last_name)) AS vendaddr_contact1, c1.cntct_phone AS vendaddr_phone1, c1.cntct_fax AS vendaddr_fax1, m.addr_city AS vendaddr_city, m.addr_state AS vendaddr_state, m.addr_postalcode AS vendaddr_zipcode, m.addr_country AS vendaddr_country FROM ((vendaddrinfo LEFT JOIN cntct c1 ON ((vendaddrinfo.vendaddr_cntct_id = c1.cntct_id))) LEFT JOIN addr m ON ((vendaddrinfo.vendaddr_addr_id = m.addr_id)));
107499
107500
107501 ALTER TABLE public.vendaddr OWNER TO admin;
107502
107503 --
107504 -- TOC entry 835 (class 1259 OID 146570049)
107505 -- Dependencies: 8
107506 -- Name: vendaddr_vendaddr_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107507 --
107508
107509 CREATE SEQUENCE vendaddr_vendaddr_id_seq
107510     START WITH 1
107511     INCREMENT BY 1
107512     NO MINVALUE
107513     MAXVALUE 2147483647
107514     CACHE 1;
107515
107516
107517 ALTER TABLE public.vendaddr_vendaddr_id_seq OWNER TO admin;
107518
107519 --
107520 -- TOC entry 836 (class 1259 OID 146570051)
107521 -- Dependencies: 393 8
107522 -- Name: vendtype_vendtype_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107523 --
107524
107525 CREATE SEQUENCE vendtype_vendtype_id_seq
107526     START WITH 1
107527     INCREMENT BY 1
107528     NO MINVALUE
107529     NO MAXVALUE
107530     CACHE 1;
107531
107532
107533 ALTER TABLE public.vendtype_vendtype_id_seq OWNER TO admin;
107534
107535 --
107536 -- TOC entry 10330 (class 0 OID 0)
107537 -- Dependencies: 836
107538 -- Name: vendtype_vendtype_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107539 --
107540
107541 ALTER SEQUENCE vendtype_vendtype_id_seq OWNED BY vendtype.vendtype_id;
107542
107543
107544 --
107545 -- TOC entry 837 (class 1259 OID 146570053)
107546 -- Dependencies: 6682 6683 6684 6685 8
107547 -- Name: vodist; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107548 --
107549
107550 CREATE TABLE vodist (
107551     vodist_id integer DEFAULT nextval(('"vodist_vodist_id_seq"'::text)::regclass) NOT NULL,
107552     vodist_poitem_id integer,
107553     vodist_vohead_id integer,
107554     vodist_costelem_id integer,
107555     vodist_accnt_id integer,
107556     vodist_amount numeric(18,6),
107557     vodist_qty numeric(18,6),
107558     vodist_expcat_id integer DEFAULT (-1),
107559     vodist_tax_id integer DEFAULT (-1),
107560     vodist_discountable boolean DEFAULT true NOT NULL,
107561     vodist_notes text
107562 );
107563
107564
107565 ALTER TABLE public.vodist OWNER TO admin;
107566
107567 --
107568 -- TOC entry 10332 (class 0 OID 0)
107569 -- Dependencies: 837
107570 -- Name: TABLE vodist; Type: COMMENT; Schema: public; Owner: admin
107571 --
107572
107573 COMMENT ON TABLE vodist IS 'Voucher distribution information';
107574
107575
107576 --
107577 -- TOC entry 838 (class 1259 OID 146570063)
107578 -- Dependencies: 8
107579 -- Name: vodist_vodist_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107580 --
107581
107582 CREATE SEQUENCE vodist_vodist_id_seq
107583     START WITH 1
107584     INCREMENT BY 1
107585     NO MINVALUE
107586     NO MAXVALUE
107587     CACHE 1;
107588
107589
107590 ALTER TABLE public.vodist_vodist_id_seq OWNER TO admin;
107591
107592 --
107593 -- TOC entry 839 (class 1259 OID 146570065)
107594 -- Dependencies: 6686 6687 6688 8
107595 -- Name: vohead; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107596 --
107597
107598 CREATE TABLE vohead (
107599     vohead_id integer DEFAULT nextval(('vohead_vohead_id_seq'::text)::regclass) NOT NULL,
107600     vohead_number text NOT NULL,
107601     vohead_pohead_id integer,
107602     vohead_posted boolean,
107603     vohead_duedate date,
107604     vohead_invcnumber text,
107605     vohead_amount numeric(16,4),
107606     vohead_docdate date,
107607     vohead_1099 boolean,
107608     vohead_distdate date,
107609     vohead_reference text,
107610     vohead_terms_id integer,
107611     vohead_vend_id integer,
107612     vohead_curr_id integer DEFAULT basecurrid(),
107613     vohead_adjtaxtype_id integer,
107614     vohead_freighttaxtype_id integer,
107615     vohead_gldistdate date,
107616     vohead_misc boolean,
107617     vohead_taxzone_id integer,
107618     vohead_taxtype_id integer,
107619     vohead_notes text,
107620     vohead_recurring_vohead_id integer,
107621     CONSTRAINT vohead_vohead_number_check CHECK ((vohead_number <> ''::text))
107622 );
107623
107624
107625 ALTER TABLE public.vohead OWNER TO admin;
107626
107627 --
107628 -- TOC entry 10335 (class 0 OID 0)
107629 -- Dependencies: 839
107630 -- Name: TABLE vohead; Type: COMMENT; Schema: public; Owner: admin
107631 --
107632
107633 COMMENT ON TABLE vohead IS 'Voucher header information';
107634
107635
107636 --
107637 -- TOC entry 840 (class 1259 OID 146570074)
107638 -- Dependencies: 8
107639 -- Name: vohead_vohead_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107640 --
107641
107642 CREATE SEQUENCE vohead_vohead_id_seq
107643     START WITH 1
107644     INCREMENT BY 1
107645     NO MINVALUE
107646     NO MAXVALUE
107647     CACHE 1;
107648
107649
107650 ALTER TABLE public.vohead_vohead_id_seq OWNER TO admin;
107651
107652 --
107653 -- TOC entry 841 (class 1259 OID 146570076)
107654 -- Dependencies: 377 8
107655 -- Name: voheadtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107656 --
107657
107658 CREATE TABLE voheadtax (
107659 )
107660 INHERITS (taxhist);
107661
107662
107663 ALTER TABLE public.voheadtax OWNER TO admin;
107664
107665 --
107666 -- TOC entry 842 (class 1259 OID 146570082)
107667 -- Dependencies: 6690 6691 8
107668 -- Name: voitem; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107669 --
107670
107671 CREATE TABLE voitem (
107672     voitem_id integer DEFAULT nextval(('"voitem_voitem_id_seq"'::text)::regclass) NOT NULL,
107673     voitem_vohead_id integer,
107674     voitem_poitem_id integer,
107675     voitem_close boolean,
107676     voitem_qty numeric(18,6),
107677     voitem_freight numeric(16,4) DEFAULT 0.0 NOT NULL,
107678     voitem_taxtype_id integer
107679 );
107680
107681
107682 ALTER TABLE public.voitem OWNER TO admin;
107683
107684 --
107685 -- TOC entry 10339 (class 0 OID 0)
107686 -- Dependencies: 842
107687 -- Name: TABLE voitem; Type: COMMENT; Schema: public; Owner: admin
107688 --
107689
107690 COMMENT ON TABLE voitem IS 'Voucher Line Item information';
107691
107692
107693 --
107694 -- TOC entry 843 (class 1259 OID 146570087)
107695 -- Dependencies: 8
107696 -- Name: voitem_voitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107697 --
107698
107699 CREATE SEQUENCE voitem_voitem_id_seq
107700     START WITH 1
107701     INCREMENT BY 1
107702     NO MINVALUE
107703     NO MAXVALUE
107704     CACHE 1;
107705
107706
107707 ALTER TABLE public.voitem_voitem_id_seq OWNER TO admin;
107708
107709 --
107710 -- TOC entry 844 (class 1259 OID 146570089)
107711 -- Dependencies: 377 8
107712 -- Name: voitemtax; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107713 --
107714
107715 CREATE TABLE voitemtax (
107716 )
107717 INHERITS (taxhist);
107718
107719
107720 ALTER TABLE public.voitemtax OWNER TO admin;
107721
107722 --
107723 -- TOC entry 845 (class 1259 OID 146570095)
107724 -- Dependencies: 8596 8
107725 -- Name: warehous; Type: VIEW; Schema: public; Owner: admin
107726 --
107727
107728 CREATE VIEW warehous AS
107729     SELECT whsinfo.warehous_id, whsinfo.warehous_code, whsinfo.warehous_descrip, m.addr_line1 AS warehous_addr1, m.addr_line2 AS warehous_addr2, m.addr_line3 AS warehous_addr3, m.addr_city AS warehous_addr4, m.addr_city AS warehous_city, m.addr_state AS warehous_state, m.addr_postalcode AS warehous_zip, m.addr_country AS warehous_country, whsinfo.warehous_fob, whsinfo.warehous_active, whsinfo.warehous_sitetype_id, whsinfo.warehous_counttag_prefix, whsinfo.warehous_counttag_number, whsinfo.warehous_bol_prefix, whsinfo.warehous_bol_number, whsinfo.warehous_shipping, whsinfo.warehous_useslips, whsinfo.warehous_usezones, whsinfo.warehous_aislesize, whsinfo.warehous_aislealpha, whsinfo.warehous_racksize, whsinfo.warehous_rackalpha, whsinfo.warehous_binsize, whsinfo.warehous_binalpha, whsinfo.warehous_locationsize, whsinfo.warehous_locationalpha, whsinfo.warehous_enforcearbl, whsinfo.warehous_default_accnt_id, whsinfo.warehous_shipping_commission FROM ((whsinfo LEFT JOIN cntct c1 ON ((whsinfo.warehous_cntct_id = c1.cntct_id))) LEFT JOIN addr m ON ((whsinfo.warehous_addr_id = m.addr_id)));
107730
107731
107732 ALTER TABLE public.warehous OWNER TO admin;
107733
107734 --
107735 -- TOC entry 846 (class 1259 OID 146570100)
107736 -- Dependencies: 8
107737 -- Name: warehous_warehous_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107738 --
107739
107740 CREATE SEQUENCE warehous_warehous_id_seq
107741     START WITH 1
107742     INCREMENT BY 1
107743     NO MINVALUE
107744     MAXVALUE 2147483647
107745     CACHE 1;
107746
107747
107748 ALTER TABLE public.warehous_warehous_id_seq OWNER TO admin;
107749
107750 --
107751 -- TOC entry 847 (class 1259 OID 146570102)
107752 -- Dependencies: 343 8
107753 -- Name: whsezone_whsezone_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107754 --
107755
107756 CREATE SEQUENCE whsezone_whsezone_id_seq
107757     START WITH 1
107758     INCREMENT BY 1
107759     NO MINVALUE
107760     NO MAXVALUE
107761     CACHE 1;
107762
107763
107764 ALTER TABLE public.whsezone_whsezone_id_seq OWNER TO admin;
107765
107766 --
107767 -- TOC entry 10345 (class 0 OID 0)
107768 -- Dependencies: 847
107769 -- Name: whsezone_whsezone_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107770 --
107771
107772 ALTER SEQUENCE whsezone_whsezone_id_seq OWNED BY whsezone.whsezone_id;
107773
107774
107775 --
107776 -- TOC entry 848 (class 1259 OID 146570104)
107777 -- Dependencies: 8
107778 -- Name: wo_wo_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107779 --
107780
107781 CREATE SEQUENCE wo_wo_id_seq
107782     START WITH 1
107783     INCREMENT BY 1
107784     NO MINVALUE
107785     MAXVALUE 2147483647
107786     CACHE 1;
107787
107788
107789 ALTER TABLE public.wo_wo_id_seq OWNER TO admin;
107790
107791 --
107792 -- TOC entry 849 (class 1259 OID 146570106)
107793 -- Dependencies: 8
107794 -- Name: womatl_womatl_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107795 --
107796
107797 CREATE SEQUENCE womatl_womatl_id_seq
107798     START WITH 1
107799     INCREMENT BY 1
107800     NO MINVALUE
107801     MAXVALUE 2147483647
107802     CACHE 1;
107803
107804
107805 ALTER TABLE public.womatl_womatl_id_seq OWNER TO admin;
107806
107807 --
107808 -- TOC entry 850 (class 1259 OID 146570108)
107809 -- Dependencies: 8
107810 -- Name: womatlpost; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107811 --
107812
107813 CREATE TABLE womatlpost (
107814     womatlpost_id integer NOT NULL,
107815     womatlpost_womatl_id integer,
107816     womatlpost_invhist_id integer
107817 );
107818
107819
107820 ALTER TABLE public.womatlpost OWNER TO admin;
107821
107822 --
107823 -- TOC entry 10349 (class 0 OID 0)
107824 -- Dependencies: 850
107825 -- Name: TABLE womatlpost; Type: COMMENT; Schema: public; Owner: admin
107826 --
107827
107828 COMMENT ON TABLE womatlpost IS 'Table to tie work order to work order material transactions for efficient queries';
107829
107830
107831 --
107832 -- TOC entry 851 (class 1259 OID 146570111)
107833 -- Dependencies: 850 8
107834 -- Name: womatlpost_womatlpost_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107835 --
107836
107837 CREATE SEQUENCE womatlpost_womatlpost_id_seq
107838     START WITH 1
107839     INCREMENT BY 1
107840     NO MINVALUE
107841     NO MAXVALUE
107842     CACHE 1;
107843
107844
107845 ALTER TABLE public.womatlpost_womatlpost_id_seq OWNER TO admin;
107846
107847 --
107848 -- TOC entry 10351 (class 0 OID 0)
107849 -- Dependencies: 851
107850 -- Name: womatlpost_womatlpost_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107851 --
107852
107853 ALTER SEQUENCE womatlpost_womatlpost_id_seq OWNED BY womatlpost.womatlpost_id;
107854
107855
107856 --
107857 -- TOC entry 852 (class 1259 OID 146570113)
107858 -- Dependencies: 6694 6695 8
107859 -- Name: womatlvar; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107860 --
107861
107862 CREATE TABLE womatlvar (
107863     womatlvar_id integer DEFAULT nextval(('"womatlvar_womatlvar_id_seq"'::text)::regclass) NOT NULL,
107864     womatlvar_number integer,
107865     womatlvar_subnumber integer,
107866     womatlvar_posted date,
107867     womatlvar_parent_itemsite_id integer,
107868     womatlvar_component_itemsite_id integer,
107869     womatlvar_qtyord numeric(18,6),
107870     womatlvar_qtyrcv numeric(18,6),
107871     womatlvar_qtyiss numeric(18,6),
107872     womatlvar_qtyper numeric(18,6),
107873     womatlvar_scrap numeric(18,6),
107874     womatlvar_wipscrap numeric(18,6),
107875     womatlvar_bomitem_id integer,
107876     womatlvar_ref text,
107877     womatlvar_notes text,
107878     womatlvar_qtyfxd numeric(20,8) DEFAULT 0 NOT NULL
107879 );
107880
107881
107882 ALTER TABLE public.womatlvar OWNER TO admin;
107883
107884 --
107885 -- TOC entry 10353 (class 0 OID 0)
107886 -- Dependencies: 852
107887 -- Name: TABLE womatlvar; Type: COMMENT; Schema: public; Owner: admin
107888 --
107889
107890 COMMENT ON TABLE womatlvar IS 'Work Order Material Requirements Variance information';
107891
107892
107893 --
107894 -- TOC entry 10354 (class 0 OID 0)
107895 -- Dependencies: 852
107896 -- Name: COLUMN womatlvar.womatlvar_qtyfxd; Type: COMMENT; Schema: public; Owner: admin
107897 --
107898
107899 COMMENT ON COLUMN womatlvar.womatlvar_qtyfxd IS 'The fixed quantity required';
107900
107901
107902 --
107903 -- TOC entry 853 (class 1259 OID 146570121)
107904 -- Dependencies: 8
107905 -- Name: womatlvar_womatlvar_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107906 --
107907
107908 CREATE SEQUENCE womatlvar_womatlvar_id_seq
107909     START WITH 1
107910     INCREMENT BY 1
107911     NO MINVALUE
107912     MAXVALUE 2147483647
107913     CACHE 1;
107914
107915
107916 ALTER TABLE public.womatlvar_womatlvar_id_seq OWNER TO admin;
107917
107918 --
107919 -- TOC entry 854 (class 1259 OID 146570123)
107920 -- Dependencies: 8
107921 -- Name: xcalitem_xcalitem_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107922 --
107923
107924 CREATE SEQUENCE xcalitem_xcalitem_id_seq
107925     START WITH 1
107926     INCREMENT BY 1
107927     NO MINVALUE
107928     NO MAXVALUE
107929     CACHE 1;
107930
107931
107932 ALTER TABLE public.xcalitem_xcalitem_id_seq OWNER TO admin;
107933
107934 --
107935 -- TOC entry 855 (class 1259 OID 146570125)
107936 -- Dependencies: 6697 6698 6699 6700 8
107937 -- Name: xsltmap; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107938 --
107939
107940 CREATE TABLE xsltmap (
107941     xsltmap_id integer NOT NULL,
107942     xsltmap_name text NOT NULL,
107943     xsltmap_doctype text NOT NULL,
107944     xsltmap_system text NOT NULL,
107945     xsltmap_import text NOT NULL,
107946     xsltmap_export text DEFAULT ''::text NOT NULL,
107947     CONSTRAINT xsltmap_check CHECK (((xsltmap_doctype <> ''::text) OR (xsltmap_system <> ''::text))),
107948     CONSTRAINT xsltmap_xsltmap_importexport_check CHECK (((xsltmap_import <> ''::text) OR (xsltmap_export <> ''::text))),
107949     CONSTRAINT xsltmap_xsltmap_name_check CHECK ((xsltmap_name <> ''::text))
107950 );
107951
107952
107953 ALTER TABLE public.xsltmap OWNER TO admin;
107954
107955 --
107956 -- TOC entry 10358 (class 0 OID 0)
107957 -- Dependencies: 855
107958 -- Name: TABLE xsltmap; Type: COMMENT; Schema: public; Owner: admin
107959 --
107960
107961 COMMENT ON TABLE xsltmap IS 'Mapping of XML System identifiers to XSLT transformation files';
107962
107963
107964 --
107965 -- TOC entry 856 (class 1259 OID 146570135)
107966 -- Dependencies: 855 8
107967 -- Name: xsltmap_xsltmap_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
107968 --
107969
107970 CREATE SEQUENCE xsltmap_xsltmap_id_seq
107971     START WITH 1
107972     INCREMENT BY 1
107973     NO MINVALUE
107974     NO MAXVALUE
107975     CACHE 1;
107976
107977
107978 ALTER TABLE public.xsltmap_xsltmap_id_seq OWNER TO admin;
107979
107980 --
107981 -- TOC entry 10360 (class 0 OID 0)
107982 -- Dependencies: 856
107983 -- Name: xsltmap_xsltmap_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
107984 --
107985
107986 ALTER SEQUENCE xsltmap_xsltmap_id_seq OWNED BY xsltmap.xsltmap_id;
107987
107988
107989 --
107990 -- TOC entry 857 (class 1259 OID 146570137)
107991 -- Dependencies: 6702 8
107992 -- Name: yearperiod; Type: TABLE; Schema: public; Owner: admin; Tablespace: 
107993 --
107994
107995 CREATE TABLE yearperiod (
107996     yearperiod_id integer NOT NULL,
107997     yearperiod_start date NOT NULL,
107998     yearperiod_end date NOT NULL,
107999     yearperiod_closed boolean DEFAULT false NOT NULL
108000 );
108001
108002
108003 ALTER TABLE public.yearperiod OWNER TO admin;
108004
108005 --
108006 -- TOC entry 10362 (class 0 OID 0)
108007 -- Dependencies: 857
108008 -- Name: TABLE yearperiod; Type: COMMENT; Schema: public; Owner: admin
108009 --
108010
108011 COMMENT ON TABLE yearperiod IS 'Accounting Year Periods information';
108012
108013
108014 --
108015 -- TOC entry 858 (class 1259 OID 146570141)
108016 -- Dependencies: 857 8
108017 -- Name: yearperiod_yearperiod_id_seq; Type: SEQUENCE; Schema: public; Owner: admin
108018 --
108019
108020 CREATE SEQUENCE yearperiod_yearperiod_id_seq
108021     START WITH 1
108022     INCREMENT BY 1
108023     NO MINVALUE
108024     NO MAXVALUE
108025     CACHE 1;
108026
108027
108028 ALTER TABLE public.yearperiod_yearperiod_id_seq OWNER TO admin;
108029
108030 --
108031 -- TOC entry 10364 (class 0 OID 0)
108032 -- Dependencies: 858
108033 -- Name: yearperiod_yearperiod_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: admin
108034 --
108035
108036 ALTER SEQUENCE yearperiod_yearperiod_id_seq OWNED BY yearperiod.yearperiod_id;
108037
108038
108039 SET search_path = te, pg_catalog;
108040
108041 --
108042 -- TOC entry 859 (class 1259 OID 146570143)
108043 -- Dependencies: 6703 397 9
108044 -- Name: pkgcmd; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108045 --
108046
108047 CREATE TABLE pkgcmd (
108048     cmd_id integer DEFAULT nextval('public.cmd_cmd_id_seq'::regclass)
108049 )
108050 INHERITS (public.cmd);
108051
108052
108053 ALTER TABLE te.pkgcmd OWNER TO admin;
108054
108055 --
108056 -- TOC entry 860 (class 1259 OID 146570150)
108057 -- Dependencies: 6704 400 9
108058 -- Name: pkgcmdarg; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108059 --
108060
108061 CREATE TABLE pkgcmdarg (
108062     cmdarg_id integer DEFAULT nextval('public.cmdarg_cmdarg_id_seq'::regclass)
108063 )
108064 INHERITS (public.cmdarg);
108065
108066
108067 ALTER TABLE te.pkgcmdarg OWNER TO admin;
108068
108069 --
108070 -- TOC entry 861 (class 1259 OID 146570157)
108071 -- Dependencies: 6705 248 9
108072 -- Name: pkgimage; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108073 --
108074
108075 CREATE TABLE pkgimage (
108076     image_id integer DEFAULT nextval('public.image_image_id_seq'::regclass)
108077 )
108078 INHERITS (public.image);
108079
108080
108081 ALTER TABLE te.pkgimage OWNER TO admin;
108082
108083 --
108084 -- TOC entry 862 (class 1259 OID 146570164)
108085 -- Dependencies: 6706 405 9
108086 -- Name: pkgmetasql; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108087 --
108088
108089 CREATE TABLE pkgmetasql (
108090     metasql_id integer DEFAULT nextval('public.metasql_metasql_id_seq'::regclass)
108091 )
108092 INHERITS (public.metasql);
108093
108094
108095 ALTER TABLE te.pkgmetasql OWNER TO admin;
108096
108097 --
108098 -- TOC entry 863 (class 1259 OID 146570172)
108099 -- Dependencies: 6708 408 9
108100 -- Name: pkgpriv; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108101 --
108102
108103 CREATE TABLE pkgpriv (
108104     priv_id integer DEFAULT nextval('public.priv_priv_id_seq'::regclass)
108105 )
108106 INHERITS (public.priv);
108107
108108
108109 ALTER TABLE te.pkgpriv OWNER TO admin;
108110
108111 --
108112 -- TOC entry 864 (class 1259 OID 146570179)
108113 -- Dependencies: 6709 411 9
108114 -- Name: pkgreport; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108115 --
108116
108117 CREATE TABLE pkgreport (
108118     report_id integer DEFAULT nextval('public.report_report_id_seq'::regclass)
108119 )
108120 INHERITS (public.report);
108121
108122
108123 ALTER TABLE te.pkgreport OWNER TO admin;
108124
108125 --
108126 -- TOC entry 865 (class 1259 OID 146570186)
108127 -- Dependencies: 6710 414 9
108128 -- Name: pkgscript; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108129 --
108130
108131 CREATE TABLE pkgscript (
108132     script_id integer DEFAULT nextval('public.script_script_id_seq'::regclass)
108133 )
108134 INHERITS (public.script);
108135
108136
108137 ALTER TABLE te.pkgscript OWNER TO admin;
108138
108139 --
108140 -- TOC entry 866 (class 1259 OID 146570194)
108141 -- Dependencies: 6712 417 9
108142 -- Name: pkguiform; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108143 --
108144
108145 CREATE TABLE pkguiform (
108146     uiform_id integer DEFAULT nextval('public.uiform_uiform_id_seq'::regclass)
108147 )
108148 INHERITS (public.uiform);
108149
108150
108151 ALTER TABLE te.pkguiform OWNER TO admin;
108152
108153 --
108154 -- TOC entry 867 (class 1259 OID 146570202)
108155 -- Dependencies: 6715 9
108156 -- Name: tecustrate; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108157 --
108158
108159 CREATE TABLE tecustrate (
108160     tecustrate_cust_id integer NOT NULL,
108161     tecustrate_rate numeric(16,4) NOT NULL,
108162     tecustrate_id integer NOT NULL,
108163     tecustrate_curr_id integer DEFAULT public.basecurrid() NOT NULL
108164 );
108165
108166
108167 ALTER TABLE te.tecustrate OWNER TO admin;
108168
108169 --
108170 -- TOC entry 10374 (class 0 OID 0)
108171 -- Dependencies: 867
108172 -- Name: TABLE tecustrate; Type: COMMENT; Schema: te; Owner: admin
108173 --
108174
108175 COMMENT ON TABLE tecustrate IS 'Default Customer Billing rate for Time/Expense';
108176
108177
108178 --
108179 -- TOC entry 868 (class 1259 OID 146570206)
108180 -- Dependencies: 867 9
108181 -- Name: tecustrate_tecustrate_id_seq; Type: SEQUENCE; Schema: te; Owner: admin
108182 --
108183
108184 CREATE SEQUENCE tecustrate_tecustrate_id_seq
108185     START WITH 1
108186     INCREMENT BY 1
108187     NO MINVALUE
108188     NO MAXVALUE
108189     CACHE 1;
108190
108191
108192 ALTER TABLE te.tecustrate_tecustrate_id_seq OWNER TO admin;
108193
108194 --
108195 -- TOC entry 10376 (class 0 OID 0)
108196 -- Dependencies: 868
108197 -- Name: tecustrate_tecustrate_id_seq; Type: SEQUENCE OWNED BY; Schema: te; Owner: admin
108198 --
108199
108200 ALTER SEQUENCE tecustrate_tecustrate_id_seq OWNED BY tecustrate.tecustrate_id;
108201
108202
108203 --
108204 -- TOC entry 869 (class 1259 OID 146570208)
108205 -- Dependencies: 6717 9
108206 -- Name: teemp; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108207 --
108208
108209 CREATE TABLE teemp (
108210     teemp_id integer NOT NULL,
108211     teemp_emp_id integer,
108212     teemp_contractor boolean DEFAULT false
108213 );
108214
108215
108216 ALTER TABLE te.teemp OWNER TO admin;
108217
108218 --
108219 -- TOC entry 870 (class 1259 OID 146570212)
108220 -- Dependencies: 869 9
108221 -- Name: teemp_teemp_id_seq; Type: SEQUENCE; Schema: te; Owner: admin
108222 --
108223
108224 CREATE SEQUENCE teemp_teemp_id_seq
108225     START WITH 1
108226     INCREMENT BY 1
108227     NO MINVALUE
108228     NO MAXVALUE
108229     CACHE 1;
108230
108231
108232 ALTER TABLE te.teemp_teemp_id_seq OWNER TO admin;
108233
108234 --
108235 -- TOC entry 10378 (class 0 OID 0)
108236 -- Dependencies: 870
108237 -- Name: teemp_teemp_id_seq; Type: SEQUENCE OWNED BY; Schema: te; Owner: admin
108238 --
108239
108240 ALTER SEQUENCE teemp_teemp_id_seq OWNED BY teemp.teemp_id;
108241
108242
108243 --
108244 -- TOC entry 871 (class 1259 OID 146570214)
108245 -- Dependencies: 9
108246 -- Name: teexp; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108247 --
108248
108249 CREATE TABLE teexp (
108250     teexp_id integer NOT NULL,
108251     teexp_expcat_id integer,
108252     teexp_accnt_id integer
108253 );
108254
108255
108256 ALTER TABLE te.teexp OWNER TO admin;
108257
108258 --
108259 -- TOC entry 10380 (class 0 OID 0)
108260 -- Dependencies: 871
108261 -- Name: TABLE teexp; Type: COMMENT; Schema: te; Owner: admin
108262 --
108263
108264 COMMENT ON TABLE teexp IS 'Expense/Item';
108265
108266
108267 --
108268 -- TOC entry 872 (class 1259 OID 146570217)
108269 -- Dependencies: 9
108270 -- Name: timesheet_seq; Type: SEQUENCE; Schema: te; Owner: admin
108271 --
108272
108273 CREATE SEQUENCE timesheet_seq
108274     START WITH 1000
108275     INCREMENT BY 1
108276     NO MINVALUE
108277     NO MAXVALUE
108278     CACHE 1;
108279
108280
108281 ALTER TABLE te.timesheet_seq OWNER TO admin;
108282
108283 --
108284 -- TOC entry 873 (class 1259 OID 146570219)
108285 -- Dependencies: 6718 6719 6720 6721 6723 9
108286 -- Name: tehead; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108287 --
108288
108289 CREATE TABLE tehead (
108290     tehead_id integer NOT NULL,
108291     tehead_number text DEFAULT nextval('timesheet_seq'::regclass),
108292     tehead_weekending date,
108293     tehead_lastupdated timestamp without time zone DEFAULT now() NOT NULL,
108294     tehead_notes text,
108295     tehead_status character(1) DEFAULT 'O'::bpchar NOT NULL,
108296     tehead_emp_id integer,
108297     tehead_warehous_id integer NOT NULL,
108298     tehead_username text DEFAULT "current_user"() NOT NULL,
108299     CONSTRAINT tehead_tehead_status_check CHECK ((tehead_status = ANY (ARRAY['O'::bpchar, 'A'::bpchar, 'C'::bpchar])))
108300 );
108301
108302
108303 ALTER TABLE te.tehead OWNER TO admin;
108304
108305 --
108306 -- TOC entry 10383 (class 0 OID 0)
108307 -- Dependencies: 873
108308 -- Name: TABLE tehead; Type: COMMENT; Schema: te; Owner: admin
108309 --
108310
108311 COMMENT ON TABLE tehead IS 'time/expense header';
108312
108313
108314 --
108315 -- TOC entry 874 (class 1259 OID 146570230)
108316 -- Dependencies: 873 9
108317 -- Name: tehead_tehead_id_seq; Type: SEQUENCE; Schema: te; Owner: admin
108318 --
108319
108320 CREATE SEQUENCE tehead_tehead_id_seq
108321     START WITH 1
108322     INCREMENT BY 1
108323     NO MINVALUE
108324     NO MAXVALUE
108325     CACHE 1;
108326
108327
108328 ALTER TABLE te.tehead_tehead_id_seq OWNER TO admin;
108329
108330 --
108331 -- TOC entry 10385 (class 0 OID 0)
108332 -- Dependencies: 874
108333 -- Name: tehead_tehead_id_seq; Type: SEQUENCE OWNED BY; Schema: te; Owner: admin
108334 --
108335
108336 ALTER SEQUENCE tehead_tehead_id_seq OWNED BY tehead.tehead_id;
108337
108338
108339 --
108340 -- TOC entry 875 (class 1259 OID 146570232)
108341 -- Dependencies: 6724 6725 6726 6727 9
108342 -- Name: teitem; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108343 --
108344
108345 CREATE TABLE teitem (
108346     teitem_id integer NOT NULL,
108347     teitem_tehead_id integer,
108348     teitem_linenumber integer NOT NULL,
108349     teitem_type character(1) NOT NULL,
108350     teitem_workdate date,
108351     teitem_cust_id integer,
108352     teitem_vend_id integer,
108353     teitem_po text,
108354     teitem_item_id integer NOT NULL,
108355     teitem_qty numeric NOT NULL,
108356     teitem_rate numeric NOT NULL,
108357     teitem_total numeric NOT NULL,
108358     teitem_prjtask_id numeric,
108359     teitem_lastupdated timestamp without time zone DEFAULT ('now'::text)::timestamp(6) with time zone NOT NULL,
108360     teitem_billable boolean,
108361     teitem_prepaid boolean,
108362     teitem_notes text,
108363     teitem_posted boolean DEFAULT false,
108364     teitem_curr_id integer DEFAULT public.basecurrid() NOT NULL,
108365     teitem_uom_id integer,
108366     teitem_invcitem_id integer,
108367     teitem_vodist_id integer,
108368     teitem_postedvalue numeric DEFAULT 0 NOT NULL,
108369     teitem_empcost numeric
108370 );
108371
108372
108373 ALTER TABLE te.teitem OWNER TO admin;
108374
108375 --
108376 -- TOC entry 10387 (class 0 OID 0)
108377 -- Dependencies: 875
108378 -- Name: TABLE teitem; Type: COMMENT; Schema: te; Owner: admin
108379 --
108380
108381 COMMENT ON TABLE teitem IS 'time/expense detail';
108382
108383
108384 --
108385 -- TOC entry 10388 (class 0 OID 0)
108386 -- Dependencies: 875
108387 -- Name: COLUMN teitem.teitem_type; Type: COMMENT; Schema: te; Owner: admin
108388 --
108389
108390 COMMENT ON COLUMN teitem.teitem_type IS 'T or E';
108391
108392
108393 --
108394 -- TOC entry 10389 (class 0 OID 0)
108395 -- Dependencies: 875
108396 -- Name: COLUMN teitem.teitem_vend_id; Type: COMMENT; Schema: te; Owner: admin
108397 --
108398
108399 COMMENT ON COLUMN teitem.teitem_vend_id IS 'future use - for payment of vendor for expenses';
108400
108401
108402 --
108403 -- TOC entry 10390 (class 0 OID 0)
108404 -- Dependencies: 875
108405 -- Name: COLUMN teitem.teitem_prepaid; Type: COMMENT; Schema: te; Owner: admin
108406 --
108407
108408 COMMENT ON COLUMN teitem.teitem_prepaid IS 'Used for expenses only.  CC paid expenses would be prepaid.';
108409
108410
108411 --
108412 -- TOC entry 876 (class 1259 OID 146570242)
108413 -- Dependencies: 875 9
108414 -- Name: teitem_teitem_id_seq; Type: SEQUENCE; Schema: te; Owner: admin
108415 --
108416
108417 CREATE SEQUENCE teitem_teitem_id_seq
108418     START WITH 1
108419     INCREMENT BY 1
108420     NO MINVALUE
108421     NO MAXVALUE
108422     CACHE 1;
108423
108424
108425 ALTER TABLE te.teitem_teitem_id_seq OWNER TO admin;
108426
108427 --
108428 -- TOC entry 10392 (class 0 OID 0)
108429 -- Dependencies: 876
108430 -- Name: teitem_teitem_id_seq; Type: SEQUENCE OWNED BY; Schema: te; Owner: admin
108431 --
108432
108433 ALTER SEQUENCE teitem_teitem_id_seq OWNED BY teitem.teitem_id;
108434
108435
108436 --
108437 -- TOC entry 877 (class 1259 OID 146570244)
108438 -- Dependencies: 9
108439 -- Name: teprj; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108440 --
108441
108442 CREATE TABLE teprj (
108443     teprj_id integer NOT NULL,
108444     teprj_prj_id integer,
108445     teprj_cust_id integer,
108446     teprj_rate numeric,
108447     teprj_curr_id integer
108448 );
108449
108450
108451 ALTER TABLE te.teprj OWNER TO admin;
108452
108453 --
108454 -- TOC entry 10394 (class 0 OID 0)
108455 -- Dependencies: 877
108456 -- Name: TABLE teprj; Type: COMMENT; Schema: te; Owner: admin
108457 --
108458
108459 COMMENT ON TABLE teprj IS 't/e information for projects';
108460
108461
108462 --
108463 -- TOC entry 878 (class 1259 OID 146570250)
108464 -- Dependencies: 877 9
108465 -- Name: teprj_teprj_id_seq; Type: SEQUENCE; Schema: te; Owner: admin
108466 --
108467
108468 CREATE SEQUENCE teprj_teprj_id_seq
108469     START WITH 1
108470     INCREMENT BY 1
108471     NO MINVALUE
108472     NO MAXVALUE
108473     CACHE 1;
108474
108475
108476 ALTER TABLE te.teprj_teprj_id_seq OWNER TO admin;
108477
108478 --
108479 -- TOC entry 10396 (class 0 OID 0)
108480 -- Dependencies: 878
108481 -- Name: teprj_teprj_id_seq; Type: SEQUENCE OWNED BY; Schema: te; Owner: admin
108482 --
108483
108484 ALTER SEQUENCE teprj_teprj_id_seq OWNED BY teprj.teprj_id;
108485
108486
108487 --
108488 -- TOC entry 879 (class 1259 OID 146570252)
108489 -- Dependencies: 6731 9
108490 -- Name: teprjtask; Type: TABLE; Schema: te; Owner: admin; Tablespace: 
108491 --
108492
108493 CREATE TABLE teprjtask (
108494     teprjtask_id integer NOT NULL,
108495     teprjtask_cust_id integer,
108496     teprjtask_rate numeric,
108497     teprjtask_item_id integer,
108498     teprjtask_prjtask_id integer,
108499     teprjtask_curr_id integer DEFAULT public.basecurrid()
108500 );
108501
108502
108503 ALTER TABLE te.teprjtask OWNER TO admin;
108504
108505 --
108506 -- TOC entry 10398 (class 0 OID 0)
108507 -- Dependencies: 879
108508 -- Name: TABLE teprjtask; Type: COMMENT; Schema: te; Owner: admin
108509 --
108510
108511 COMMENT ON TABLE teprjtask IS 't/e information for tasks';
108512
108513
108514 --
108515 -- TOC entry 880 (class 1259 OID 146570259)
108516 -- Dependencies: 879 9
108517 -- Name: teprjtask_teprjtask_id_seq; Type: SEQUENCE; Schema: te; Owner: admin
108518 --
108519
108520 CREATE SEQUENCE teprjtask_teprjtask_id_seq
108521     START WITH 1
108522     INCREMENT BY 1
108523     NO MINVALUE
108524     NO MAXVALUE
108525     CACHE 1;
108526
108527
108528 ALTER TABLE te.teprjtask_teprjtask_id_seq OWNER TO admin;
108529
108530 --
108531 -- TOC entry 10400 (class 0 OID 0)
108532 -- Dependencies: 880
108533 -- Name: teprjtask_teprjtask_id_seq; Type: SEQUENCE OWNED BY; Schema: te; Owner: admin
108534 --
108535
108536 ALTER SEQUENCE teprjtask_teprjtask_id_seq OWNED BY teprjtask.teprjtask_id;
108537
108538
108539 SET search_path = xtdesktop, pg_catalog;
108540
108541 --
108542 -- TOC entry 881 (class 1259 OID 146570261)
108543 -- Dependencies: 6732 397 10
108544 -- Name: pkgcmd; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108545 --
108546
108547 CREATE TABLE pkgcmd (
108548     cmd_id integer DEFAULT nextval('public.cmd_cmd_id_seq'::regclass)
108549 )
108550 INHERITS (public.cmd);
108551
108552
108553 ALTER TABLE xtdesktop.pkgcmd OWNER TO admin;
108554
108555 --
108556 -- TOC entry 882 (class 1259 OID 146570268)
108557 -- Dependencies: 6733 400 10
108558 -- Name: pkgcmdarg; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108559 --
108560
108561 CREATE TABLE pkgcmdarg (
108562     cmdarg_id integer DEFAULT nextval('public.cmdarg_cmdarg_id_seq'::regclass)
108563 )
108564 INHERITS (public.cmdarg);
108565
108566
108567 ALTER TABLE xtdesktop.pkgcmdarg OWNER TO admin;
108568
108569 --
108570 -- TOC entry 883 (class 1259 OID 146570275)
108571 -- Dependencies: 6734 248 10
108572 -- Name: pkgimage; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108573 --
108574
108575 CREATE TABLE pkgimage (
108576     image_id integer DEFAULT nextval('public.image_image_id_seq'::regclass)
108577 )
108578 INHERITS (public.image);
108579
108580
108581 ALTER TABLE xtdesktop.pkgimage OWNER TO admin;
108582
108583 --
108584 -- TOC entry 884 (class 1259 OID 146570282)
108585 -- Dependencies: 6735 405 10
108586 -- Name: pkgmetasql; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108587 --
108588
108589 CREATE TABLE pkgmetasql (
108590     metasql_id integer DEFAULT nextval('public.metasql_metasql_id_seq'::regclass)
108591 )
108592 INHERITS (public.metasql);
108593
108594
108595 ALTER TABLE xtdesktop.pkgmetasql OWNER TO admin;
108596
108597 --
108598 -- TOC entry 885 (class 1259 OID 146570290)
108599 -- Dependencies: 6737 408 10
108600 -- Name: pkgpriv; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108601 --
108602
108603 CREATE TABLE pkgpriv (
108604     priv_id integer DEFAULT nextval('public.priv_priv_id_seq'::regclass)
108605 )
108606 INHERITS (public.priv);
108607
108608
108609 ALTER TABLE xtdesktop.pkgpriv OWNER TO admin;
108610
108611 --
108612 -- TOC entry 886 (class 1259 OID 146570297)
108613 -- Dependencies: 6738 411 10
108614 -- Name: pkgreport; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108615 --
108616
108617 CREATE TABLE pkgreport (
108618     report_id integer DEFAULT nextval('public.report_report_id_seq'::regclass)
108619 )
108620 INHERITS (public.report);
108621
108622
108623 ALTER TABLE xtdesktop.pkgreport OWNER TO admin;
108624
108625 --
108626 -- TOC entry 887 (class 1259 OID 146570304)
108627 -- Dependencies: 6739 414 10
108628 -- Name: pkgscript; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108629 --
108630
108631 CREATE TABLE pkgscript (
108632     script_id integer DEFAULT nextval('public.script_script_id_seq'::regclass)
108633 )
108634 INHERITS (public.script);
108635
108636
108637 ALTER TABLE xtdesktop.pkgscript OWNER TO admin;
108638
108639 --
108640 -- TOC entry 888 (class 1259 OID 146570312)
108641 -- Dependencies: 6741 417 10
108642 -- Name: pkguiform; Type: TABLE; Schema: xtdesktop; Owner: admin; Tablespace: 
108643 --
108644
108645 CREATE TABLE pkguiform (
108646     uiform_id integer DEFAULT nextval('public.uiform_uiform_id_seq'::regclass)
108647 )
108648 INHERITS (public.uiform);
108649
108650
108651 ALTER TABLE xtdesktop.pkguiform OWNER TO admin;
108652
108653 SET search_path = fixcountry, pg_catalog;
108654
108655 --
108656 -- TOC entry 6273 (class 2604 OID 146568264)
108657 -- Dependencies: 407 407
108658 -- Name: metasql_grade; Type: DEFAULT; Schema: fixcountry; Owner: admin
108659 --
108660
108661 ALTER TABLE ONLY pkgmetasql ALTER COLUMN metasql_grade SET DEFAULT 0;
108662
108663
108664 --
108665 -- TOC entry 6281 (class 2604 OID 146568314)
108666 -- Dependencies: 416 416
108667 -- Name: script_enabled; Type: DEFAULT; Schema: fixcountry; Owner: admin
108668 --
108669
108670 ALTER TABLE ONLY pkgscript ALTER COLUMN script_enabled SET DEFAULT false;
108671
108672
108673 --
108674 -- TOC entry 6285 (class 2604 OID 146568332)
108675 -- Dependencies: 419 419
108676 -- Name: uiform_enabled; Type: DEFAULT; Schema: fixcountry; Owner: admin
108677 --
108678
108679 ALTER TABLE ONLY pkguiform ALTER COLUMN uiform_enabled SET DEFAULT false;
108680
108681
108682 SET search_path = public, pg_catalog;
108683
108684 --
108685 -- TOC entry 6055 (class 2604 OID 146570320)
108686 -- Dependencies: 422 234
108687 -- Name: addr_id; Type: DEFAULT; Schema: public; Owner: admin
108688 --
108689
108690 ALTER TABLE ONLY addr ALTER COLUMN addr_id SET DEFAULT nextval('addr_addr_id_seq'::regclass);
108691
108692
108693 --
108694 -- TOC entry 6290 (class 2604 OID 146570321)
108695 -- Dependencies: 425 424
108696 -- Name: alarm_id; Type: DEFAULT; Schema: public; Owner: admin
108697 --
108698
108699 ALTER TABLE ONLY alarm ALTER COLUMN alarm_id SET DEFAULT nextval('alarm_alarm_id_seq'::regclass);
108700
108701
108702 --
108703 -- TOC entry 6291 (class 2604 OID 146570322)
108704 -- Dependencies: 427 426
108705 -- Name: apaccnt_id; Type: DEFAULT; Schema: public; Owner: admin
108706 --
108707
108708 ALTER TABLE ONLY apaccnt ALTER COLUMN apaccnt_id SET DEFAULT nextval('apaccnt_apaccnt_id_seq'::regclass);
108709
108710
108711 --
108712 -- TOC entry 6292 (class 2604 OID 146570323)
108713 -- Dependencies: 429 428
108714 -- Name: apapply_id; Type: DEFAULT; Schema: public; Owner: admin
108715 --
108716
108717 ALTER TABLE ONLY apapply ALTER COLUMN apapply_id SET DEFAULT nextval('apapply_apapply_id_seq'::regclass);
108718
108719
108720 --
108721 -- TOC entry 6310 (class 2604 OID 146570324)
108722 -- Dependencies: 435 434
108723 -- Name: apcreditapply_id; Type: DEFAULT; Schema: public; Owner: admin
108724 --
108725
108726 ALTER TABLE ONLY apcreditapply ALTER COLUMN apcreditapply_id SET DEFAULT nextval('apcreditapply_apcreditapply_id_seq'::regclass);
108727
108728
108729 --
108730 -- TOC entry 6312 (class 2604 OID 146570448)
108731 -- Dependencies: 438 378 438
108732 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
108733 --
108734
108735 ALTER TABLE ONLY apopentax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
108736
108737
108738 --
108739 -- TOC entry 6313 (class 2604 OID 146570325)
108740 -- Dependencies: 440 439
108741 -- Name: apselect_id; Type: DEFAULT; Schema: public; Owner: admin
108742 --
108743
108744 ALTER TABLE ONLY apselect ALTER COLUMN apselect_id SET DEFAULT nextval('apselect_apselect_id_seq'::regclass);
108745
108746
108747 --
108748 -- TOC entry 6317 (class 2604 OID 146570326)
108749 -- Dependencies: 444 443
108750 -- Name: arapply_id; Type: DEFAULT; Schema: public; Owner: admin
108751 --
108752
108753 ALTER TABLE ONLY arapply ALTER COLUMN arapply_id SET DEFAULT nextval('arapply_arapply_id_seq'::regclass);
108754
108755
108756 --
108757 -- TOC entry 6321 (class 2604 OID 146570449)
108758 -- Dependencies: 450 378 450
108759 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
108760 --
108761
108762 ALTER TABLE ONLY aropentax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
108763
108764
108765 --
108766 -- TOC entry 6322 (class 2604 OID 146570327)
108767 -- Dependencies: 452 451
108768 -- Name: asohist_id; Type: DEFAULT; Schema: public; Owner: admin
108769 --
108770
108771 ALTER TABLE ONLY asohist ALTER COLUMN asohist_id SET DEFAULT nextval('asohist_asohist_id_seq'::regclass);
108772
108773
108774 --
108775 -- TOC entry 6324 (class 2604 OID 146570450)
108776 -- Dependencies: 453 378 453
108777 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
108778 --
108779
108780 ALTER TABLE ONLY asohisttax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
108781
108782
108783 --
108784 -- TOC entry 6325 (class 2604 OID 146570328)
108785 -- Dependencies: 455 454
108786 -- Name: atlasmap_id; Type: DEFAULT; Schema: public; Owner: admin
108787 --
108788
108789 ALTER TABLE ONLY atlasmap ALTER COLUMN atlasmap_id SET DEFAULT nextval('atlasmap_atlasmap_id_seq'::regclass);
108790
108791
108792 --
108793 -- TOC entry 6107 (class 2604 OID 146570329)
108794 -- Dependencies: 457 266
108795 -- Name: bankaccnt_id; Type: DEFAULT; Schema: public; Owner: admin
108796 --
108797
108798 ALTER TABLE ONLY bankaccnt ALTER COLUMN bankaccnt_id SET DEFAULT nextval('bankaccnt_bankaccnt_id_seq'::regclass);
108799
108800
108801 --
108802 -- TOC entry 6332 (class 2604 OID 146570330)
108803 -- Dependencies: 459 458
108804 -- Name: bankadj_id; Type: DEFAULT; Schema: public; Owner: admin
108805 --
108806
108807 ALTER TABLE ONLY bankadj ALTER COLUMN bankadj_id SET DEFAULT nextval('bankadj_bankadj_id_seq'::regclass);
108808
108809
108810 --
108811 -- TOC entry 6333 (class 2604 OID 146570331)
108812 -- Dependencies: 461 460
108813 -- Name: bankadjtype_id; Type: DEFAULT; Schema: public; Owner: admin
108814 --
108815
108816 ALTER TABLE ONLY bankadjtype ALTER COLUMN bankadjtype_id SET DEFAULT nextval('bankadjtype_bankadjtype_id_seq'::regclass);
108817
108818
108819 --
108820 -- TOC entry 6339 (class 2604 OID 146570332)
108821 -- Dependencies: 463 462
108822 -- Name: bankrec_id; Type: DEFAULT; Schema: public; Owner: admin
108823 --
108824
108825 ALTER TABLE ONLY bankrec ALTER COLUMN bankrec_id SET DEFAULT nextval('bankrec_bankrec_id_seq'::regclass);
108826
108827
108828 --
108829 -- TOC entry 6340 (class 2604 OID 146570333)
108830 -- Dependencies: 465 464
108831 -- Name: bankrecitem_id; Type: DEFAULT; Schema: public; Owner: admin
108832 --
108833
108834 ALTER TABLE ONLY bankrecitem ALTER COLUMN bankrecitem_id SET DEFAULT nextval('bankrecitem_bankrecitem_id_seq'::regclass);
108835
108836
108837 --
108838 -- TOC entry 6346 (class 2604 OID 146570334)
108839 -- Dependencies: 469 468
108840 -- Name: bomitemcost_id; Type: DEFAULT; Schema: public; Owner: admin
108841 --
108842
108843 ALTER TABLE ONLY bomitemcost ALTER COLUMN bomitemcost_id SET DEFAULT nextval('bomitemcost_bomitemcost_id_seq'::regclass);
108844
108845
108846 --
108847 -- TOC entry 6092 (class 2604 OID 146570335)
108848 -- Dependencies: 470 258
108849 -- Name: bomitemsub_id; Type: DEFAULT; Schema: public; Owner: admin
108850 --
108851
108852 ALTER TABLE ONLY bomitemsub ALTER COLUMN bomitemsub_id SET DEFAULT nextval('bomitemsub_bomitemsub_id_seq'::regclass);
108853
108854
108855 --
108856 -- TOC entry 6347 (class 2604 OID 146570336)
108857 -- Dependencies: 472 471
108858 -- Name: bomwork_id; Type: DEFAULT; Schema: public; Owner: admin
108859 --
108860
108861 ALTER TABLE ONLY bomwork ALTER COLUMN bomwork_id SET DEFAULT nextval('bomwork_bomwork_id_seq'::regclass);
108862
108863
108864 --
108865 -- TOC entry 6093 (class 2604 OID 146570337)
108866 -- Dependencies: 474 260
108867 -- Name: budghead_id; Type: DEFAULT; Schema: public; Owner: admin
108868 --
108869
108870 ALTER TABLE ONLY budghead ALTER COLUMN budghead_id SET DEFAULT nextval('budghead_budghead_id_seq'::regclass);
108871
108872
108873 --
108874 -- TOC entry 6099 (class 2604 OID 146570338)
108875 -- Dependencies: 475 263
108876 -- Name: budgitem_id; Type: DEFAULT; Schema: public; Owner: admin
108877 --
108878
108879 ALTER TABLE ONLY budgitem ALTER COLUMN budgitem_id SET DEFAULT nextval('budgitem_budgitem_id_seq'::regclass);
108880
108881
108882 --
108883 -- TOC entry 6116 (class 2604 OID 146570339)
108884 -- Dependencies: 479 267
108885 -- Name: cashrcpt_id; Type: DEFAULT; Schema: public; Owner: admin
108886 --
108887
108888 ALTER TABLE ONLY cashrcpt ALTER COLUMN cashrcpt_id SET DEFAULT nextval('cashrcpt_cashrcpt_id_seq'::regclass);
108889
108890
108891 --
108892 -- TOC entry 6118 (class 2604 OID 146570340)
108893 -- Dependencies: 445 269
108894 -- Name: cashrcptitem_id; Type: DEFAULT; Schema: public; Owner: admin
108895 --
108896
108897 ALTER TABLE ONLY cashrcptitem ALTER COLUMN cashrcptitem_id SET DEFAULT nextval('cashrcptitem_cashrcptitem_id_seq'::regclass);
108898
108899
108900 --
108901 -- TOC entry 6121 (class 2604 OID 146570341)
108902 -- Dependencies: 480 271
108903 -- Name: cashrcptmisc_id; Type: DEFAULT; Schema: public; Owner: admin
108904 --
108905
108906 ALTER TABLE ONLY cashrcptmisc ALTER COLUMN cashrcptmisc_id SET DEFAULT nextval('cashrcptmisc_cashrcptmisc_id_seq'::regclass);
108907
108908
108909 --
108910 -- TOC entry 6129 (class 2604 OID 146570342)
108911 -- Dependencies: 481 278
108912 -- Name: ccard_id; Type: DEFAULT; Schema: public; Owner: admin
108913 --
108914
108915 ALTER TABLE ONLY ccard ALTER COLUMN ccard_id SET DEFAULT nextval('ccard_ccard_id_seq'::regclass);
108916
108917
108918 --
108919 -- TOC entry 6352 (class 2604 OID 146570343)
108920 -- Dependencies: 483 482
108921 -- Name: ccardaud_id; Type: DEFAULT; Schema: public; Owner: admin
108922 --
108923
108924 ALTER TABLE ONLY ccardaud ALTER COLUMN ccardaud_id SET DEFAULT nextval('ccardaud_ccardaud_id_seq'::regclass);
108925
108926
108927 --
108928 -- TOC entry 6355 (class 2604 OID 146570344)
108929 -- Dependencies: 485 484
108930 -- Name: ccbank_id; Type: DEFAULT; Schema: public; Owner: admin
108931 --
108932
108933 ALTER TABLE ONLY ccbank ALTER COLUMN ccbank_id SET DEFAULT nextval('ccbank_ccbank_id_seq'::regclass);
108934
108935
108936 --
108937 -- TOC entry 6362 (class 2604 OID 146570345)
108938 -- Dependencies: 487 486
108939 -- Name: ccpay_id; Type: DEFAULT; Schema: public; Owner: admin
108940 --
108941
108942 ALTER TABLE ONLY ccpay ALTER COLUMN ccpay_id SET DEFAULT nextval('ccpay_ccpay_id_seq'::regclass);
108943
108944
108945 --
108946 -- TOC entry 6070 (class 2604 OID 146570346)
108947 -- Dependencies: 488 236
108948 -- Name: char_id; Type: DEFAULT; Schema: public; Owner: admin
108949 --
108950
108951 ALTER TABLE ONLY "char" ALTER COLUMN char_id SET DEFAULT nextval('char_char_id_seq'::regclass);
108952
108953
108954 --
108955 -- TOC entry 6072 (class 2604 OID 146570347)
108956 -- Dependencies: 489 237
108957 -- Name: charass_id; Type: DEFAULT; Schema: public; Owner: admin
108958 --
108959
108960 ALTER TABLE ONLY charass ALTER COLUMN charass_id SET DEFAULT nextval('charass_charass_id_seq'::regclass);
108961
108962
108963 --
108964 -- TOC entry 6363 (class 2604 OID 146570348)
108965 -- Dependencies: 491 490
108966 -- Name: charopt_id; Type: DEFAULT; Schema: public; Owner: admin
108967 --
108968
108969 ALTER TABLE ONLY charopt ALTER COLUMN charopt_id SET DEFAULT nextval('charopt_charopt_id_seq'::regclass);
108970
108971
108972 --
108973 -- TOC entry 6302 (class 2604 OID 146570349)
108974 -- Dependencies: 492 430
108975 -- Name: checkhead_id; Type: DEFAULT; Schema: public; Owner: admin
108976 --
108977
108978 ALTER TABLE ONLY checkhead ALTER COLUMN checkhead_id SET DEFAULT nextval('checkhead_checkhead_id_seq'::regclass);
108979
108980
108981 --
108982 -- TOC entry 6308 (class 2604 OID 146570350)
108983 -- Dependencies: 493 432
108984 -- Name: checkitem_id; Type: DEFAULT; Schema: public; Owner: admin
108985 --
108986
108987 ALTER TABLE ONLY checkitem ALTER COLUMN checkitem_id SET DEFAULT nextval('checkitem_checkitem_id_seq'::regclass);
108988
108989
108990 --
108991 -- TOC entry 6265 (class 2604 OID 146568218)
108992 -- Dependencies: 398 397
108993 -- Name: cmd_id; Type: DEFAULT; Schema: public; Owner: admin
108994 --
108995
108996 ALTER TABLE ONLY cmd ALTER COLUMN cmd_id SET DEFAULT nextval('cmd_cmd_id_seq'::regclass);
108997
108998
108999 --
109000 -- TOC entry 6267 (class 2604 OID 146568234)
109001 -- Dependencies: 401 400
109002 -- Name: cmdarg_id; Type: DEFAULT; Schema: public; Owner: admin
109003 --
109004
109005 ALTER TABLE ONLY cmdarg ALTER COLUMN cmdarg_id SET DEFAULT nextval('cmdarg_cmdarg_id_seq'::regclass);
109006
109007
109008 --
109009 -- TOC entry 6365 (class 2604 OID 146570451)
109010 -- Dependencies: 497 378 497
109011 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109012 --
109013
109014 ALTER TABLE ONLY cmheadtax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109015
109016
109017 --
109018 -- TOC entry 6366 (class 2604 OID 146570452)
109019 -- Dependencies: 499 378 499
109020 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109021 --
109022
109023 ALTER TABLE ONLY cmitemtax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109024
109025
109026 --
109027 -- TOC entry 6075 (class 2604 OID 146570351)
109028 -- Dependencies: 500 239
109029 -- Name: cmnttype_id; Type: DEFAULT; Schema: public; Owner: admin
109030 --
109031
109032 ALTER TABLE ONLY cmnttype ALTER COLUMN cmnttype_id SET DEFAULT nextval('cmnttype_cmnttype_id_seq'::regclass);
109033
109034
109035 --
109036 -- TOC entry 6367 (class 2604 OID 146570352)
109037 -- Dependencies: 502 501
109038 -- Name: cmnttypesource_id; Type: DEFAULT; Schema: public; Owner: admin
109039 --
109040
109041 ALTER TABLE ONLY cmnttypesource ALTER COLUMN cmnttypesource_id SET DEFAULT nextval('cmnttypesource_cmnttypesource_id_seq'::regclass);
109042
109043
109044 --
109045 -- TOC entry 5944 (class 2604 OID 146570353)
109046 -- Dependencies: 503 204
109047 -- Name: cntct_id; Type: DEFAULT; Schema: public; Owner: admin
109048 --
109049
109050 ALTER TABLE ONLY cntct ALTER COLUMN cntct_id SET DEFAULT nextval('cntct_cntct_id_seq'::regclass);
109051
109052
109053 --
109054 -- TOC entry 6368 (class 2604 OID 146570354)
109055 -- Dependencies: 505 504
109056 -- Name: cntctaddr_id; Type: DEFAULT; Schema: public; Owner: admin
109057 --
109058
109059 ALTER TABLE ONLY cntctaddr ALTER COLUMN cntctaddr_id SET DEFAULT nextval('cntctaddr_cntctaddr_id_seq'::regclass);
109060
109061
109062 --
109063 -- TOC entry 6369 (class 2604 OID 146570355)
109064 -- Dependencies: 507 506
109065 -- Name: cntctdata_id; Type: DEFAULT; Schema: public; Owner: admin
109066 --
109067
109068 ALTER TABLE ONLY cntctdata ALTER COLUMN cntctdata_id SET DEFAULT nextval('cntctdata_cntctdata_id_seq'::regclass);
109069
109070
109071 --
109072 -- TOC entry 6370 (class 2604 OID 146570356)
109073 -- Dependencies: 509 508
109074 -- Name: cntcteml_id; Type: DEFAULT; Schema: public; Owner: admin
109075 --
109076
109077 ALTER TABLE ONLY cntcteml ALTER COLUMN cntcteml_id SET DEFAULT nextval('cntcteml_cntcteml_id_seq'::regclass);
109078
109079
109080 --
109081 -- TOC entry 6390 (class 2604 OID 146570453)
109082 -- Dependencies: 515 378 515
109083 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109084 --
109085
109086 ALTER TABLE ONLY cobilltax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109087
109088
109089 --
109090 -- TOC entry 6393 (class 2604 OID 146570454)
109091 -- Dependencies: 518 378 518
109092 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109093 --
109094
109095 ALTER TABLE ONLY cobmisctax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109096
109097
109098 --
109099 -- TOC entry 6258 (class 2604 OID 146570447)
109100 -- Dependencies: 379 378 379
109101 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109102 --
109103
109104 ALTER TABLE ONLY cohisttax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109105
109106
109107 --
109108 -- TOC entry 6394 (class 2604 OID 146570357)
109109 -- Dependencies: 524 523
109110 -- Name: company_id; Type: DEFAULT; Schema: public; Owner: admin
109111 --
109112
109113 ALTER TABLE ONLY company ALTER COLUMN company_id SET DEFAULT nextval('company_company_id_seq'::regclass);
109114
109115
109116 --
109117 -- TOC entry 6193 (class 2604 OID 146570358)
109118 -- Dependencies: 525 329
109119 -- Name: contrct_id; Type: DEFAULT; Schema: public; Owner: admin
109120 --
109121
109122 ALTER TABLE ONLY contrct ALTER COLUMN contrct_id SET DEFAULT nextval('contrct_contrct_id_seq'::regclass);
109123
109124
109125 --
109126 -- TOC entry 6411 (class 2604 OID 146570359)
109127 -- Dependencies: 539 538
109128 -- Name: country_id; Type: DEFAULT; Schema: public; Owner: admin
109129 --
109130
109131 ALTER TABLE ONLY country ALTER COLUMN country_id SET DEFAULT nextval('country_country_id_seq'::regclass);
109132
109133
109134 --
109135 -- TOC entry 5946 (class 2604 OID 146570360)
109136 -- Dependencies: 543 205
109137 -- Name: crmacct_id; Type: DEFAULT; Schema: public; Owner: admin
109138 --
109139
109140 ALTER TABLE ONLY crmacct ALTER COLUMN crmacct_id SET DEFAULT nextval('crmacct_crmacct_id_seq'::regclass);
109141
109142
109143 --
109144 -- TOC entry 6433 (class 2604 OID 146570361)
109145 -- Dependencies: 546 545
109146 -- Name: curr_rate_id; Type: DEFAULT; Schema: public; Owner: admin
109147 --
109148
109149 ALTER TABLE ONLY curr_rate ALTER COLUMN curr_rate_id SET DEFAULT nextval('curr_rate_curr_rate_id_seq'::regclass);
109150
109151
109152 --
109153 -- TOC entry 5965 (class 2604 OID 146570362)
109154 -- Dependencies: 547 208
109155 -- Name: curr_id; Type: DEFAULT; Schema: public; Owner: admin
109156 --
109157
109158 ALTER TABLE ONLY curr_symbol ALTER COLUMN curr_id SET DEFAULT nextval('curr_symbol_curr_id_seq'::regclass);
109159
109160
109161 --
109162 -- TOC entry 6144 (class 2604 OID 146570363)
109163 -- Dependencies: 557 291
109164 -- Name: dept_id; Type: DEFAULT; Schema: public; Owner: admin
109165 --
109166
109167 ALTER TABLE ONLY dept ALTER COLUMN dept_id SET DEFAULT nextval('dept_dept_id_seq'::regclass);
109168
109169
109170 --
109171 -- TOC entry 6080 (class 2604 OID 146570364)
109172 -- Dependencies: 247 242
109173 -- Name: docass_id; Type: DEFAULT; Schema: public; Owner: admin
109174 --
109175
109176 ALTER TABLE ONLY docass ALTER COLUMN docass_id SET DEFAULT nextval('docass_docass_id_seq'::regclass);
109177
109178
109179 --
109180 -- TOC entry 6149 (class 2604 OID 146570365)
109181 -- Dependencies: 562 292
109182 -- Name: emp_id; Type: DEFAULT; Schema: public; Owner: admin
109183 --
109184
109185 ALTER TABLE ONLY emp ALTER COLUMN emp_id SET DEFAULT nextval('emp_emp_id_seq'::regclass);
109186
109187
109188 --
109189 -- TOC entry 6449 (class 2604 OID 146570366)
109190 -- Dependencies: 564 563
109191 -- Name: empgrp_id; Type: DEFAULT; Schema: public; Owner: admin
109192 --
109193
109194 ALTER TABLE ONLY empgrp ALTER COLUMN empgrp_id SET DEFAULT nextval('empgrp_empgrp_id_seq'::regclass);
109195
109196
109197 --
109198 -- TOC entry 6451 (class 2604 OID 146570367)
109199 -- Dependencies: 566 565
109200 -- Name: empgrpitem_id; Type: DEFAULT; Schema: public; Owner: admin
109201 --
109202
109203 ALTER TABLE ONLY empgrpitem ALTER COLUMN empgrpitem_id SET DEFAULT nextval('empgrpitem_empgrpitem_id_seq'::regclass);
109204
109205
109206 --
109207 -- TOC entry 6228 (class 2604 OID 146570368)
109208 -- Dependencies: 573 358
109209 -- Name: expcat_id; Type: DEFAULT; Schema: public; Owner: admin
109210 --
109211
109212 ALTER TABLE ONLY expcat ALTER COLUMN expcat_id SET DEFAULT nextval('expcat_expcat_id_seq'::regclass);
109213
109214
109215 --
109216 -- TOC entry 6084 (class 2604 OID 146570369)
109217 -- Dependencies: 574 243
109218 -- Name: file_id; Type: DEFAULT; Schema: public; Owner: admin
109219 --
109220
109221 ALTER TABLE ONLY file ALTER COLUMN file_id SET DEFAULT nextval('file_file_id_seq'::regclass);
109222
109223
109224 --
109225 -- TOC entry 6456 (class 2604 OID 146570370)
109226 -- Dependencies: 576 575
109227 -- Name: filter_id; Type: DEFAULT; Schema: public; Owner: admin
109228 --
109229
109230 ALTER TABLE ONLY filter ALTER COLUMN filter_id SET DEFAULT nextval('filter_filter_id_seq'::regclass);
109231
109232
109233 --
109234 -- TOC entry 6458 (class 2604 OID 146570371)
109235 -- Dependencies: 578 577
109236 -- Name: fincharg_id; Type: DEFAULT; Schema: public; Owner: admin
109237 --
109238
109239 ALTER TABLE ONLY fincharg ALTER COLUMN fincharg_id SET DEFAULT nextval('fincharg_fincharg_id_seq'::regclass);
109240
109241
109242 --
109243 -- TOC entry 6491 (class 2604 OID 146570372)
109244 -- Dependencies: 583 582
109245 -- Name: flcol_id; Type: DEFAULT; Schema: public; Owner: admin
109246 --
109247
109248 ALTER TABLE ONLY flcol ALTER COLUMN flcol_id SET DEFAULT nextval('flcol_flcol_id_seq'::regclass);
109249
109250
109251 --
109252 -- TOC entry 6509 (class 2604 OID 146570373)
109253 -- Dependencies: 585 584
109254 -- Name: flgrp_id; Type: DEFAULT; Schema: public; Owner: admin
109255 --
109256
109257 ALTER TABLE ONLY flgrp ALTER COLUMN flgrp_id SET DEFAULT nextval('flgrp_flgrp_id_seq'::regclass);
109258
109259
109260 --
109261 -- TOC entry 6477 (class 2604 OID 146570374)
109262 -- Dependencies: 586 579
109263 -- Name: flhead_id; Type: DEFAULT; Schema: public; Owner: admin
109264 --
109265
109266 ALTER TABLE ONLY flhead ALTER COLUMN flhead_id SET DEFAULT nextval('flhead_flhead_id_seq'::regclass);
109267
109268
109269 --
109270 -- TOC entry 6490 (class 2604 OID 146570375)
109271 -- Dependencies: 587 580
109272 -- Name: flitem_id; Type: DEFAULT; Schema: public; Owner: admin
109273 --
109274
109275 ALTER TABLE ONLY flitem ALTER COLUMN flitem_id SET DEFAULT nextval('flitem_flitem_id_seq'::regclass);
109276
109277
109278 --
109279 -- TOC entry 6510 (class 2604 OID 146570376)
109280 -- Dependencies: 589 588
109281 -- Name: flnotes_id; Type: DEFAULT; Schema: public; Owner: admin
109282 --
109283
109284 ALTER TABLE ONLY flnotes ALTER COLUMN flnotes_id SET DEFAULT nextval('flnotes_flnotes_id_seq'::regclass);
109285
109286
109287 --
109288 -- TOC entry 6512 (class 2604 OID 146570377)
109289 -- Dependencies: 591 590
109290 -- Name: flrpt_id; Type: DEFAULT; Schema: public; Owner: admin
109291 --
109292
109293 ALTER TABLE ONLY flrpt ALTER COLUMN flrpt_id SET DEFAULT nextval('flrpt_flrpt_id_seq'::regclass);
109294
109295
109296 --
109297 -- TOC entry 6527 (class 2604 OID 146570378)
109298 -- Dependencies: 593 592
109299 -- Name: flspec_id; Type: DEFAULT; Schema: public; Owner: admin
109300 --
109301
109302 ALTER TABLE ONLY flspec ALTER COLUMN flspec_id SET DEFAULT nextval('flspec_flspec_id_seq'::regclass);
109303
109304
109305 --
109306 -- TOC entry 6160 (class 2604 OID 146570379)
109307 -- Dependencies: 596 299
109308 -- Name: freightclass_id; Type: DEFAULT; Schema: public; Owner: admin
109309 --
109310
109311 ALTER TABLE ONLY freightclass ALTER COLUMN freightclass_id SET DEFAULT nextval('freightclass_freightclass_id_seq'::regclass);
109312
109313
109314 --
109315 -- TOC entry 6531 (class 2604 OID 146570380)
109316 -- Dependencies: 602 601
109317 -- Name: grp_id; Type: DEFAULT; Schema: public; Owner: admin
109318 --
109319
109320 ALTER TABLE ONLY grp ALTER COLUMN grp_id SET DEFAULT nextval('grp_grp_id_seq'::regclass);
109321
109322
109323 --
109324 -- TOC entry 6533 (class 2604 OID 146570381)
109325 -- Dependencies: 604 603
109326 -- Name: grppriv_id; Type: DEFAULT; Schema: public; Owner: admin
109327 --
109328
109329 ALTER TABLE ONLY grppriv ALTER COLUMN grppriv_id SET DEFAULT nextval('grppriv_grppriv_id_seq'::regclass);
109330
109331
109332 --
109333 -- TOC entry 6534 (class 2604 OID 146570382)
109334 -- Dependencies: 606 605
109335 -- Name: hnfc_id; Type: DEFAULT; Schema: public; Owner: admin
109336 --
109337
109338 ALTER TABLE ONLY hnfc ALTER COLUMN hnfc_id SET DEFAULT nextval('hnfc_hnfc_id_seq'::regclass);
109339
109340
109341 --
109342 -- TOC entry 5955 (class 2604 OID 146570383)
109343 -- Dependencies: 607 206
109344 -- Name: incdt_id; Type: DEFAULT; Schema: public; Owner: admin
109345 --
109346
109347 ALTER TABLE ONLY incdt ALTER COLUMN incdt_id SET DEFAULT nextval('incdt_incdt_id_seq'::regclass);
109348
109349
109350 --
109351 -- TOC entry 6168 (class 2604 OID 146570384)
109352 -- Dependencies: 608 304
109353 -- Name: incdtcat_id; Type: DEFAULT; Schema: public; Owner: admin
109354 --
109355
109356 ALTER TABLE ONLY incdtcat ALTER COLUMN incdtcat_id SET DEFAULT nextval('incdtcat_incdtcat_id_seq'::regclass);
109357
109358
109359 --
109360 -- TOC entry 6536 (class 2604 OID 146570385)
109361 -- Dependencies: 610 609
109362 -- Name: incdthist_id; Type: DEFAULT; Schema: public; Owner: admin
109363 --
109364
109365 ALTER TABLE ONLY incdthist ALTER COLUMN incdthist_id SET DEFAULT nextval('incdthist_incdthist_id_seq'::regclass);
109366
109367
109368 --
109369 -- TOC entry 6170 (class 2604 OID 146570386)
109370 -- Dependencies: 611 305
109371 -- Name: incdtpriority_id; Type: DEFAULT; Schema: public; Owner: admin
109372 --
109373
109374 ALTER TABLE ONLY incdtpriority ALTER COLUMN incdtpriority_id SET DEFAULT nextval('incdtpriority_incdtpriority_id_seq'::regclass);
109375
109376
109377 --
109378 -- TOC entry 6172 (class 2604 OID 146570387)
109379 -- Dependencies: 612 306
109380 -- Name: incdtresolution_id; Type: DEFAULT; Schema: public; Owner: admin
109381 --
109382
109383 ALTER TABLE ONLY incdtresolution ALTER COLUMN incdtresolution_id SET DEFAULT nextval('incdtresolution_incdtresolution_id_seq'::regclass);
109384
109385
109386 --
109387 -- TOC entry 6174 (class 2604 OID 146570388)
109388 -- Dependencies: 613 307
109389 -- Name: incdtseverity_id; Type: DEFAULT; Schema: public; Owner: admin
109390 --
109391
109392 ALTER TABLE ONLY incdtseverity ALTER COLUMN incdtseverity_id SET DEFAULT nextval('incdtseverity_incdtseverity_id_seq'::regclass);
109393
109394
109395 --
109396 -- TOC entry 5935 (class 2604 OID 146570389)
109397 -- Dependencies: 614 202
109398 -- Name: invbal_id; Type: DEFAULT; Schema: public; Owner: admin
109399 --
109400
109401 ALTER TABLE ONLY invbal ALTER COLUMN invbal_id SET DEFAULT nextval('invbal_invbal_id_seq'::regclass);
109402
109403
109404 --
109405 -- TOC entry 6025 (class 2604 OID 146570390)
109406 -- Dependencies: 616 224
109407 -- Name: invchead_id; Type: DEFAULT; Schema: public; Owner: admin
109408 --
109409
109410 ALTER TABLE ONLY invchead ALTER COLUMN invchead_id SET DEFAULT nextval('invchead_invchead_id_seq'::regclass);
109411
109412
109413 --
109414 -- TOC entry 6539 (class 2604 OID 146570455)
109415 -- Dependencies: 617 378 617
109416 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109417 --
109418
109419 ALTER TABLE ONLY invcheadtax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109420
109421
109422 --
109423 -- TOC entry 6034 (class 2604 OID 146570391)
109424 -- Dependencies: 618 229
109425 -- Name: invcitem_id; Type: DEFAULT; Schema: public; Owner: admin
109426 --
109427
109428 ALTER TABLE ONLY invcitem ALTER COLUMN invcitem_id SET DEFAULT nextval('invcitem_invcitem_id_seq'::regclass);
109429
109430
109431 --
109432 -- TOC entry 6540 (class 2604 OID 146570456)
109433 -- Dependencies: 619 378 619
109434 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109435 --
109436
109437 ALTER TABLE ONLY invcitemtax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109438
109439
109440 --
109441 -- TOC entry 6549 (class 2604 OID 146570392)
109442 -- Dependencies: 626 625
109443 -- Name: invhistexpcat_id; Type: DEFAULT; Schema: public; Owner: admin
109444 --
109445
109446 ALTER TABLE ONLY invhistexpcat ALTER COLUMN invhistexpcat_id SET DEFAULT nextval('invhistexpcat_invhistexpcat_id_seq'::regclass);
109447
109448
109449 --
109450 -- TOC entry 6217 (class 2604 OID 146570393)
109451 -- Dependencies: 628 347
109452 -- Name: ipsass_id; Type: DEFAULT; Schema: public; Owner: admin
109453 --
109454
109455 ALTER TABLE ONLY ipsass ALTER COLUMN ipsass_id SET DEFAULT nextval('ipsass_ipsass_id_seq'::regclass);
109456
109457
109458 --
109459 -- TOC entry 6162 (class 2604 OID 146570394)
109460 -- Dependencies: 631 300
109461 -- Name: ipsfreight_id; Type: DEFAULT; Schema: public; Owner: admin
109462 --
109463
109464 ALTER TABLE ONLY ipsfreight ALTER COLUMN ipsfreight_id SET DEFAULT nextval('ipsfreight_ipsfreight_id_seq'::regclass);
109465
109466
109467 --
109468 -- TOC entry 6223 (class 2604 OID 146570395)
109469 -- Dependencies: 634 351
109470 -- Name: ipsitemchar_id; Type: DEFAULT; Schema: public; Owner: admin
109471 --
109472
109473 ALTER TABLE ONLY ipsitemchar ALTER COLUMN ipsitemchar_id SET DEFAULT nextval('ipsitemchar_ipsitemchar_id_seq'::regclass);
109474
109475
109476 --
109477 -- TOC entry 6550 (class 2604 OID 146570396)
109478 -- Dependencies: 637 636
109479 -- Name: ipsprodcat_id; Type: DEFAULT; Schema: public; Owner: admin
109480 --
109481
109482 ALTER TABLE ONLY ipsprodcat_bak ALTER COLUMN ipsprodcat_id SET DEFAULT nextval('ipsprodcat_ipsprodcat_id_seq'::regclass);
109483
109484
109485 --
109486 -- TOC entry 6562 (class 2604 OID 146570397)
109487 -- Dependencies: 655 654
109488 -- Name: itemlocpost_id; Type: DEFAULT; Schema: public; Owner: admin
109489 --
109490
109491 ALTER TABLE ONLY itemlocpost ALTER COLUMN itemlocpost_id SET DEFAULT nextval('itemlocpost_itemlocpost_id_seq'::regclass);
109492
109493
109494 --
109495 -- TOC entry 6207 (class 2604 OID 146570398)
109496 -- Dependencies: 661 336
109497 -- Name: itemtax_id; Type: DEFAULT; Schema: public; Owner: admin
109498 --
109499
109500 ALTER TABLE ONLY itemtax ALTER COLUMN itemtax_id SET DEFAULT nextval('itemtax_itemtax_id_seq'::regclass);
109501
109502
109503 --
109504 -- TOC entry 6563 (class 2604 OID 146570399)
109505 -- Dependencies: 663 662
109506 -- Name: itemtrans_id; Type: DEFAULT; Schema: public; Owner: admin
109507 --
109508
109509 ALTER TABLE ONLY itemtrans ALTER COLUMN itemtrans_id SET DEFAULT nextval('itemtrans_itemtrans_id_seq'::regclass);
109510
109511
109512 --
109513 -- TOC entry 6564 (class 2604 OID 146570400)
109514 -- Dependencies: 665 664
109515 -- Name: itemuom_id; Type: DEFAULT; Schema: public; Owner: admin
109516 --
109517
109518 ALTER TABLE ONLY itemuom ALTER COLUMN itemuom_id SET DEFAULT nextval('itemuom_itemuom_id_seq'::regclass);
109519
109520
109521 --
109522 -- TOC entry 6208 (class 2604 OID 146570401)
109523 -- Dependencies: 666 338
109524 -- Name: itemuomconv_id; Type: DEFAULT; Schema: public; Owner: admin
109525 --
109526
109527 ALTER TABLE ONLY itemuomconv ALTER COLUMN itemuomconv_id SET DEFAULT nextval('itemuomconv_itemuomconv_id_seq'::regclass);
109528
109529
109530 --
109531 -- TOC entry 6566 (class 2604 OID 146570402)
109532 -- Dependencies: 671 670
109533 -- Name: labeldef_id; Type: DEFAULT; Schema: public; Owner: admin
109534 --
109535
109536 ALTER TABLE ONLY labeldef ALTER COLUMN labeldef_id SET DEFAULT nextval('labeldef_labeldef_id_seq'::regclass);
109537
109538
109539 --
109540 -- TOC entry 6569 (class 2604 OID 146570403)
109541 -- Dependencies: 675 674
109542 -- Name: lang_id; Type: DEFAULT; Schema: public; Owner: admin
109543 --
109544
109545 ALTER TABLE ONLY lang ALTER COLUMN lang_id SET DEFAULT nextval('lang_lang_id_seq'::regclass);
109546
109547
109548 --
109549 -- TOC entry 6270 (class 2604 OID 146568260)
109550 -- Dependencies: 406 405
109551 -- Name: metasql_id; Type: DEFAULT; Schema: public; Owner: admin
109552 --
109553
109554 ALTER TABLE ONLY metasql ALTER COLUMN metasql_id SET DEFAULT nextval('metasql_metasql_id_seq'::regclass);
109555
109556
109557 --
109558 -- TOC entry 6577 (class 2604 OID 146570404)
109559 -- Dependencies: 685 684
109560 -- Name: metricenc_id; Type: DEFAULT; Schema: public; Owner: admin
109561 --
109562
109563 ALTER TABLE ONLY metricenc ALTER COLUMN metricenc_id SET DEFAULT nextval('metricenc_metricenc_id_seq'::regclass);
109564
109565
109566 --
109567 -- TOC entry 6037 (class 2604 OID 146570405)
109568 -- Dependencies: 695 231
109569 -- Name: ophead_id; Type: DEFAULT; Schema: public; Owner: admin
109570 --
109571
109572 ALTER TABLE ONLY ophead ALTER COLUMN ophead_id SET DEFAULT nextval('ophead_ophead_id_seq'::regclass);
109573
109574
109575 --
109576 -- TOC entry 6584 (class 2604 OID 146570406)
109577 -- Dependencies: 697 696
109578 -- Name: opsource_id; Type: DEFAULT; Schema: public; Owner: admin
109579 --
109580
109581 ALTER TABLE ONLY opsource ALTER COLUMN opsource_id SET DEFAULT nextval('opsource_opsource_id_seq'::regclass);
109582
109583
109584 --
109585 -- TOC entry 6586 (class 2604 OID 146570407)
109586 -- Dependencies: 699 698
109587 -- Name: opstage_id; Type: DEFAULT; Schema: public; Owner: admin
109588 --
109589
109590 ALTER TABLE ONLY opstage ALTER COLUMN opstage_id SET DEFAULT nextval('opstage_opstage_id_seq'::regclass);
109591
109592
109593 --
109594 -- TOC entry 6590 (class 2604 OID 146570408)
109595 -- Dependencies: 701 700
109596 -- Name: optype_id; Type: DEFAULT; Schema: public; Owner: admin
109597 --
109598
109599 ALTER TABLE ONLY optype ALTER COLUMN optype_id SET DEFAULT nextval('optype_optype_id_seq'::regclass);
109600
109601
109602 --
109603 -- TOC entry 6594 (class 2604 OID 146570409)
109604 -- Dependencies: 707 706
109605 -- Name: pack_id; Type: DEFAULT; Schema: public; Owner: admin
109606 --
109607
109608 ALTER TABLE ONLY pack ALTER COLUMN pack_id SET DEFAULT nextval('pack_pack_id_seq'::regclass);
109609
109610
109611 --
109612 -- TOC entry 6100 (class 2604 OID 146570410)
109613 -- Dependencies: 710 264
109614 -- Name: period_id; Type: DEFAULT; Schema: public; Owner: admin
109615 --
109616
109617 ALTER TABLE ONLY period ALTER COLUMN period_id SET DEFAULT nextval('period_period_id_seq'::regclass);
109618
109619
109620 --
109621 -- TOC entry 6601 (class 2604 OID 146570411)
109622 -- Dependencies: 712 711
109623 -- Name: pkgdep_id; Type: DEFAULT; Schema: public; Owner: admin
109624 --
109625
109626 ALTER TABLE ONLY pkgdep ALTER COLUMN pkgdep_id SET DEFAULT nextval('pkgdep_pkgdep_id_seq'::regclass);
109627
109628
109629 --
109630 -- TOC entry 6602 (class 2604 OID 146570412)
109631 -- Dependencies: 714 713
109632 -- Name: pkghead_id; Type: DEFAULT; Schema: public; Owner: admin
109633 --
109634
109635 ALTER TABLE ONLY pkghead ALTER COLUMN pkghead_id SET DEFAULT nextval('pkghead_pkghead_id_seq'::regclass);
109636
109637
109638 --
109639 -- TOC entry 6605 (class 2604 OID 146570413)
109640 -- Dependencies: 716 715
109641 -- Name: pkgitem_id; Type: DEFAULT; Schema: public; Owner: admin
109642 --
109643
109644 ALTER TABLE ONLY pkgitem ALTER COLUMN pkgitem_id SET DEFAULT nextval('pkgitem_pkgitem_id_seq'::regclass);
109645
109646
109647 --
109648 -- TOC entry 6613 (class 2604 OID 146570414)
109649 -- Dependencies: 727 726
109650 -- Name: potype_id; Type: DEFAULT; Schema: public; Owner: admin
109651 --
109652
109653 ALTER TABLE ONLY potype ALTER COLUMN potype_id SET DEFAULT nextval('potype_potype_id_seq'::regclass);
109654
109655
109656 --
109657 -- TOC entry 6616 (class 2604 OID 146570415)
109658 -- Dependencies: 731 730
109659 -- Name: prftcntr_id; Type: DEFAULT; Schema: public; Owner: admin
109660 --
109661
109662 ALTER TABLE ONLY prftcntr ALTER COLUMN prftcntr_id SET DEFAULT nextval('prftcntr_prftcntr_id_seq'::regclass);
109663
109664
109665 --
109666 -- TOC entry 6027 (class 2604 OID 146570416)
109667 -- Dependencies: 735 225
109668 -- Name: prj_id; Type: DEFAULT; Schema: public; Owner: admin
109669 --
109670
109671 ALTER TABLE ONLY prj ALTER COLUMN prj_id SET DEFAULT nextval('prj_prj_id_seq'::regclass);
109672
109673
109674 --
109675 -- TOC entry 6040 (class 2604 OID 146570417)
109676 -- Dependencies: 736 232
109677 -- Name: prjtask_id; Type: DEFAULT; Schema: public; Owner: admin
109678 --
109679
109680 ALTER TABLE ONLY prjtask ALTER COLUMN prjtask_id SET DEFAULT nextval('prjtask_prjtask_id_seq'::regclass);
109681
109682
109683 --
109684 -- TOC entry 6620 (class 2604 OID 146570418)
109685 -- Dependencies: 738 737
109686 -- Name: prjtaskuser_id; Type: DEFAULT; Schema: public; Owner: admin
109687 --
109688
109689 ALTER TABLE ONLY prjtaskuser ALTER COLUMN prjtaskuser_id SET DEFAULT nextval('prjtaskuser_prjtaskuser_id_seq'::regclass);
109690
109691
109692 --
109693 -- TOC entry 6621 (class 2604 OID 146570419)
109694 -- Dependencies: 740 739
109695 -- Name: prjtype_id; Type: DEFAULT; Schema: public; Owner: admin
109696 --
109697
109698 ALTER TABLE ONLY prjtype ALTER COLUMN prjtype_id SET DEFAULT nextval('prjtype_prjtype_id_seq'::regclass);
109699
109700
109701 --
109702 -- TOC entry 6623 (class 2604 OID 146570420)
109703 -- Dependencies: 743 742
109704 -- Name: qryhead_id; Type: DEFAULT; Schema: public; Owner: admin
109705 --
109706
109707 ALTER TABLE ONLY qryhead ALTER COLUMN qryhead_id SET DEFAULT nextval('qryhead_qryhead_id_seq'::regclass);
109708
109709
109710 --
109711 -- TOC entry 6630 (class 2604 OID 146570421)
109712 -- Dependencies: 745 744
109713 -- Name: qryitem_id; Type: DEFAULT; Schema: public; Owner: admin
109714 --
109715
109716 ALTER TABLE ONLY qryitem ALTER COLUMN qryitem_id SET DEFAULT nextval('qryitem_qryitem_id_seq'::regclass);
109717
109718
109719 --
109720 -- TOC entry 6634 (class 2604 OID 146570422)
109721 -- Dependencies: 750 749
109722 -- Name: recur_id; Type: DEFAULT; Schema: public; Owner: admin
109723 --
109724
109725 ALTER TABLE ONLY recur ALTER COLUMN recur_id SET DEFAULT nextval('recur_recur_id_seq'::regclass);
109726
109727
109728 --
109729 -- TOC entry 6638 (class 2604 OID 146570423)
109730 -- Dependencies: 752 751
109731 -- Name: recurtype_id; Type: DEFAULT; Schema: public; Owner: admin
109732 --
109733
109734 ALTER TABLE ONLY recurtype ALTER COLUMN recurtype_id SET DEFAULT nextval('recurtype_recurtype_id_seq'::regclass);
109735
109736
109737 --
109738 -- TOC entry 6610 (class 2604 OID 146570424)
109739 -- Dependencies: 753 721
109740 -- Name: recv_id; Type: DEFAULT; Schema: public; Owner: admin
109741 --
109742
109743 ALTER TABLE ONLY recv ALTER COLUMN recv_id SET DEFAULT nextval('recv_recv_id_seq'::regclass);
109744
109745
109746 --
109747 -- TOC entry 6006 (class 2604 OID 146570425)
109748 -- Dependencies: 757 214
109749 -- Name: rsncode_id; Type: DEFAULT; Schema: public; Owner: admin
109750 --
109751
109752 ALTER TABLE ONLY rsncode ALTER COLUMN rsncode_id SET DEFAULT nextval('rsncode_rsncode_id_seq'::regclass);
109753
109754
109755 --
109756 -- TOC entry 6008 (class 2604 OID 146570426)
109757 -- Dependencies: 761 215
109758 -- Name: salescat_id; Type: DEFAULT; Schema: public; Owner: admin
109759 --
109760
109761 ALTER TABLE ONLY salescat ALTER COLUMN salescat_id SET DEFAULT nextval('salescat_salescat_id_seq'::regclass);
109762
109763
109764 --
109765 -- TOC entry 6030 (class 2604 OID 146570427)
109766 -- Dependencies: 765 226
109767 -- Name: saletype_id; Type: DEFAULT; Schema: public; Owner: admin
109768 --
109769
109770 ALTER TABLE ONLY saletype ALTER COLUMN saletype_id SET DEFAULT nextval('saletype_saletype_id_seq'::regclass);
109771
109772
109773 --
109774 -- TOC entry 6643 (class 2604 OID 146570428)
109775 -- Dependencies: 767 766
109776 -- Name: schemaord_id; Type: DEFAULT; Schema: public; Owner: admin
109777 --
109778
109779 ALTER TABLE ONLY schemaord ALTER COLUMN schemaord_id SET DEFAULT nextval('schemaord_schemaord_id_seq'::regclass);
109780
109781
109782 --
109783 -- TOC entry 6278 (class 2604 OID 146568310)
109784 -- Dependencies: 415 414
109785 -- Name: script_id; Type: DEFAULT; Schema: public; Owner: admin
109786 --
109787
109788 ALTER TABLE ONLY script ALTER COLUMN script_id SET DEFAULT nextval('script_script_id_seq'::regclass);
109789
109790
109791 --
109792 -- TOC entry 6154 (class 2604 OID 146570429)
109793 -- Dependencies: 769 293
109794 -- Name: shift_id; Type: DEFAULT; Schema: public; Owner: admin
109795 --
109796
109797 ALTER TABLE ONLY shift ALTER COLUMN shift_id SET DEFAULT nextval('shift_shift_id_seq'::regclass);
109798
109799
109800 --
109801 -- TOC entry 6133 (class 2604 OID 146570430)
109802 -- Dependencies: 770 281
109803 -- Name: shipchrg_id; Type: DEFAULT; Schema: public; Owner: admin
109804 --
109805
109806 ALTER TABLE ONLY shipchrg ALTER COLUMN shipchrg_id SET DEFAULT nextval('shipchrg_shipchrg_id_seq'::regclass);
109807
109808
109809 --
109810 -- TOC entry 6400 (class 2604 OID 146570431)
109811 -- Dependencies: 773 526
109812 -- Name: shiphead_id; Type: DEFAULT; Schema: public; Owner: admin
109813 --
109814
109815 ALTER TABLE ONLY shiphead ALTER COLUMN shiphead_id SET DEFAULT nextval('shiphead_shiphead_id_seq'::regclass);
109816
109817
109818 --
109819 -- TOC entry 6404 (class 2604 OID 146570432)
109820 -- Dependencies: 774 527
109821 -- Name: shipitem_id; Type: DEFAULT; Schema: public; Owner: admin
109822 --
109823
109824 ALTER TABLE ONLY shipitem ALTER COLUMN shipitem_id SET DEFAULT nextval('shipitem_shipitem_id_seq'::regclass);
109825
109826
109827 --
109828 -- TOC entry 6261 (class 2604 OID 146570433)
109829 -- Dependencies: 780 387
109830 -- Name: sitetype_id; Type: DEFAULT; Schema: public; Owner: admin
109831 --
109832
109833 ALTER TABLE ONLY sitetype ALTER COLUMN sitetype_id SET DEFAULT nextval('sitetype_sitetype_id_seq'::regclass);
109834
109835
109836 --
109837 -- TOC entry 6654 (class 2604 OID 146570434)
109838 -- Dependencies: 786 785
109839 -- Name: source_id; Type: DEFAULT; Schema: public; Owner: admin
109840 --
109841
109842 ALTER TABLE ONLY source ALTER COLUMN source_id SET DEFAULT nextval('source_source_id_seq'::regclass);
109843
109844
109845 --
109846 -- TOC entry 6656 (class 2604 OID 146570435)
109847 -- Dependencies: 788 787
109848 -- Name: state_id; Type: DEFAULT; Schema: public; Owner: admin
109849 --
109850
109851 ALTER TABLE ONLY state ALTER COLUMN state_id SET DEFAULT nextval('state_state_id_seq'::regclass);
109852
109853
109854 --
109855 -- TOC entry 6658 (class 2604 OID 146570436)
109856 -- Dependencies: 790 789
109857 -- Name: status_id; Type: DEFAULT; Schema: public; Owner: admin
109858 --
109859
109860 ALTER TABLE ONLY status ALTER COLUMN status_id SET DEFAULT nextval('status_status_id_seq'::regclass);
109861
109862
109863 --
109864 -- TOC entry 6660 (class 2604 OID 146570437)
109865 -- Dependencies: 792 791
109866 -- Name: stdjrnl_id; Type: DEFAULT; Schema: public; Owner: admin
109867 --
109868
109869 ALTER TABLE ONLY stdjrnl ALTER COLUMN stdjrnl_id SET DEFAULT nextval('stdjrnl_stdjrnl_id_seq'::regclass);
109870
109871
109872 --
109873 -- TOC entry 6662 (class 2604 OID 146570438)
109874 -- Dependencies: 794 793
109875 -- Name: stdjrnlgrp_id; Type: DEFAULT; Schema: public; Owner: admin
109876 --
109877
109878 ALTER TABLE ONLY stdjrnlgrp ALTER COLUMN stdjrnlgrp_id SET DEFAULT nextval('stdjrnlgrp_stdjrnlgrp_id_seq'::regclass);
109879
109880
109881 --
109882 -- TOC entry 6664 (class 2604 OID 146570439)
109883 -- Dependencies: 796 795
109884 -- Name: stdjrnlgrpitem_id; Type: DEFAULT; Schema: public; Owner: admin
109885 --
109886
109887 ALTER TABLE ONLY stdjrnlgrpitem ALTER COLUMN stdjrnlgrpitem_id SET DEFAULT nextval('stdjrnlgrpitem_stdjrnlgrpitem_id_seq'::regclass);
109888
109889
109890 --
109891 -- TOC entry 6665 (class 2604 OID 146570440)
109892 -- Dependencies: 798 797
109893 -- Name: stdjrnlitem_id; Type: DEFAULT; Schema: public; Owner: admin
109894 --
109895
109896 ALTER TABLE ONLY stdjrnlitem ALTER COLUMN stdjrnlitem_id SET DEFAULT nextval('stdjrnlitem_stdjrnlitem_id_seq'::regclass);
109897
109898
109899 --
109900 -- TOC entry 6666 (class 2604 OID 146570441)
109901 -- Dependencies: 800 799
109902 -- Name: subaccnt_id; Type: DEFAULT; Schema: public; Owner: admin
109903 --
109904
109905 ALTER TABLE ONLY subaccnt ALTER COLUMN subaccnt_id SET DEFAULT nextval('subaccnt_subaccnt_id_seq'::regclass);
109906
109907
109908 --
109909 -- TOC entry 6668 (class 2604 OID 146570442)
109910 -- Dependencies: 802 801
109911 -- Name: subaccnttype_id; Type: DEFAULT; Schema: public; Owner: admin
109912 --
109913
109914 ALTER TABLE ONLY subaccnttype ALTER COLUMN subaccnttype_id SET DEFAULT nextval('subaccnttype_subaccnttype_id_seq'::regclass);
109915
109916
109917 --
109918 -- TOC entry 6669 (class 2604 OID 146570443)
109919 -- Dependencies: 805 804
109920 -- Name: taxass_id; Type: DEFAULT; Schema: public; Owner: admin
109921 --
109922
109923 ALTER TABLE ONLY taxass ALTER COLUMN taxass_id SET DEFAULT nextval('taxass_taxass_id_seq'::regclass);
109924
109925
109926 --
109927 -- TOC entry 6137 (class 2604 OID 146570444)
109928 -- Dependencies: 806 284
109929 -- Name: taxauth_id; Type: DEFAULT; Schema: public; Owner: admin
109930 --
109931
109932 ALTER TABLE ONLY taxauth ALTER COLUMN taxauth_id SET DEFAULT nextval('taxauth_taxauth_id_seq'::regclass);
109933
109934
109935 --
109936 -- TOC entry 6670 (class 2604 OID 146570445)
109937 -- Dependencies: 808 807
109938 -- Name: taxclass_id; Type: DEFAULT; Schema: public; Owner: admin
109939 --
109940
109941 ALTER TABLE ONLY taxclass ALTER COLUMN taxclass_id SET DEFAULT nextval('taxclass_taxclass_id_seq'::regclass);
109942
109943
109944 --
109945 -- TOC entry 6257 (class 2604 OID 146570446)
109946 -- Dependencies: 378 377
109947 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
109948 --
109949
109950 ALTER TABLE ONLY taxhist ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
109951
109952
109953 --
109954 -- TOC entry 6672 (class 2604 OID 146570459)
109955 -- Dependencies: 810 809
109956 -- Name: taxrate_id; Type: DEFAULT; Schema: public; Owner: admin
109957 --
109958
109959 ALTER TABLE ONLY taxrate ALTER COLUMN taxrate_id SET DEFAULT nextval('taxrate_taxrate_id_seq'::regclass);
109960
109961
109962 --
109963 -- TOC entry 6142 (class 2604 OID 146570460)
109964 -- Dependencies: 811 285
109965 -- Name: taxreg_id; Type: DEFAULT; Schema: public; Owner: admin
109966 --
109967
109968 ALTER TABLE ONLY taxreg ALTER COLUMN taxreg_id SET DEFAULT nextval('taxreg_taxreg_id_seq'::regclass);
109969
109970
109971 --
109972 -- TOC entry 5929 (class 2604 OID 146570461)
109973 -- Dependencies: 812 199
109974 -- Name: taxtype_id; Type: DEFAULT; Schema: public; Owner: admin
109975 --
109976
109977 ALTER TABLE ONLY taxtype ALTER COLUMN taxtype_id SET DEFAULT nextval('taxtype_taxtype_id_seq'::regclass);
109978
109979
109980 --
109981 -- TOC entry 6018 (class 2604 OID 146570462)
109982 -- Dependencies: 813 220
109983 -- Name: taxzone_id; Type: DEFAULT; Schema: public; Owner: admin
109984 --
109985
109986 ALTER TABLE ONLY taxzone ALTER COLUMN taxzone_id SET DEFAULT nextval('taxzone_taxzone_id_seq'::regclass);
109987
109988
109989 --
109990 -- TOC entry 6045 (class 2604 OID 146570463)
109991 -- Dependencies: 815 233
109992 -- Name: todoitem_id; Type: DEFAULT; Schema: public; Owner: admin
109993 --
109994
109995 ALTER TABLE ONLY todoitem ALTER COLUMN todoitem_id SET DEFAULT nextval('todoitem_todoitem_id_seq'::regclass);
109996
109997
109998 --
109999 -- TOC entry 6673 (class 2604 OID 146570464)
110000 -- Dependencies: 818 817
110001 -- Name: trialbal_id; Type: DEFAULT; Schema: public; Owner: admin
110002 --
110003
110004 ALTER TABLE ONLY trialbal ALTER COLUMN trialbal_id SET DEFAULT nextval('trialbal_trialbal_id_seq'::regclass);
110005
110006
110007 --
110008 -- TOC entry 6282 (class 2604 OID 146568328)
110009 -- Dependencies: 418 417
110010 -- Name: uiform_id; Type: DEFAULT; Schema: public; Owner: admin
110011 --
110012
110013 ALTER TABLE ONLY uiform ALTER COLUMN uiform_id SET DEFAULT nextval('uiform_uiform_id_seq'::regclass);
110014
110015
110016 --
110017 -- TOC entry 5932 (class 2604 OID 146570465)
110018 -- Dependencies: 819 200
110019 -- Name: uom_id; Type: DEFAULT; Schema: public; Owner: admin
110020 --
110021
110022 ALTER TABLE ONLY uom ALTER COLUMN uom_id SET DEFAULT nextval('uom_uom_id_seq'::regclass);
110023
110024
110025 --
110026 -- TOC entry 6675 (class 2604 OID 146570466)
110027 -- Dependencies: 821 820
110028 -- Name: uomconv_id; Type: DEFAULT; Schema: public; Owner: admin
110029 --
110030
110031 ALTER TABLE ONLY uomconv ALTER COLUMN uomconv_id SET DEFAULT nextval('uomconv_uomconv_id_seq'::regclass);
110032
110033
110034 --
110035 -- TOC entry 6677 (class 2604 OID 146570467)
110036 -- Dependencies: 823 822
110037 -- Name: uomtype_id; Type: DEFAULT; Schema: public; Owner: admin
110038 --
110039
110040 ALTER TABLE ONLY uomtype ALTER COLUMN uomtype_id SET DEFAULT nextval('uomtype_uomtype_id_seq'::regclass);
110041
110042
110043 --
110044 -- TOC entry 6085 (class 2604 OID 146570468)
110045 -- Dependencies: 824 244
110046 -- Name: url_id; Type: DEFAULT; Schema: public; Owner: admin
110047 --
110048
110049 ALTER TABLE ONLY urlinfo ALTER COLUMN url_id SET DEFAULT nextval('urlinfo_url_id_seq'::regclass);
110050
110051
110052 --
110053 -- TOC entry 6618 (class 2604 OID 146570469)
110054 -- Dependencies: 829 732
110055 -- Name: usrgrp_id; Type: DEFAULT; Schema: public; Owner: admin
110056 --
110057
110058 ALTER TABLE ONLY usrgrp ALTER COLUMN usrgrp_id SET DEFAULT nextval('usrgrp_usrgrp_id_seq'::regclass);
110059
110060
110061 --
110062 -- TOC entry 6263 (class 2604 OID 146570470)
110063 -- Dependencies: 836 393
110064 -- Name: vendtype_id; Type: DEFAULT; Schema: public; Owner: admin
110065 --
110066
110067 ALTER TABLE ONLY vendtype ALTER COLUMN vendtype_id SET DEFAULT nextval('vendtype_vendtype_id_seq'::regclass);
110068
110069
110070 --
110071 -- TOC entry 6689 (class 2604 OID 146570457)
110072 -- Dependencies: 841 378 841
110073 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
110074 --
110075
110076 ALTER TABLE ONLY voheadtax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
110077
110078
110079 --
110080 -- TOC entry 6692 (class 2604 OID 146570458)
110081 -- Dependencies: 844 378 844
110082 -- Name: taxhist_id; Type: DEFAULT; Schema: public; Owner: admin
110083 --
110084
110085 ALTER TABLE ONLY voitemtax ALTER COLUMN taxhist_id SET DEFAULT nextval('taxhist_taxhist_id_seq'::regclass);
110086
110087
110088 --
110089 -- TOC entry 6216 (class 2604 OID 146570471)
110090 -- Dependencies: 847 343
110091 -- Name: whsezone_id; Type: DEFAULT; Schema: public; Owner: admin
110092 --
110093
110094 ALTER TABLE ONLY whsezone ALTER COLUMN whsezone_id SET DEFAULT nextval('whsezone_whsezone_id_seq'::regclass);
110095
110096
110097 --
110098 -- TOC entry 6693 (class 2604 OID 146570472)
110099 -- Dependencies: 851 850
110100 -- Name: womatlpost_id; Type: DEFAULT; Schema: public; Owner: admin
110101 --
110102
110103 ALTER TABLE ONLY womatlpost ALTER COLUMN womatlpost_id SET DEFAULT nextval('womatlpost_womatlpost_id_seq'::regclass);
110104
110105
110106 --
110107 -- TOC entry 6696 (class 2604 OID 146570473)
110108 -- Dependencies: 856 855
110109 -- Name: xsltmap_id; Type: DEFAULT; Schema: public; Owner: admin
110110 --
110111
110112 ALTER TABLE ONLY xsltmap ALTER COLUMN xsltmap_id SET DEFAULT nextval('xsltmap_xsltmap_id_seq'::regclass);
110113
110114
110115 --
110116 -- TOC entry 6701 (class 2604 OID 146570474)
110117 -- Dependencies: 858 857
110118 -- Name: yearperiod_id; Type: DEFAULT; Schema: public; Owner: admin
110119 --
110120
110121 ALTER TABLE ONLY yearperiod ALTER COLUMN yearperiod_id SET DEFAULT nextval('yearperiod_yearperiod_id_seq'::regclass);
110122
110123
110124 SET search_path = te, pg_catalog;
110125
110126 --
110127 -- TOC entry 6707 (class 2604 OID 146570167)
110128 -- Dependencies: 862 862
110129 -- Name: metasql_grade; Type: DEFAULT; Schema: te; Owner: admin
110130 --
110131
110132 ALTER TABLE ONLY pkgmetasql ALTER COLUMN metasql_grade SET DEFAULT 0;
110133
110134
110135 --
110136 -- TOC entry 6711 (class 2604 OID 146570189)
110137 -- Dependencies: 865 865
110138 -- Name: script_enabled; Type: DEFAULT; Schema: te; Owner: admin
110139 --
110140
110141 ALTER TABLE ONLY pkgscript ALTER COLUMN script_enabled SET DEFAULT false;
110142
110143
110144 --
110145 -- TOC entry 6713 (class 2604 OID 146570197)
110146 -- Dependencies: 866 866
110147 -- Name: uiform_enabled; Type: DEFAULT; Schema: te; Owner: admin
110148 --
110149
110150 ALTER TABLE ONLY pkguiform ALTER COLUMN uiform_enabled SET DEFAULT false;
110151
110152
110153 --
110154 -- TOC entry 6714 (class 2604 OID 146570475)
110155 -- Dependencies: 868 867
110156 -- Name: tecustrate_id; Type: DEFAULT; Schema: te; Owner: admin
110157 --
110158
110159 ALTER TABLE ONLY tecustrate ALTER COLUMN tecustrate_id SET DEFAULT nextval('tecustrate_tecustrate_id_seq'::regclass);
110160
110161
110162 --
110163 -- TOC entry 6716 (class 2604 OID 146570476)
110164 -- Dependencies: 870 869
110165 -- Name: teemp_id; Type: DEFAULT; Schema: te; Owner: admin
110166 --
110167
110168 ALTER TABLE ONLY teemp ALTER COLUMN teemp_id SET DEFAULT nextval('teemp_teemp_id_seq'::regclass);
110169
110170
110171 --
110172 -- TOC entry 6722 (class 2604 OID 146570477)
110173 -- Dependencies: 874 873
110174 -- Name: tehead_id; Type: DEFAULT; Schema: te; Owner: admin
110175 --
110176
110177 ALTER TABLE ONLY tehead ALTER COLUMN tehead_id SET DEFAULT nextval('tehead_tehead_id_seq'::regclass);
110178
110179
110180 --
110181 -- TOC entry 6728 (class 2604 OID 146570478)
110182 -- Dependencies: 876 875
110183 -- Name: teitem_id; Type: DEFAULT; Schema: te; Owner: admin
110184 --
110185
110186 ALTER TABLE ONLY teitem ALTER COLUMN teitem_id SET DEFAULT nextval('teitem_teitem_id_seq'::regclass);
110187
110188
110189 --
110190 -- TOC entry 6729 (class 2604 OID 146570479)
110191 -- Dependencies: 878 877
110192 -- Name: teprj_id; Type: DEFAULT; Schema: te; Owner: admin
110193 --
110194
110195 ALTER TABLE ONLY teprj ALTER COLUMN teprj_id SET DEFAULT nextval('teprj_teprj_id_seq'::regclass);
110196
110197
110198 --
110199 -- TOC entry 6730 (class 2604 OID 146570480)
110200 -- Dependencies: 880 879
110201 -- Name: teprjtask_id; Type: DEFAULT; Schema: te; Owner: admin
110202 --
110203
110204 ALTER TABLE ONLY teprjtask ALTER COLUMN teprjtask_id SET DEFAULT nextval('teprjtask_teprjtask_id_seq'::regclass);
110205
110206
110207 SET search_path = xtdesktop, pg_catalog;
110208
110209 --
110210 -- TOC entry 6736 (class 2604 OID 146570285)
110211 -- Dependencies: 884 884
110212 -- Name: metasql_grade; Type: DEFAULT; Schema: xtdesktop; Owner: admin
110213 --
110214
110215 ALTER TABLE ONLY pkgmetasql ALTER COLUMN metasql_grade SET DEFAULT 0;
110216
110217
110218 --
110219 -- TOC entry 6740 (class 2604 OID 146570307)
110220 -- Dependencies: 887 887
110221 -- Name: script_enabled; Type: DEFAULT; Schema: xtdesktop; Owner: admin
110222 --
110223
110224 ALTER TABLE ONLY pkgscript ALTER COLUMN script_enabled SET DEFAULT false;
110225
110226
110227 --
110228 -- TOC entry 6742 (class 2604 OID 146570315)
110229 -- Dependencies: 888 888
110230 -- Name: uiform_enabled; Type: DEFAULT; Schema: xtdesktop; Owner: admin
110231 --
110232
110233 ALTER TABLE ONLY pkguiform ALTER COLUMN uiform_enabled SET DEFAULT false;
110234
110235
110236 SET search_path = fixcountry, pg_catalog;
110237
110238 --
110239 -- TOC entry 7165 (class 2606 OID 146570802)
110240 -- Dependencies: 399 399 8894
110241 -- Name: pkgcmd_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110242 --
110243
110244 ALTER TABLE ONLY pkgcmd
110245     ADD CONSTRAINT pkgcmd_pkey PRIMARY KEY (cmd_id);
110246
110247
110248 --
110249 -- TOC entry 7169 (class 2606 OID 146570804)
110250 -- Dependencies: 402 402 8894
110251 -- Name: pkgcmdarg_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110252 --
110253
110254 ALTER TABLE ONLY pkgcmdarg
110255     ADD CONSTRAINT pkgcmdarg_pkey PRIMARY KEY (cmdarg_id);
110256
110257
110258 --
110259 -- TOC entry 7171 (class 2606 OID 146570806)
110260 -- Dependencies: 404 404 8894
110261 -- Name: pkgimage_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110262 --
110263
110264 ALTER TABLE ONLY pkgimage
110265     ADD CONSTRAINT pkgimage_pkey PRIMARY KEY (image_id);
110266
110267
110268 --
110269 -- TOC entry 7177 (class 2606 OID 146570808)
110270 -- Dependencies: 407 407 8894
110271 -- Name: pkgmetasql_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110272 --
110273
110274 ALTER TABLE ONLY pkgmetasql
110275     ADD CONSTRAINT pkgmetasql_pkey PRIMARY KEY (metasql_id);
110276
110277
110278 --
110279 -- TOC entry 7182 (class 2606 OID 146570810)
110280 -- Dependencies: 410 410 8894
110281 -- Name: pkgpriv_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110282 --
110283
110284 ALTER TABLE ONLY pkgpriv
110285     ADD CONSTRAINT pkgpriv_pkey PRIMARY KEY (priv_id);
110286
110287
110288 --
110289 -- TOC entry 7187 (class 2606 OID 146570812)
110290 -- Dependencies: 413 413 8894
110291 -- Name: pkgreport_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110292 --
110293
110294 ALTER TABLE ONLY pkgreport
110295     ADD CONSTRAINT pkgreport_pkey PRIMARY KEY (report_id);
110296
110297
110298 --
110299 -- TOC entry 7191 (class 2606 OID 146570814)
110300 -- Dependencies: 416 416 8894
110301 -- Name: pkgscript_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110302 --
110303
110304 ALTER TABLE ONLY pkgscript
110305     ADD CONSTRAINT pkgscript_pkey PRIMARY KEY (script_id);
110306
110307
110308 --
110309 -- TOC entry 7195 (class 2606 OID 146570816)
110310 -- Dependencies: 419 419 8894
110311 -- Name: pkguiform_pkey; Type: CONSTRAINT; Schema: fixcountry; Owner: admin; Tablespace: 
110312 --
110313
110314 ALTER TABLE ONLY pkguiform
110315     ADD CONSTRAINT pkguiform_pkey PRIMARY KEY (uiform_id);
110316
110317
110318 SET search_path = public, pg_catalog;
110319
110320 --
110321 -- TOC entry 7197 (class 2606 OID 146570818)
110322 -- Dependencies: 420 420 8894
110323 -- Name: acalitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110324 --
110325
110326 ALTER TABLE ONLY acalitem
110327     ADD CONSTRAINT acalitem_pkey PRIMARY KEY (acalitem_id);
110328
110329
110330 --
110331 -- TOC entry 6955 (class 2606 OID 146570820)
110332 -- Dependencies: 262 262 8894
110333 -- Name: accnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110334 --
110335
110336 ALTER TABLE ONLY accnt
110337     ADD CONSTRAINT accnt_pkey PRIMARY KEY (accnt_id);
110338
110339
110340 --
110341 -- TOC entry 6919 (class 2606 OID 146570822)
110342 -- Dependencies: 234 234 8894
110343 -- Name: addr_addr_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110344 --
110345
110346 ALTER TABLE ONLY addr
110347     ADD CONSTRAINT addr_addr_number_key UNIQUE (addr_number);
110348
110349
110350 --
110351 -- TOC entry 6921 (class 2606 OID 146570824)
110352 -- Dependencies: 234 234 8894
110353 -- Name: addr_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110354 --
110355
110356 ALTER TABLE ONLY addr
110357     ADD CONSTRAINT addr_pkey PRIMARY KEY (addr_id);
110358
110359
110360 --
110361 -- TOC entry 7199 (class 2606 OID 146570826)
110362 -- Dependencies: 424 424 8894
110363 -- Name: alarm_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110364 --
110365
110366 ALTER TABLE ONLY alarm
110367     ADD CONSTRAINT alarm_pkey PRIMARY KEY (alarm_id);
110368
110369
110370 --
110371 -- TOC entry 7201 (class 2606 OID 146570828)
110372 -- Dependencies: 426 426 8894
110373 -- Name: apaccnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110374 --
110375
110376 ALTER TABLE ONLY apaccnt
110377     ADD CONSTRAINT apaccnt_pkey PRIMARY KEY (apaccnt_id);
110378
110379
110380 --
110381 -- TOC entry 7203 (class 2606 OID 146570830)
110382 -- Dependencies: 428 428 8894
110383 -- Name: apapply_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110384 --
110385
110386 ALTER TABLE ONLY apapply
110387     ADD CONSTRAINT apapply_pkey PRIMARY KEY (apapply_id);
110388
110389
110390 --
110391 -- TOC entry 7212 (class 2606 OID 146570832)
110392 -- Dependencies: 434 434 8894
110393 -- Name: apcreditapply_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110394 --
110395
110396 ALTER TABLE ONLY apcreditapply
110397     ADD CONSTRAINT apcreditapply_pkey PRIMARY KEY (apcreditapply_id);
110398
110399
110400 --
110401 -- TOC entry 6829 (class 2606 OID 146570834)
110402 -- Dependencies: 207 207 8894
110403 -- Name: apopen_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110404 --
110405
110406 ALTER TABLE ONLY apopen
110407     ADD CONSTRAINT apopen_pkey PRIMARY KEY (apopen_id);
110408
110409
110410 --
110411 -- TOC entry 7214 (class 2606 OID 146570836)
110412 -- Dependencies: 438 438 8894
110413 -- Name: apopentax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110414 --
110415
110416 ALTER TABLE ONLY apopentax
110417     ADD CONSTRAINT apopentax_pkey PRIMARY KEY (taxhist_id);
110418
110419
110420 --
110421 -- TOC entry 7217 (class 2606 OID 146570838)
110422 -- Dependencies: 439 439 8894
110423 -- Name: apselect_apselect_apopen_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110424 --
110425
110426 ALTER TABLE ONLY apselect
110427     ADD CONSTRAINT apselect_apselect_apopen_id_key UNIQUE (apselect_apopen_id);
110428
110429
110430 --
110431 -- TOC entry 7219 (class 2606 OID 146570840)
110432 -- Dependencies: 439 439 8894
110433 -- Name: apselect_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110434 --
110435
110436 ALTER TABLE ONLY apselect
110437     ADD CONSTRAINT apselect_pkey PRIMARY KEY (apselect_id);
110438
110439
110440 --
110441 -- TOC entry 7221 (class 2606 OID 146570842)
110442 -- Dependencies: 441 441 8894
110443 -- Name: araccnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110444 --
110445
110446 ALTER TABLE ONLY araccnt
110447     ADD CONSTRAINT araccnt_pkey PRIMARY KEY (araccnt_id);
110448
110449
110450 --
110451 -- TOC entry 7224 (class 2606 OID 146570844)
110452 -- Dependencies: 443 443 8894
110453 -- Name: arapply_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110454 --
110455
110456 ALTER TABLE ONLY arapply
110457     ADD CONSTRAINT arapply_pkey PRIMARY KEY (arapply_id);
110458
110459
110460 --
110461 -- TOC entry 7226 (class 2606 OID 146570846)
110462 -- Dependencies: 446 446 8894
110463 -- Name: arcreditapply_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110464 --
110465
110466 ALTER TABLE ONLY arcreditapply
110467     ADD CONSTRAINT arcreditapply_pkey PRIMARY KEY (arcreditapply_id);
110468
110469
110470 --
110471 -- TOC entry 6850 (class 2606 OID 146570848)
110472 -- Dependencies: 212 212 8894
110473 -- Name: aropen_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110474 --
110475
110476 ALTER TABLE ONLY aropen
110477     ADD CONSTRAINT aropen_pkey PRIMARY KEY (aropen_id);
110478
110479
110480 --
110481 -- TOC entry 7138 (class 2606 OID 146570850)
110482 -- Dependencies: 374 374 374 374 8894
110483 -- Name: aropenalloc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110484 --
110485
110486 ALTER TABLE ONLY aropenalloc
110487     ADD CONSTRAINT aropenalloc_pkey PRIMARY KEY (aropenalloc_aropen_id, aropenalloc_doctype, aropenalloc_doc_id);
110488
110489
110490 --
110491 -- TOC entry 7228 (class 2606 OID 146570852)
110492 -- Dependencies: 450 450 8894
110493 -- Name: aropentax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110494 --
110495
110496 ALTER TABLE ONLY aropentax
110497     ADD CONSTRAINT aropentax_pkey PRIMARY KEY (taxhist_id);
110498
110499
110500 --
110501 -- TOC entry 7230 (class 2606 OID 146570854)
110502 -- Dependencies: 451 451 8894
110503 -- Name: asohist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110504 --
110505
110506 ALTER TABLE ONLY asohist
110507     ADD CONSTRAINT asohist_pkey PRIMARY KEY (asohist_id);
110508
110509
110510 --
110511 -- TOC entry 7232 (class 2606 OID 146570856)
110512 -- Dependencies: 453 453 8894
110513 -- Name: asohisttax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110514 --
110515
110516 ALTER TABLE ONLY asohisttax
110517     ADD CONSTRAINT asohisttax_pkey PRIMARY KEY (taxhist_id);
110518
110519
110520 --
110521 -- TOC entry 7234 (class 2606 OID 146570858)
110522 -- Dependencies: 454 454 8894
110523 -- Name: atlasmap_atlasmap_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110524 --
110525
110526 ALTER TABLE ONLY atlasmap
110527     ADD CONSTRAINT atlasmap_atlasmap_name_key UNIQUE (atlasmap_name);
110528
110529
110530 --
110531 -- TOC entry 7236 (class 2606 OID 146570860)
110532 -- Dependencies: 454 454 8894
110533 -- Name: atlasmap_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110534 --
110535
110536 ALTER TABLE ONLY atlasmap
110537     ADD CONSTRAINT atlasmap_pkey PRIMARY KEY (atlasmap_id);
110538
110539
110540 --
110541 -- TOC entry 6962 (class 2606 OID 146570862)
110542 -- Dependencies: 266 266 8894
110543 -- Name: bankaccnt_bankaccnt_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110544 --
110545
110546 ALTER TABLE ONLY bankaccnt
110547     ADD CONSTRAINT bankaccnt_bankaccnt_name_key UNIQUE (bankaccnt_name);
110548
110549
110550 --
110551 -- TOC entry 6964 (class 2606 OID 146570864)
110552 -- Dependencies: 266 266 8894
110553 -- Name: bankaccnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110554 --
110555
110556 ALTER TABLE ONLY bankaccnt
110557     ADD CONSTRAINT bankaccnt_pkey PRIMARY KEY (bankaccnt_id);
110558
110559
110560 --
110561 -- TOC entry 7238 (class 2606 OID 146570866)
110562 -- Dependencies: 458 458 8894
110563 -- Name: bankadj_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110564 --
110565
110566 ALTER TABLE ONLY bankadj
110567     ADD CONSTRAINT bankadj_pkey PRIMARY KEY (bankadj_id);
110568
110569
110570 --
110571 -- TOC entry 7240 (class 2606 OID 146570868)
110572 -- Dependencies: 460 460 8894
110573 -- Name: bankadjtype_bankadjtype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110574 --
110575
110576 ALTER TABLE ONLY bankadjtype
110577     ADD CONSTRAINT bankadjtype_bankadjtype_name_key UNIQUE (bankadjtype_name);
110578
110579
110580 --
110581 -- TOC entry 7242 (class 2606 OID 146570870)
110582 -- Dependencies: 460 460 8894
110583 -- Name: bankadjtype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110584 --
110585
110586 ALTER TABLE ONLY bankadjtype
110587     ADD CONSTRAINT bankadjtype_pkey PRIMARY KEY (bankadjtype_id);
110588
110589
110590 --
110591 -- TOC entry 7244 (class 2606 OID 146570872)
110592 -- Dependencies: 462 462 8894
110593 -- Name: bankrec_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110594 --
110595
110596 ALTER TABLE ONLY bankrec
110597     ADD CONSTRAINT bankrec_pkey PRIMARY KEY (bankrec_id);
110598
110599
110600 --
110601 -- TOC entry 7246 (class 2606 OID 146570874)
110602 -- Dependencies: 464 464 8894
110603 -- Name: bankrecitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110604 --
110605
110606 ALTER TABLE ONLY bankrecitem
110607     ADD CONSTRAINT bankrecitem_pkey PRIMARY KEY (bankrecitem_id);
110608
110609
110610 --
110611 -- TOC entry 6947 (class 2606 OID 146570876)
110612 -- Dependencies: 254 254 8894
110613 -- Name: bomhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110614 --
110615
110616 ALTER TABLE ONLY bomhead
110617     ADD CONSTRAINT bomhead_pkey PRIMARY KEY (bomhead_id);
110618
110619
110620 --
110621 -- TOC entry 6811 (class 2606 OID 146570878)
110622 -- Dependencies: 203 203 8894
110623 -- Name: bomitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110624 --
110625
110626 ALTER TABLE ONLY bomitem
110627     ADD CONSTRAINT bomitem_pkey PRIMARY KEY (bomitem_id);
110628
110629
110630 --
110631 -- TOC entry 7250 (class 2606 OID 146570880)
110632 -- Dependencies: 468 468 8894
110633 -- Name: bomitemcost_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110634 --
110635
110636 ALTER TABLE ONLY bomitemcost
110637     ADD CONSTRAINT bomitemcost_pkey PRIMARY KEY (bomitemcost_id);
110638
110639
110640 --
110641 -- TOC entry 6949 (class 2606 OID 146570882)
110642 -- Dependencies: 258 258 8894
110643 -- Name: bomitemsub_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110644 --
110645
110646 ALTER TABLE ONLY bomitemsub
110647     ADD CONSTRAINT bomitemsub_pkey PRIMARY KEY (bomitemsub_id);
110648
110649
110650 --
110651 -- TOC entry 7252 (class 2606 OID 146570884)
110652 -- Dependencies: 471 471 8894
110653 -- Name: bomwork_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110654 --
110655
110656 ALTER TABLE ONLY bomwork
110657     ADD CONSTRAINT bomwork_pkey PRIMARY KEY (bomwork_id);
110658
110659
110660 --
110661 -- TOC entry 6951 (class 2606 OID 146570886)
110662 -- Dependencies: 260 260 8894
110663 -- Name: budghead_budghead_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110664 --
110665
110666 ALTER TABLE ONLY budghead
110667     ADD CONSTRAINT budghead_budghead_name_key UNIQUE (budghead_name);
110668
110669
110670 --
110671 -- TOC entry 6953 (class 2606 OID 146570888)
110672 -- Dependencies: 260 260 8894
110673 -- Name: budghead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110674 --
110675
110676 ALTER TABLE ONLY budghead
110677     ADD CONSTRAINT budghead_pkey PRIMARY KEY (budghead_id);
110678
110679
110680 --
110681 -- TOC entry 6958 (class 2606 OID 146570890)
110682 -- Dependencies: 263 263 8894
110683 -- Name: budgitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110684 --
110685
110686 ALTER TABLE ONLY budgitem
110687     ADD CONSTRAINT budgitem_pkey PRIMARY KEY (budgitem_id);
110688
110689
110690 --
110691 -- TOC entry 7254 (class 2606 OID 146570892)
110692 -- Dependencies: 476 476 8894
110693 -- Name: calhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110694 --
110695
110696 ALTER TABLE ONLY calhead
110697     ADD CONSTRAINT calhead_pkey PRIMARY KEY (calhead_id);
110698
110699
110700 --
110701 -- TOC entry 6966 (class 2606 OID 146570894)
110702 -- Dependencies: 267 267 8894
110703 -- Name: cashrcpt_cashrcpt_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110704 --
110705
110706 ALTER TABLE ONLY cashrcpt
110707     ADD CONSTRAINT cashrcpt_cashrcpt_number_key UNIQUE (cashrcpt_number);
110708
110709
110710 --
110711 -- TOC entry 6968 (class 2606 OID 146570896)
110712 -- Dependencies: 267 267 8894
110713 -- Name: cashrcpt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110714 --
110715
110716 ALTER TABLE ONLY cashrcpt
110717     ADD CONSTRAINT cashrcpt_pkey PRIMARY KEY (cashrcpt_id);
110718
110719
110720 --
110721 -- TOC entry 6972 (class 2606 OID 146570898)
110722 -- Dependencies: 269 269 8894
110723 -- Name: cashrcptitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110724 --
110725
110726 ALTER TABLE ONLY cashrcptitem
110727     ADD CONSTRAINT cashrcptitem_pkey PRIMARY KEY (cashrcptitem_id);
110728
110729
110730 --
110731 -- TOC entry 6974 (class 2606 OID 146570900)
110732 -- Dependencies: 271 271 8894
110733 -- Name: cashrcptmisc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110734 --
110735
110736 ALTER TABLE ONLY cashrcptmisc
110737     ADD CONSTRAINT cashrcptmisc_pkey PRIMARY KEY (cashrcptmisc_id);
110738
110739
110740 --
110741 -- TOC entry 6977 (class 2606 OID 146570902)
110742 -- Dependencies: 278 278 8894
110743 -- Name: ccard_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110744 --
110745
110746 ALTER TABLE ONLY ccard
110747     ADD CONSTRAINT ccard_pkey PRIMARY KEY (ccard_id);
110748
110749
110750 --
110751 -- TOC entry 7258 (class 2606 OID 146570904)
110752 -- Dependencies: 482 482 8894
110753 -- Name: ccardaud_ccard_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110754 --
110755
110756 ALTER TABLE ONLY ccardaud
110757     ADD CONSTRAINT ccardaud_ccard_pkey PRIMARY KEY (ccardaud_id);
110758
110759
110760 --
110761 -- TOC entry 7260 (class 2606 OID 146570906)
110762 -- Dependencies: 484 484 8894
110763 -- Name: ccbank_ccbank_ccard_type_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110764 --
110765
110766 ALTER TABLE ONLY ccbank
110767     ADD CONSTRAINT ccbank_ccbank_ccard_type_key UNIQUE (ccbank_ccard_type);
110768
110769
110770 --
110771 -- TOC entry 7262 (class 2606 OID 146570908)
110772 -- Dependencies: 484 484 8894
110773 -- Name: ccbank_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110774 --
110775
110776 ALTER TABLE ONLY ccbank
110777     ADD CONSTRAINT ccbank_pkey PRIMARY KEY (ccbank_id);
110778
110779
110780 --
110781 -- TOC entry 7267 (class 2606 OID 146570910)
110782 -- Dependencies: 486 486 8894
110783 -- Name: ccpay_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110784 --
110785
110786 ALTER TABLE ONLY ccpay
110787     ADD CONSTRAINT ccpay_pkey PRIMARY KEY (ccpay_id);
110788
110789
110790 --
110791 -- TOC entry 6923 (class 2606 OID 146570912)
110792 -- Dependencies: 236 236 8894
110793 -- Name: char_char_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110794 --
110795
110796 ALTER TABLE ONLY "char"
110797     ADD CONSTRAINT char_char_name_key UNIQUE (char_name);
110798
110799
110800 --
110801 -- TOC entry 6925 (class 2606 OID 146570914)
110802 -- Dependencies: 236 236 8894
110803 -- Name: char_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110804 --
110805
110806 ALTER TABLE ONLY "char"
110807     ADD CONSTRAINT char_pkey PRIMARY KEY (char_id);
110808
110809
110810 --
110811 -- TOC entry 6927 (class 2606 OID 146570916)
110812 -- Dependencies: 237 237 8894
110813 -- Name: charass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110814 --
110815
110816 ALTER TABLE ONLY charass
110817     ADD CONSTRAINT charass_pkey PRIMARY KEY (charass_id);
110818
110819
110820 --
110821 -- TOC entry 7269 (class 2606 OID 146570918)
110822 -- Dependencies: 490 490 8894
110823 -- Name: charopt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110824 --
110825
110826 ALTER TABLE ONLY charopt
110827     ADD CONSTRAINT charopt_pkey PRIMARY KEY (charopt_id);
110828
110829
110830 --
110831 -- TOC entry 7205 (class 2606 OID 146570920)
110832 -- Dependencies: 430 430 8894
110833 -- Name: checkhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110834 --
110835
110836 ALTER TABLE ONLY checkhead
110837     ADD CONSTRAINT checkhead_pkey PRIMARY KEY (checkhead_id);
110838
110839
110840 --
110841 -- TOC entry 7210 (class 2606 OID 146570922)
110842 -- Dependencies: 432 432 8894
110843 -- Name: checkitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110844 --
110845
110846 ALTER TABLE ONLY checkitem
110847     ADD CONSTRAINT checkitem_pkey PRIMARY KEY (checkitem_id);
110848
110849
110850 --
110851 -- TOC entry 7036 (class 2606 OID 146570924)
110852 -- Dependencies: 313 313 8894
110853 -- Name: classcode_classcode_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110854 --
110855
110856 ALTER TABLE ONLY classcode
110857     ADD CONSTRAINT classcode_classcode_code_key UNIQUE (classcode_code);
110858
110859
110860 --
110861 -- TOC entry 7038 (class 2606 OID 146570926)
110862 -- Dependencies: 313 313 8894
110863 -- Name: classcode_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110864 --
110865
110866 ALTER TABLE ONLY classcode
110867     ADD CONSTRAINT classcode_pkey PRIMARY KEY (classcode_id);
110868
110869
110870 --
110871 -- TOC entry 7163 (class 2606 OID 146570928)
110872 -- Dependencies: 397 397 8894
110873 -- Name: cmd_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110874 --
110875
110876 ALTER TABLE ONLY cmd
110877     ADD CONSTRAINT cmd_pkey PRIMARY KEY (cmd_id);
110878
110879
110880 --
110881 -- TOC entry 7167 (class 2606 OID 146570930)
110882 -- Dependencies: 400 400 8894
110883 -- Name: cmdarg_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110884 --
110885
110886 ALTER TABLE ONLY cmdarg
110887     ADD CONSTRAINT cmdarg_pkey PRIMARY KEY (cmdarg_id);
110888
110889
110890 --
110891 -- TOC entry 6870 (class 2606 OID 146570932)
110892 -- Dependencies: 218 218 8894
110893 -- Name: cmhead_cmhead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110894 --
110895
110896 ALTER TABLE ONLY cmhead
110897     ADD CONSTRAINT cmhead_cmhead_number_key UNIQUE (cmhead_number);
110898
110899
110900 --
110901 -- TOC entry 6873 (class 2606 OID 146570934)
110902 -- Dependencies: 218 218 8894
110903 -- Name: cmhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110904 --
110905
110906 ALTER TABLE ONLY cmhead
110907     ADD CONSTRAINT cmhead_pkey PRIMARY KEY (cmhead_id);
110908
110909
110910 --
110911 -- TOC entry 7271 (class 2606 OID 146570936)
110912 -- Dependencies: 497 497 8894
110913 -- Name: cmheadtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110914 --
110915
110916 ALTER TABLE ONLY cmheadtax
110917     ADD CONSTRAINT cmheadtax_pkey PRIMARY KEY (taxhist_id);
110918
110919
110920 --
110921 -- TOC entry 6883 (class 2606 OID 146570938)
110922 -- Dependencies: 222 222 222 8894
110923 -- Name: cmitem_cmhead_id_linenumber_unique; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110924 --
110925
110926 ALTER TABLE ONLY cmitem
110927     ADD CONSTRAINT cmitem_cmhead_id_linenumber_unique UNIQUE (cmitem_cmhead_id, cmitem_linenumber);
110928
110929
110930 --
110931 -- TOC entry 6885 (class 2606 OID 146570940)
110932 -- Dependencies: 222 222 8894
110933 -- Name: cmitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110934 --
110935
110936 ALTER TABLE ONLY cmitem
110937     ADD CONSTRAINT cmitem_pkey PRIMARY KEY (cmitem_id);
110938
110939
110940 --
110941 -- TOC entry 7273 (class 2606 OID 146570942)
110942 -- Dependencies: 499 499 8894
110943 -- Name: cmitemtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110944 --
110945
110946 ALTER TABLE ONLY cmitemtax
110947     ADD CONSTRAINT cmitemtax_pkey PRIMARY KEY (taxhist_id);
110948
110949
110950 --
110951 -- TOC entry 6930 (class 2606 OID 146570944)
110952 -- Dependencies: 239 239 8894
110953 -- Name: cmnttype_cmnttype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110954 --
110955
110956 ALTER TABLE ONLY cmnttype
110957     ADD CONSTRAINT cmnttype_cmnttype_name_key UNIQUE (cmnttype_name);
110958
110959
110960 --
110961 -- TOC entry 6932 (class 2606 OID 146570946)
110962 -- Dependencies: 239 239 8894
110963 -- Name: cmnttype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110964 --
110965
110966 ALTER TABLE ONLY cmnttype
110967     ADD CONSTRAINT cmnttype_pkey PRIMARY KEY (cmnttype_id);
110968
110969
110970 --
110971 -- TOC entry 7275 (class 2606 OID 146570948)
110972 -- Dependencies: 501 501 8894
110973 -- Name: cmnttypesource_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110974 --
110975
110976 ALTER TABLE ONLY cmnttypesource
110977     ADD CONSTRAINT cmnttypesource_pkey PRIMARY KEY (cmnttypesource_id);
110978
110979
110980 --
110981 -- TOC entry 6813 (class 2606 OID 146570950)
110982 -- Dependencies: 204 204 8894
110983 -- Name: cntct_cntct_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110984 --
110985
110986 ALTER TABLE ONLY cntct
110987     ADD CONSTRAINT cntct_cntct_number_key UNIQUE (cntct_number);
110988
110989
110990 --
110991 -- TOC entry 6817 (class 2606 OID 146570953)
110992 -- Dependencies: 204 204 8894
110993 -- Name: cntct_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
110994 --
110995
110996 ALTER TABLE ONLY cntct
110997     ADD CONSTRAINT cntct_pkey PRIMARY KEY (cntct_id);
110998
110999
111000 --
111001 -- TOC entry 7277 (class 2606 OID 146570955)
111002 -- Dependencies: 504 504 8894
111003 -- Name: cntctaddr_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111004 --
111005
111006 ALTER TABLE ONLY cntctaddr
111007     ADD CONSTRAINT cntctaddr_pkey PRIMARY KEY (cntctaddr_id);
111008
111009
111010 --
111011 -- TOC entry 7279 (class 2606 OID 146570958)
111012 -- Dependencies: 506 506 8894
111013 -- Name: cntctdata_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111014 --
111015
111016 ALTER TABLE ONLY cntctdata
111017     ADD CONSTRAINT cntctdata_pkey PRIMARY KEY (cntctdata_id);
111018
111019
111020 --
111021 -- TOC entry 7281 (class 2606 OID 146570960)
111022 -- Dependencies: 508 508 8894
111023 -- Name: cntcteml_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111024 --
111025
111026 ALTER TABLE ONLY cntcteml
111027     ADD CONSTRAINT cntcteml_pkey PRIMARY KEY (cntcteml_id);
111028
111029
111030 --
111031 -- TOC entry 7283 (class 2606 OID 146570962)
111032 -- Dependencies: 510 510 8894
111033 -- Name: cntctmrgd_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111034 --
111035
111036 ALTER TABLE ONLY cntctmrgd
111037     ADD CONSTRAINT cntctmrgd_pkey PRIMARY KEY (cntctmrgd_cntct_id);
111038
111039
111040 --
111041 -- TOC entry 7285 (class 2606 OID 146570964)
111042 -- Dependencies: 511 511 8894
111043 -- Name: cntctsel_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111044 --
111045
111046 ALTER TABLE ONLY cntctsel
111047     ADD CONSTRAINT cntctsel_pkey PRIMARY KEY (cntctsel_cntct_id);
111048
111049
111050 --
111051 -- TOC entry 6744 (class 2606 OID 146570967)
111052 -- Dependencies: 189 189 8894
111053 -- Name: cntslip_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111054 --
111055
111056 ALTER TABLE ONLY cntslip
111057     ADD CONSTRAINT cntslip_pkey PRIMARY KEY (cntslip_id);
111058
111059
111060 --
111061 -- TOC entry 7289 (class 2606 OID 146570969)
111062 -- Dependencies: 513 513 8894
111063 -- Name: cobill_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111064 --
111065
111066 ALTER TABLE ONLY cobill
111067     ADD CONSTRAINT cobill_pkey PRIMARY KEY (cobill_id);
111068
111069
111070 --
111071 -- TOC entry 7291 (class 2606 OID 146570972)
111072 -- Dependencies: 515 515 8894
111073 -- Name: cobilltax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111074 --
111075
111076 ALTER TABLE ONLY cobilltax
111077     ADD CONSTRAINT cobilltax_pkey PRIMARY KEY (taxhist_id);
111078
111079
111080 --
111081 -- TOC entry 7294 (class 2606 OID 146570974)
111082 -- Dependencies: 516 516 8894
111083 -- Name: cobmisc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111084 --
111085
111086 ALTER TABLE ONLY cobmisc
111087     ADD CONSTRAINT cobmisc_pkey PRIMARY KEY (cobmisc_id);
111088
111089
111090 --
111091 -- TOC entry 7297 (class 2606 OID 146570976)
111092 -- Dependencies: 518 518 8894
111093 -- Name: cobmisctax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111094 --
111095
111096 ALTER TABLE ONLY cobmisctax
111097     ADD CONSTRAINT cobmisctax_pkey PRIMARY KEY (taxhist_id);
111098
111099
111100 --
111101 -- TOC entry 6768 (class 2606 OID 146570978)
111102 -- Dependencies: 195 195 8894
111103 -- Name: cohead_cohead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111104 --
111105
111106 ALTER TABLE ONLY cohead
111107     ADD CONSTRAINT cohead_cohead_number_key UNIQUE (cohead_number);
111108
111109
111110 --
111111 -- TOC entry 6774 (class 2606 OID 146570980)
111112 -- Dependencies: 195 195 8894
111113 -- Name: cohead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111114 --
111115
111116 ALTER TABLE ONLY cohead
111117     ADD CONSTRAINT cohead_pkey PRIMARY KEY (cohead_id);
111118
111119
111120 --
111121 -- TOC entry 7143 (class 2606 OID 146570982)
111122 -- Dependencies: 376 376 8894
111123 -- Name: cohist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111124 --
111125
111126 ALTER TABLE ONLY cohist
111127     ADD CONSTRAINT cohist_pkey PRIMARY KEY (cohist_id);
111128
111129
111130 --
111131 -- TOC entry 7149 (class 2606 OID 146570984)
111132 -- Dependencies: 379 379 8894
111133 -- Name: cohisttax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111134 --
111135
111136 ALTER TABLE ONLY cohisttax
111137     ADD CONSTRAINT cohisttax_pkey PRIMARY KEY (taxhist_id);
111138
111139
111140 --
111141 -- TOC entry 6781 (class 2606 OID 146570986)
111142 -- Dependencies: 196 196 8894
111143 -- Name: coitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111144 --
111145
111146 ALTER TABLE ONLY coitem
111147     ADD CONSTRAINT coitem_pkey PRIMARY KEY (coitem_id);
111148
111149
111150 --
111151 -- TOC entry 6935 (class 2606 OID 146570989)
111152 -- Dependencies: 240 240 8894
111153 -- Name: comment_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111154 --
111155
111156 ALTER TABLE ONLY comment
111157     ADD CONSTRAINT comment_pkey PRIMARY KEY (comment_id);
111158
111159
111160 --
111161 -- TOC entry 7299 (class 2606 OID 146570991)
111162 -- Dependencies: 523 523 8894
111163 -- Name: company_company_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111164 --
111165
111166 ALTER TABLE ONLY company
111167     ADD CONSTRAINT company_company_number_key UNIQUE (company_number);
111168
111169
111170 --
111171 -- TOC entry 7301 (class 2606 OID 146570993)
111172 -- Dependencies: 523 523 8894
111173 -- Name: company_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111174 --
111175
111176 ALTER TABLE ONLY company
111177     ADD CONSTRAINT company_pkey PRIMARY KEY (company_id);
111178
111179
111180 --
111181 -- TOC entry 7065 (class 2606 OID 146570995)
111182 -- Dependencies: 329 329 8894
111183 -- Name: contrct_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111184 --
111185
111186 ALTER TABLE ONLY contrct
111187     ADD CONSTRAINT contrct_pkey PRIMARY KEY (contrct_id);
111188
111189
111190 --
111191 -- TOC entry 7056 (class 2606 OID 146570997)
111192 -- Dependencies: 325 325 8894
111193 -- Name: costcat_costcat_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111194 --
111195
111196 ALTER TABLE ONLY costcat
111197     ADD CONSTRAINT costcat_costcat_code_key UNIQUE (costcat_code);
111198
111199
111200 --
111201 -- TOC entry 7058 (class 2606 OID 146570999)
111202 -- Dependencies: 325 325 8894
111203 -- Name: costcat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111204 --
111205
111206 ALTER TABLE ONLY costcat
111207     ADD CONSTRAINT costcat_pkey PRIMARY KEY (costcat_id);
111208
111209
111210 --
111211 -- TOC entry 7048 (class 2606 OID 146571001)
111212 -- Dependencies: 320 320 8894
111213 -- Name: costelem_costelem_type_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111214 --
111215
111216 ALTER TABLE ONLY costelem
111217     ADD CONSTRAINT costelem_costelem_type_key UNIQUE (costelem_type);
111218
111219
111220 --
111221 -- TOC entry 7050 (class 2606 OID 146571004)
111222 -- Dependencies: 320 320 8894
111223 -- Name: costelem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111224 --
111225
111226 ALTER TABLE ONLY costelem
111227     ADD CONSTRAINT costelem_pkey PRIMARY KEY (costelem_id);
111228
111229
111230 --
111231 -- TOC entry 7314 (class 2606 OID 146571006)
111232 -- Dependencies: 535 535 8894
111233 -- Name: costhist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111234 --
111235
111236 ALTER TABLE ONLY costhist
111237     ADD CONSTRAINT costhist_pkey PRIMARY KEY (costhist_id);
111238
111239
111240 --
111241 -- TOC entry 7316 (class 2606 OID 146571013)
111242 -- Dependencies: 537 537 8894
111243 -- Name: costupdate_costupdate_item_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111244 --
111245
111246 ALTER TABLE ONLY costupdate
111247     ADD CONSTRAINT costupdate_costupdate_item_id_key UNIQUE (costupdate_item_id);
111248
111249
111250 --
111251 -- TOC entry 7318 (class 2606 OID 146571017)
111252 -- Dependencies: 538 538 8894
111253 -- Name: country_country_abbr_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111254 --
111255
111256 ALTER TABLE ONLY country
111257     ADD CONSTRAINT country_country_abbr_key UNIQUE (country_abbr);
111258
111259
111260 --
111261 -- TOC entry 7320 (class 2606 OID 146571019)
111262 -- Dependencies: 538 538 8894
111263 -- Name: country_country_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111264 --
111265
111266 ALTER TABLE ONLY country
111267     ADD CONSTRAINT country_country_name_key UNIQUE (country_name);
111268
111269
111270 --
111271 -- TOC entry 7322 (class 2606 OID 146571021)
111272 -- Dependencies: 538 538 8894
111273 -- Name: country_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111274 --
111275
111276 ALTER TABLE ONLY country
111277     ADD CONSTRAINT country_pkey PRIMARY KEY (country_id);
111278
111279
111280 --
111281 -- TOC entry 6819 (class 2606 OID 146571023)
111282 -- Dependencies: 205 205 8894
111283 -- Name: crmacct_crmacct_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111284 --
111285
111286 ALTER TABLE ONLY crmacct
111287     ADD CONSTRAINT crmacct_crmacct_number_key UNIQUE (crmacct_number);
111288
111289
111290 --
111291 -- TOC entry 6821 (class 2606 OID 146571025)
111292 -- Dependencies: 205 205 8894
111293 -- Name: crmacct_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111294 --
111295
111296 ALTER TABLE ONLY crmacct
111297     ADD CONSTRAINT crmacct_pkey PRIMARY KEY (crmacct_id);
111298
111299
111300 --
111301 -- TOC entry 7328 (class 2606 OID 146571027)
111302 -- Dependencies: 544 544 8894
111303 -- Name: crmacctsel_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111304 --
111305
111306 ALTER TABLE ONLY crmacctsel
111307     ADD CONSTRAINT crmacctsel_pkey PRIMARY KEY (crmacctsel_src_crmacct_id);
111308
111309
111310 --
111311 -- TOC entry 7330 (class 2606 OID 146571029)
111312 -- Dependencies: 545 545 545 8894
111313 -- Name: curr_rate_curr_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111314 --
111315
111316 ALTER TABLE ONLY curr_rate
111317     ADD CONSTRAINT curr_rate_curr_id_key UNIQUE (curr_id, curr_effective);
111318
111319
111320 --
111321 -- TOC entry 7332 (class 2606 OID 146571031)
111322 -- Dependencies: 545 545 8894
111323 -- Name: curr_rate_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111324 --
111325
111326 ALTER TABLE ONLY curr_rate
111327     ADD CONSTRAINT curr_rate_pkey PRIMARY KEY (curr_rate_id);
111328
111329
111330 --
111331 -- TOC entry 6831 (class 2606 OID 146571033)
111332 -- Dependencies: 208 208 8894
111333 -- Name: curr_symbol_curr_abbr_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111334 --
111335
111336 ALTER TABLE ONLY curr_symbol
111337     ADD CONSTRAINT curr_symbol_curr_abbr_key UNIQUE (curr_abbr);
111338
111339
111340 --
111341 -- TOC entry 6833 (class 2606 OID 146571035)
111342 -- Dependencies: 208 208 8894
111343 -- Name: curr_symbol_curr_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111344 --
111345
111346 ALTER TABLE ONLY curr_symbol
111347     ADD CONSTRAINT curr_symbol_curr_name_key UNIQUE (curr_name);
111348
111349
111350 --
111351 -- TOC entry 6835 (class 2606 OID 146571037)
111352 -- Dependencies: 208 208 8894
111353 -- Name: curr_symbol_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111354 --
111355
111356 ALTER TABLE ONLY curr_symbol
111357     ADD CONSTRAINT curr_symbol_pkey PRIMARY KEY (curr_id);
111358
111359
111360 --
111361 -- TOC entry 6854 (class 2606 OID 146571039)
111362 -- Dependencies: 213 213 8894
111363 -- Name: cust_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111364 --
111365
111366 ALTER TABLE ONLY custinfo
111367     ADD CONSTRAINT cust_pkey PRIMARY KEY (cust_id);
111368
111369
111370 --
111371 -- TOC entry 7334 (class 2606 OID 146571041)
111372 -- Dependencies: 550 550 8894
111373 -- Name: custform_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111374 --
111375
111376 ALTER TABLE ONLY custform
111377     ADD CONSTRAINT custform_pkey PRIMARY KEY (custform_id);
111378
111379
111380 --
111381 -- TOC entry 7336 (class 2606 OID 146571043)
111382 -- Dependencies: 552 552 8894
111383 -- Name: custgrp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111384 --
111385
111386 ALTER TABLE ONLY custgrp
111387     ADD CONSTRAINT custgrp_pkey PRIMARY KEY (custgrp_id);
111388
111389
111390 --
111391 -- TOC entry 7338 (class 2606 OID 146571045)
111392 -- Dependencies: 554 554 8894
111393 -- Name: custgrpitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111394 --
111395
111396 ALTER TABLE ONLY custgrpitem
111397     ADD CONSTRAINT custgrpitem_pkey PRIMARY KEY (custgrpitem_id);
111398
111399
111400 --
111401 -- TOC entry 6856 (class 2606 OID 146571047)
111402 -- Dependencies: 213 213 8894
111403 -- Name: custinfo_cust_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111404 --
111405
111406 ALTER TABLE ONLY custinfo
111407     ADD CONSTRAINT custinfo_cust_number_key UNIQUE (cust_number);
111408
111409
111410 --
111411 -- TOC entry 6979 (class 2606 OID 146571049)
111412 -- Dependencies: 280 280 8894
111413 -- Name: custtype_custtype_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111414 --
111415
111416 ALTER TABLE ONLY custtype
111417     ADD CONSTRAINT custtype_custtype_code_key UNIQUE (custtype_code);
111418
111419
111420 --
111421 -- TOC entry 6981 (class 2606 OID 146571051)
111422 -- Dependencies: 280 280 8894
111423 -- Name: custtype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111424 --
111425
111426 ALTER TABLE ONLY custtype
111427     ADD CONSTRAINT custtype_pkey PRIMARY KEY (custtype_id);
111428
111429
111430 --
111431 -- TOC entry 6995 (class 2606 OID 146571053)
111432 -- Dependencies: 291 291 8894
111433 -- Name: dept_dept_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111434 --
111435
111436 ALTER TABLE ONLY dept
111437     ADD CONSTRAINT dept_dept_number_key UNIQUE (dept_number);
111438
111439
111440 --
111441 -- TOC entry 6997 (class 2606 OID 146571055)
111442 -- Dependencies: 291 291 8894
111443 -- Name: dept_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111444 --
111445
111446 ALTER TABLE ONLY dept
111447     ADD CONSTRAINT dept_pkey PRIMARY KEY (dept_id);
111448
111449
111450 --
111451 -- TOC entry 7340 (class 2606 OID 146571057)
111452 -- Dependencies: 558 558 8894
111453 -- Name: destination_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111454 --
111455
111456 ALTER TABLE ONLY destination
111457     ADD CONSTRAINT destination_pkey PRIMARY KEY (destination_id);
111458
111459
111460 --
111461 -- TOC entry 6937 (class 2606 OID 146571059)
111462 -- Dependencies: 242 242 8894
111463 -- Name: docass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111464 --
111465
111466 ALTER TABLE ONLY docass
111467     ADD CONSTRAINT docass_pkey PRIMARY KEY (docass_id);
111468
111469
111470 --
111471 -- TOC entry 6999 (class 2606 OID 146571061)
111472 -- Dependencies: 292 292 8894
111473 -- Name: emp_emp_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111474 --
111475
111476 ALTER TABLE ONLY emp
111477     ADD CONSTRAINT emp_emp_code_key UNIQUE (emp_code);
111478
111479
111480 --
111481 -- TOC entry 7001 (class 2606 OID 146571063)
111482 -- Dependencies: 292 292 8894
111483 -- Name: emp_emp_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111484 --
111485
111486 ALTER TABLE ONLY emp
111487     ADD CONSTRAINT emp_emp_number_key UNIQUE (emp_number);
111488
111489
111490 --
111491 -- TOC entry 7003 (class 2606 OID 146571065)
111492 -- Dependencies: 292 292 8894
111493 -- Name: emp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111494 --
111495
111496 ALTER TABLE ONLY emp
111497     ADD CONSTRAINT emp_pkey PRIMARY KEY (emp_id);
111498
111499
111500 --
111501 -- TOC entry 7349 (class 2606 OID 146571068)
111502 -- Dependencies: 563 563 8894
111503 -- Name: empgrp_empgrp_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111504 --
111505
111506 ALTER TABLE ONLY empgrp
111507     ADD CONSTRAINT empgrp_empgrp_name_key UNIQUE (empgrp_name);
111508
111509
111510 --
111511 -- TOC entry 7351 (class 2606 OID 146571070)
111512 -- Dependencies: 563 563 8894
111513 -- Name: empgrp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111514 --
111515
111516 ALTER TABLE ONLY empgrp
111517     ADD CONSTRAINT empgrp_pkey PRIMARY KEY (empgrp_id);
111518
111519
111520 --
111521 -- TOC entry 7353 (class 2606 OID 146571072)
111522 -- Dependencies: 565 565 8894
111523 -- Name: empgrpitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111524 --
111525
111526 ALTER TABLE ONLY empgrpitem
111527     ADD CONSTRAINT empgrpitem_pkey PRIMARY KEY (empgrpitem_id);
111528
111529
111530 --
111531 -- TOC entry 7357 (class 2606 OID 146571075)
111532 -- Dependencies: 567 567 8894
111533 -- Name: evntlog_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111534 --
111535
111536 ALTER TABLE ONLY evntlog
111537     ADD CONSTRAINT evntlog_pkey PRIMARY KEY (evntlog_id);
111538
111539
111540 --
111541 -- TOC entry 7360 (class 2606 OID 146571077)
111542 -- Dependencies: 569 569 8894
111543 -- Name: evntnot_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111544 --
111545
111546 ALTER TABLE ONLY evntnot
111547     ADD CONSTRAINT evntnot_pkey PRIMARY KEY (evntnot_id);
111548
111549
111550 --
111551 -- TOC entry 7363 (class 2606 OID 146571079)
111552 -- Dependencies: 571 571 8894
111553 -- Name: evnttype_evnttype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111554 --
111555
111556 ALTER TABLE ONLY evnttype
111557     ADD CONSTRAINT evnttype_evnttype_name_key UNIQUE (evnttype_name);
111558
111559
111560 --
111561 -- TOC entry 7365 (class 2606 OID 146571081)
111562 -- Dependencies: 571 571 8894
111563 -- Name: evnttype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111564 --
111565
111566 ALTER TABLE ONLY evnttype
111567     ADD CONSTRAINT evnttype_pkey PRIMARY KEY (evnttype_id);
111568
111569
111570 --
111571 -- TOC entry 7117 (class 2606 OID 146571083)
111572 -- Dependencies: 358 358 8894
111573 -- Name: expcat_expcat_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111574 --
111575
111576 ALTER TABLE ONLY expcat
111577     ADD CONSTRAINT expcat_expcat_code_key UNIQUE (expcat_code);
111578
111579
111580 --
111581 -- TOC entry 7119 (class 2606 OID 146571085)
111582 -- Dependencies: 358 358 8894
111583 -- Name: expcat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111584 --
111585
111586 ALTER TABLE ONLY expcat
111587     ADD CONSTRAINT expcat_pkey PRIMARY KEY (expcat_id);
111588
111589
111590 --
111591 -- TOC entry 6939 (class 2606 OID 146571087)
111592 -- Dependencies: 243 243 8894
111593 -- Name: file_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111594 --
111595
111596 ALTER TABLE ONLY file
111597     ADD CONSTRAINT file_pkey PRIMARY KEY (file_id);
111598
111599
111600 --
111601 -- TOC entry 7368 (class 2606 OID 146571089)
111602 -- Dependencies: 575 575 8894
111603 -- Name: filter_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111604 --
111605
111606 ALTER TABLE ONLY filter
111607     ADD CONSTRAINT filter_pkey PRIMARY KEY (filter_id);
111608
111609
111610 --
111611 -- TOC entry 7370 (class 2606 OID 146571091)
111612 -- Dependencies: 577 577 8894
111613 -- Name: fincharg_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111614 --
111615
111616 ALTER TABLE ONLY fincharg
111617     ADD CONSTRAINT fincharg_pkey PRIMARY KEY (fincharg_id);
111618
111619
111620 --
111621 -- TOC entry 7378 (class 2606 OID 146571093)
111622 -- Dependencies: 582 582 8894
111623 -- Name: fkey_flcol_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111624 --
111625
111626 ALTER TABLE ONLY flcol
111627     ADD CONSTRAINT fkey_flcol_key PRIMARY KEY (flcol_id);
111628
111629
111630 --
111631 -- TOC entry 7380 (class 2606 OID 146571095)
111632 -- Dependencies: 584 584 8894
111633 -- Name: flgrp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111634 --
111635
111636 ALTER TABLE ONLY flgrp
111637     ADD CONSTRAINT flgrp_pkey PRIMARY KEY (flgrp_id);
111638
111639
111640 --
111641 -- TOC entry 7372 (class 2606 OID 146571097)
111642 -- Dependencies: 579 579 8894
111643 -- Name: flhead_flhead_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111644 --
111645
111646 ALTER TABLE ONLY flhead
111647     ADD CONSTRAINT flhead_flhead_name_key UNIQUE (flhead_name);
111648
111649
111650 --
111651 -- TOC entry 7374 (class 2606 OID 146571099)
111652 -- Dependencies: 579 579 8894
111653 -- Name: flhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111654 --
111655
111656 ALTER TABLE ONLY flhead
111657     ADD CONSTRAINT flhead_pkey PRIMARY KEY (flhead_id);
111658
111659
111660 --
111661 -- TOC entry 7376 (class 2606 OID 146571101)
111662 -- Dependencies: 580 580 8894
111663 -- Name: flitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111664 --
111665
111666 ALTER TABLE ONLY flitem
111667     ADD CONSTRAINT flitem_pkey PRIMARY KEY (flitem_id);
111668
111669
111670 --
111671 -- TOC entry 7382 (class 2606 OID 146571103)
111672 -- Dependencies: 588 588 588 8894
111673 -- Name: flnotes_flnotes_flhead_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111674 --
111675
111676 ALTER TABLE ONLY flnotes
111677     ADD CONSTRAINT flnotes_flnotes_flhead_id_key UNIQUE (flnotes_flhead_id, flnotes_period_id);
111678
111679
111680 --
111681 -- TOC entry 7384 (class 2606 OID 146571105)
111682 -- Dependencies: 590 590 8894
111683 -- Name: flrpt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111684 --
111685
111686 ALTER TABLE ONLY flrpt
111687     ADD CONSTRAINT flrpt_pkey PRIMARY KEY (flrpt_id);
111688
111689
111690 --
111691 -- TOC entry 7386 (class 2606 OID 146571107)
111692 -- Dependencies: 592 592 8894
111693 -- Name: flspec_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111694 --
111695
111696 ALTER TABLE ONLY flspec
111697     ADD CONSTRAINT flspec_pkey PRIMARY KEY (flspec_id);
111698
111699
111700 --
111701 -- TOC entry 7388 (class 2606 OID 146571109)
111702 -- Dependencies: 594 594 8894
111703 -- Name: form_form_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111704 --
111705
111706 ALTER TABLE ONLY form
111707     ADD CONSTRAINT form_form_name_key UNIQUE (form_name);
111708
111709
111710 --
111711 -- TOC entry 7390 (class 2606 OID 146571111)
111712 -- Dependencies: 594 594 8894
111713 -- Name: form_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111714 --
111715
111716 ALTER TABLE ONLY form
111717     ADD CONSTRAINT form_pkey PRIMARY KEY (form_id);
111718
111719
111720 --
111721 -- TOC entry 7010 (class 2606 OID 146571113)
111722 -- Dependencies: 299 299 8894
111723 -- Name: freightclass_freightclass_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111724 --
111725
111726 ALTER TABLE ONLY freightclass
111727     ADD CONSTRAINT freightclass_freightclass_code_key UNIQUE (freightclass_code);
111728
111729
111730 --
111731 -- TOC entry 7012 (class 2606 OID 146571115)
111732 -- Dependencies: 299 299 8894
111733 -- Name: freightclass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111734 --
111735
111736 ALTER TABLE ONLY freightclass
111737     ADD CONSTRAINT freightclass_pkey PRIMARY KEY (freightclass_id);
111738
111739
111740 --
111741 -- TOC entry 7392 (class 2606 OID 146571117)
111742 -- Dependencies: 597 597 8894
111743 -- Name: glseries_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111744 --
111745
111746 ALTER TABLE ONLY glseries
111747     ADD CONSTRAINT glseries_pkey PRIMARY KEY (glseries_id);
111748
111749
111750 --
111751 -- TOC entry 7090 (class 2606 OID 146571119)
111752 -- Dependencies: 340 340 8894
111753 -- Name: gltrans_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111754 --
111755
111756 ALTER TABLE ONLY gltrans
111757     ADD CONSTRAINT gltrans_pkey PRIMARY KEY (gltrans_id);
111758
111759
111760 --
111761 -- TOC entry 7394 (class 2606 OID 146571121)
111762 -- Dependencies: 601 601 8894
111763 -- Name: grp_grp_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111764 --
111765
111766 ALTER TABLE ONLY grp
111767     ADD CONSTRAINT grp_grp_name_key UNIQUE (grp_name);
111768
111769
111770 --
111771 -- TOC entry 7396 (class 2606 OID 146571123)
111772 -- Dependencies: 601 601 8894
111773 -- Name: grp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111774 --
111775
111776 ALTER TABLE ONLY grp
111777     ADD CONSTRAINT grp_pkey PRIMARY KEY (grp_id);
111778
111779
111780 --
111781 -- TOC entry 7398 (class 2606 OID 146571125)
111782 -- Dependencies: 603 603 8894
111783 -- Name: grppriv_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111784 --
111785
111786 ALTER TABLE ONLY grppriv
111787     ADD CONSTRAINT grppriv_pkey PRIMARY KEY (grppriv_id);
111788
111789
111790 --
111791 -- TOC entry 7400 (class 2606 OID 146571127)
111792 -- Dependencies: 605 605 8894
111793 -- Name: hnfc_hnfc_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111794 --
111795
111796 ALTER TABLE ONLY hnfc
111797     ADD CONSTRAINT hnfc_hnfc_code_key UNIQUE (hnfc_code);
111798
111799
111800 --
111801 -- TOC entry 7402 (class 2606 OID 146571129)
111802 -- Dependencies: 605 605 8894
111803 -- Name: hnfc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111804 --
111805
111806 ALTER TABLE ONLY hnfc
111807     ADD CONSTRAINT hnfc_pkey PRIMARY KEY (hnfc_id);
111808
111809
111810 --
111811 -- TOC entry 6943 (class 2606 OID 146571131)
111812 -- Dependencies: 248 248 8894
111813 -- Name: image_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111814 --
111815
111816 ALTER TABLE ONLY image
111817     ADD CONSTRAINT image_pkey PRIMARY KEY (image_id);
111818
111819
111820 --
111821 -- TOC entry 6945 (class 2606 OID 146571133)
111822 -- Dependencies: 249 249 8894
111823 -- Name: imageass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111824 --
111825
111826 ALTER TABLE ONLY imageass
111827     ADD CONSTRAINT imageass_pkey PRIMARY KEY (imageass_id);
111828
111829
111830 --
111831 -- TOC entry 6823 (class 2606 OID 146571135)
111832 -- Dependencies: 206 206 8894
111833 -- Name: incdt_incdt_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111834 --
111835
111836 ALTER TABLE ONLY incdt
111837     ADD CONSTRAINT incdt_incdt_number_key UNIQUE (incdt_number);
111838
111839
111840 --
111841 -- TOC entry 6825 (class 2606 OID 146571137)
111842 -- Dependencies: 206 206 8894
111843 -- Name: incdt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111844 --
111845
111846 ALTER TABLE ONLY incdt
111847     ADD CONSTRAINT incdt_pkey PRIMARY KEY (incdt_id);
111848
111849
111850 --
111851 -- TOC entry 7020 (class 2606 OID 146571139)
111852 -- Dependencies: 304 304 8894
111853 -- Name: incdtcat_incdtcat_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111854 --
111855
111856 ALTER TABLE ONLY incdtcat
111857     ADD CONSTRAINT incdtcat_incdtcat_name_key UNIQUE (incdtcat_name);
111858
111859
111860 --
111861 -- TOC entry 7022 (class 2606 OID 146571141)
111862 -- Dependencies: 304 304 8894
111863 -- Name: incdtcat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111864 --
111865
111866 ALTER TABLE ONLY incdtcat
111867     ADD CONSTRAINT incdtcat_pkey PRIMARY KEY (incdtcat_id);
111868
111869
111870 --
111871 -- TOC entry 7404 (class 2606 OID 146571143)
111872 -- Dependencies: 609 609 8894
111873 -- Name: incdthist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111874 --
111875
111876 ALTER TABLE ONLY incdthist
111877     ADD CONSTRAINT incdthist_pkey PRIMARY KEY (incdthist_id);
111878
111879
111880 --
111881 -- TOC entry 7024 (class 2606 OID 146571145)
111882 -- Dependencies: 305 305 8894
111883 -- Name: incdtpriority_incdtpriority_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111884 --
111885
111886 ALTER TABLE ONLY incdtpriority
111887     ADD CONSTRAINT incdtpriority_incdtpriority_name_key UNIQUE (incdtpriority_name);
111888
111889
111890 --
111891 -- TOC entry 7026 (class 2606 OID 146571147)
111892 -- Dependencies: 305 305 8894
111893 -- Name: incdtpriority_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111894 --
111895
111896 ALTER TABLE ONLY incdtpriority
111897     ADD CONSTRAINT incdtpriority_pkey PRIMARY KEY (incdtpriority_id);
111898
111899
111900 --
111901 -- TOC entry 7028 (class 2606 OID 146571149)
111902 -- Dependencies: 306 306 8894
111903 -- Name: incdtresolution_incdtresolution_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111904 --
111905
111906 ALTER TABLE ONLY incdtresolution
111907     ADD CONSTRAINT incdtresolution_incdtresolution_name_key UNIQUE (incdtresolution_name);
111908
111909
111910 --
111911 -- TOC entry 7030 (class 2606 OID 146571151)
111912 -- Dependencies: 306 306 8894
111913 -- Name: incdtresolution_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111914 --
111915
111916 ALTER TABLE ONLY incdtresolution
111917     ADD CONSTRAINT incdtresolution_pkey PRIMARY KEY (incdtresolution_id);
111918
111919
111920 --
111921 -- TOC entry 7032 (class 2606 OID 146571153)
111922 -- Dependencies: 307 307 8894
111923 -- Name: incdtseverity_incdtseverity_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111924 --
111925
111926 ALTER TABLE ONLY incdtseverity
111927     ADD CONSTRAINT incdtseverity_incdtseverity_name_key UNIQUE (incdtseverity_name);
111928
111929
111930 --
111931 -- TOC entry 7034 (class 2606 OID 146571155)
111932 -- Dependencies: 307 307 8894
111933 -- Name: incdtseverity_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111934 --
111935
111936 ALTER TABLE ONLY incdtseverity
111937     ADD CONSTRAINT incdtseverity_pkey PRIMARY KEY (incdtseverity_id);
111938
111939
111940 --
111941 -- TOC entry 6805 (class 2606 OID 146571157)
111942 -- Dependencies: 202 202 8894
111943 -- Name: invbal_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111944 --
111945
111946 ALTER TABLE ONLY invbal
111947     ADD CONSTRAINT invbal_pkey PRIMARY KEY (invbal_id);
111948
111949
111950 --
111951 -- TOC entry 6888 (class 2606 OID 146571159)
111952 -- Dependencies: 224 224 8894
111953 -- Name: invchead_invcnumber_unique; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111954 --
111955
111956 ALTER TABLE ONLY invchead
111957     ADD CONSTRAINT invchead_invcnumber_unique UNIQUE (invchead_invcnumber);
111958
111959
111960 --
111961 -- TOC entry 6890 (class 2606 OID 146571161)
111962 -- Dependencies: 224 224 8894
111963 -- Name: invchead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111964 --
111965
111966 ALTER TABLE ONLY invchead
111967     ADD CONSTRAINT invchead_pkey PRIMARY KEY (invchead_id);
111968
111969
111970 --
111971 -- TOC entry 7406 (class 2606 OID 146571163)
111972 -- Dependencies: 617 617 8894
111973 -- Name: invcheadtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111974 --
111975
111976 ALTER TABLE ONLY invcheadtax
111977     ADD CONSTRAINT invcheadtax_pkey PRIMARY KEY (taxhist_id);
111978
111979
111980 --
111981 -- TOC entry 6902 (class 2606 OID 146571165)
111982 -- Dependencies: 229 229 229 8894
111983 -- Name: invcitem_invchead_id_linenumber_unique; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111984 --
111985
111986 ALTER TABLE ONLY invcitem
111987     ADD CONSTRAINT invcitem_invchead_id_linenumber_unique UNIQUE (invcitem_invchead_id, invcitem_linenumber);
111988
111989
111990 --
111991 -- TOC entry 6906 (class 2606 OID 146571167)
111992 -- Dependencies: 229 229 8894
111993 -- Name: invcitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
111994 --
111995
111996 ALTER TABLE ONLY invcitem
111997     ADD CONSTRAINT invcitem_pkey PRIMARY KEY (invcitem_id);
111998
111999
112000 --
112001 -- TOC entry 7408 (class 2606 OID 146571169)
112002 -- Dependencies: 619 619 8894
112003 -- Name: invcitemtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112004 --
112005
112006 ALTER TABLE ONLY invcitemtax
112007     ADD CONSTRAINT invcitemtax_pkey PRIMARY KEY (taxhist_id);
112008
112009
112010 --
112011 -- TOC entry 6746 (class 2606 OID 146571171)
112012 -- Dependencies: 190 190 8894
112013 -- Name: invcnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112014 --
112015
112016 ALTER TABLE ONLY invcnt
112017     ADD CONSTRAINT invcnt_pkey PRIMARY KEY (invcnt_id);
112018
112019
112020 --
112021 -- TOC entry 7413 (class 2606 OID 146571173)
112022 -- Dependencies: 621 621 8894
112023 -- Name: invdetail_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112024 --
112025
112026 ALTER TABLE ONLY invdetail
112027     ADD CONSTRAINT invdetail_pkey PRIMARY KEY (invdetail_id);
112028
112029
112030 --
112031 -- TOC entry 7418 (class 2606 OID 146571175)
112032 -- Dependencies: 623 623 8894
112033 -- Name: invhist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112034 --
112035
112036 ALTER TABLE ONLY invhist
112037     ADD CONSTRAINT invhist_pkey PRIMARY KEY (invhist_id);
112038
112039
112040 --
112041 -- TOC entry 7423 (class 2606 OID 146571177)
112042 -- Dependencies: 625 625 625 8894
112043 -- Name: invhistexpcat_invhist_id_expcat_id; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112044 --
112045
112046 ALTER TABLE ONLY invhistexpcat
112047     ADD CONSTRAINT invhistexpcat_invhist_id_expcat_id UNIQUE (invhistexpcat_invhist_id, invhistexpcat_expcat_id);
112048
112049
112050 --
112051 -- TOC entry 7425 (class 2606 OID 146571179)
112052 -- Dependencies: 625 625 8894
112053 -- Name: invhistexpcat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112054 --
112055
112056 ALTER TABLE ONLY invhistexpcat
112057     ADD CONSTRAINT invhistexpcat_pkey PRIMARY KEY (invhistexpcat_id);
112058
112059
112060 --
112061 -- TOC entry 7098 (class 2606 OID 146571181)
112062 -- Dependencies: 347 347 347 347 347 347 347 8894
112063 -- Name: ipsass_ipsass_ipshead_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112064 --
112065
112066 ALTER TABLE ONLY ipsass
112067     ADD CONSTRAINT ipsass_ipsass_ipshead_id_key UNIQUE (ipsass_ipshead_id, ipsass_cust_id, ipsass_custtype_id, ipsass_custtype_pattern, ipsass_shipto_id, ipsass_shipto_pattern);
112068
112069
112070 --
112071 -- TOC entry 7100 (class 2606 OID 146571183)
112072 -- Dependencies: 347 347 8894
112073 -- Name: ipsass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112074 --
112075
112076 ALTER TABLE ONLY ipsass
112077     ADD CONSTRAINT ipsass_pkey PRIMARY KEY (ipsass_id);
112078
112079
112080 --
112081 -- TOC entry 7014 (class 2606 OID 146571185)
112082 -- Dependencies: 300 300 8894
112083 -- Name: ipsfreight_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112084 --
112085
112086 ALTER TABLE ONLY ipsfreight
112087     ADD CONSTRAINT ipsfreight_pkey PRIMARY KEY (ipsfreight_id);
112088
112089
112090 --
112091 -- TOC entry 7016 (class 2606 OID 146571187)
112092 -- Dependencies: 301 301 8894
112093 -- Name: ipshead_ipshead_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112094 --
112095
112096 ALTER TABLE ONLY ipshead
112097     ADD CONSTRAINT ipshead_ipshead_name_key UNIQUE (ipshead_name);
112098
112099
112100 --
112101 -- TOC entry 7018 (class 2606 OID 146571189)
112102 -- Dependencies: 301 301 8894
112103 -- Name: ipshead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112104 --
112105
112106 ALTER TABLE ONLY ipshead
112107     ADD CONSTRAINT ipshead_pkey PRIMARY KEY (ipshead_id);
112108
112109
112110 --
112111 -- TOC entry 7103 (class 2606 OID 146571191)
112112 -- Dependencies: 349 349 349 349 349 349 349 8894
112113 -- Name: ipsitem_ipsitem_ipshead_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112114 --
112115
112116 ALTER TABLE ONLY ipsiteminfo
112117     ADD CONSTRAINT ipsitem_ipsitem_ipshead_id_key UNIQUE (ipsitem_ipshead_id, ipsitem_item_id, ipsitem_prodcat_id, ipsitem_qtybreak, ipsitem_qty_uom_id, ipsitem_price_uom_id);
112118
112119
112120 --
112121 -- TOC entry 7105 (class 2606 OID 146571193)
112122 -- Dependencies: 349 349 8894
112123 -- Name: ipsitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112124 --
112125
112126 ALTER TABLE ONLY ipsiteminfo
112127     ADD CONSTRAINT ipsitem_pkey PRIMARY KEY (ipsitem_id);
112128
112129
112130 --
112131 -- TOC entry 7107 (class 2606 OID 146571195)
112132 -- Dependencies: 351 351 351 351 8894
112133 -- Name: ipsitemchar_ipsitemchar_ipsitem_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112134 --
112135
112136 ALTER TABLE ONLY ipsitemchar
112137     ADD CONSTRAINT ipsitemchar_ipsitemchar_ipsitem_id_key UNIQUE (ipsitemchar_ipsitem_id, ipsitemchar_char_id, ipsitemchar_value);
112138
112139
112140 --
112141 -- TOC entry 7109 (class 2606 OID 146571197)
112142 -- Dependencies: 351 351 351 351 8894
112143 -- Name: ipsitemchar_ipsitemchar_ipsitem_id_key1; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112144 --
112145
112146 ALTER TABLE ONLY ipsitemchar
112147     ADD CONSTRAINT ipsitemchar_ipsitemchar_ipsitem_id_key1 UNIQUE (ipsitemchar_ipsitem_id, ipsitemchar_char_id, ipsitemchar_value);
112148
112149
112150 --
112151 -- TOC entry 7111 (class 2606 OID 146571199)
112152 -- Dependencies: 351 351 8894
112153 -- Name: ipsitemchar_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112154 --
112155
112156 ALTER TABLE ONLY ipsitemchar
112157     ADD CONSTRAINT ipsitemchar_pkey PRIMARY KEY (ipsitemchar_id);
112158
112159
112160 --
112161 -- TOC entry 7427 (class 2606 OID 146571201)
112162 -- Dependencies: 636 636 8894
112163 -- Name: ipsprodcat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112164 --
112165
112166 ALTER TABLE ONLY ipsprodcat_bak
112167     ADD CONSTRAINT ipsprodcat_pkey PRIMARY KEY (ipsprodcat_id);
112168
112169
112170 --
112171 -- TOC entry 6749 (class 2606 OID 146571203)
112172 -- Dependencies: 191 191 8894
112173 -- Name: item_item_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112174 --
112175
112176 ALTER TABLE ONLY item
112177     ADD CONSTRAINT item_item_number_key UNIQUE (item_number);
112178
112179
112180 --
112181 -- TOC entry 6752 (class 2606 OID 146571205)
112182 -- Dependencies: 191 191 8894
112183 -- Name: item_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112184 --
112185
112186 ALTER TABLE ONLY item
112187     ADD CONSTRAINT item_pkey PRIMARY KEY (item_id);
112188
112189
112190 --
112191 -- TOC entry 7044 (class 2606 OID 146571207)
112192 -- Dependencies: 316 316 316 8894
112193 -- Name: itemalias_itemalias_item_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112194 --
112195
112196 ALTER TABLE ONLY itemalias
112197     ADD CONSTRAINT itemalias_itemalias_item_id_key UNIQUE (itemalias_item_id, itemalias_number);
112198
112199
112200 --
112201 -- TOC entry 7046 (class 2606 OID 146571209)
112202 -- Dependencies: 316 316 8894
112203 -- Name: itemalias_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112204 --
112205
112206 ALTER TABLE ONLY itemalias
112207     ADD CONSTRAINT itemalias_pkey PRIMARY KEY (itemalias_id);
112208
112209
112210 --
112211 -- TOC entry 7054 (class 2606 OID 146571211)
112212 -- Dependencies: 321 321 8894
112213 -- Name: itemcost_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112214 --
112215
112216 ALTER TABLE ONLY itemcost
112217     ADD CONSTRAINT itemcost_pkey PRIMARY KEY (itemcost_id);
112218
112219
112220 --
112221 -- TOC entry 7429 (class 2606 OID 146571213)
112222 -- Dependencies: 643 643 8894
112223 -- Name: itemgrp_itemgrp_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112224 --
112225
112226 ALTER TABLE ONLY itemgrp
112227     ADD CONSTRAINT itemgrp_itemgrp_name_key UNIQUE (itemgrp_name);
112228
112229
112230 --
112231 -- TOC entry 7431 (class 2606 OID 146571215)
112232 -- Dependencies: 643 643 8894
112233 -- Name: itemgrp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112234 --
112235
112236 ALTER TABLE ONLY itemgrp
112237     ADD CONSTRAINT itemgrp_pkey PRIMARY KEY (itemgrp_id);
112238
112239
112240 --
112241 -- TOC entry 7433 (class 2606 OID 146571217)
112242 -- Dependencies: 645 645 8894
112243 -- Name: itemgrpitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112244 --
112245
112246 ALTER TABLE ONLY itemgrpitem
112247     ADD CONSTRAINT itemgrpitem_pkey PRIMARY KEY (itemgrpitem_id);
112248
112249
112250 --
112251 -- TOC entry 7435 (class 2606 OID 146571219)
112252 -- Dependencies: 645 645 645 645 8894
112253 -- Name: itemgrpitem_unique_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112254 --
112255
112256 ALTER TABLE ONLY itemgrpitem
112257     ADD CONSTRAINT itemgrpitem_unique_key UNIQUE (itemgrpitem_itemgrp_id, itemgrpitem_item_id, itemgrpitem_item_type);
112258
112259
112260 --
112261 -- TOC entry 7439 (class 2606 OID 146571221)
112262 -- Dependencies: 649 649 8894
112263 -- Name: itemloc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112264 --
112265
112266 ALTER TABLE ONLY itemloc
112267     ADD CONSTRAINT itemloc_pkey PRIMARY KEY (itemloc_id);
112268
112269
112270 --
112271 -- TOC entry 7441 (class 2606 OID 146571223)
112272 -- Dependencies: 652 652 8894
112273 -- Name: itemlocdist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112274 --
112275
112276 ALTER TABLE ONLY itemlocdist
112277     ADD CONSTRAINT itemlocdist_pkey PRIMARY KEY (itemlocdist_id);
112278
112279
112280 --
112281 -- TOC entry 7443 (class 2606 OID 146571225)
112282 -- Dependencies: 654 654 8894
112283 -- Name: itemlocpost_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112284 --
112285
112286 ALTER TABLE ONLY itemlocpost
112287     ADD CONSTRAINT itemlocpost_pkey PRIMARY KEY (itemlocpost_id);
112288
112289
112290 --
112291 -- TOC entry 6759 (class 2606 OID 146571227)
112292 -- Dependencies: 192 192 8894
112293 -- Name: itemsite_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112294 --
112295
112296 ALTER TABLE ONLY itemsite
112297     ADD CONSTRAINT itemsite_pkey PRIMARY KEY (itemsite_id);
112298
112299
112300 --
112301 -- TOC entry 7067 (class 2606 OID 146571229)
112302 -- Dependencies: 330 330 330 330 330 330 330 330 330 8894
112303 -- Name: itemsrc_itemsrc_vend_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112304 --
112305
112306 ALTER TABLE ONLY itemsrc
112307     ADD CONSTRAINT itemsrc_itemsrc_vend_id_key UNIQUE (itemsrc_vend_id, itemsrc_item_id, itemsrc_effective, itemsrc_expires, itemsrc_vend_item_number, itemsrc_manuf_name, itemsrc_manuf_item_number, itemsrc_contrct_id);
112308
112309
112310 --
112311 -- TOC entry 7069 (class 2606 OID 146571231)
112312 -- Dependencies: 330 330 8894
112313 -- Name: itemsrc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112314 --
112315
112316 ALTER TABLE ONLY itemsrc
112317     ADD CONSTRAINT itemsrc_pkey PRIMARY KEY (itemsrc_id);
112318
112319
112320 --
112321 -- TOC entry 7073 (class 2606 OID 146571233)
112322 -- Dependencies: 332 332 332 332 332 8894
112323 -- Name: itemsrcp_itemsrcp_itemsrc_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112324 --
112325
112326 ALTER TABLE ONLY itemsrcp
112327     ADD CONSTRAINT itemsrcp_itemsrcp_itemsrc_id_key UNIQUE (itemsrcp_itemsrc_id, itemsrcp_warehous_id, itemsrcp_dropship, itemsrcp_qtybreak);
112328
112329
112330 --
112331 -- TOC entry 7075 (class 2606 OID 146571235)
112332 -- Dependencies: 332 332 8894
112333 -- Name: itemsrcp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112334 --
112335
112336 ALTER TABLE ONLY itemsrcp
112337     ADD CONSTRAINT itemsrcp_pkey PRIMARY KEY (itemsrcp_id);
112338
112339
112340 --
112341 -- TOC entry 7077 (class 2606 OID 146571237)
112342 -- Dependencies: 334 334 334 8894
112343 -- Name: itemsub_itemsub_parent_item_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112344 --
112345
112346 ALTER TABLE ONLY itemsub
112347     ADD CONSTRAINT itemsub_itemsub_parent_item_id_key UNIQUE (itemsub_parent_item_id, itemsub_sub_item_id);
112348
112349
112350 --
112351 -- TOC entry 7080 (class 2606 OID 146571239)
112352 -- Dependencies: 334 334 8894
112353 -- Name: itemsub_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112354 --
112355
112356 ALTER TABLE ONLY itemsub
112357     ADD CONSTRAINT itemsub_pkey PRIMARY KEY (itemsub_id);
112358
112359
112360 --
112361 -- TOC entry 7083 (class 2606 OID 146571241)
112362 -- Dependencies: 336 336 8894
112363 -- Name: itemtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112364 --
112365
112366 ALTER TABLE ONLY itemtax
112367     ADD CONSTRAINT itemtax_pkey PRIMARY KEY (itemtax_id);
112368
112369
112370 --
112371 -- TOC entry 7445 (class 2606 OID 146571243)
112372 -- Dependencies: 662 662 662 8894
112373 -- Name: itemtrans_itemtrans_source_item_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112374 --
112375
112376 ALTER TABLE ONLY itemtrans
112377     ADD CONSTRAINT itemtrans_itemtrans_source_item_id_key UNIQUE (itemtrans_source_item_id, itemtrans_target_item_id);
112378
112379
112380 --
112381 -- TOC entry 7447 (class 2606 OID 146571245)
112382 -- Dependencies: 662 662 8894
112383 -- Name: itemtrans_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112384 --
112385
112386 ALTER TABLE ONLY itemtrans
112387     ADD CONSTRAINT itemtrans_pkey PRIMARY KEY (itemtrans_id);
112388
112389
112390 --
112391 -- TOC entry 7449 (class 2606 OID 146571247)
112392 -- Dependencies: 664 664 8894
112393 -- Name: itemuom_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112394 --
112395
112396 ALTER TABLE ONLY itemuom
112397     ADD CONSTRAINT itemuom_pkey PRIMARY KEY (itemuom_id);
112398
112399
112400 --
112401 -- TOC entry 7085 (class 2606 OID 146571249)
112402 -- Dependencies: 338 338 8894
112403 -- Name: itemuomconv_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112404 --
112405
112406 ALTER TABLE ONLY itemuomconv
112407     ADD CONSTRAINT itemuomconv_pkey PRIMARY KEY (itemuomconv_id);
112408
112409
112410 --
112411 -- TOC entry 7451 (class 2606 OID 146571251)
112412 -- Dependencies: 668 668 8894
112413 -- Name: jrnluse_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112414 --
112415
112416 ALTER TABLE ONLY jrnluse
112417     ADD CONSTRAINT jrnluse_pkey PRIMARY KEY (jrnluse_id);
112418
112419
112420 --
112421 -- TOC entry 7453 (class 2606 OID 146571253)
112422 -- Dependencies: 670 670 8894
112423 -- Name: labeldef_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112424 --
112425
112426 ALTER TABLE ONLY labeldef
112427     ADD CONSTRAINT labeldef_pkey PRIMARY KEY (labeldef_id);
112428
112429
112430 --
112431 -- TOC entry 7455 (class 2606 OID 146571255)
112432 -- Dependencies: 672 672 8894
112433 -- Name: labelform_labelform_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112434 --
112435
112436 ALTER TABLE ONLY labelform
112437     ADD CONSTRAINT labelform_labelform_name_key UNIQUE (labelform_name);
112438
112439
112440 --
112441 -- TOC entry 7457 (class 2606 OID 146571257)
112442 -- Dependencies: 672 672 8894
112443 -- Name: labelform_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112444 --
112445
112446 ALTER TABLE ONLY labelform
112447     ADD CONSTRAINT labelform_pkey PRIMARY KEY (labelform_id);
112448
112449
112450 --
112451 -- TOC entry 7459 (class 2606 OID 146571259)
112452 -- Dependencies: 674 674 8894
112453 -- Name: lang_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112454 --
112455
112456 ALTER TABLE ONLY lang
112457     ADD CONSTRAINT lang_pkey PRIMARY KEY (lang_id);
112458
112459
112460 --
112461 -- TOC entry 7461 (class 2606 OID 146571261)
112462 -- Dependencies: 676 676 8894
112463 -- Name: locale_locale_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112464 --
112465
112466 ALTER TABLE ONLY locale
112467     ADD CONSTRAINT locale_locale_code_key UNIQUE (locale_code);
112468
112469
112470 --
112471 -- TOC entry 7463 (class 2606 OID 146571263)
112472 -- Dependencies: 676 676 8894
112473 -- Name: locale_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112474 --
112475
112476 ALTER TABLE ONLY locale
112477     ADD CONSTRAINT locale_pkey PRIMARY KEY (locale_id);
112478
112479
112480 --
112481 -- TOC entry 7093 (class 2606 OID 146571265)
112482 -- Dependencies: 342 342 8894
112483 -- Name: location_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112484 --
112485
112486 ALTER TABLE ONLY location
112487     ADD CONSTRAINT location_pkey PRIMARY KEY (location_id);
112488
112489
112490 --
112491 -- TOC entry 7465 (class 2606 OID 146571267)
112492 -- Dependencies: 679 679 8894
112493 -- Name: locitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112494 --
112495
112496 ALTER TABLE ONLY locitem
112497     ADD CONSTRAINT locitem_pkey PRIMARY KEY (locitem_id);
112498
112499
112500 --
112501 -- TOC entry 7173 (class 2606 OID 146571269)
112502 -- Dependencies: 405 405 405 405 8894
112503 -- Name: metasql_metasql_group_name_grade_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112504 --
112505
112506 ALTER TABLE ONLY metasql
112507     ADD CONSTRAINT metasql_metasql_group_name_grade_key UNIQUE (metasql_group, metasql_name, metasql_grade);
112508
112509
112510 --
112511 -- TOC entry 7175 (class 2606 OID 146571271)
112512 -- Dependencies: 405 405 8894
112513 -- Name: metasql_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112514 --
112515
112516 ALTER TABLE ONLY metasql
112517     ADD CONSTRAINT metasql_pkey PRIMARY KEY (metasql_id);
112518
112519
112520 --
112521 -- TOC entry 7467 (class 2606 OID 146571273)
112522 -- Dependencies: 682 682 8894
112523 -- Name: metric_metric_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112524 --
112525
112526 ALTER TABLE ONLY metric
112527     ADD CONSTRAINT metric_metric_name_key UNIQUE (metric_name);
112528
112529
112530 --
112531 -- TOC entry 7469 (class 2606 OID 146571275)
112532 -- Dependencies: 682 682 8894
112533 -- Name: metric_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112534 --
112535
112536 ALTER TABLE ONLY metric
112537     ADD CONSTRAINT metric_pkey PRIMARY KEY (metric_id);
112538
112539
112540 --
112541 -- TOC entry 7471 (class 2606 OID 146571277)
112542 -- Dependencies: 684 684 8894
112543 -- Name: metricenc_metricenc_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112544 --
112545
112546 ALTER TABLE ONLY metricenc
112547     ADD CONSTRAINT metricenc_metricenc_name_key UNIQUE (metricenc_name);
112548
112549
112550 --
112551 -- TOC entry 7473 (class 2606 OID 146571279)
112552 -- Dependencies: 684 684 8894
112553 -- Name: metricenc_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112554 --
112555
112556 ALTER TABLE ONLY metricenc
112557     ADD CONSTRAINT metricenc_pkey PRIMARY KEY (metricenc_id);
112558
112559
112560 --
112561 -- TOC entry 7475 (class 2606 OID 146571281)
112562 -- Dependencies: 687 687 687 687 687 687 8894
112563 -- Name: mrghist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112564 --
112565
112566 ALTER TABLE ONLY mrghist
112567     ADD CONSTRAINT mrghist_pkey PRIMARY KEY (mrghist_cntct_id, mrghist_table, mrghist_pkey_col, mrghist_pkey_id, mrghist_cntct_col);
112568
112569
112570 --
112571 -- TOC entry 7477 (class 2606 OID 146571283)
112572 -- Dependencies: 688 688 688 688 688 688 8894
112573 -- Name: mrgundo_mrgundo_schema_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112574 --
112575
112576 ALTER TABLE ONLY mrgundo
112577     ADD CONSTRAINT mrgundo_mrgundo_schema_key UNIQUE (mrgundo_schema, mrgundo_table, mrgundo_pkey_col, mrgundo_pkey_id, mrgundo_col);
112578
112579
112580 --
112581 -- TOC entry 7479 (class 2606 OID 146571285)
112582 -- Dependencies: 689 689 8894
112583 -- Name: msg_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112584 --
112585
112586 ALTER TABLE ONLY msg
112587     ADD CONSTRAINT msg_pkey PRIMARY KEY (msg_id);
112588
112589
112590 --
112591 -- TOC entry 7481 (class 2606 OID 146571287)
112592 -- Dependencies: 691 691 8894
112593 -- Name: msguser_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112594 --
112595
112596 ALTER TABLE ONLY msguser
112597     ADD CONSTRAINT msguser_pkey PRIMARY KEY (msguser_id);
112598
112599
112600 --
112601 -- TOC entry 7483 (class 2606 OID 146571289)
112602 -- Dependencies: 694 694 8894
112603 -- Name: obsolete_tax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112604 --
112605
112606 ALTER TABLE ONLY obsolete_tax
112607     ADD CONSTRAINT obsolete_tax_pkey PRIMARY KEY (tax_id);
112608
112609
112610 --
112611 -- TOC entry 6908 (class 2606 OID 146571291)
112612 -- Dependencies: 231 231 8894
112613 -- Name: ophead_ophead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112614 --
112615
112616 ALTER TABLE ONLY ophead
112617     ADD CONSTRAINT ophead_ophead_number_key UNIQUE (ophead_number);
112618
112619
112620 --
112621 -- TOC entry 6910 (class 2606 OID 146571293)
112622 -- Dependencies: 231 231 8894
112623 -- Name: ophead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112624 --
112625
112626 ALTER TABLE ONLY ophead
112627     ADD CONSTRAINT ophead_pkey PRIMARY KEY (ophead_id);
112628
112629
112630 --
112631 -- TOC entry 7485 (class 2606 OID 146571295)
112632 -- Dependencies: 696 696 8894
112633 -- Name: opsource_opsource_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112634 --
112635
112636 ALTER TABLE ONLY opsource
112637     ADD CONSTRAINT opsource_opsource_name_key UNIQUE (opsource_name);
112638
112639
112640 --
112641 -- TOC entry 7487 (class 2606 OID 146571297)
112642 -- Dependencies: 696 696 8894
112643 -- Name: opsource_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112644 --
112645
112646 ALTER TABLE ONLY opsource
112647     ADD CONSTRAINT opsource_pkey PRIMARY KEY (opsource_id);
112648
112649
112650 --
112651 -- TOC entry 7489 (class 2606 OID 146571299)
112652 -- Dependencies: 698 698 8894
112653 -- Name: opstage_opstage_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112654 --
112655
112656 ALTER TABLE ONLY opstage
112657     ADD CONSTRAINT opstage_opstage_name_key UNIQUE (opstage_name);
112658
112659
112660 --
112661 -- TOC entry 7491 (class 2606 OID 146571301)
112662 -- Dependencies: 698 698 8894
112663 -- Name: opstage_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112664 --
112665
112666 ALTER TABLE ONLY opstage
112667     ADD CONSTRAINT opstage_pkey PRIMARY KEY (opstage_id);
112668
112669
112670 --
112671 -- TOC entry 7493 (class 2606 OID 146571303)
112672 -- Dependencies: 700 700 8894
112673 -- Name: optype_optype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112674 --
112675
112676 ALTER TABLE ONLY optype
112677     ADD CONSTRAINT optype_optype_name_key UNIQUE (optype_name);
112678
112679
112680 --
112681 -- TOC entry 7495 (class 2606 OID 146571305)
112682 -- Dependencies: 700 700 8894
112683 -- Name: optype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112684 --
112685
112686 ALTER TABLE ONLY optype
112687     ADD CONSTRAINT optype_pkey PRIMARY KEY (optype_id);
112688
112689
112690 --
112691 -- TOC entry 7497 (class 2606 OID 146571307)
112692 -- Dependencies: 704 704 8894
112693 -- Name: orderseq_orderseq_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112694 --
112695
112696 ALTER TABLE ONLY orderseq
112697     ADD CONSTRAINT orderseq_orderseq_name_key UNIQUE (orderseq_name);
112698
112699
112700 --
112701 -- TOC entry 7499 (class 2606 OID 146571309)
112702 -- Dependencies: 704 704 8894
112703 -- Name: orderseq_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112704 --
112705
112706 ALTER TABLE ONLY orderseq
112707     ADD CONSTRAINT orderseq_pkey PRIMARY KEY (orderseq_id);
112708
112709
112710 --
112711 -- TOC entry 7501 (class 2606 OID 146571311)
112712 -- Dependencies: 706 706 8894
112713 -- Name: pack_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112714 --
112715
112716 ALTER TABLE ONLY pack
112717     ADD CONSTRAINT pack_pkey PRIMARY KEY (pack_id);
112718
112719
112720 --
112721 -- TOC entry 7505 (class 2606 OID 146571313)
112722 -- Dependencies: 708 708 708 8894
112723 -- Name: payaropen_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112724 --
112725
112726 ALTER TABLE ONLY payaropen
112727     ADD CONSTRAINT payaropen_pkey PRIMARY KEY (payaropen_ccpay_id, payaropen_aropen_id);
112728
112729
112730 --
112731 -- TOC entry 6960 (class 2606 OID 146571315)
112732 -- Dependencies: 264 264 8894
112733 -- Name: period_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112734 --
112735
112736 ALTER TABLE ONLY period
112737     ADD CONSTRAINT period_pkey PRIMARY KEY (period_id);
112738
112739
112740 --
112741 -- TOC entry 7538 (class 2606 OID 146571317)
112742 -- Dependencies: 739 739 8894
112743 -- Name: pk_prjtype; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112744 --
112745
112746 ALTER TABLE ONLY prjtype
112747     ADD CONSTRAINT pk_prjtype PRIMARY KEY (prjtype_id);
112748
112749
112750 --
112751 -- TOC entry 7509 (class 2606 OID 146571319)
112752 -- Dependencies: 711 711 8894
112753 -- Name: pkgdep_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112754 --
112755
112756 ALTER TABLE ONLY pkgdep
112757     ADD CONSTRAINT pkgdep_pkey PRIMARY KEY (pkgdep_id);
112758
112759
112760 --
112761 -- TOC entry 7511 (class 2606 OID 146571321)
112762 -- Dependencies: 713 713 8894
112763 -- Name: pkghead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112764 --
112765
112766 ALTER TABLE ONLY pkghead
112767     ADD CONSTRAINT pkghead_pkey PRIMARY KEY (pkghead_id);
112768
112769
112770 --
112771 -- TOC entry 7513 (class 2606 OID 146571323)
112772 -- Dependencies: 715 715 8894
112773 -- Name: pkgitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112774 --
112775
112776 ALTER TABLE ONLY pkgitem
112777     ADD CONSTRAINT pkgitem_pkey PRIMARY KEY (pkgitem_id);
112778
112779
112780 --
112781 -- TOC entry 7515 (class 2606 OID 146571325)
112782 -- Dependencies: 715 715 715 715 8894
112783 -- Name: pkgitem_pkgitem_pkghead_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112784 --
112785
112786 ALTER TABLE ONLY pkgitem
112787     ADD CONSTRAINT pkgitem_pkgitem_pkghead_id_key UNIQUE (pkgitem_pkghead_id, pkgitem_type, pkgitem_name);
112788
112789
112790 --
112791 -- TOC entry 7517 (class 2606 OID 146571327)
112792 -- Dependencies: 715 715 715 715 8894
112793 -- Name: pkgitem_pkgitem_pkghead_id_key1; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112794 --
112795
112796 ALTER TABLE ONLY pkgitem
112797     ADD CONSTRAINT pkgitem_pkgitem_pkghead_id_key1 UNIQUE (pkgitem_pkghead_id, pkgitem_type, pkgitem_item_id);
112798
112799
112800 --
112801 -- TOC entry 7060 (class 2606 OID 146571329)
112802 -- Dependencies: 326 326 8894
112803 -- Name: plancode_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112804 --
112805
112806 ALTER TABLE ONLY plancode
112807     ADD CONSTRAINT plancode_pkey PRIMARY KEY (plancode_id);
112808
112809
112810 --
112811 -- TOC entry 7062 (class 2606 OID 146571331)
112812 -- Dependencies: 326 326 8894
112813 -- Name: plancode_plancode_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112814 --
112815
112816 ALTER TABLE ONLY plancode
112817     ADD CONSTRAINT plancode_plancode_code_key UNIQUE (plancode_code);
112818
112819
112820 --
112821 -- TOC entry 6784 (class 2606 OID 146571333)
112822 -- Dependencies: 197 197 8894
112823 -- Name: pohead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112824 --
112825
112826 ALTER TABLE ONLY pohead
112827     ADD CONSTRAINT pohead_pkey PRIMARY KEY (pohead_id);
112828
112829
112830 --
112831 -- TOC entry 6786 (class 2606 OID 146571335)
112832 -- Dependencies: 197 197 8894
112833 -- Name: pohead_pohead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112834 --
112835
112836 ALTER TABLE ONLY pohead
112837     ADD CONSTRAINT pohead_pohead_number_key UNIQUE (pohead_number);
112838
112839
112840 --
112841 -- TOC entry 6791 (class 2606 OID 146571337)
112842 -- Dependencies: 198 198 8894
112843 -- Name: poitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112844 --
112845
112846 ALTER TABLE ONLY poitem
112847     ADD CONSTRAINT poitem_pkey PRIMARY KEY (poitem_id);
112848
112849
112850 --
112851 -- TOC entry 6794 (class 2606 OID 146571339)
112852 -- Dependencies: 198 198 198 8894
112853 -- Name: poitem_poitem_pohead_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112854 --
112855
112856 ALTER TABLE ONLY poitem
112857     ADD CONSTRAINT poitem_poitem_pohead_id_key UNIQUE (poitem_pohead_id, poitem_linenumber);
112858
112859
112860 --
112861 -- TOC entry 7522 (class 2606 OID 146571341)
112862 -- Dependencies: 724 724 8894
112863 -- Name: poreject_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112864 --
112865
112866 ALTER TABLE ONLY poreject
112867     ADD CONSTRAINT poreject_pkey PRIMARY KEY (poreject_id);
112868
112869
112870 --
112871 -- TOC entry 7524 (class 2606 OID 146571343)
112872 -- Dependencies: 726 726 8894
112873 -- Name: potype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112874 --
112875
112876 ALTER TABLE ONLY potype
112877     ADD CONSTRAINT potype_pkey PRIMARY KEY (potype_id);
112878
112879
112880 --
112881 -- TOC entry 7526 (class 2606 OID 146571345)
112882 -- Dependencies: 728 728 8894
112883 -- Name: pr_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112884 --
112885
112886 ALTER TABLE ONLY pr
112887     ADD CONSTRAINT pr_pkey PRIMARY KEY (pr_id);
112888
112889
112890 --
112891 -- TOC entry 7528 (class 2606 OID 146571347)
112892 -- Dependencies: 730 730 8894
112893 -- Name: prftcntr_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112894 --
112895
112896 ALTER TABLE ONLY prftcntr
112897     ADD CONSTRAINT prftcntr_pkey PRIMARY KEY (prftcntr_id);
112898
112899
112900 --
112901 -- TOC entry 7530 (class 2606 OID 146571349)
112902 -- Dependencies: 730 730 8894
112903 -- Name: prftcntr_prftcntr_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112904 --
112905
112906 ALTER TABLE ONLY prftcntr
112907     ADD CONSTRAINT prftcntr_prftcntr_number_key UNIQUE (prftcntr_number);
112908
112909
112910 --
112911 -- TOC entry 7180 (class 2606 OID 146571351)
112912 -- Dependencies: 408 408 8894
112913 -- Name: priv_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112914 --
112915
112916 ALTER TABLE ONLY priv
112917     ADD CONSTRAINT priv_pkey PRIMARY KEY (priv_id);
112918
112919
112920 --
112921 -- TOC entry 6892 (class 2606 OID 146571353)
112922 -- Dependencies: 225 225 8894
112923 -- Name: prj_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112924 --
112925
112926 ALTER TABLE ONLY prj
112927     ADD CONSTRAINT prj_pkey PRIMARY KEY (prj_id);
112928
112929
112930 --
112931 -- TOC entry 6894 (class 2606 OID 146571355)
112932 -- Dependencies: 225 225 8894
112933 -- Name: prj_prj_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112934 --
112935
112936 ALTER TABLE ONLY prj
112937     ADD CONSTRAINT prj_prj_number_key UNIQUE (prj_number);
112938
112939
112940 --
112941 -- TOC entry 6912 (class 2606 OID 146571357)
112942 -- Dependencies: 232 232 8894
112943 -- Name: prjtask_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112944 --
112945
112946 ALTER TABLE ONLY prjtask
112947     ADD CONSTRAINT prjtask_pkey PRIMARY KEY (prjtask_id);
112948
112949
112950 --
112951 -- TOC entry 6914 (class 2606 OID 146571359)
112952 -- Dependencies: 232 232 232 8894
112953 -- Name: prjtask_prjtask_prj_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112954 --
112955
112956 ALTER TABLE ONLY prjtask
112957     ADD CONSTRAINT prjtask_prjtask_prj_id_key UNIQUE (prjtask_prj_id, prjtask_number);
112958
112959
112960 --
112961 -- TOC entry 7536 (class 2606 OID 146571361)
112962 -- Dependencies: 737 737 8894
112963 -- Name: prjtaskuser_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112964 --
112965
112966 ALTER TABLE ONLY prjtaskuser
112967     ADD CONSTRAINT prjtaskuser_pkey PRIMARY KEY (prjtaskuser_id);
112968
112969
112970 --
112971 -- TOC entry 7040 (class 2606 OID 146571363)
112972 -- Dependencies: 314 314 8894
112973 -- Name: prodcat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112974 --
112975
112976 ALTER TABLE ONLY prodcat
112977     ADD CONSTRAINT prodcat_pkey PRIMARY KEY (prodcat_id);
112978
112979
112980 --
112981 -- TOC entry 7042 (class 2606 OID 146571365)
112982 -- Dependencies: 314 314 8894
112983 -- Name: prodcat_prodcat_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112984 --
112985
112986 ALTER TABLE ONLY prodcat
112987     ADD CONSTRAINT prodcat_prodcat_code_key UNIQUE (prodcat_code);
112988
112989
112990 --
112991 -- TOC entry 7113 (class 2606 OID 146571367)
112992 -- Dependencies: 356 356 8894
112993 -- Name: prospect_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
112994 --
112995
112996 ALTER TABLE ONLY prospect
112997     ADD CONSTRAINT prospect_pkey PRIMARY KEY (prospect_id);
112998
112999
113000 --
113001 -- TOC entry 7115 (class 2606 OID 146571369)
113002 -- Dependencies: 356 356 8894
113003 -- Name: prospect_prospect_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113004 --
113005
113006 ALTER TABLE ONLY prospect
113007     ADD CONSTRAINT prospect_prospect_number_key UNIQUE (prospect_number);
113008
113009
113010 --
113011 -- TOC entry 7542 (class 2606 OID 146571371)
113012 -- Dependencies: 742 742 8894
113013 -- Name: qryhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113014 --
113015
113016 ALTER TABLE ONLY qryhead
113017     ADD CONSTRAINT qryhead_pkey PRIMARY KEY (qryhead_id);
113018
113019
113020 --
113021 -- TOC entry 7544 (class 2606 OID 146571373)
113022 -- Dependencies: 742 742 8894
113023 -- Name: qryhead_qryhead_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113024 --
113025
113026 ALTER TABLE ONLY qryhead
113027     ADD CONSTRAINT qryhead_qryhead_name_key UNIQUE (qryhead_name);
113028
113029
113030 --
113031 -- TOC entry 7546 (class 2606 OID 146571375)
113032 -- Dependencies: 744 744 744 8894
113033 -- Name: qryitem_qryitem_qryhead_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113034 --
113035
113036 ALTER TABLE ONLY qryitem
113037     ADD CONSTRAINT qryitem_qryitem_qryhead_id_key UNIQUE (qryitem_qryhead_id, qryitem_name);
113038
113039
113040 --
113041 -- TOC entry 7548 (class 2606 OID 146571377)
113042 -- Dependencies: 744 744 744 8894
113043 -- Name: qryitem_qryitem_qryhead_id_key1; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113044 --
113045
113046 ALTER TABLE ONLY qryitem
113047     ADD CONSTRAINT qryitem_qryitem_qryhead_id_key1 UNIQUE (qryitem_qryhead_id, qryitem_order);
113048
113049
113050 --
113051 -- TOC entry 7129 (class 2606 OID 146571379)
113052 -- Dependencies: 367 367 8894
113053 -- Name: quhead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113054 --
113055
113056 ALTER TABLE ONLY quhead
113057     ADD CONSTRAINT quhead_pkey PRIMARY KEY (quhead_id);
113058
113059
113060 --
113061 -- TOC entry 7131 (class 2606 OID 146571381)
113062 -- Dependencies: 367 367 8894
113063 -- Name: quhead_quhead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113064 --
113065
113066 ALTER TABLE ONLY quhead
113067     ADD CONSTRAINT quhead_quhead_number_key UNIQUE (quhead_number);
113068
113069
113070 --
113071 -- TOC entry 7133 (class 2606 OID 146571383)
113072 -- Dependencies: 370 370 8894
113073 -- Name: quitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113074 --
113075
113076 ALTER TABLE ONLY quitem
113077     ADD CONSTRAINT quitem_pkey PRIMARY KEY (quitem_id);
113078
113079
113080 --
113081 -- TOC entry 7550 (class 2606 OID 146571385)
113082 -- Dependencies: 748 748 8894
113083 -- Name: rcalitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113084 --
113085
113086 ALTER TABLE ONLY rcalitem
113087     ADD CONSTRAINT rcalitem_pkey PRIMARY KEY (rcalitem_id);
113088
113089
113090 --
113091 -- TOC entry 7552 (class 2606 OID 146571387)
113092 -- Dependencies: 749 749 8894
113093 -- Name: recur_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113094 --
113095
113096 ALTER TABLE ONLY recur
113097     ADD CONSTRAINT recur_pkey PRIMARY KEY (recur_id);
113098
113099
113100 --
113101 -- TOC entry 7554 (class 2606 OID 146571389)
113102 -- Dependencies: 749 749 749 8894
113103 -- Name: recur_recur_parent_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113104 --
113105
113106 ALTER TABLE ONLY recur
113107     ADD CONSTRAINT recur_recur_parent_id_key UNIQUE (recur_parent_id, recur_parent_type);
113108
113109
113110 --
113111 -- TOC entry 7556 (class 2606 OID 146571391)
113112 -- Dependencies: 751 751 8894
113113 -- Name: recurtype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113114 --
113115
113116 ALTER TABLE ONLY recurtype
113117     ADD CONSTRAINT recurtype_pkey PRIMARY KEY (recurtype_id);
113118
113119
113120 --
113121 -- TOC entry 7558 (class 2606 OID 146571393)
113122 -- Dependencies: 751 751 8894
113123 -- Name: recurtype_recurtype_type_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113124 --
113125
113126 ALTER TABLE ONLY recurtype
113127     ADD CONSTRAINT recurtype_recurtype_type_key UNIQUE (recurtype_type);
113128
113129
113130 --
113131 -- TOC entry 7520 (class 2606 OID 146571395)
113132 -- Dependencies: 721 721 8894
113133 -- Name: recv_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113134 --
113135
113136 ALTER TABLE ONLY recv
113137     ADD CONSTRAINT recv_pkey PRIMARY KEY (recv_id);
113138
113139
113140 --
113141 -- TOC entry 7185 (class 2606 OID 146571397)
113142 -- Dependencies: 411 411 8894
113143 -- Name: report_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113144 --
113145
113146 ALTER TABLE ONLY report
113147     ADD CONSTRAINT report_pkey PRIMARY KEY (report_id);
113148
113149
113150 --
113151 -- TOC entry 7560 (class 2606 OID 146571399)
113152 -- Dependencies: 755 755 8894
113153 -- Name: rjctcode_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113154 --
113155
113156 ALTER TABLE ONLY rjctcode
113157     ADD CONSTRAINT rjctcode_pkey PRIMARY KEY (rjctcode_id);
113158
113159
113160 --
113161 -- TOC entry 7562 (class 2606 OID 146571401)
113162 -- Dependencies: 755 755 8894
113163 -- Name: rjctcode_rjctcode_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113164 --
113165
113166 ALTER TABLE ONLY rjctcode
113167     ADD CONSTRAINT rjctcode_rjctcode_code_key UNIQUE (rjctcode_code);
113168
113169
113170 --
113171 -- TOC entry 6858 (class 2606 OID 146571403)
113172 -- Dependencies: 214 214 8894
113173 -- Name: rsncode_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113174 --
113175
113176 ALTER TABLE ONLY rsncode
113177     ADD CONSTRAINT rsncode_pkey PRIMARY KEY (rsncode_id);
113178
113179
113180 --
113181 -- TOC entry 6860 (class 2606 OID 146571405)
113182 -- Dependencies: 214 214 8894
113183 -- Name: rsncode_rsncode_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113184 --
113185
113186 ALTER TABLE ONLY rsncode
113187     ADD CONSTRAINT rsncode_rsncode_code_key UNIQUE (rsncode_code);
113188
113189
113190 --
113191 -- TOC entry 7564 (class 2606 OID 146571407)
113192 -- Dependencies: 758 758 8894
113193 -- Name: sale_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113194 --
113195
113196 ALTER TABLE ONLY sale
113197     ADD CONSTRAINT sale_pkey PRIMARY KEY (sale_id);
113198
113199
113200 --
113201 -- TOC entry 7566 (class 2606 OID 146571409)
113202 -- Dependencies: 758 758 8894
113203 -- Name: sale_sale_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113204 --
113205
113206 ALTER TABLE ONLY sale
113207     ADD CONSTRAINT sale_sale_name_key UNIQUE (sale_name);
113208
113209
113210 --
113211 -- TOC entry 7324 (class 2606 OID 146571411)
113212 -- Dependencies: 540 540 8894
113213 -- Name: salesaccnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113214 --
113215
113216 ALTER TABLE ONLY salesaccnt
113217     ADD CONSTRAINT salesaccnt_pkey PRIMARY KEY (salesaccnt_id);
113218
113219
113220 --
113221 -- TOC entry 6862 (class 2606 OID 146571413)
113222 -- Dependencies: 215 215 8894
113223 -- Name: salescat_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113224 --
113225
113226 ALTER TABLE ONLY salescat
113227     ADD CONSTRAINT salescat_pkey PRIMARY KEY (salescat_id);
113228
113229
113230 --
113231 -- TOC entry 6864 (class 2606 OID 146571415)
113232 -- Dependencies: 215 215 8894
113233 -- Name: salescat_salescat_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113234 --
113235
113236 ALTER TABLE ONLY salescat
113237     ADD CONSTRAINT salescat_salescat_name_key UNIQUE (salescat_name);
113238
113239
113240 --
113241 -- TOC entry 6866 (class 2606 OID 146571417)
113242 -- Dependencies: 216 216 8894
113243 -- Name: salesrep_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113244 --
113245
113246 ALTER TABLE ONLY salesrep
113247     ADD CONSTRAINT salesrep_pkey PRIMARY KEY (salesrep_id);
113248
113249
113250 --
113251 -- TOC entry 6868 (class 2606 OID 146571419)
113252 -- Dependencies: 216 216 8894
113253 -- Name: salesrep_salesrep_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113254 --
113255
113256 ALTER TABLE ONLY salesrep
113257     ADD CONSTRAINT salesrep_salesrep_number_key UNIQUE (salesrep_number);
113258
113259
113260 --
113261 -- TOC entry 6896 (class 2606 OID 146571421)
113262 -- Dependencies: 226 226 8894
113263 -- Name: saletype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113264 --
113265
113266 ALTER TABLE ONLY saletype
113267     ADD CONSTRAINT saletype_pkey PRIMARY KEY (saletype_id);
113268
113269
113270 --
113271 -- TOC entry 7568 (class 2606 OID 146571423)
113272 -- Dependencies: 766 766 8894
113273 -- Name: schemaord_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113274 --
113275
113276 ALTER TABLE ONLY schemaord
113277     ADD CONSTRAINT schemaord_pkey PRIMARY KEY (schemaord_id);
113278
113279
113280 --
113281 -- TOC entry 7570 (class 2606 OID 146571425)
113282 -- Dependencies: 766 766 8894
113283 -- Name: schemaord_schemaord_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113284 --
113285
113286 ALTER TABLE ONLY schemaord
113287     ADD CONSTRAINT schemaord_schemaord_name_key UNIQUE (schemaord_name);
113288
113289
113290 --
113291 -- TOC entry 7572 (class 2606 OID 146571427)
113292 -- Dependencies: 766 766 8894
113293 -- Name: schemaord_schemaord_order_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113294 --
113295
113296 ALTER TABLE ONLY schemaord
113297     ADD CONSTRAINT schemaord_schemaord_order_key UNIQUE (schemaord_order);
113298
113299
113300 --
113301 -- TOC entry 7189 (class 2606 OID 146571429)
113302 -- Dependencies: 414 414 8894
113303 -- Name: script_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113304 --
113305
113306 ALTER TABLE ONLY script
113307     ADD CONSTRAINT script_pkey PRIMARY KEY (script_id);
113308
113309
113310 --
113311 -- TOC entry 7005 (class 2606 OID 146571431)
113312 -- Dependencies: 293 293 8894
113313 -- Name: shift_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113314 --
113315
113316 ALTER TABLE ONLY shift
113317     ADD CONSTRAINT shift_pkey PRIMARY KEY (shift_id);
113318
113319
113320 --
113321 -- TOC entry 6983 (class 2606 OID 146571433)
113322 -- Dependencies: 281 281 8894
113323 -- Name: shipchrg_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113324 --
113325
113326 ALTER TABLE ONLY shipchrg
113327     ADD CONSTRAINT shipchrg_pkey PRIMARY KEY (shipchrg_id);
113328
113329
113330 --
113331 -- TOC entry 7008 (class 2606 OID 146571435)
113332 -- Dependencies: 297 297 297 297 297 8894
113333 -- Name: shipdata_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113334 --
113335
113336 ALTER TABLE ONLY shipdata
113337     ADD CONSTRAINT shipdata_pkey PRIMARY KEY (shipdata_cohead_number, shipdata_cosmisc_tracknum, shipdata_cosmisc_packnum_tracknum, shipdata_void_ind);
113338
113339
113340 --
113341 -- TOC entry 7576 (class 2606 OID 146571437)
113342 -- Dependencies: 771 771 771 771 8894
113343 -- Name: shipdatasum_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113344 --
113345
113346 ALTER TABLE ONLY shipdatasum
113347     ADD CONSTRAINT shipdatasum_pkey PRIMARY KEY (shipdatasum_cohead_number, shipdatasum_cosmisc_tracknum, shipdatasum_cosmisc_packnum_tracknum);
113348
113349
113350 --
113351 -- TOC entry 6985 (class 2606 OID 146571439)
113352 -- Dependencies: 282 282 8894
113353 -- Name: shipform_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113354 --
113355
113356 ALTER TABLE ONLY shipform
113357     ADD CONSTRAINT shipform_pkey PRIMARY KEY (shipform_id);
113358
113359
113360 --
113361 -- TOC entry 6987 (class 2606 OID 146571441)
113362 -- Dependencies: 282 282 8894
113363 -- Name: shipform_shipform_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113364 --
113365
113366 ALTER TABLE ONLY shipform
113367     ADD CONSTRAINT shipform_shipform_name_key UNIQUE (shipform_name);
113368
113369
113370 --
113371 -- TOC entry 7304 (class 2606 OID 146571443)
113372 -- Dependencies: 526 526 8894
113373 -- Name: shiphead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113374 --
113375
113376 ALTER TABLE ONLY shiphead
113377     ADD CONSTRAINT shiphead_pkey PRIMARY KEY (shiphead_id);
113378
113379
113380 --
113381 -- TOC entry 7306 (class 2606 OID 146571445)
113382 -- Dependencies: 526 526 8894
113383 -- Name: shiphead_shiphead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113384 --
113385
113386 ALTER TABLE ONLY shiphead
113387     ADD CONSTRAINT shiphead_shiphead_number_key UNIQUE (shiphead_number);
113388
113389
113390 --
113391 -- TOC entry 7311 (class 2606 OID 146571447)
113392 -- Dependencies: 527 527 8894
113393 -- Name: shipitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113394 --
113395
113396 ALTER TABLE ONLY shipitem
113397     ADD CONSTRAINT shipitem_pkey PRIMARY KEY (shipitem_id);
113398
113399
113400 --
113401 -- TOC entry 6875 (class 2606 OID 146571449)
113402 -- Dependencies: 219 219 219 8894
113403 -- Name: shipto_num_cust_unique; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113404 --
113405
113406 ALTER TABLE ONLY shiptoinfo
113407     ADD CONSTRAINT shipto_num_cust_unique UNIQUE (shipto_cust_id, shipto_num);
113408
113409
113410 --
113411 -- TOC entry 6877 (class 2606 OID 146571451)
113412 -- Dependencies: 219 219 8894
113413 -- Name: shipto_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113414 --
113415
113416 ALTER TABLE ONLY shiptoinfo
113417     ADD CONSTRAINT shipto_pkey PRIMARY KEY (shipto_id);
113418
113419
113420 --
113421 -- TOC entry 7151 (class 2606 OID 146571453)
113422 -- Dependencies: 386 386 8894
113423 -- Name: shipvia_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113424 --
113425
113426 ALTER TABLE ONLY shipvia
113427     ADD CONSTRAINT shipvia_pkey PRIMARY KEY (shipvia_id);
113428
113429
113430 --
113431 -- TOC entry 7153 (class 2606 OID 146571455)
113432 -- Dependencies: 386 386 8894
113433 -- Name: shipvia_shipvia_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113434 --
113435
113436 ALTER TABLE ONLY shipvia
113437     ADD CONSTRAINT shipvia_shipvia_code_key UNIQUE (shipvia_code);
113438
113439
113440 --
113441 -- TOC entry 6898 (class 2606 OID 146571457)
113442 -- Dependencies: 227 227 8894
113443 -- Name: shipzone_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113444 --
113445
113446 ALTER TABLE ONLY shipzone
113447     ADD CONSTRAINT shipzone_pkey PRIMARY KEY (shipzone_id);
113448
113449
113450 --
113451 -- TOC entry 6900 (class 2606 OID 146571459)
113452 -- Dependencies: 227 227 8894
113453 -- Name: shipzone_shipzone_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113454 --
113455
113456 ALTER TABLE ONLY shipzone
113457     ADD CONSTRAINT shipzone_shipzone_name_key UNIQUE (shipzone_name);
113458
113459
113460 --
113461 -- TOC entry 7155 (class 2606 OID 146571461)
113462 -- Dependencies: 387 387 8894
113463 -- Name: sitetype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113464 --
113465
113466 ALTER TABLE ONLY sitetype
113467     ADD CONSTRAINT sitetype_pkey PRIMARY KEY (sitetype_id);
113468
113469
113470 --
113471 -- TOC entry 7157 (class 2606 OID 146571463)
113472 -- Dependencies: 387 387 8894
113473 -- Name: sitetype_sitetype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113474 --
113475
113476 ALTER TABLE ONLY sitetype
113477     ADD CONSTRAINT sitetype_sitetype_name_key UNIQUE (sitetype_name);
113478
113479
113480 --
113481 -- TOC entry 7578 (class 2606 OID 146571465)
113482 -- Dependencies: 781 781 8894
113483 -- Name: sltrans_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113484 --
113485
113486 ALTER TABLE ONLY sltrans
113487     ADD CONSTRAINT sltrans_pkey PRIMARY KEY (sltrans_id);
113488
113489
113490 --
113491 -- TOC entry 7584 (class 2606 OID 146571467)
113492 -- Dependencies: 785 785 8894
113493 -- Name: source_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113494 --
113495
113496 ALTER TABLE ONLY source
113497     ADD CONSTRAINT source_pkey PRIMARY KEY (source_id);
113498
113499
113500 --
113501 -- TOC entry 7586 (class 2606 OID 146571469)
113502 -- Dependencies: 785 785 8894
113503 -- Name: source_source_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113504 --
113505
113506 ALTER TABLE ONLY source
113507     ADD CONSTRAINT source_source_name_key UNIQUE (source_name);
113508
113509
113510 --
113511 -- TOC entry 7588 (class 2606 OID 146571471)
113512 -- Dependencies: 787 787 8894
113513 -- Name: state_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113514 --
113515
113516 ALTER TABLE ONLY state
113517     ADD CONSTRAINT state_pkey PRIMARY KEY (state_id);
113518
113519
113520 --
113521 -- TOC entry 7590 (class 2606 OID 146571473)
113522 -- Dependencies: 787 787 787 8894
113523 -- Name: state_state_country_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113524 --
113525
113526 ALTER TABLE ONLY state
113527     ADD CONSTRAINT state_state_country_id_key UNIQUE (state_country_id, state_name);
113528
113529
113530 --
113531 -- TOC entry 7592 (class 2606 OID 146571475)
113532 -- Dependencies: 789 789 8894
113533 -- Name: status_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113534 --
113535
113536 ALTER TABLE ONLY status
113537     ADD CONSTRAINT status_pkey PRIMARY KEY (status_id);
113538
113539
113540 --
113541 -- TOC entry 7594 (class 2606 OID 146571477)
113542 -- Dependencies: 789 789 789 8894
113543 -- Name: status_status_type_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113544 --
113545
113546 ALTER TABLE ONLY status
113547     ADD CONSTRAINT status_status_type_key UNIQUE (status_type, status_code);
113548
113549
113550 --
113551 -- TOC entry 7596 (class 2606 OID 146571479)
113552 -- Dependencies: 791 791 8894
113553 -- Name: stdjrnl_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113554 --
113555
113556 ALTER TABLE ONLY stdjrnl
113557     ADD CONSTRAINT stdjrnl_pkey PRIMARY KEY (stdjrnl_id);
113558
113559
113560 --
113561 -- TOC entry 7598 (class 2606 OID 146571481)
113562 -- Dependencies: 791 791 8894
113563 -- Name: stdjrnl_stdjrnl_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113564 --
113565
113566 ALTER TABLE ONLY stdjrnl
113567     ADD CONSTRAINT stdjrnl_stdjrnl_name_key UNIQUE (stdjrnl_name);
113568
113569
113570 --
113571 -- TOC entry 7600 (class 2606 OID 146571483)
113572 -- Dependencies: 793 793 8894
113573 -- Name: stdjrnlgrp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113574 --
113575
113576 ALTER TABLE ONLY stdjrnlgrp
113577     ADD CONSTRAINT stdjrnlgrp_pkey PRIMARY KEY (stdjrnlgrp_id);
113578
113579
113580 --
113581 -- TOC entry 7602 (class 2606 OID 146571485)
113582 -- Dependencies: 793 793 8894
113583 -- Name: stdjrnlgrp_stdjrnlgrp_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113584 --
113585
113586 ALTER TABLE ONLY stdjrnlgrp
113587     ADD CONSTRAINT stdjrnlgrp_stdjrnlgrp_name_key UNIQUE (stdjrnlgrp_name);
113588
113589
113590 --
113591 -- TOC entry 7604 (class 2606 OID 146571487)
113592 -- Dependencies: 795 795 8894
113593 -- Name: stdjrnlgrpitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113594 --
113595
113596 ALTER TABLE ONLY stdjrnlgrpitem
113597     ADD CONSTRAINT stdjrnlgrpitem_pkey PRIMARY KEY (stdjrnlgrpitem_id);
113598
113599
113600 --
113601 -- TOC entry 7606 (class 2606 OID 146571489)
113602 -- Dependencies: 797 797 8894
113603 -- Name: stdjrnlitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113604 --
113605
113606 ALTER TABLE ONLY stdjrnlitem
113607     ADD CONSTRAINT stdjrnlitem_pkey PRIMARY KEY (stdjrnlitem_id);
113608
113609
113610 --
113611 -- TOC entry 7608 (class 2606 OID 146571491)
113612 -- Dependencies: 799 799 8894
113613 -- Name: subaccnt_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113614 --
113615
113616 ALTER TABLE ONLY subaccnt
113617     ADD CONSTRAINT subaccnt_pkey PRIMARY KEY (subaccnt_id);
113618
113619
113620 --
113621 -- TOC entry 7610 (class 2606 OID 146571493)
113622 -- Dependencies: 799 799 8894
113623 -- Name: subaccnt_subaccnt_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113624 --
113625
113626 ALTER TABLE ONLY subaccnt
113627     ADD CONSTRAINT subaccnt_subaccnt_number_key UNIQUE (subaccnt_number);
113628
113629
113630 --
113631 -- TOC entry 7613 (class 2606 OID 146571495)
113632 -- Dependencies: 801 801 8894
113633 -- Name: subaccnttype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113634 --
113635
113636 ALTER TABLE ONLY subaccnttype
113637     ADD CONSTRAINT subaccnttype_pkey PRIMARY KEY (subaccnttype_id);
113638
113639
113640 --
113641 -- TOC entry 7125 (class 2606 OID 146571497)
113642 -- Dependencies: 363 363 8894
113643 -- Name: tax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113644 --
113645
113646 ALTER TABLE ONLY tax
113647     ADD CONSTRAINT tax_pkey PRIMARY KEY (tax_id);
113648
113649
113650 --
113651 -- TOC entry 7615 (class 2606 OID 146571499)
113652 -- Dependencies: 804 804 8894
113653 -- Name: taxass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113654 --
113655
113656 ALTER TABLE ONLY taxass
113657     ADD CONSTRAINT taxass_pkey PRIMARY KEY (taxass_id);
113658
113659
113660 --
113661 -- TOC entry 7617 (class 2606 OID 146571501)
113662 -- Dependencies: 804 804 804 804 8894
113663 -- Name: taxass_taxass_taxzone_id_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113664 --
113665
113666 ALTER TABLE ONLY taxass
113667     ADD CONSTRAINT taxass_taxass_taxzone_id_key UNIQUE (taxass_taxzone_id, taxass_taxtype_id, taxass_tax_id);
113668
113669
113670 --
113671 -- TOC entry 6989 (class 2606 OID 146571503)
113672 -- Dependencies: 284 284 8894
113673 -- Name: taxauth_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113674 --
113675
113676 ALTER TABLE ONLY taxauth
113677     ADD CONSTRAINT taxauth_pkey PRIMARY KEY (taxauth_id);
113678
113679
113680 --
113681 -- TOC entry 6991 (class 2606 OID 146571505)
113682 -- Dependencies: 284 284 8894
113683 -- Name: taxauth_taxauth_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113684 --
113685
113686 ALTER TABLE ONLY taxauth
113687     ADD CONSTRAINT taxauth_taxauth_code_key UNIQUE (taxauth_code);
113688
113689
113690 --
113691 -- TOC entry 7619 (class 2606 OID 146571507)
113692 -- Dependencies: 807 807 8894
113693 -- Name: taxclass_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113694 --
113695
113696 ALTER TABLE ONLY taxclass
113697     ADD CONSTRAINT taxclass_pkey PRIMARY KEY (taxclass_id);
113698
113699
113700 --
113701 -- TOC entry 7621 (class 2606 OID 146571509)
113702 -- Dependencies: 807 807 8894
113703 -- Name: taxclass_taxclass_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113704 --
113705
113706 ALTER TABLE ONLY taxclass
113707     ADD CONSTRAINT taxclass_taxclass_code_key UNIQUE (taxclass_code);
113708
113709
113710 --
113711 -- TOC entry 7147 (class 2606 OID 146571511)
113712 -- Dependencies: 377 377 8894
113713 -- Name: taxhist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113714 --
113715
113716 ALTER TABLE ONLY taxhist
113717     ADD CONSTRAINT taxhist_pkey PRIMARY KEY (taxhist_id);
113718
113719
113720 --
113721 -- TOC entry 7623 (class 2606 OID 146571513)
113722 -- Dependencies: 809 809 8894
113723 -- Name: taxrate_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113724 --
113725
113726 ALTER TABLE ONLY taxrate
113727     ADD CONSTRAINT taxrate_pkey PRIMARY KEY (taxrate_id);
113728
113729
113730 --
113731 -- TOC entry 6993 (class 2606 OID 146571515)
113732 -- Dependencies: 285 285 8894
113733 -- Name: taxreg_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113734 --
113735
113736 ALTER TABLE ONLY taxreg
113737     ADD CONSTRAINT taxreg_pkey PRIMARY KEY (taxreg_id);
113738
113739
113740 --
113741 -- TOC entry 6797 (class 2606 OID 146571517)
113742 -- Dependencies: 199 199 8894
113743 -- Name: taxtype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113744 --
113745
113746 ALTER TABLE ONLY taxtype
113747     ADD CONSTRAINT taxtype_pkey PRIMARY KEY (taxtype_id);
113748
113749
113750 --
113751 -- TOC entry 6799 (class 2606 OID 146571519)
113752 -- Dependencies: 199 199 8894
113753 -- Name: taxtype_taxtype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113754 --
113755
113756 ALTER TABLE ONLY taxtype
113757     ADD CONSTRAINT taxtype_taxtype_name_key UNIQUE (taxtype_name);
113758
113759
113760 --
113761 -- TOC entry 6879 (class 2606 OID 146571521)
113762 -- Dependencies: 220 220 8894
113763 -- Name: taxzone_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113764 --
113765
113766 ALTER TABLE ONLY taxzone
113767     ADD CONSTRAINT taxzone_pkey PRIMARY KEY (taxzone_id);
113768
113769
113770 --
113771 -- TOC entry 6881 (class 2606 OID 146571523)
113772 -- Dependencies: 220 220 8894
113773 -- Name: taxzone_taxzone_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113774 --
113775
113776 ALTER TABLE ONLY taxzone
113777     ADD CONSTRAINT taxzone_taxzone_code_key UNIQUE (taxzone_code);
113778
113779
113780 --
113781 -- TOC entry 6837 (class 2606 OID 146571525)
113782 -- Dependencies: 209 209 8894
113783 -- Name: terms_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113784 --
113785
113786 ALTER TABLE ONLY terms
113787     ADD CONSTRAINT terms_pkey PRIMARY KEY (terms_id);
113788
113789
113790 --
113791 -- TOC entry 6839 (class 2606 OID 146571527)
113792 -- Dependencies: 209 209 8894
113793 -- Name: terms_terms_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113794 --
113795
113796 ALTER TABLE ONLY terms
113797     ADD CONSTRAINT terms_terms_code_key UNIQUE (terms_code);
113798
113799
113800 --
113801 -- TOC entry 6916 (class 2606 OID 146571529)
113802 -- Dependencies: 233 233 8894
113803 -- Name: todoitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113804 --
113805
113806 ALTER TABLE ONLY todoitem
113807     ADD CONSTRAINT todoitem_pkey PRIMARY KEY (todoitem_id);
113808
113809
113810 --
113811 -- TOC entry 7626 (class 2606 OID 146571531)
113812 -- Dependencies: 817 817 8894
113813 -- Name: trialbal_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113814 --
113815
113816 ALTER TABLE ONLY trialbal
113817     ADD CONSTRAINT trialbal_pkey PRIMARY KEY (trialbal_id);
113818
113819
113820 --
113821 -- TOC entry 7193 (class 2606 OID 146571533)
113822 -- Dependencies: 417 417 8894
113823 -- Name: uiform_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113824 --
113825
113826 ALTER TABLE ONLY uiform
113827     ADD CONSTRAINT uiform_pkey PRIMARY KEY (uiform_id);
113828
113829
113830 --
113831 -- TOC entry 7540 (class 2606 OID 146571535)
113832 -- Dependencies: 739 739 8894
113833 -- Name: unq_prjtype_code; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113834 --
113835
113836 ALTER TABLE ONLY prjtype
113837     ADD CONSTRAINT unq_prjtype_code UNIQUE (prjtype_code);
113838
113839
113840 --
113841 -- TOC entry 6801 (class 2606 OID 146571537)
113842 -- Dependencies: 200 200 8894
113843 -- Name: uom_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113844 --
113845
113846 ALTER TABLE ONLY uom
113847     ADD CONSTRAINT uom_pkey PRIMARY KEY (uom_id);
113848
113849
113850 --
113851 -- TOC entry 6803 (class 2606 OID 146571539)
113852 -- Dependencies: 200 200 8894
113853 -- Name: uom_uom_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113854 --
113855
113856 ALTER TABLE ONLY uom
113857     ADD CONSTRAINT uom_uom_name_key UNIQUE (uom_name);
113858
113859
113860 --
113861 -- TOC entry 7628 (class 2606 OID 146571541)
113862 -- Dependencies: 820 820 8894
113863 -- Name: uomconv_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113864 --
113865
113866 ALTER TABLE ONLY uomconv
113867     ADD CONSTRAINT uomconv_pkey PRIMARY KEY (uomconv_id);
113868
113869
113870 --
113871 -- TOC entry 7630 (class 2606 OID 146571543)
113872 -- Dependencies: 822 822 8894
113873 -- Name: uomtype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113874 --
113875
113876 ALTER TABLE ONLY uomtype
113877     ADD CONSTRAINT uomtype_pkey PRIMARY KEY (uomtype_id);
113878
113879
113880 --
113881 -- TOC entry 7632 (class 2606 OID 146571545)
113882 -- Dependencies: 822 822 8894
113883 -- Name: uomtype_uomtype_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113884 --
113885
113886 ALTER TABLE ONLY uomtype
113887     ADD CONSTRAINT uomtype_uomtype_name_key UNIQUE (uomtype_name);
113888
113889
113890 --
113891 -- TOC entry 6941 (class 2606 OID 146571547)
113892 -- Dependencies: 244 244 8894
113893 -- Name: urlinfo_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113894 --
113895
113896 ALTER TABLE ONLY urlinfo
113897     ADD CONSTRAINT urlinfo_pkey PRIMARY KEY (url_id);
113898
113899
113900 --
113901 -- TOC entry 7637 (class 2606 OID 146571549)
113902 -- Dependencies: 827 827 8894
113903 -- Name: usr_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113904 --
113905
113906 ALTER TABLE ONLY usr_bak
113907     ADD CONSTRAINT usr_pkey PRIMARY KEY (usr_id);
113908
113909
113910 --
113911 -- TOC entry 7639 (class 2606 OID 146571551)
113912 -- Dependencies: 827 827 8894
113913 -- Name: usr_usr_username_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113914 --
113915
113916 ALTER TABLE ONLY usr_bak
113917     ADD CONSTRAINT usr_usr_username_key UNIQUE (usr_username);
113918
113919
113920 --
113921 -- TOC entry 7532 (class 2606 OID 146571553)
113922 -- Dependencies: 732 732 8894
113923 -- Name: usrgrp_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113924 --
113925
113926 ALTER TABLE ONLY usrgrp
113927     ADD CONSTRAINT usrgrp_pkey PRIMARY KEY (usrgrp_id);
113928
113929
113930 --
113931 -- TOC entry 7634 (class 2606 OID 146571555)
113932 -- Dependencies: 825 825 8894
113933 -- Name: usrpref_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113934 --
113935
113936 ALTER TABLE ONLY usrpref
113937     ADD CONSTRAINT usrpref_pkey PRIMARY KEY (usrpref_id);
113938
113939
113940 --
113941 -- TOC entry 7534 (class 2606 OID 146571557)
113942 -- Dependencies: 733 733 8894
113943 -- Name: usrpriv_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113944 --
113945
113946 ALTER TABLE ONLY usrpriv
113947     ADD CONSTRAINT usrpriv_pkey PRIMARY KEY (usrpriv_id);
113948
113949
113950 --
113951 -- TOC entry 6842 (class 2606 OID 146571559)
113952 -- Dependencies: 210 210 8894
113953 -- Name: vend_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113954 --
113955
113956 ALTER TABLE ONLY vendinfo
113957     ADD CONSTRAINT vend_pkey PRIMARY KEY (vend_id);
113958
113959
113960 --
113961 -- TOC entry 7127 (class 2606 OID 146571561)
113962 -- Dependencies: 364 364 8894
113963 -- Name: vendaddr_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113964 --
113965
113966 ALTER TABLE ONLY vendaddrinfo
113967     ADD CONSTRAINT vendaddr_pkey PRIMARY KEY (vendaddr_id);
113968
113969
113970 --
113971 -- TOC entry 6844 (class 2606 OID 146571563)
113972 -- Dependencies: 210 210 8894
113973 -- Name: vendinfo_vend_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113974 --
113975
113976 ALTER TABLE ONLY vendinfo
113977     ADD CONSTRAINT vendinfo_vend_number_key UNIQUE (vend_number);
113978
113979
113980 --
113981 -- TOC entry 7159 (class 2606 OID 146571565)
113982 -- Dependencies: 393 393 8894
113983 -- Name: vendtype_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113984 --
113985
113986 ALTER TABLE ONLY vendtype
113987     ADD CONSTRAINT vendtype_pkey PRIMARY KEY (vendtype_id);
113988
113989
113990 --
113991 -- TOC entry 7161 (class 2606 OID 146571567)
113992 -- Dependencies: 393 393 8894
113993 -- Name: vendtype_vendtype_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
113994 --
113995
113996 ALTER TABLE ONLY vendtype
113997     ADD CONSTRAINT vendtype_vendtype_code_key UNIQUE (vendtype_code);
113998
113999
114000 --
114001 -- TOC entry 7641 (class 2606 OID 146571569)
114002 -- Dependencies: 837 837 8894
114003 -- Name: vodist_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114004 --
114005
114006 ALTER TABLE ONLY vodist
114007     ADD CONSTRAINT vodist_pkey PRIMARY KEY (vodist_id);
114008
114009
114010 --
114011 -- TOC entry 7643 (class 2606 OID 146571571)
114012 -- Dependencies: 839 839 8894
114013 -- Name: vohead_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114014 --
114015
114016 ALTER TABLE ONLY vohead
114017     ADD CONSTRAINT vohead_pkey PRIMARY KEY (vohead_id);
114018
114019
114020 --
114021 -- TOC entry 7645 (class 2606 OID 146571573)
114022 -- Dependencies: 839 839 8894
114023 -- Name: vohead_vohead_number_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114024 --
114025
114026 ALTER TABLE ONLY vohead
114027     ADD CONSTRAINT vohead_vohead_number_key UNIQUE (vohead_number);
114028
114029
114030 --
114031 -- TOC entry 7647 (class 2606 OID 146571575)
114032 -- Dependencies: 841 841 8894
114033 -- Name: voheadtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114034 --
114035
114036 ALTER TABLE ONLY voheadtax
114037     ADD CONSTRAINT voheadtax_pkey PRIMARY KEY (taxhist_id);
114038
114039
114040 --
114041 -- TOC entry 7649 (class 2606 OID 146571577)
114042 -- Dependencies: 842 842 8894
114043 -- Name: voitem_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114044 --
114045
114046 ALTER TABLE ONLY voitem
114047     ADD CONSTRAINT voitem_pkey PRIMARY KEY (voitem_id);
114048
114049
114050 --
114051 -- TOC entry 7651 (class 2606 OID 146571579)
114052 -- Dependencies: 844 844 8894
114053 -- Name: voitemtax_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114054 --
114055
114056 ALTER TABLE ONLY voitemtax
114057     ADD CONSTRAINT voitemtax_pkey PRIMARY KEY (taxhist_id);
114058
114059
114060 --
114061 -- TOC entry 6764 (class 2606 OID 146571581)
114062 -- Dependencies: 193 193 8894
114063 -- Name: warehous_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114064 --
114065
114066 ALTER TABLE ONLY whsinfo
114067     ADD CONSTRAINT warehous_pkey PRIMARY KEY (warehous_id);
114068
114069
114070 --
114071 -- TOC entry 7096 (class 2606 OID 146571583)
114072 -- Dependencies: 343 343 8894
114073 -- Name: whsezone_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114074 --
114075
114076 ALTER TABLE ONLY whsezone
114077     ADD CONSTRAINT whsezone_pkey PRIMARY KEY (whsezone_id);
114078
114079
114080 --
114081 -- TOC entry 6766 (class 2606 OID 146571585)
114082 -- Dependencies: 193 193 8894
114083 -- Name: whsinfo_warehous_code_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114084 --
114085
114086 ALTER TABLE ONLY whsinfo
114087     ADD CONSTRAINT whsinfo_warehous_code_key UNIQUE (warehous_code);
114088
114089
114090 --
114091 -- TOC entry 7345 (class 2606 OID 146571587)
114092 -- Dependencies: 560 560 8894
114093 -- Name: wo_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114094 --
114095
114096 ALTER TABLE ONLY wo
114097     ADD CONSTRAINT wo_pkey PRIMARY KEY (wo_id);
114098
114099
114100 --
114101 -- TOC entry 7122 (class 2606 OID 146571589)
114102 -- Dependencies: 359 359 8894
114103 -- Name: womatl_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114104 --
114105
114106 ALTER TABLE ONLY womatl
114107     ADD CONSTRAINT womatl_pkey PRIMARY KEY (womatl_id);
114108
114109
114110 --
114111 -- TOC entry 7653 (class 2606 OID 146571591)
114112 -- Dependencies: 850 850 8894
114113 -- Name: womatlpost_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114114 --
114115
114116 ALTER TABLE ONLY womatlpost
114117     ADD CONSTRAINT womatlpost_pkey PRIMARY KEY (womatlpost_id);
114118
114119
114120 --
114121 -- TOC entry 7655 (class 2606 OID 146571593)
114122 -- Dependencies: 852 852 8894
114123 -- Name: womatlvar_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114124 --
114125
114126 ALTER TABLE ONLY womatlvar
114127     ADD CONSTRAINT womatlvar_pkey PRIMARY KEY (womatlvar_id);
114128
114129
114130 --
114131 -- TOC entry 7657 (class 2606 OID 146571595)
114132 -- Dependencies: 855 855 8894
114133 -- Name: xsltmap_name_key; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114134 --
114135
114136 ALTER TABLE ONLY xsltmap
114137     ADD CONSTRAINT xsltmap_name_key UNIQUE (xsltmap_name);
114138
114139
114140 --
114141 -- TOC entry 7659 (class 2606 OID 146571597)
114142 -- Dependencies: 855 855 8894
114143 -- Name: xsltmap_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114144 --
114145
114146 ALTER TABLE ONLY xsltmap
114147     ADD CONSTRAINT xsltmap_pkey PRIMARY KEY (xsltmap_id);
114148
114149
114150 --
114151 -- TOC entry 7661 (class 2606 OID 146571599)
114152 -- Dependencies: 857 857 8894
114153 -- Name: yearperiod_pkey; Type: CONSTRAINT; Schema: public; Owner: admin; Tablespace: 
114154 --
114155
114156 ALTER TABLE ONLY yearperiod
114157     ADD CONSTRAINT yearperiod_pkey PRIMARY KEY (yearperiod_id);
114158
114159
114160 SET search_path = te, pg_catalog;
114161
114162 --
114163 -- TOC entry 7663 (class 2606 OID 146571601)
114164 -- Dependencies: 859 859 8894
114165 -- Name: pkgcmd_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114166 --
114167
114168 ALTER TABLE ONLY pkgcmd
114169     ADD CONSTRAINT pkgcmd_pkey PRIMARY KEY (cmd_id);
114170
114171
114172 --
114173 -- TOC entry 7665 (class 2606 OID 146571603)
114174 -- Dependencies: 860 860 8894
114175 -- Name: pkgcmdarg_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114176 --
114177
114178 ALTER TABLE ONLY pkgcmdarg
114179     ADD CONSTRAINT pkgcmdarg_pkey PRIMARY KEY (cmdarg_id);
114180
114181
114182 --
114183 -- TOC entry 7667 (class 2606 OID 146571605)
114184 -- Dependencies: 861 861 8894
114185 -- Name: pkgimage_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114186 --
114187
114188 ALTER TABLE ONLY pkgimage
114189     ADD CONSTRAINT pkgimage_pkey PRIMARY KEY (image_id);
114190
114191
114192 --
114193 -- TOC entry 7669 (class 2606 OID 146571607)
114194 -- Dependencies: 862 862 8894
114195 -- Name: pkgmetasql_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114196 --
114197
114198 ALTER TABLE ONLY pkgmetasql
114199     ADD CONSTRAINT pkgmetasql_pkey PRIMARY KEY (metasql_id);
114200
114201
114202 --
114203 -- TOC entry 7671 (class 2606 OID 146571609)
114204 -- Dependencies: 863 863 8894
114205 -- Name: pkgpriv_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114206 --
114207
114208 ALTER TABLE ONLY pkgpriv
114209     ADD CONSTRAINT pkgpriv_pkey PRIMARY KEY (priv_id);
114210
114211
114212 --
114213 -- TOC entry 7673 (class 2606 OID 146571611)
114214 -- Dependencies: 864 864 8894
114215 -- Name: pkgreport_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114216 --
114217
114218 ALTER TABLE ONLY pkgreport
114219     ADD CONSTRAINT pkgreport_pkey PRIMARY KEY (report_id);
114220
114221
114222 --
114223 -- TOC entry 7675 (class 2606 OID 146571613)
114224 -- Dependencies: 865 865 8894
114225 -- Name: pkgscript_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114226 --
114227
114228 ALTER TABLE ONLY pkgscript
114229     ADD CONSTRAINT pkgscript_pkey PRIMARY KEY (script_id);
114230
114231
114232 --
114233 -- TOC entry 7677 (class 2606 OID 146571615)
114234 -- Dependencies: 866 866 8894
114235 -- Name: pkguiform_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114236 --
114237
114238 ALTER TABLE ONLY pkguiform
114239     ADD CONSTRAINT pkguiform_pkey PRIMARY KEY (uiform_id);
114240
114241
114242 --
114243 -- TOC entry 7679 (class 2606 OID 146571617)
114244 -- Dependencies: 867 867 8894
114245 -- Name: tecustrate_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114246 --
114247
114248 ALTER TABLE ONLY tecustrate
114249     ADD CONSTRAINT tecustrate_pkey PRIMARY KEY (tecustrate_cust_id);
114250
114251
114252 --
114253 -- TOC entry 7681 (class 2606 OID 146571619)
114254 -- Dependencies: 871 871 8894
114255 -- Name: teexp_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114256 --
114257
114258 ALTER TABLE ONLY teexp
114259     ADD CONSTRAINT teexp_pkey PRIMARY KEY (teexp_id);
114260
114261
114262 --
114263 -- TOC entry 7683 (class 2606 OID 146571621)
114264 -- Dependencies: 873 873 8894
114265 -- Name: tehead_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114266 --
114267
114268 ALTER TABLE ONLY tehead
114269     ADD CONSTRAINT tehead_pkey PRIMARY KEY (tehead_id);
114270
114271
114272 --
114273 -- TOC entry 7685 (class 2606 OID 146571623)
114274 -- Dependencies: 875 875 8894
114275 -- Name: teitem_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114276 --
114277
114278 ALTER TABLE ONLY teitem
114279     ADD CONSTRAINT teitem_pkey PRIMARY KEY (teitem_id);
114280
114281
114282 --
114283 -- TOC entry 7688 (class 2606 OID 146571625)
114284 -- Dependencies: 877 877 8894
114285 -- Name: teprj_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114286 --
114287
114288 ALTER TABLE ONLY teprj
114289     ADD CONSTRAINT teprj_pkey PRIMARY KEY (teprj_id);
114290
114291
114292 --
114293 -- TOC entry 7690 (class 2606 OID 146571627)
114294 -- Dependencies: 879 879 8894
114295 -- Name: teprjtask_pkey; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114296 --
114297
114298 ALTER TABLE ONLY teprjtask
114299     ADD CONSTRAINT teprjtask_pkey PRIMARY KEY (teprjtask_id);
114300
114301
114302 --
114303 -- TOC entry 7692 (class 2606 OID 146571629)
114304 -- Dependencies: 879 879 8894
114305 -- Name: teprjtask_teprjtask_prjtask_id_key; Type: CONSTRAINT; Schema: te; Owner: admin; Tablespace: 
114306 --
114307
114308 ALTER TABLE ONLY teprjtask
114309     ADD CONSTRAINT teprjtask_teprjtask_prjtask_id_key UNIQUE (teprjtask_prjtask_id);
114310
114311
114312 SET search_path = xtdesktop, pg_catalog;
114313
114314 --
114315 -- TOC entry 7694 (class 2606 OID 146571631)
114316 -- Dependencies: 881 881 8894
114317 -- Name: pkgcmd_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114318 --
114319
114320 ALTER TABLE ONLY pkgcmd
114321     ADD CONSTRAINT pkgcmd_pkey PRIMARY KEY (cmd_id);
114322
114323
114324 --
114325 -- TOC entry 7696 (class 2606 OID 146571633)
114326 -- Dependencies: 882 882 8894
114327 -- Name: pkgcmdarg_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114328 --
114329
114330 ALTER TABLE ONLY pkgcmdarg
114331     ADD CONSTRAINT pkgcmdarg_pkey PRIMARY KEY (cmdarg_id);
114332
114333
114334 --
114335 -- TOC entry 7698 (class 2606 OID 146571635)
114336 -- Dependencies: 883 883 8894
114337 -- Name: pkgimage_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114338 --
114339
114340 ALTER TABLE ONLY pkgimage
114341     ADD CONSTRAINT pkgimage_pkey PRIMARY KEY (image_id);
114342
114343
114344 --
114345 -- TOC entry 7700 (class 2606 OID 146571637)
114346 -- Dependencies: 884 884 8894
114347 -- Name: pkgmetasql_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114348 --
114349
114350 ALTER TABLE ONLY pkgmetasql
114351     ADD CONSTRAINT pkgmetasql_pkey PRIMARY KEY (metasql_id);
114352
114353
114354 --
114355 -- TOC entry 7702 (class 2606 OID 146571639)
114356 -- Dependencies: 885 885 8894
114357 -- Name: pkgpriv_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114358 --
114359
114360 ALTER TABLE ONLY pkgpriv
114361     ADD CONSTRAINT pkgpriv_pkey PRIMARY KEY (priv_id);
114362
114363
114364 --
114365 -- TOC entry 7704 (class 2606 OID 146571641)
114366 -- Dependencies: 886 886 8894
114367 -- Name: pkgreport_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114368 --
114369
114370 ALTER TABLE ONLY pkgreport
114371     ADD CONSTRAINT pkgreport_pkey PRIMARY KEY (report_id);
114372
114373
114374 --
114375 -- TOC entry 7706 (class 2606 OID 146571643)
114376 -- Dependencies: 887 887 8894
114377 -- Name: pkgscript_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114378 --
114379
114380 ALTER TABLE ONLY pkgscript
114381     ADD CONSTRAINT pkgscript_pkey PRIMARY KEY (script_id);
114382
114383
114384 --
114385 -- TOC entry 7708 (class 2606 OID 146571645)
114386 -- Dependencies: 888 888 8894
114387 -- Name: pkguiform_pkey; Type: CONSTRAINT; Schema: xtdesktop; Owner: admin; Tablespace: 
114388 --
114389
114390 ALTER TABLE ONLY pkguiform
114391     ADD CONSTRAINT pkguiform_pkey PRIMARY KEY (uiform_id);
114392
114393
114394 SET search_path = public, pg_catalog;
114395
114396 --
114397 -- TOC entry 6956 (class 1259 OID 146571646)
114398 -- Dependencies: 262 262 262 262 8894
114399 -- Name: accnt_unique_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114400 --
114401
114402 CREATE UNIQUE INDEX accnt_unique_idx ON accnt USING btree (accnt_number, accnt_profit, accnt_sub, accnt_company);
114403
114404
114405 --
114406 -- TOC entry 6826 (class 1259 OID 146571647)
114407 -- Dependencies: 207 8894
114408 -- Name: apopen_apopen_open_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114409 --
114410
114411 CREATE INDEX apopen_apopen_open_idx ON apopen USING btree (apopen_open);
114412
114413
114414 --
114415 -- TOC entry 6827 (class 1259 OID 146571648)
114416 -- Dependencies: 207 8894
114417 -- Name: apopen_apopen_vend_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114418 --
114419
114420 CREATE INDEX apopen_apopen_vend_id_idx ON apopen USING btree (apopen_vend_id);
114421
114422
114423 --
114424 -- TOC entry 7215 (class 1259 OID 146571649)
114425 -- Dependencies: 439 8894
114426 -- Name: apselect_apselect_apopen_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114427 --
114428
114429 CREATE INDEX apselect_apselect_apopen_id_idx ON apselect USING btree (apselect_apopen_id);
114430
114431
114432 --
114433 -- TOC entry 7222 (class 1259 OID 146571650)
114434 -- Dependencies: 443 8894
114435 -- Name: arapply_arapply_target_docnumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114436 --
114437
114438 CREATE INDEX arapply_arapply_target_docnumber_idx ON arapply USING btree (arapply_target_docnumber);
114439
114440
114441 --
114442 -- TOC entry 6845 (class 1259 OID 146571651)
114443 -- Dependencies: 212 8894
114444 -- Name: aropen_aropen_cust_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114445 --
114446
114447 CREATE INDEX aropen_aropen_cust_id_idx ON aropen USING btree (aropen_cust_id);
114448
114449
114450 --
114451 -- TOC entry 6846 (class 1259 OID 146571652)
114452 -- Dependencies: 212 8894
114453 -- Name: aropen_aropen_docnumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114454 --
114455
114456 CREATE INDEX aropen_aropen_docnumber_idx ON aropen USING btree (aropen_docnumber);
114457
114458
114459 --
114460 -- TOC entry 6847 (class 1259 OID 146571653)
114461 -- Dependencies: 212 8894
114462 -- Name: aropen_aropen_doctype_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114463 --
114464
114465 CREATE INDEX aropen_aropen_doctype_idx ON aropen USING btree (aropen_doctype);
114466
114467
114468 --
114469 -- TOC entry 6848 (class 1259 OID 146571654)
114470 -- Dependencies: 212 8894
114471 -- Name: aropen_aropen_open_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114472 --
114473
114474 CREATE INDEX aropen_aropen_open_idx ON aropen USING btree (aropen_open);
114475
114476
114477 --
114478 -- TOC entry 6851 (class 1259 OID 146571655)
114479 -- Dependencies: 212 8894
114480 -- Name: aropen_posted_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114481 --
114482
114483 CREATE INDEX aropen_posted_idx ON aropen USING btree (aropen_posted);
114484
114485
114486 --
114487 -- TOC entry 7135 (class 1259 OID 146571656)
114488 -- Dependencies: 374 8894
114489 -- Name: aropenalloc_aropen_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114490 --
114491
114492 CREATE INDEX aropenalloc_aropen_id_idx ON aropenalloc USING btree (aropenalloc_aropen_id);
114493
114494
114495 --
114496 -- TOC entry 7136 (class 1259 OID 146571657)
114497 -- Dependencies: 374 8894
114498 -- Name: aropenalloc_doc_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114499 --
114500
114501 CREATE INDEX aropenalloc_doc_id_idx ON aropenalloc USING btree (aropenalloc_doc_id);
114502
114503
114504 --
114505 -- TOC entry 6806 (class 1259 OID 146571658)
114506 -- Dependencies: 203 8894
114507 -- Name: bomitem_bomitem_item_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114508 --
114509
114510 CREATE INDEX bomitem_bomitem_item_id_idx ON bomitem USING btree (bomitem_item_id);
114511
114512
114513 --
114514 -- TOC entry 6807 (class 1259 OID 146571659)
114515 -- Dependencies: 203 8894
114516 -- Name: bomitem_effective_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114517 --
114518
114519 CREATE INDEX bomitem_effective_key ON bomitem USING btree (bomitem_effective);
114520
114521
114522 --
114523 -- TOC entry 6808 (class 1259 OID 146571660)
114524 -- Dependencies: 203 8894
114525 -- Name: bomitem_expires_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114526 --
114527
114528 CREATE INDEX bomitem_expires_key ON bomitem USING btree (bomitem_expires);
114529
114530
114531 --
114532 -- TOC entry 6809 (class 1259 OID 146571661)
114533 -- Dependencies: 203 8894
114534 -- Name: bomitem_parent_item_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114535 --
114536
114537 CREATE INDEX bomitem_parent_item_id ON bomitem USING btree (bomitem_parent_item_id);
114538
114539
114540 --
114541 -- TOC entry 7247 (class 1259 OID 146571662)
114542 -- Dependencies: 468 8894
114543 -- Name: bomitemcost_bomitem_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114544 --
114545
114546 CREATE INDEX bomitemcost_bomitem_id_key ON bomitemcost USING btree (bomitemcost_bomitem_id);
114547
114548
114549 --
114550 -- TOC entry 7248 (class 1259 OID 146571663)
114551 -- Dependencies: 468 468 468 8894
114552 -- Name: bomitemcost_master_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114553 --
114554
114555 CREATE UNIQUE INDEX bomitemcost_master_idx ON bomitemcost USING btree (bomitemcost_bomitem_id, bomitemcost_costelem_id, bomitemcost_lowlevel);
114556
114557
114558 --
114559 -- TOC entry 6969 (class 1259 OID 146571664)
114560 -- Dependencies: 269 8894
114561 -- Name: cashrcptitem_aropen_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114562 --
114563
114564 CREATE INDEX cashrcptitem_aropen_idx ON cashrcptitem USING btree (cashrcptitem_aropen_id);
114565
114566
114567 --
114568 -- TOC entry 6970 (class 1259 OID 146571665)
114569 -- Dependencies: 269 8894
114570 -- Name: cashrcptitem_cashrcpt_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114571 --
114572
114573 CREATE INDEX cashrcptitem_cashrcpt_idx ON cashrcptitem USING btree (cashrcptitem_cashrcpt_id);
114574
114575
114576 --
114577 -- TOC entry 6975 (class 1259 OID 146571666)
114578 -- Dependencies: 278 8894
114579 -- Name: ccard_cust_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114580 --
114581
114582 CREATE INDEX ccard_cust_id_idx ON ccard USING btree (ccard_cust_id);
114583
114584
114585 --
114586 -- TOC entry 7255 (class 1259 OID 146571667)
114587 -- Dependencies: 482 8894
114588 -- Name: ccardaud_ccard_cust_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114589 --
114590
114591 CREATE INDEX ccardaud_ccard_cust_id_idx ON ccardaud USING btree (ccardaud_ccard_cust_id_new);
114592
114593
114594 --
114595 -- TOC entry 7256 (class 1259 OID 146571668)
114596 -- Dependencies: 482 8894
114597 -- Name: ccardaud_ccard_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114598 --
114599
114600 CREATE INDEX ccardaud_ccard_id_idx ON ccardaud USING btree (ccardaud_ccard_id);
114601
114602
114603 --
114604 -- TOC entry 7263 (class 1259 OID 146571669)
114605 -- Dependencies: 486 8894
114606 -- Name: ccpay_ccard_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114607 --
114608
114609 CREATE INDEX ccpay_ccard_id_idx ON ccpay USING btree (ccpay_ccard_id);
114610
114611
114612 --
114613 -- TOC entry 7264 (class 1259 OID 146571670)
114614 -- Dependencies: 486 8894
114615 -- Name: ccpay_cust_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114616 --
114617
114618 CREATE INDEX ccpay_cust_id_idx ON ccpay USING btree (ccpay_cust_id);
114619
114620
114621 --
114622 -- TOC entry 7265 (class 1259 OID 146571671)
114623 -- Dependencies: 486 8894
114624 -- Name: ccpay_order_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114625 --
114626
114627 CREATE INDEX ccpay_order_number_idx ON ccpay USING btree (ccpay_order_number);
114628
114629
114630 --
114631 -- TOC entry 6928 (class 1259 OID 146571672)
114632 -- Dependencies: 237 237 8894
114633 -- Name: charass_target_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114634 --
114635
114636 CREATE INDEX charass_target_idx ON charass USING btree (charass_target_type, charass_target_id);
114637
114638
114639 --
114640 -- TOC entry 7206 (class 1259 OID 146571673)
114641 -- Dependencies: 430 8894
114642 -- Name: checkhead_posted_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114643 --
114644
114645 CREATE INDEX checkhead_posted_idx ON checkhead USING btree (checkhead_posted);
114646
114647
114648 --
114649 -- TOC entry 7207 (class 1259 OID 146571674)
114650 -- Dependencies: 430 8894
114651 -- Name: checkhead_replaced_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114652 --
114653
114654 CREATE INDEX checkhead_replaced_idx ON checkhead USING btree (checkhead_replaced);
114655
114656
114657 --
114658 -- TOC entry 7208 (class 1259 OID 146571675)
114659 -- Dependencies: 432 8894
114660 -- Name: checkitem_apopenitem_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114661 --
114662
114663 CREATE INDEX checkitem_apopenitem_id_idx ON checkitem USING btree (checkitem_apopen_id);
114664
114665
114666 --
114667 -- TOC entry 6871 (class 1259 OID 146571676)
114668 -- Dependencies: 218 8894
114669 -- Name: cmhead_invcnumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114670 --
114671
114672 CREATE INDEX cmhead_invcnumber_idx ON cmhead USING btree (cmhead_invcnumber);
114673
114674
114675 --
114676 -- TOC entry 6814 (class 1259 OID 146571677)
114677 -- Dependencies: 204 8894
114678 -- Name: cntct_email_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114679 --
114680
114681 CREATE INDEX cntct_email_idx ON cntct USING btree (cntct_email);
114682
114683
114684 --
114685 -- TOC entry 6815 (class 1259 OID 146571678)
114686 -- Dependencies: 204 8894
114687 -- Name: cntct_name_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114688 --
114689
114690 CREATE INDEX cntct_name_idx ON cntct USING btree (cntct_name);
114691
114692
114693 --
114694 -- TOC entry 7286 (class 1259 OID 146571679)
114695 -- Dependencies: 513 8894
114696 -- Name: cobill_cobmisc_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114697 --
114698
114699 CREATE INDEX cobill_cobmisc_id ON cobill USING btree (cobill_cobmisc_id);
114700
114701
114702 --
114703 -- TOC entry 7287 (class 1259 OID 146571680)
114704 -- Dependencies: 513 8894
114705 -- Name: cobill_coitem_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114706 --
114707
114708 CREATE INDEX cobill_coitem_id ON cobill USING btree (cobill_coitem_id);
114709
114710
114711 --
114712 -- TOC entry 7292 (class 1259 OID 146571681)
114713 -- Dependencies: 516 8894
114714 -- Name: cobmisc_cohead_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114715 --
114716
114717 CREATE INDEX cobmisc_cohead_id ON cobmisc USING btree (cobmisc_cohead_id);
114718
114719
114720 --
114721 -- TOC entry 7295 (class 1259 OID 146571682)
114722 -- Dependencies: 516 8894
114723 -- Name: cobmisc_posted; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114724 --
114725
114726 CREATE INDEX cobmisc_posted ON cobmisc USING btree (cobmisc_posted);
114727
114728
114729 --
114730 -- TOC entry 6769 (class 1259 OID 146571683)
114731 -- Dependencies: 195 8894
114732 -- Name: cohead_cohead_status_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114733 --
114734
114735 CREATE INDEX cohead_cohead_status_idx ON cohead USING btree (cohead_status);
114736
114737
114738 --
114739 -- TOC entry 6770 (class 1259 OID 146571684)
114740 -- Dependencies: 195 8894
114741 -- Name: cohead_cust_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114742 --
114743
114744 CREATE INDEX cohead_cust_id_key ON cohead USING btree (cohead_cust_id);
114745
114746
114747 --
114748 -- TOC entry 6771 (class 1259 OID 146571685)
114749 -- Dependencies: 195 8894
114750 -- Name: cohead_custponumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114751 --
114752
114753 CREATE INDEX cohead_custponumber_idx ON cohead USING btree (cohead_custponumber);
114754
114755
114756 --
114757 -- TOC entry 6772 (class 1259 OID 146571686)
114758 -- Dependencies: 195 8894
114759 -- Name: cohead_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114760 --
114761
114762 CREATE UNIQUE INDEX cohead_number_idx ON cohead USING btree (cohead_number);
114763
114764
114765 --
114766 -- TOC entry 6775 (class 1259 OID 146571687)
114767 -- Dependencies: 195 8894
114768 -- Name: cohead_shipto_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114769 --
114770
114771 CREATE INDEX cohead_shipto_id ON cohead USING btree (cohead_shipto_id);
114772
114773
114774 --
114775 -- TOC entry 7139 (class 1259 OID 146571688)
114776 -- Dependencies: 376 8894
114777 -- Name: cohist_cust_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114778 --
114779
114780 CREATE INDEX cohist_cust_id ON cohist USING btree (cohist_cust_id);
114781
114782
114783 --
114784 -- TOC entry 7140 (class 1259 OID 146571689)
114785 -- Dependencies: 376 8894
114786 -- Name: cohist_invcnumber; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114787 --
114788
114789 CREATE INDEX cohist_invcnumber ON cohist USING btree (cohist_invcnumber);
114790
114791
114792 --
114793 -- TOC entry 7141 (class 1259 OID 146571690)
114794 -- Dependencies: 376 8894
114795 -- Name: cohist_itemsite_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114796 --
114797
114798 CREATE INDEX cohist_itemsite_id ON cohist USING btree (cohist_itemsite_id);
114799
114800
114801 --
114802 -- TOC entry 7144 (class 1259 OID 146571691)
114803 -- Dependencies: 376 8894
114804 -- Name: cohist_shipdate; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114805 --
114806
114807 CREATE INDEX cohist_shipdate ON cohist USING btree (cohist_shipdate);
114808
114809
114810 --
114811 -- TOC entry 7145 (class 1259 OID 146571692)
114812 -- Dependencies: 376 8894
114813 -- Name: cohist_shipto_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114814 --
114815
114816 CREATE INDEX cohist_shipto_id ON cohist USING btree (cohist_shipto_id);
114817
114818
114819 --
114820 -- TOC entry 6776 (class 1259 OID 146571693)
114821 -- Dependencies: 196 8894
114822 -- Name: coitem_cohead_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114823 --
114824
114825 CREATE INDEX coitem_cohead_id_key ON coitem USING btree (coitem_cohead_id);
114826
114827
114828 --
114829 -- TOC entry 6777 (class 1259 OID 146571694)
114830 -- Dependencies: 196 196 196 8894
114831 -- Name: coitem_coitem_cohead_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114832 --
114833
114834 CREATE UNIQUE INDEX coitem_coitem_cohead_id_key ON coitem USING btree (coitem_cohead_id, coitem_linenumber, coitem_subnumber);
114835
114836
114837 --
114838 -- TOC entry 6778 (class 1259 OID 146571695)
114839 -- Dependencies: 196 8894
114840 -- Name: coitem_itemsite_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114841 --
114842
114843 CREATE INDEX coitem_itemsite_id ON coitem USING btree (coitem_itemsite_id);
114844
114845
114846 --
114847 -- TOC entry 6779 (class 1259 OID 146571696)
114848 -- Dependencies: 196 8894
114849 -- Name: coitem_linenumber_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114850 --
114851
114852 CREATE INDEX coitem_linenumber_key ON coitem USING btree (coitem_linenumber);
114853
114854
114855 --
114856 -- TOC entry 6782 (class 1259 OID 146571697)
114857 -- Dependencies: 196 8894
114858 -- Name: coitem_status_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114859 --
114860
114861 CREATE INDEX coitem_status_key ON coitem USING btree (coitem_status);
114862
114863
114864 --
114865 -- TOC entry 6933 (class 1259 OID 146571698)
114866 -- Dependencies: 240 240 8894
114867 -- Name: comment_comment_source_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114868 --
114869
114870 CREATE INDEX comment_comment_source_idx ON comment USING btree (comment_source, comment_source_id);
114871
114872
114873 --
114874 -- TOC entry 7063 (class 1259 OID 146571699)
114875 -- Dependencies: 329 329 8894
114876 -- Name: contrct_master_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114877 --
114878
114879 CREATE UNIQUE INDEX contrct_master_idx ON contrct USING btree (contrct_number, contrct_vend_id);
114880
114881
114882 --
114883 -- TOC entry 6852 (class 1259 OID 146571700)
114884 -- Dependencies: 213 8894
114885 -- Name: cust_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114886 --
114887
114888 CREATE UNIQUE INDEX cust_number_idx ON custinfo USING btree (cust_number);
114889
114890
114891 --
114892 -- TOC entry 7354 (class 1259 OID 146571701)
114893 -- Dependencies: 567 8894
114894 -- Name: evntlog_dispatched_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114895 --
114896
114897 CREATE INDEX evntlog_dispatched_idx ON evntlog USING btree (evntlog_dispatched);
114898
114899
114900 --
114901 -- TOC entry 7355 (class 1259 OID 146571702)
114902 -- Dependencies: 567 8894
114903 -- Name: evntlog_evntlog_username_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114904 --
114905
114906 CREATE INDEX evntlog_evntlog_username_idx ON evntlog USING btree (evntlog_username);
114907
114908
114909 --
114910 -- TOC entry 7358 (class 1259 OID 146571703)
114911 -- Dependencies: 569 8894
114912 -- Name: evntnot_evnttype_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114913 --
114914
114915 CREATE INDEX evntnot_evnttype_id_idx ON evntnot USING btree (evntnot_evnttype_id);
114916
114917
114918 --
114919 -- TOC entry 7361 (class 1259 OID 146571704)
114920 -- Dependencies: 569 8894
114921 -- Name: evntnot_warehous_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114922 --
114923
114924 CREATE INDEX evntnot_warehous_id_idx ON evntnot USING btree (evntnot_warehous_id);
114925
114926
114927 --
114928 -- TOC entry 7366 (class 1259 OID 146571705)
114929 -- Dependencies: 575 575 575 8894
114930 -- Name: filter_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114931 --
114932
114933 CREATE INDEX filter_idx ON filter USING btree (filter_screen, filter_username, filter_name);
114934
114935
114936 --
114937 -- TOC entry 7086 (class 1259 OID 146571706)
114938 -- Dependencies: 340 8894
114939 -- Name: gltrans_gltrans_accnt_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114940 --
114941
114942 CREATE INDEX gltrans_gltrans_accnt_id_idx ON gltrans USING btree (gltrans_accnt_id);
114943
114944
114945 --
114946 -- TOC entry 7087 (class 1259 OID 146571707)
114947 -- Dependencies: 340 8894
114948 -- Name: gltrans_gltrans_date_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114949 --
114950
114951 CREATE INDEX gltrans_gltrans_date_idx ON gltrans USING btree (gltrans_date);
114952
114953
114954 --
114955 -- TOC entry 7088 (class 1259 OID 146571708)
114956 -- Dependencies: 340 8894
114957 -- Name: gltrans_gltrans_journalnumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114958 --
114959
114960 CREATE INDEX gltrans_gltrans_journalnumber_idx ON gltrans USING btree (gltrans_journalnumber);
114961
114962
114963 --
114964 -- TOC entry 7091 (class 1259 OID 146571709)
114965 -- Dependencies: 340 8894
114966 -- Name: gltrans_sequence_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114967 --
114968
114969 CREATE INDEX gltrans_sequence_idx ON gltrans USING btree (gltrans_sequence);
114970
114971
114972 --
114973 -- TOC entry 6886 (class 1259 OID 146571710)
114974 -- Dependencies: 224 8894
114975 -- Name: invchead_invchead_ordernumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114976 --
114977
114978 CREATE INDEX invchead_invchead_ordernumber_idx ON invchead USING btree (invchead_ordernumber);
114979
114980
114981 --
114982 -- TOC entry 6903 (class 1259 OID 146571711)
114983 -- Dependencies: 229 8894
114984 -- Name: invcitem_invcitem_invchead_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114985 --
114986
114987 CREATE INDEX invcitem_invcitem_invchead_id_idx ON invcitem USING btree (invcitem_invchead_id);
114988
114989
114990 --
114991 -- TOC entry 6904 (class 1259 OID 146571712)
114992 -- Dependencies: 229 229 8894
114993 -- Name: invcitem_invcitem_itemsite_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
114994 --
114995
114996 CREATE INDEX invcitem_invcitem_itemsite_id_idx ON invcitem USING btree (invcitem_item_id, invcitem_warehous_id);
114997
114998
114999 --
115000 -- TOC entry 7409 (class 1259 OID 146571713)
115001 -- Dependencies: 619 8894
115002 -- Name: invcitemtax_taxhist_parent_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115003 --
115004
115005 CREATE INDEX invcitemtax_taxhist_parent_id_idx ON invcitemtax USING btree (taxhist_parent_id);
115006
115007
115008 --
115009 -- TOC entry 7410 (class 1259 OID 146571714)
115010 -- Dependencies: 621 8894
115011 -- Name: invdetail_invdetail_invcitem_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115012 --
115013
115014 CREATE INDEX invdetail_invdetail_invcitem_id_idx ON invdetail USING btree (invdetail_invcitem_id);
115015
115016
115017 --
115018 -- TOC entry 7411 (class 1259 OID 146571715)
115019 -- Dependencies: 621 8894
115020 -- Name: invdetail_invdetail_invhist_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115021 --
115022
115023 CREATE INDEX invdetail_invdetail_invhist_id_idx ON invdetail USING btree (invdetail_invhist_id);
115024
115025
115026 --
115027 -- TOC entry 7414 (class 1259 OID 146571716)
115028 -- Dependencies: 623 8894
115029 -- Name: invhist_hasdetail; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115030 --
115031
115032 CREATE INDEX invhist_hasdetail ON invhist USING btree (invhist_hasdetail);
115033
115034
115035 --
115036 -- TOC entry 7415 (class 1259 OID 146571717)
115037 -- Dependencies: 623 8894
115038 -- Name: invhist_invhist_ordnumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115039 --
115040
115041 CREATE INDEX invhist_invhist_ordnumber_idx ON invhist USING btree (invhist_ordnumber);
115042
115043
115044 --
115045 -- TOC entry 7416 (class 1259 OID 146571718)
115046 -- Dependencies: 623 8894
115047 -- Name: invhist_itemsite_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115048 --
115049
115050 CREATE INDEX invhist_itemsite_id ON invhist USING btree (invhist_itemsite_id);
115051
115052
115053 --
115054 -- TOC entry 7419 (class 1259 OID 146571719)
115055 -- Dependencies: 623 8894
115056 -- Name: invhist_series; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115057 --
115058
115059 CREATE INDEX invhist_series ON invhist USING btree (invhist_series);
115060
115061
115062 --
115063 -- TOC entry 7420 (class 1259 OID 146571720)
115064 -- Dependencies: 623 8894
115065 -- Name: invhist_transdate; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115066 --
115067
115068 CREATE INDEX invhist_transdate ON invhist USING btree (invhist_transdate);
115069
115070
115071 --
115072 -- TOC entry 7421 (class 1259 OID 146571721)
115073 -- Dependencies: 623 8894
115074 -- Name: invhist_transtype; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115075 --
115076
115077 CREATE INDEX invhist_transtype ON invhist USING btree (invhist_transtype);
115078
115079
115080 --
115081 -- TOC entry 7101 (class 1259 OID 146571722)
115082 -- Dependencies: 349 8894
115083 -- Name: ipsitem_ipshead_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115084 --
115085
115086 CREATE INDEX ipsitem_ipshead_id_idx ON ipsiteminfo USING btree (ipsitem_ipshead_id);
115087
115088
115089 --
115090 -- TOC entry 6747 (class 1259 OID 146571723)
115091 -- Dependencies: 191 8894
115092 -- Name: item_classcode_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115093 --
115094
115095 CREATE INDEX item_classcode_id ON item USING btree (item_classcode_id);
115096
115097
115098 --
115099 -- TOC entry 6750 (class 1259 OID 146571724)
115100 -- Dependencies: 191 8894
115101 -- Name: item_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115102 --
115103
115104 CREATE UNIQUE INDEX item_number_idx ON item USING btree (item_number);
115105
115106
115107 --
115108 -- TOC entry 6753 (class 1259 OID 146571725)
115109 -- Dependencies: 191 8894
115110 -- Name: item_prodcat_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115111 --
115112
115113 CREATE INDEX item_prodcat_id_idx ON item USING btree (item_prodcat_id);
115114
115115
115116 --
115117 -- TOC entry 6754 (class 1259 OID 146571726)
115118 -- Dependencies: 191 8894
115119 -- Name: item_upccode_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115120 --
115121
115122 CREATE INDEX item_upccode_idx ON item USING btree (item_upccode);
115123
115124
115125 --
115126 -- TOC entry 7051 (class 1259 OID 146571727)
115127 -- Dependencies: 321 8894
115128 -- Name: itemcost_item_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115129 --
115130
115131 CREATE INDEX itemcost_item_id_key ON itemcost USING btree (itemcost_item_id);
115132
115133
115134 --
115135 -- TOC entry 7052 (class 1259 OID 146571728)
115136 -- Dependencies: 321 321 321 8894
115137 -- Name: itemcost_master_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115138 --
115139
115140 CREATE UNIQUE INDEX itemcost_master_idx ON itemcost USING btree (itemcost_item_id, itemcost_costelem_id, itemcost_lowlevel);
115141
115142
115143 --
115144 -- TOC entry 7436 (class 1259 OID 146571729)
115145 -- Dependencies: 649 8894
115146 -- Name: itemloc_itemsite_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115147 --
115148
115149 CREATE INDEX itemloc_itemsite_idx ON itemloc USING btree (itemloc_itemsite_id);
115150
115151
115152 --
115153 -- TOC entry 7437 (class 1259 OID 146571730)
115154 -- Dependencies: 649 8894
115155 -- Name: itemloc_location_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115156 --
115157
115158 CREATE INDEX itemloc_location_idx ON itemloc USING btree (itemloc_location_id);
115159
115160
115161 --
115162 -- TOC entry 6755 (class 1259 OID 146571731)
115163 -- Dependencies: 192 8894
115164 -- Name: itemsite_active_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115165 --
115166
115167 CREATE INDEX itemsite_active_key ON itemsite USING btree (itemsite_active);
115168
115169
115170 --
115171 -- TOC entry 6756 (class 1259 OID 146571732)
115172 -- Dependencies: 192 8894
115173 -- Name: itemsite_item_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115174 --
115175
115176 CREATE INDEX itemsite_item_id_key ON itemsite USING btree (itemsite_item_id);
115177
115178
115179 --
115180 -- TOC entry 6757 (class 1259 OID 146571733)
115181 -- Dependencies: 192 192 8894
115182 -- Name: itemsite_item_warehous_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115183 --
115184
115185 CREATE UNIQUE INDEX itemsite_item_warehous_id_key ON itemsite USING btree (itemsite_item_id, itemsite_warehous_id);
115186
115187
115188 --
115189 -- TOC entry 6760 (class 1259 OID 146571734)
115190 -- Dependencies: 192 8894
115191 -- Name: itemsite_plancode_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115192 --
115193
115194 CREATE INDEX itemsite_plancode_id_key ON itemsite USING btree (itemsite_plancode_id);
115195
115196
115197 --
115198 -- TOC entry 6761 (class 1259 OID 146571735)
115199 -- Dependencies: 192 8894
115200 -- Name: itemsite_warehous_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115201 --
115202
115203 CREATE INDEX itemsite_warehous_id_key ON itemsite USING btree (itemsite_warehous_id);
115204
115205
115206 --
115207 -- TOC entry 7070 (class 1259 OID 146571736)
115208 -- Dependencies: 330 8894
115209 -- Name: itemsrc_vend_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115210 --
115211
115212 CREATE INDEX itemsrc_vend_id_idx ON itemsrc USING btree (itemsrc_vend_id);
115213
115214
115215 --
115216 -- TOC entry 7071 (class 1259 OID 146571737)
115217 -- Dependencies: 332 8894
115218 -- Name: itemsrcp_itemsrc_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115219 --
115220
115221 CREATE INDEX itemsrcp_itemsrc_id_key ON itemsrcp USING btree (itemsrcp_itemsrc_id);
115222
115223
115224 --
115225 -- TOC entry 7078 (class 1259 OID 146571738)
115226 -- Dependencies: 334 8894
115227 -- Name: itemsub_parent_item_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115228 --
115229
115230 CREATE INDEX itemsub_parent_item_id_key ON itemsub USING btree (itemsub_parent_item_id);
115231
115232
115233 --
115234 -- TOC entry 7081 (class 1259 OID 146571739)
115235 -- Dependencies: 334 8894
115236 -- Name: itemsub_sub_item_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115237 --
115238
115239 CREATE INDEX itemsub_sub_item_id_key ON itemsub USING btree (itemsub_sub_item_id);
115240
115241
115242 --
115243 -- TOC entry 7094 (class 1259 OID 146571740)
115244 -- Dependencies: 342 8894
115245 -- Name: location_warehous_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115246 --
115247
115248 CREATE INDEX location_warehous_idx ON location USING btree (location_warehous_id);
115249
115250
115251 --
115252 -- TOC entry 7502 (class 1259 OID 146571741)
115253 -- Dependencies: 708 8894
115254 -- Name: payaropen_aropen_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115255 --
115256
115257 CREATE INDEX payaropen_aropen_id_idx ON payaropen USING btree (payaropen_aropen_id);
115258
115259
115260 --
115261 -- TOC entry 7503 (class 1259 OID 146571742)
115262 -- Dependencies: 708 8894
115263 -- Name: payaropen_ccpay_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115264 --
115265
115266 CREATE INDEX payaropen_ccpay_id_idx ON payaropen USING btree (payaropen_ccpay_id);
115267
115268
115269 --
115270 -- TOC entry 7506 (class 1259 OID 146571743)
115271 -- Dependencies: 709 8894
115272 -- Name: payco_ccpay_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115273 --
115274
115275 CREATE INDEX payco_ccpay_id_idx ON payco USING btree (payco_ccpay_id);
115276
115277
115278 --
115279 -- TOC entry 7507 (class 1259 OID 146571744)
115280 -- Dependencies: 709 8894
115281 -- Name: payco_cohead_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115282 --
115283
115284 CREATE INDEX payco_cohead_id_idx ON payco USING btree (payco_cohead_id);
115285
115286
115287 --
115288 -- TOC entry 6787 (class 1259 OID 146571745)
115289 -- Dependencies: 197 8894
115290 -- Name: pohead_pohead_status_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115291 --
115292
115293 CREATE INDEX pohead_pohead_status_idx ON pohead USING btree (pohead_status);
115294
115295
115296 --
115297 -- TOC entry 6788 (class 1259 OID 146571746)
115298 -- Dependencies: 198 8894
115299 -- Name: poitem_itemsite_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115300 --
115301
115302 CREATE INDEX poitem_itemsite_id_key ON poitem USING btree (poitem_itemsite_id);
115303
115304
115305 --
115306 -- TOC entry 6789 (class 1259 OID 146571747)
115307 -- Dependencies: 198 198 198 8894
115308 -- Name: poitem_itemsite_status_duedate_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115309 --
115310
115311 CREATE INDEX poitem_itemsite_status_duedate_key ON poitem USING btree (poitem_itemsite_id, poitem_status, poitem_duedate);
115312
115313
115314 --
115315 -- TOC entry 6792 (class 1259 OID 146571748)
115316 -- Dependencies: 198 8894
115317 -- Name: poitem_pohead_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115318 --
115319
115320 CREATE INDEX poitem_pohead_id_key ON poitem USING btree (poitem_pohead_id);
115321
115322
115323 --
115324 -- TOC entry 6795 (class 1259 OID 146571749)
115325 -- Dependencies: 198 8894
115326 -- Name: poitem_status_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115327 --
115328
115329 CREATE INDEX poitem_status_key ON poitem USING btree (poitem_status);
115330
115331
115332 --
115333 -- TOC entry 7178 (class 1259 OID 146571750)
115334 -- Dependencies: 408 8894
115335 -- Name: priv_name_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115336 --
115337
115338 CREATE UNIQUE INDEX priv_name_idx ON priv USING btree (priv_name);
115339
115340
115341 --
115342 -- TOC entry 7134 (class 1259 OID 146571751)
115343 -- Dependencies: 370 8894
115344 -- Name: quitem_quhead_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115345 --
115346
115347 CREATE INDEX quitem_quhead_id_key ON quitem USING btree (quitem_quhead_id);
115348
115349
115350 --
115351 -- TOC entry 7518 (class 1259 OID 146571752)
115352 -- Dependencies: 721 721 8894
115353 -- Name: recv_ordertypeid_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115354 --
115355
115356 CREATE INDEX recv_ordertypeid_idx ON recv USING btree (recv_order_type, recv_orderitem_id);
115357
115358
115359 --
115360 -- TOC entry 7183 (class 1259 OID 146571753)
115361 -- Dependencies: 411 411 8894
115362 -- Name: report_name_grade_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115363 --
115364
115365 CREATE UNIQUE INDEX report_name_grade_idx ON report USING btree (report_name, report_grade);
115366
115367
115368 --
115369 -- TOC entry 7325 (class 1259 OID 146571754)
115370 -- Dependencies: 540 8894
115371 -- Name: salesaccnt_prodcat_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115372 --
115373
115374 CREATE INDEX salesaccnt_prodcat_id_idx ON salesaccnt USING btree (salesaccnt_prodcat_id);
115375
115376
115377 --
115378 -- TOC entry 7326 (class 1259 OID 146571755)
115379 -- Dependencies: 540 8894
115380 -- Name: salesaccnt_warehous_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115381 --
115382
115383 CREATE INDEX salesaccnt_warehous_id_idx ON salesaccnt USING btree (salesaccnt_warehous_id);
115384
115385
115386 --
115387 -- TOC entry 7006 (class 1259 OID 146571756)
115388 -- Dependencies: 297 8894
115389 -- Name: shipdata_cohead_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115390 --
115391
115392 CREATE INDEX shipdata_cohead_number_idx ON shipdata USING btree (shipdata_cohead_number);
115393
115394
115395 --
115396 -- TOC entry 7573 (class 1259 OID 146571757)
115397 -- Dependencies: 771 8894
115398 -- Name: shipdatasum_cohead_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115399 --
115400
115401 CREATE INDEX shipdatasum_cohead_number_idx ON shipdatasum USING btree (shipdatasum_cohead_number);
115402
115403
115404 --
115405 -- TOC entry 7574 (class 1259 OID 146571758)
115406 -- Dependencies: 771 8894
115407 -- Name: shipdatasum_cosmisc_tracknum_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115408 --
115409
115410 CREATE INDEX shipdatasum_cosmisc_tracknum_idx ON shipdatasum USING btree (shipdatasum_cosmisc_tracknum);
115411
115412
115413 --
115414 -- TOC entry 7302 (class 1259 OID 146571759)
115415 -- Dependencies: 526 8894
115416 -- Name: shiphead_order_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115417 --
115418
115419 CREATE INDEX shiphead_order_id_idx ON shiphead USING btree (shiphead_order_id);
115420
115421
115422 --
115423 -- TOC entry 7307 (class 1259 OID 146571760)
115424 -- Dependencies: 526 8894
115425 -- Name: shiphead_shipped_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115426 --
115427
115428 CREATE INDEX shiphead_shipped_idx ON shiphead USING btree (shiphead_shipped);
115429
115430
115431 --
115432 -- TOC entry 7308 (class 1259 OID 146571761)
115433 -- Dependencies: 527 8894
115434 -- Name: shipitem_invcitem_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115435 --
115436
115437 CREATE INDEX shipitem_invcitem_id_idx ON shipitem USING btree (shipitem_invcitem_id);
115438
115439
115440 --
115441 -- TOC entry 7309 (class 1259 OID 146571762)
115442 -- Dependencies: 527 8894
115443 -- Name: shipitem_orderitem_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115444 --
115445
115446 CREATE INDEX shipitem_orderitem_id_idx ON shipitem USING btree (shipitem_orderitem_id);
115447
115448
115449 --
115450 -- TOC entry 7312 (class 1259 OID 146571763)
115451 -- Dependencies: 527 8894
115452 -- Name: shipitem_shiphead_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115453 --
115454
115455 CREATE INDEX shipitem_shiphead_id_idx ON shipitem USING btree (shipitem_shiphead_id);
115456
115457
115458 --
115459 -- TOC entry 7579 (class 1259 OID 146571764)
115460 -- Dependencies: 781 8894
115461 -- Name: sltrans_sequence_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115462 --
115463
115464 CREATE INDEX sltrans_sequence_idx ON sltrans USING btree (sltrans_sequence);
115465
115466
115467 --
115468 -- TOC entry 7580 (class 1259 OID 146571765)
115469 -- Dependencies: 781 8894
115470 -- Name: sltrans_sltrans_accnt_id_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115471 --
115472
115473 CREATE INDEX sltrans_sltrans_accnt_id_idx ON sltrans USING btree (sltrans_accnt_id);
115474
115475
115476 --
115477 -- TOC entry 7581 (class 1259 OID 146571766)
115478 -- Dependencies: 781 8894
115479 -- Name: sltrans_sltrans_date_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115480 --
115481
115482 CREATE INDEX sltrans_sltrans_date_idx ON sltrans USING btree (sltrans_date);
115483
115484
115485 --
115486 -- TOC entry 7582 (class 1259 OID 146571767)
115487 -- Dependencies: 781 8894
115488 -- Name: sltrans_sltrans_journalnumber_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115489 --
115490
115491 CREATE INDEX sltrans_sltrans_journalnumber_idx ON sltrans USING btree (sltrans_journalnumber);
115492
115493
115494 --
115495 -- TOC entry 7611 (class 1259 OID 146571768)
115496 -- Dependencies: 801 8894
115497 -- Name: subaccnttype_code_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115498 --
115499
115500 CREATE UNIQUE INDEX subaccnttype_code_idx ON subaccnttype USING btree (subaccnttype_code);
115501
115502
115503 --
115504 -- TOC entry 6917 (class 1259 OID 146571769)
115505 -- Dependencies: 233 8894
115506 -- Name: todoitem_todoitem_username_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115507 --
115508
115509 CREATE INDEX todoitem_todoitem_username_idx ON todoitem USING btree (todoitem_username);
115510
115511
115512 --
115513 -- TOC entry 7624 (class 1259 OID 146571770)
115514 -- Dependencies: 817 817 8894
115515 -- Name: trialbal_accnt_period_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115516 --
115517
115518 CREATE UNIQUE INDEX trialbal_accnt_period_idx ON trialbal USING btree (trialbal_accnt_id, trialbal_period_id);
115519
115520
115521 --
115522 -- TOC entry 7635 (class 1259 OID 146571771)
115523 -- Dependencies: 825 8894
115524 -- Name: usrpref_userpref_name_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115525 --
115526
115527 CREATE INDEX usrpref_userpref_name_idx ON usrpref USING btree (usrpref_name);
115528
115529
115530 --
115531 -- TOC entry 6840 (class 1259 OID 146571772)
115532 -- Dependencies: 210 8894
115533 -- Name: vend_number_idx; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115534 --
115535
115536 CREATE UNIQUE INDEX vend_number_idx ON vendinfo USING btree (vend_number);
115537
115538
115539 --
115540 -- TOC entry 6762 (class 1259 OID 146571773)
115541 -- Dependencies: 193 8894
115542 -- Name: warehous_code_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115543 --
115544
115545 CREATE INDEX warehous_code_key ON whsinfo USING btree (warehous_code bpchar_ops);
115546
115547
115548 --
115549 -- TOC entry 7341 (class 1259 OID 146571774)
115550 -- Dependencies: 560 8894
115551 -- Name: wo_duedate; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115552 --
115553
115554 CREATE INDEX wo_duedate ON wo USING btree (wo_duedate);
115555
115556
115557 --
115558 -- TOC entry 7342 (class 1259 OID 146571775)
115559 -- Dependencies: 560 8894
115560 -- Name: wo_itemsite_id; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115561 --
115562
115563 CREATE INDEX wo_itemsite_id ON wo USING btree (wo_itemsite_id);
115564
115565
115566 --
115567 -- TOC entry 7343 (class 1259 OID 146571776)
115568 -- Dependencies: 560 8894
115569 -- Name: wo_ordtype; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115570 --
115571
115572 CREATE INDEX wo_ordtype ON wo USING btree (wo_ordtype);
115573
115574
115575 --
115576 -- TOC entry 7346 (class 1259 OID 146571777)
115577 -- Dependencies: 560 8894
115578 -- Name: wo_startdate; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115579 --
115580
115581 CREATE INDEX wo_startdate ON wo USING btree (wo_startdate);
115582
115583
115584 --
115585 -- TOC entry 7347 (class 1259 OID 146571778)
115586 -- Dependencies: 560 8894
115587 -- Name: wo_status; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115588 --
115589
115590 CREATE INDEX wo_status ON wo USING btree (wo_status);
115591
115592
115593 --
115594 -- TOC entry 7120 (class 1259 OID 146571779)
115595 -- Dependencies: 359 8894
115596 -- Name: womatl_itemsite_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115597 --
115598
115599 CREATE INDEX womatl_itemsite_id_key ON womatl USING btree (womatl_itemsite_id);
115600
115601
115602 --
115603 -- TOC entry 7123 (class 1259 OID 146571780)
115604 -- Dependencies: 359 8894
115605 -- Name: womatl_wo_id_key; Type: INDEX; Schema: public; Owner: admin; Tablespace: 
115606 --
115607
115608 CREATE INDEX womatl_wo_id_key ON womatl USING btree (womatl_wo_id);
115609
115610
115611 SET search_path = te, pg_catalog;
115612
115613 --
115614 -- TOC entry 7686 (class 1259 OID 146571781)
115615 -- Dependencies: 875 8894
115616 -- Name: teitem_teitem_tehead_id_idx; Type: INDEX; Schema: te; Owner: admin; Tablespace: 
115617 --
115618
115619 CREATE INDEX teitem_teitem_tehead_id_idx ON teitem USING btree (teitem_tehead_id);
115620
115621
115622 SET search_path = api, pg_catalog;
115623
115624 --
115625 -- TOC entry 8597 (class 2618 OID 146571782)
115626 -- Dependencies: 201 201 201 196 196 196 1672 201 8894
115627 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115628 --
115629
115630 CREATE RULE "_DELETE" AS ON DELETE TO salesline DO INSTEAD DELETE FROM public.coitem WHERE (((coitem.coitem_cohead_id = public.getcoheadid((old.order_number)::text)) AND (((coitem.coitem_linenumber)::character varying)::text = (old.line_number)::text)) AND (coitem.coitem_subnumber = 0));
115631
115632
115633 --
115634 -- TOC entry 8598 (class 2618 OID 146571783)
115635 -- Dependencies: 211 211 211 8894
115636 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115637 --
115638
115639 CREATE RULE "_DELETE" AS ON DELETE TO apmemo DO INSTEAD NOTHING;
115640
115641
115642 --
115643 -- TOC entry 8599 (class 2618 OID 146571784)
115644 -- Dependencies: 217 217 217 8894
115645 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115646 --
115647
115648 CREATE RULE "_DELETE" AS ON DELETE TO armemo DO INSTEAD NOTHING;
115649
115650
115651 --
115652 -- TOC entry 8600 (class 2618 OID 146571785)
115653 -- Dependencies: 194 194 194 8894
115654 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115655 --
115656
115657 CREATE RULE "_DELETE" AS ON DELETE TO physinvcount DO INSTEAD NOTHING;
115658
115659
115660 --
115661 -- TOC entry 8601 (class 2618 OID 146571786)
115662 -- Dependencies: 235 235 205 235 8894
115663 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115664 --
115665
115666 CREATE RULE "_DELETE" AS ON DELETE TO account DO INSTEAD DELETE FROM public.crmacct WHERE (crmacct.crmacct_number = (old.account_number)::text);
115667
115668
115669 --
115670 -- TOC entry 8602 (class 2618 OID 146571787)
115671 -- Dependencies: 238 238 238 237 237 237 1680 1665 238 8894
115672 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115673 --
115674
115675 CREATE RULE "_DELETE" AS ON DELETE TO accountchar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'CRMACCT'::text) AND (charass.charass_target_id = public.getcrmacctid((old.account_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'CRMACCT'::text)));
115676
115677
115678 --
115679 -- TOC entry 8603 (class 2618 OID 146571788)
115680 -- Dependencies: 241 241 241 8894
115681 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115682 --
115683
115684 CREATE RULE "_DELETE" AS ON DELETE TO accountcomment DO INSTEAD NOTHING;
115685
115686
115687 --
115688 -- TOC entry 8604 (class 2618 OID 146571789)
115689 -- Dependencies: 246 246 246 246 245 245 245 245 1680 246 8894
115690 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115691 --
115692
115693 CREATE RULE "_DELETE" AS ON DELETE TO accountfile DO INSTEAD DELETE FROM public.url WHERE ((((url.url_source_id = public.getcrmacctid(old.account_number)) AND (url.url_source = 'CRMA'::text)) AND (url.url_title = old.title)) AND (url.url_url = old.url));
115694
115695
115696 --
115697 -- TOC entry 8605 (class 2618 OID 146571790)
115698 -- Dependencies: 250 250 250 249 249 249 1702 1680 250 8894
115699 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115700 --
115701
115702 CREATE RULE "_DELETE" AS ON DELETE TO accountimage DO INSTEAD DELETE FROM public.imageass WHERE (((imageass.imageass_source_id = public.getcrmacctid(old.account_number)) AND (imageass.imageass_source = 'CRMA'::text)) AND (imageass.imageass_image_id = public.getimageid(old.image_name)));
115703
115704
115705 --
115706 -- TOC entry 8606 (class 2618 OID 146571791)
115707 -- Dependencies: 251 251 1658 1400 251 8894
115708 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115709 --
115710
115711 CREATE RULE "_DELETE" AS ON DELETE TO address DO INSTEAD SELECT public.deleteaddress(public.getaddrid((old.address_number)::text)) AS deleteaddress;
115712
115713
115714 --
115715 -- TOC entry 8607 (class 2618 OID 146571792)
115716 -- Dependencies: 252 252 252 237 237 237 1665 1658 252 8894
115717 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115718 --
115719
115720 CREATE RULE "_DELETE" AS ON DELETE TO addresschar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'ADDR'::text) AND (charass.charass_target_id = public.getaddrid((old.address_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'ADDR'::text)));
115721
115722
115723 --
115724 -- TOC entry 8608 (class 2618 OID 146571793)
115725 -- Dependencies: 253 253 253 8894
115726 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115727 --
115728
115729 CREATE RULE "_DELETE" AS ON DELETE TO addresscomment DO INSTEAD NOTHING;
115730
115731
115732 --
115733 -- TOC entry 8609 (class 2618 OID 146571794)
115734 -- Dependencies: 255 255 1714 1404 255 8894
115735 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115736 --
115737
115738 CREATE RULE "_DELETE" AS ON DELETE TO bom DO INSTEAD SELECT public.deletebom(public.getitemid((old.item_number)::text)) AS deletebom;
115739
115740
115741 --
115742 -- TOC entry 8610 (class 2618 OID 146571795)
115743 -- Dependencies: 256 256 203 1545 256 8894
115744 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115745 --
115746
115747 CREATE RULE "_DELETE" AS ON DELETE TO bomitem DO INSTEAD DELETE FROM public.bomitem WHERE ((bomitem.bomitem_id = old.id) AND public.fetchmetricbool('AllowBOMItemDelete'::text));
115748
115749
115750 --
115751 -- TOC entry 8611 (class 2618 OID 146571796)
115752 -- Dependencies: 257 257 257 8894
115753 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115754 --
115755
115756 CREATE RULE "_DELETE" AS ON DELETE TO bomitemcomment DO INSTEAD NOTHING;
115757
115758
115759 --
115760 -- TOC entry 8612 (class 2618 OID 146571797)
115761 -- Dependencies: 259 259 259 258 258 1714 259 8894
115762 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115763 --
115764
115765 CREATE RULE "_DELETE" AS ON DELETE TO bomitemsubstitute DO INSTEAD DELETE FROM public.bomitemsub WHERE ((bomitemsub.bomitemsub_bomitem_id = old.bomitem_id) AND (bomitemsub.bomitemsub_item_id = public.getitemid((old.substitute_item_number)::text)));
115766
115767
115768 --
115769 -- TOC entry 8613 (class 2618 OID 146571798)
115770 -- Dependencies: 261 261 260 261 8894
115771 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115772 --
115773
115774 CREATE RULE "_DELETE" AS ON DELETE TO budget DO INSTEAD DELETE FROM public.budghead WHERE (budghead.budghead_name = old.name);
115775
115776
115777 --
115778 -- TOC entry 8614 (class 2618 OID 146571799)
115779 -- Dependencies: 265 265 265 265 263 263 263 1730 1700 1663 265 8894
115780 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115781 --
115782
115783 CREATE RULE "_DELETE" AS ON DELETE TO budgetentry DO INSTEAD DELETE FROM public.budgitem WHERE (((budgitem.budgitem_budghead_id = public.getbudgheadid(old.name)) AND (budgitem.budgitem_period_id = public.getperiodid(old.period_start))) AND (budgitem.budgitem_accnt_id = public.getglaccntid(old.account)));
115784
115785
115786 --
115787 -- TOC entry 8615 (class 2618 OID 146571800)
115788 -- Dependencies: 268 268 268 268 267 1664 1409 268 8894
115789 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115790 --
115791
115792 CREATE RULE "_DELETE" AS ON DELETE TO cashreceipt DO INSTEAD SELECT public.deletecashrcpt(cashrcpt.cashrcpt_id) AS deletecashrcpt FROM public.cashrcpt WHERE (cashrcpt.cashrcpt_id = public.getcashrcptid((old.customer_number)::text, CASE WHEN ((old.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((old.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((old.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((old.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((old.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((old.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((old.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((old.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((old.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (old.check_document_number)::text));
115793
115794
115795 --
115796 -- TOC entry 8616 (class 2618 OID 146571802)
115797 -- Dependencies: 270 270 270 270 270 270 269 269 1664 1660 270 8894
115798 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115799 --
115800
115801 CREATE RULE "_DELETE" AS ON DELETE TO cashreceiptapply DO INSTEAD DELETE FROM public.cashrcptitem WHERE ((cashrcptitem.cashrcptitem_cashrcpt_id = public.getcashrcptid((old.customer_number)::text, CASE WHEN ((old.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((old.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((old.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((old.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((old.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((old.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((old.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((old.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((old.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (old.check_document_number)::text)) AND (cashrcptitem.cashrcptitem_aropen_id = public.getaropenid((old.customer_number)::text, (old.doc_type)::bpchar, (old.doc_number)::text)));
115802
115803
115804 --
115805 -- TOC entry 8617 (class 2618 OID 146571804)
115806 -- Dependencies: 272 272 272 272 272 271 271 1700 1664 272 8894
115807 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115808 --
115809
115810 CREATE RULE "_DELETE" AS ON DELETE TO cashreceiptapplymisc DO INSTEAD DELETE FROM public.cashrcptmisc WHERE ((cashrcptmisc.cashrcptmisc_cashrcpt_id = public.getcashrcptid((old.customer_number)::text, CASE WHEN ((old.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((old.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((old.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((old.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((old.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((old.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((old.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((old.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((old.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (old.check_document_number)::text)) AND (cashrcptmisc.cashrcptmisc_accnt_id = public.getglaccntid((old.account)::text)));
115811
115812
115813 --
115814 -- TOC entry 8618 (class 2618 OID 146571806)
115815 -- Dependencies: 273 273 204 273 8894
115816 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115817 --
115818
115819 CREATE RULE "_DELETE" AS ON DELETE TO contact DO INSTEAD DELETE FROM public.cntct WHERE (cntct.cntct_number = (old.contact_number)::text);
115820
115821
115822 --
115823 -- TOC entry 8619 (class 2618 OID 146571807)
115824 -- Dependencies: 274 274 274 237 237 237 1670 1665 274 8894
115825 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115826 --
115827
115828 CREATE RULE "_DELETE" AS ON DELETE TO contactchar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'CNTCT'::text) AND (charass.charass_target_id = public.getcntctid(old.contact_number))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'CNTCT'::text)));
115829
115830
115831 --
115832 -- TOC entry 8620 (class 2618 OID 146571808)
115833 -- Dependencies: 275 275 275 8894
115834 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115835 --
115836
115837 CREATE RULE "_DELETE" AS ON DELETE TO contactcomment DO INSTEAD NOTHING;
115838
115839
115840 --
115841 -- TOC entry 8621 (class 2618 OID 146571809)
115842 -- Dependencies: 221 221 218 218 218 1414 221 8894
115843 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115844 --
115845
115846 CREATE RULE "_DELETE" AS ON DELETE TO creditmemo DO INSTEAD SELECT public.deletecreditmemo(cmhead.cmhead_id) AS deletecreditmemo FROM public.cmhead WHERE ((cmhead.cmhead_number = old.memo_number) AND (cmhead.cmhead_posted = false));
115847
115848
115849 --
115850 -- TOC entry 8622 (class 2618 OID 146571810)
115851 -- Dependencies: 223 223 223 222 222 1668 223 8894
115852 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115853 --
115854
115855 CREATE RULE "_DELETE" AS ON DELETE TO creditmemoline DO INSTEAD DELETE FROM public.cmitem WHERE ((cmitem.cmitem_cmhead_id = public.getcmheadid(old.memo_number, false)) AND (cmitem.cmitem_linenumber = old.line_number));
115856
115857
115858 --
115859 -- TOC entry 8623 (class 2618 OID 146571811)
115860 -- Dependencies: 276 276 276 237 237 237 1682 1665 276 8894
115861 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115862 --
115863
115864 CREATE RULE "_DELETE" AS ON DELETE TO custchar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'C'::text) AND (charass.charass_target_id = public.getcustid((old.customer_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'C'::text)));
115865
115866
115867 --
115868 -- TOC entry 8624 (class 2618 OID 146571812)
115869 -- Dependencies: 277 277 277 8894
115870 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115871 --
115872
115873 CREATE RULE "_DELETE" AS ON DELETE TO custcomment DO INSTEAD NOTHING;
115874
115875
115876 --
115877 -- TOC entry 8625 (class 2618 OID 146571813)
115878 -- Dependencies: 279 279 279 8894
115879 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115880 --
115881
115882 CREATE RULE "_DELETE" AS ON DELETE TO custcreditcard DO INSTEAD NOTHING;
115883
115884
115885 --
115886 -- TOC entry 8626 (class 2618 OID 146571814)
115887 -- Dependencies: 283 283 213 283 8894
115888 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115889 --
115890
115891 CREATE RULE "_DELETE" AS ON DELETE TO customer DO INSTEAD DELETE FROM public.custinfo WHERE (custinfo.cust_number = (old.customer_number)::text);
115892
115893
115894 --
115895 -- TOC entry 8627 (class 2618 OID 146571816)
115896 -- Dependencies: 287 287 280 287 8894
115897 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115898 --
115899
115900 CREATE RULE "_DELETE" AS ON DELETE TO customertype DO INSTEAD DELETE FROM public.custtype WHERE (custtype.custtype_code = (old.code)::text);
115901
115902
115903 --
115904 -- TOC entry 8628 (class 2618 OID 146571817)
115905 -- Dependencies: 288 288 288 237 237 237 1686 1665 288 8894
115906 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115907 --
115908
115909 CREATE RULE "_DELETE" AS ON DELETE TO customertypechar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'CT'::text) AND (charass.charass_target_id = public.getcusttypeid((old.customer_type)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'CT'::text)));
115910
115911
115912 --
115913 -- TOC entry 8629 (class 2618 OID 146571818)
115914 -- Dependencies: 289 289 289 1756 1456 289 8894
115915 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115916 --
115917
115918 CREATE RULE "_DELETE" AS ON DELETE TO custshipto DO INSTEAD SELECT public.deleteshipto(public.getshiptoid((old.customer_number)::text, (old.shipto_number)::text)) AS deleteshipto;
115919
115920
115921 --
115922 -- TOC entry 8630 (class 2618 OID 146571819)
115923 -- Dependencies: 290 290 290 285 285 285 1765 1682 290 8894
115924 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115925 --
115926
115927 CREATE RULE "_DELETE" AS ON DELETE TO custtax DO INSTEAD DELETE FROM public.taxreg WHERE (((taxreg.taxreg_rel_type = 'C'::bpchar) AND (taxreg.taxreg_rel_id = public.getcustid((old.customer_number)::text))) AND (taxreg.taxreg_taxauth_id = public.gettaxauthid((old.tax_authority)::text)));
115928
115929
115930 --
115931 -- TOC entry 8631 (class 2618 OID 146571820)
115932 -- Dependencies: 294 294 292 294 8894
115933 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115934 --
115935
115936 CREATE RULE "_DELETE" AS ON DELETE TO employee DO INSTEAD DELETE FROM public.emp WHERE (emp.emp_code = (old.code)::text);
115937
115938
115939 --
115940 -- TOC entry 8632 (class 2618 OID 146571821)
115941 -- Dependencies: 295 295 295 237 237 237 1690 1665 295 8894
115942 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115943 --
115944
115945 CREATE RULE "_DELETE" AS ON DELETE TO employeechar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'EMP'::text) AND (charass.charass_target_id = public.getempid((old.employee_code)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'EMP'::text)));
115946
115947
115948 --
115949 -- TOC entry 8633 (class 2618 OID 146571822)
115950 -- Dependencies: 296 296 296 8894
115951 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115952 --
115953
115954 CREATE RULE "_DELETE" AS ON DELETE TO employeecomment DO INSTEAD NOTHING;
115955
115956
115957 --
115958 -- TOC entry 8634 (class 2618 OID 146571823)
115959 -- Dependencies: 298 298 298 298 298 297 297 297 297 298 8894
115960 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115961 --
115962
115963 CREATE RULE "_DELETE" AS ON DELETE TO extshipmaint DO INSTEAD DELETE FROM public.shipdata WHERE ((((shipdata.shipdata_cohead_number = (old.so_number)::text) AND (shipdata.shipdata_shiphead_number = (old.shipment_number)::text)) AND (shipdata.shipdata_shipper = (old.shipper)::text)) AND (shipdata.shipdata_cosmisc_packnum_tracknum = (old.package_tracking_number)::text));
115964
115965
115966 --
115967 -- TOC entry 8635 (class 2618 OID 146571824)
115968 -- Dependencies: 302 302 302 302 302 302 302 302 302 300 300 300 300 300 300 300 300 1780 1759 1684 1697 302 8894
115969 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115970 --
115971
115972 CREATE RULE "_DELETE" AS ON DELETE TO freightpricingscheduleitem DO INSTEAD DELETE FROM public.ipsfreight WHERE (((((((((ipsfreight.ipsfreight_ipshead_id = public.getipsheadid((old.pricing_schedule)::text)) AND (ipsfreight.ipsfreight_qtybreak = old.qty_break)) AND (ipsfreight.ipsfreight_price = old.price)) AND ((ipsfreight.ipsfreight_type)::text = CASE WHEN (old.price_type = 'Flat Rate'::text) THEN 'F'::text WHEN (old.price_type = 'Price Per UOM'::text) THEN 'P'::text ELSE NULL::text END)) AND ((ipsfreight.ipsfreight_warehous_id IS NULL) AND (old.from_site = 'Any'::text))) OR ((ipsfreight.ipsfreight_warehous_id = CASE WHEN (old.from_site = 'Any'::text) THEN 0 ELSE public.getwarehousid(old.from_site, 'All'::text) END) AND ((ipsfreight.ipsfreight_shipzone_id IS NULL) AND (old.to_shipzone = 'Any'::text)))) OR ((ipsfreight.ipsfreight_shipzone_id = CASE WHEN (old.to_shipzone = 'Any'::text) THEN 0 ELSE public.getshipzoneid(old.to_shipzone) END) AND ((ipsfreight.ipsfreight_freightclass_id IS NULL) AND (old.freight_class = 'Any'::text)))) OR ((ipsfreight.ipsfreight_freightclass_id = CASE WHEN (old.freight_class = 'Any'::text) THEN 0 ELSE public.getfreightclassid(old.freight_class) END) AND ((ipsfreight.ipsfreight_shipvia IS NULL) AND (old.ship_via = 'Any'::text)))) OR (ipsfreight.ipsfreight_shipvia = old.ship_via));
115973
115974
115975 --
115976 -- TOC entry 8636 (class 2618 OID 146571826)
115977 -- Dependencies: 308 308 308 8894
115978 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115979 --
115980
115981 CREATE RULE "_DELETE" AS ON DELETE TO incident DO INSTEAD NOTHING;
115982
115983
115984 --
115985 -- TOC entry 8637 (class 2618 OID 146571827)
115986 -- Dependencies: 309 309 309 237 237 237 1708 1665 309 8894
115987 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115988 --
115989
115990 CREATE RULE "_DELETE" AS ON DELETE TO incidentchar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'INCDT'::text) AND (charass.charass_target_id = public.getincidentid(old.incident_number))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'INCDT'::text)));
115991
115992
115993 --
115994 -- TOC entry 8638 (class 2618 OID 146571828)
115995 -- Dependencies: 310 310 310 8894
115996 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
115997 --
115998
115999 CREATE RULE "_DELETE" AS ON DELETE TO incidentcomment DO INSTEAD NOTHING;
116000
116001
116002 --
116003 -- TOC entry 8639 (class 2618 OID 146571829)
116004 -- Dependencies: 311 311 311 311 245 245 245 245 1708 311 8894
116005 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116006 --
116007
116008 CREATE RULE "_DELETE" AS ON DELETE TO incidentfile DO INSTEAD DELETE FROM public.url WHERE ((((url.url_source_id = public.getincidentid(old.incident_number)) AND (url.url_source = 'INCDT'::text)) AND (url.url_title = old.title)) AND (url.url_url = old.url));
116009
116010
116011 --
116012 -- TOC entry 8640 (class 2618 OID 146571830)
116013 -- Dependencies: 312 312 312 249 249 249 1708 1702 312 8894
116014 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116015 --
116016
116017 CREATE RULE "_DELETE" AS ON DELETE TO incidentimage DO INSTEAD DELETE FROM public.imageass WHERE (((imageass.imageass_source_id = public.getincidentid(old.incident_number)) AND (imageass.imageass_source = 'INCDT'::text)) AND (imageass.imageass_image_id = public.getimageid(old.image_name)));
116018
116019
116020 --
116021 -- TOC entry 8641 (class 2618 OID 146571831)
116022 -- Dependencies: 228 228 224 224 224 1423 228 8894
116023 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116024 --
116025
116026 CREATE RULE "_DELETE" AS ON DELETE TO invoice DO INSTEAD SELECT public.deleteinvoice(invchead.invchead_id) AS deleteinvoice FROM public.invchead WHERE ((invchead.invchead_invcnumber = old.invoice_number) AND (invchead.invchead_posted = false));
116027
116028
116029 --
116030 -- TOC entry 8642 (class 2618 OID 146571832)
116031 -- Dependencies: 230 230 229 224 224 224 230 8894
116032 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116033 --
116034
116035 CREATE RULE "_DELETE" AS ON DELETE TO invoiceline DO INSTEAD DELETE FROM public.invcitem WHERE (invcitem.invcitem_invchead_id = (SELECT invchead.invchead_id FROM public.invchead WHERE ((invchead.invchead_invcnumber = old.invoice_number) AND (invchead.invchead_posted = false))));
116036
116037
116038 --
116039 -- TOC entry 8643 (class 2618 OID 146571833)
116040 -- Dependencies: 315 315 1714 1426 315 8894
116041 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116042 --
116043
116044 CREATE RULE "_DELETE" AS ON DELETE TO item DO INSTEAD SELECT public.deleteitem(public.getitemid((old.item_number)::text)) AS deleteitem;
116045
116046
116047 --
116048 -- TOC entry 8644 (class 2618 OID 146571834)
116049 -- Dependencies: 317 317 317 316 316 1714 317 8894
116050 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116051 --
116052
116053 CREATE RULE "_DELETE" AS ON DELETE TO itemalias DO INSTEAD DELETE FROM public.itemalias WHERE ((itemalias.itemalias_item_id = public.getitemid((old.item_number)::text)) AND (itemalias.itemalias_number = old.alias_number));
116054
116055
116056 --
116057 -- TOC entry 8645 (class 2618 OID 146571835)
116058 -- Dependencies: 318 318 318 237 237 237 1714 1665 318 8894
116059 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116060 --
116061
116062 CREATE RULE "_DELETE" AS ON DELETE TO itemchar DO INSTEAD DELETE FROM public.charass WHERE (((charass.charass_target_type = 'I'::text) AND (charass.charass_target_id = public.getitemid((old.item_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'I'::text)));
116063
116064
116065 --
116066 -- TOC entry 8646 (class 2618 OID 146571836)
116067 -- Dependencies: 319 319 319 8894
116068 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116069 --
116070
116071 CREATE RULE "_DELETE" AS ON DELETE TO itemcomment DO INSTEAD NOTHING;
116072
116073
116074 --
116075 -- TOC entry 8647 (class 2618 OID 146571837)
116076 -- Dependencies: 322 322 322 1714 1679 1427 322 8894
116077 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116078 --
116079
116080 CREATE RULE "_DELETE" AS ON DELETE TO itemcost DO INSTEAD SELECT public.deleteitemcost(public.getitemid((old.item_number)::text), public.getcostelemid((old.costing_element)::text)) AS deleteitemcost;
116081
116082
116083 --
116084 -- TOC entry 8648 (class 2618 OID 146571838)
116085 -- Dependencies: 323 323 323 323 245 245 245 245 1714 323 8894
116086 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116087 --
116088
116089 CREATE RULE "_DELETE" AS ON DELETE TO itemfile DO INSTEAD DELETE FROM public.url WHERE ((((url.url_source_id = public.getitemid((old.item_number)::text)) AND (url.url_source = 'I'::text)) AND (url.url_title = old.title)) AND (url.url_url = old.url));
116090
116091
116092 --
116093 -- TOC entry 8649 (class 2618 OID 146571839)
116094 -- Dependencies: 324 324 324 249 249 249 1714 1702 324 8894
116095 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116096 --
116097
116098 CREATE RULE "_DELETE" AS ON DELETE TO itemimage DO INSTEAD DELETE FROM public.imageass WHERE (((imageass.imageass_source_id = public.getitemid((old.item_number)::text)) AND (imageass.imageass_source = 'I'::text)) AND (imageass.imageass_image_id = public.getimageid(old.image_name)));
116099
116100
116101 --
116102 -- TOC entry 8650 (class 2618 OID 146571840)
116103 -- Dependencies: 327 327 327 1716 1428 327 8894
116104 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116105 --
116106
116107 CREATE RULE "_DELETE" AS ON DELETE TO itemsite DO INSTEAD SELECT public.deleteitemsite(public.getitemsiteid((old.site)::text, (old.item_number)::text)) AS deleteitemsite;
116108
116109
116110 --
116111 -- TOC entry 8651 (class 2618 OID 146571841)
116112 -- Dependencies: 328 328 328 8894
116113 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116114 --
116115
116116 CREATE RULE "_DELETE" AS ON DELETE TO itemsitecomment DO INSTEAD NOTHING;
116117
116118
116119 --
116120 -- TOC entry 8652 (class 2618 OID 146571842)
116121 -- Dependencies: 331 331 331 331 331 331 330 330 330 330 330 1778 1714 331 8894
116122 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116123 --
116124
116125 CREATE RULE "_DELETE" AS ON DELETE TO itemsource DO INSTEAD DELETE FROM public.itemsrc WHERE (((((itemsrc.itemsrc_item_id = public.getitemid((old.item_number)::text)) AND (itemsrc.itemsrc_vend_id = public.getvendid((old.vendor)::text))) AND (itemsrc.itemsrc_vend_item_number = old.vendor_item_number)) AND (itemsrc.itemsrc_manuf_name = old.manufacturer_name)) AND (itemsrc.itemsrc_manuf_item_number = old.manufacturer_item_number));
116126
116127
116128 --
116129 -- TOC entry 8653 (class 2618 OID 146571843)
116130 -- Dependencies: 333 333 333 333 332 332 1718 333 8894
116131 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116132 --
116133
116134 CREATE RULE "_DELETE" AS ON DELETE TO itemsourceprice DO INSTEAD DELETE FROM public.itemsrcp WHERE ((itemsrcp.itemsrcp_itemsrc_id = public.getitemsrcid((old.item_number)::text, (old.vendor)::text)) AND (itemsrcp.itemsrcp_qtybreak = old.qty_break));
116135
116136
116137 --
116138 -- TOC entry 8654 (class 2618 OID 146571844)
116139 -- Dependencies: 335 335 335 334 334 1714 335 8894
116140 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116141 --
116142
116143 CREATE RULE "_DELETE" AS ON DELETE TO itemsubstitute DO INSTEAD DELETE FROM public.itemsub WHERE ((itemsub.itemsub_parent_item_id = public.getitemid((old.root_item_number)::text)) AND (itemsub.itemsub_sub_item_id = public.getitemid((old.substitute_item_number)::text)));
116144
116145
116146 --
116147 -- TOC entry 8655 (class 2618 OID 146571845)
116148 -- Dependencies: 337 337 337 337 336 336 336 1768 1767 1714 337 8894
116149 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116150 --
116151
116152 CREATE RULE "_DELETE" AS ON DELETE TO itemtaxtype DO INSTEAD DELETE FROM public.itemtax WHERE (((itemtax.itemtax_item_id = public.getitemid((old.item_number)::text)) AND CASE WHEN ((old.tax_zone)::text = 'Any'::text) THEN (itemtax.itemtax_taxzone_id IS NULL) ELSE (itemtax.itemtax_taxzone_id = public.gettaxzoneid((old.tax_zone)::text)) END) AND (itemtax.itemtax_taxtype_id = public.gettaxtypeid(old.tax_type)));
116153
116154
116155 --
116156 -- TOC entry 8656 (class 2618 OID 146571846)
116157 -- Dependencies: 339 339 339 339 338 338 338 338 1771 1714 1430 339 8894
116158 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116159 --
116160
116161 CREATE RULE "_DELETE" AS ON DELETE TO itemuomconversion DO INSTEAD SELECT public.deleteitemuomconv(itemuomconv.itemuomconv_id) AS deleteitemuomconv FROM public.itemuomconv WHERE ((itemuomconv.itemuomconv_item_id = public.getitemid((old.item_number)::text)) AND (((itemuomconv.itemuomconv_from_uom_id = public.getuomid((old.uom)::text)) AND (itemuomconv.itemuomconv_to_uom_id = public.getuomid(old.per_uom))) OR ((itemuomconv.itemuomconv_from_uom_id = public.getuomid(old.per_uom)) AND (itemuomconv.itemuomconv_to_uom_id = public.getuomid((old.uom)::text)))));
116162
116163
116164 --
116165 -- TOC entry 8657 (class 2618 OID 146571847)
116166 -- Dependencies: 341 341 341 8894
116167 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116168 --
116169
116170 CREATE RULE "_DELETE" AS ON DELETE TO journalentry DO INSTEAD NOTHING;
116171
116172
116173 --
116174 -- TOC entry 8658 (class 2618 OID 146571848)
116175 -- Dependencies: 344 344 344 342 342 1780 344 8894
116176 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116177 --
116178
116179 CREATE RULE "_DELETE" AS ON DELETE TO location DO INSTEAD DELETE FROM public.location WHERE ((location.location_warehous_id = public.getwarehousid((old.site)::text, 'ACTIVE'::text)) AND (location.location_name = (old.location)::text));
116180
116181
116182 --
116183 -- TOC entry 8659 (class 2618 OID 146571849)
116184 -- Dependencies: 345 345 345 8894
116185 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116186 --
116187
116188 CREATE RULE "_DELETE" AS ON DELETE TO misccounttag DO INSTEAD NOTHING;
116189
116190
116191 --
116192 -- TOC entry 8660 (class 2618 OID 146571850)
116193 -- Dependencies: 346 346 301 346 8894
116194 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116195 --
116196
116197 CREATE RULE "_DELETE" AS ON DELETE TO pricingschedule DO INSTEAD DELETE FROM public.ipshead WHERE ((old.name)::text = ipshead.ipshead_name);
116198
116199
116200 --
116201 -- TOC entry 8661 (class 2618 OID 146571851)
116202 -- Dependencies: 348 348 348 348 348 348 348 347 347 347 347 347 347 1756 1684 1686 1682 348 8894
116203 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116204 --
116205
116206 CREATE RULE "_DELETE" AS ON DELETE TO pricingscheduleassign DO INSTEAD DELETE FROM public.ipsass WHERE ((((((ipsass.ipsass_ipshead_id = public.getipsheadid((old.pricing_schedule)::text)) AND (ipsass.ipsass_cust_id = CASE WHEN ((old.customer_number)::text = 'Any'::text) THEN (-1) ELSE public.getcustid((old.customer_number)::text) END)) AND (ipsass.ipsass_custtype_id = CASE WHEN ((old.customer_type)::text = 'N/A'::text) THEN (-1) ELSE public.getcusttypeid((old.customer_type)::text) END)) AND (ipsass.ipsass_custtype_pattern = (old.customer_type_pattern)::text)) AND (ipsass.ipsass_shipto_id = CASE WHEN ((old.customer_shipto)::text = 'Any'::text) THEN (-1) ELSE public.getshiptoid((old.customer_number)::text, (old.customer_shipto)::text) END)) AND (ipsass.ipsass_shipto_pattern = (old.customer_shipto_pattern)::text));
116207
116208
116209 --
116210 -- TOC entry 8662 (class 2618 OID 146571852)
116211 -- Dependencies: 350 350 350 350 350 350 350 350 1713 1712 1425 1424 350 8894
116212 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116213 --
116214
116215 CREATE RULE "_DELETE" AS ON DELETE TO pricingscheduleitem DO INSTEAD SELECT CASE WHEN ((old.type)::text = 'Item'::text) THEN public.deleteipsitem(public.getipsitemid((old.pricing_schedule)::text, (old.item_number)::text, old.qty_break, (old.qty_uom)::text, (old.price_uom)::text)) WHEN ((old.type)::text = 'Product Category'::text) THEN public.deleteipsprodcat(public.getipsprodcatid((old.pricing_schedule)::text, (old.product_category)::text, old.qty_break)) ELSE NULL::integer END AS result;
116216
116217
116218 --
116219 -- TOC entry 8663 (class 2618 OID 146571853)
116220 -- Dependencies: 352 352 352 352 352 352 352 352 351 351 351 1712 1665 352 8894
116221 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116222 --
116223
116224 CREATE RULE "_DELETE" AS ON DELETE TO pricingscheduleitemchar DO INSTEAD DELETE FROM public.ipsitemchar WHERE (((ipsitemchar.ipsitemchar_ipsitem_id = public.getipsitemid((old.pricing_schedule)::text, (old.item_number)::text, old.qty_break, (old.qty_uom)::text, (old.price_uom)::text)) AND (ipsitemchar.ipsitemchar_char_id = public.getcharid((old.characteristic)::text, 'I'::text))) AND (ipsitemchar.ipsitemchar_value = (old.value)::text));
116225
116226
116227 --
116228 -- TOC entry 8664 (class 2618 OID 146571854)
116229 -- Dependencies: 353 353 1736 1444 353 8894
116230 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116231 --
116232
116233 CREATE RULE "_DELETE" AS ON DELETE TO project DO INSTEAD SELECT public.deleteproject(public.getprjid(old.number)) AS deleteproject;
116234
116235
116236 --
116237 -- TOC entry 8665 (class 2618 OID 146571855)
116238 -- Dependencies: 354 354 354 8894
116239 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116240 --
116241
116242 CREATE RULE "_DELETE" AS ON DELETE TO projectcomment DO INSTEAD NOTHING;
116243
116244
116245 --
116246 -- TOC entry 8666 (class 2618 OID 146571856)
116247 -- Dependencies: 357 357 356 357 8894
116248 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116249 --
116250
116251 CREATE RULE "_DELETE" AS ON DELETE TO prospect DO INSTEAD DELETE FROM public.prospect WHERE (prospect.prospect_number = (old.prospect_number)::text);
116252
116253
116254 --
116255 -- TOC entry 8667 (class 2618 OID 146571857)
116256 -- Dependencies: 360 360 360 198 1734 360 8894
116257 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116258 --
116259
116260 CREATE RULE "_DELETE" AS ON DELETE TO purchaseline DO INSTEAD DELETE FROM public.poitem WHERE (poitem.poitem_id = public.getpoitemid((old.order_number)::text, old.line_number));
116261
116262
116263 --
116264 -- TOC entry 8668 (class 2618 OID 146571858)
116265 -- Dependencies: 361 361 361 8894
116266 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116267 --
116268
116269 CREATE RULE "_DELETE" AS ON DELETE TO purchaselinechar DO INSTEAD NOTHING;
116270
116271
116272 --
116273 -- TOC entry 8669 (class 2618 OID 146571859)
116274 -- Dependencies: 362 362 362 8894
116275 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116276 --
116277
116278 CREATE RULE "_DELETE" AS ON DELETE TO purchaselinecomment DO INSTEAD NOTHING;
116279
116280
116281 --
116282 -- TOC entry 8670 (class 2618 OID 146571860)
116283 -- Dependencies: 365 365 197 197 1438 365 8894
116284 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116285 --
116286
116287 CREATE RULE "_DELETE" AS ON DELETE TO purchaseorder DO INSTEAD SELECT public.deletepo(pohead.pohead_id) AS deletepo FROM public.pohead WHERE (pohead.pohead_number = (old.order_number)::text);
116288
116289
116290 --
116291 -- TOC entry 8671 (class 2618 OID 146571861)
116292 -- Dependencies: 366 366 366 8894
116293 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116294 --
116295
116296 CREATE RULE "_DELETE" AS ON DELETE TO purchaseordercomment DO INSTEAD NOTHING;
116297
116298
116299 --
116300 -- TOC entry 8672 (class 2618 OID 146571862)
116301 -- Dependencies: 368 368 367 367 1447 368 8894
116302 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116303 --
116304
116305 CREATE RULE "_DELETE" AS ON DELETE TO quote DO INSTEAD SELECT public.deletequote(quhead.quhead_id, (old.quote_number)::text) AS deletequote FROM public.quhead WHERE (quhead.quhead_number = (old.quote_number)::text);
116306
116307
116308 --
116309 -- TOC entry 8673 (class 2618 OID 146571863)
116310 -- Dependencies: 369 369 369 8894
116311 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116312 --
116313
116314 CREATE RULE "_DELETE" AS ON DELETE TO quotecomment DO INSTEAD NOTHING;
116315
116316
116317 --
116318 -- TOC entry 8674 (class 2618 OID 146571864)
116319 -- Dependencies: 371 371 371 370 370 1720 371 8894
116320 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116321 --
116322
116323 CREATE RULE "_DELETE" AS ON DELETE TO quoteline DO INSTEAD DELETE FROM public.quitem WHERE ((quitem.quitem_quhead_id = public.getquoteid(old.quote_number)) AND (quitem.quitem_linenumber = old.line_number));
116324
116325
116326 --
116327 -- TOC entry 8675 (class 2618 OID 146571865)
116328 -- Dependencies: 372 372 372 8894
116329 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116330 --
116331
116332 CREATE RULE "_DELETE" AS ON DELETE TO quotelinechar DO INSTEAD NOTHING;
116333
116334
116335 --
116336 -- TOC entry 8676 (class 2618 OID 146571866)
116337 -- Dependencies: 373 373 373 8894
116338 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116339 --
116340
116341 CREATE RULE "_DELETE" AS ON DELETE TO quotelinecomment DO INSTEAD NOTHING;
116342
116343
116344 --
116345 -- TOC entry 8677 (class 2618 OID 146571867)
116346 -- Dependencies: 380 380 380 8894
116347 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116348 --
116349
116350 CREATE RULE "_DELETE" AS ON DELETE TO saleshistory DO INSTEAD NOTHING;
116351
116352
116353 --
116354 -- TOC entry 8678 (class 2618 OID 146571868)
116355 -- Dependencies: 381 381 381 8894
116356 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116357 --
116358
116359 CREATE RULE "_DELETE" AS ON DELETE TO saleslinechar DO INSTEAD NOTHING;
116360
116361
116362 --
116363 -- TOC entry 8679 (class 2618 OID 146571869)
116364 -- Dependencies: 382 382 382 8894
116365 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116366 --
116367
116368 CREATE RULE "_DELETE" AS ON DELETE TO saleslinecomment DO INSTEAD NOTHING;
116369
116370
116371 --
116372 -- TOC entry 8680 (class 2618 OID 146571870)
116373 -- Dependencies: 383 383 195 195 1458 383 8894
116374 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116375 --
116376
116377 CREATE RULE "_DELETE" AS ON DELETE TO salesorder DO INSTEAD SELECT public.deleteso(cohead.cohead_id, (old.order_number)::text) AS deleteso FROM public.cohead WHERE (cohead.cohead_number = (old.order_number)::text);
116378
116379
116380 --
116381 -- TOC entry 8681 (class 2618 OID 146571872)
116382 -- Dependencies: 384 384 384 8894
116383 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116384 --
116385
116386 CREATE RULE "_DELETE" AS ON DELETE TO salesordercomment DO INSTEAD NOTHING;
116387
116388
116389 --
116390 -- TOC entry 8682 (class 2618 OID 146571873)
116391 -- Dependencies: 385 385 216 385 8894
116392 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116393 --
116394
116395 CREATE RULE "_DELETE" AS ON DELETE TO salesrep DO INSTEAD DELETE FROM public.salesrep WHERE (salesrep.salesrep_number = (old.number)::text);
116396
116397
116398 --
116399 -- TOC entry 8683 (class 2618 OID 146571874)
116400 -- Dependencies: 388 388 388 8894
116401 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116402 --
116403
116404 CREATE RULE "_DELETE" AS ON DELETE TO site DO NOTHING;
116405
116406
116407 --
116408 -- TOC entry 8684 (class 2618 OID 146571875)
116409 -- Dependencies: 389 389 389 343 343 1780 389 8894
116410 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116411 --
116412
116413 CREATE RULE "_DELETE" AS ON DELETE TO sitezone DO INSTEAD DELETE FROM public.whsezone WHERE ((whsezone.whsezone_warehous_id = public.getwarehousid((old.site)::text, 'ACTIVE'::text)) AND (whsezone.whsezone_name = (old.name)::text));
116414
116415
116416 --
116417 -- TOC entry 8685 (class 2618 OID 146571876)
116418 -- Dependencies: 390 390 390 232 232 1736 390 8894
116419 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116420 --
116421
116422 CREATE RULE "_DELETE" AS ON DELETE TO task DO INSTEAD DELETE FROM public.prjtask WHERE ((prjtask.prjtask_prj_id = public.getprjid(old.project_number)) AND (prjtask.prjtask_number = old.number));
116423
116424
116425 --
116426 -- TOC entry 8686 (class 2618 OID 146571877)
116427 -- Dependencies: 391 391 391 8894
116428 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116429 --
116430
116431 CREATE RULE "_DELETE" AS ON DELETE TO taskcomment DO INSTEAD NOTHING;
116432
116433
116434 --
116435 -- TOC entry 8687 (class 2618 OID 146571878)
116436 -- Dependencies: 392 392 1468 392 8894
116437 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116438 --
116439
116440 CREATE RULE "_DELETE" AS ON DELETE TO todo DO INSTEAD SELECT public.deletetodoitem(old.task_number) AS deletetodoitem;
116441
116442
116443 --
116444 -- TOC entry 8688 (class 2618 OID 146571879)
116445 -- Dependencies: 394 394 210 394 8894
116446 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116447 --
116448
116449 CREATE RULE "_DELETE" AS ON DELETE TO vendor DO INSTEAD DELETE FROM public.vendinfo WHERE (vendinfo.vend_number = (old.vendor_number)::text);
116450
116451
116452 --
116453 -- TOC entry 8689 (class 2618 OID 146571880)
116454 -- Dependencies: 395 395 395 1777 1479 395 8894
116455 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116456 --
116457
116458 CREATE RULE "_DELETE" AS ON DELETE TO vendoraddress DO INSTEAD SELECT public.deletevendoraddress(public.getvendaddrid((old.vendor_number)::text, (old.vendor_address_number)::text)) AS deletevendoraddress;
116459
116460
116461 --
116462 -- TOC entry 8690 (class 2618 OID 146571881)
116463 -- Dependencies: 396 396 1779 1480 396 8894
116464 -- Name: _DELETE; Type: RULE; Schema: api; Owner: admin
116465 --
116466
116467 CREATE RULE "_DELETE" AS ON DELETE TO vendortype DO INSTEAD SELECT public.deletevendortype(public.getvendtypeid((old.code)::text)) AS deletevendortype;
116468
116469
116470 --
116471 -- TOC entry 8691 (class 2618 OID 146571882)
116472 -- Dependencies: 201 201 1832 201 8894
116473 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116474 --
116475
116476 CREATE RULE "_INSERT" AS ON INSERT TO salesline DO INSTEAD SELECT public.insertsalesline(new.*) AS insertsalesline;
116477
116478
116479 --
116480 -- TOC entry 8692 (class 2618 OID 146571883)
116481 -- Dependencies: 211 211 1813 211 8894
116482 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116483 --
116484
116485 CREATE RULE "_INSERT" AS ON INSERT TO apmemo DO INSTEAD SELECT public.insertapmemo(new.*) AS insertapmemo;
116486
116487
116488 --
116489 -- TOC entry 8693 (class 2618 OID 146571884)
116490 -- Dependencies: 217 217 1814 217 8894
116491 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116492 --
116493
116494 CREATE RULE "_INSERT" AS ON INSERT TO armemo DO INSTEAD SELECT public.insertarmemo(new.*) AS insertarmemo;
116495
116496
116497 --
116498 -- TOC entry 8694 (class 2618 OID 146571885)
116499 -- Dependencies: 194 194 906 194 8894
116500 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116501 --
116502
116503 CREATE RULE "_INSERT" AS ON INSERT TO physinvcount DO INSTEAD SELECT insertphysinvcount(new.*) AS insertphysinvcount;
116504
116505
116506 --
116507 -- TOC entry 8695 (class 2618 OID 146571886)
116508 -- Dependencies: 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 235 205 2162 2158 1680 1670 1658 1537 235 8894
116509 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116510 --
116511
116512 CREATE RULE "_INSERT" AS ON INSERT TO account DO INSTEAD INSERT INTO public.crmacct (crmacct_number, crmacct_parent_id, crmacct_name, crmacct_active, crmacct_type, crmacct_cntct_id_1, crmacct_cntct_id_2, crmacct_notes) VALUES (COALESCE(new.account_number, ((public.fetchcrmaccountnumber())::text)::character varying), public.getcrmacctid(new.parent_account), new.account_name, COALESCE(new.active, true), CASE WHEN (new.type = 'Individual'::text) THEN 'I'::text ELSE 'O'::text END, public.savecntct(public.getcntctid(new.primary_contact_number), new.primary_contact_number, public.saveaddr(public.getaddrid(new.primary_contact_address_number), new.primary_contact_address_number, new.primary_contact_address1, new.primary_contact_address2, new.primary_contact_address3, new.primary_contact_city, new.primary_contact_state, new.primary_contact_postalcode, new.primary_contact_country, new.primary_contact_address_change), new.primary_contact_honorific, new.primary_contact_first, new.primary_contact_middle, new.primary_contact_last, new.primary_contact_suffix, new.primary_contact_voice, NULL::text, new.primary_contact_fax, new.primary_contact_email, NULL::text, new.primary_contact_job_title, new.primary_contact_change), public.savecntct(public.getcntctid(new.secondary_contact_number), new.secondary_contact_number, public.saveaddr(public.getaddrid(new.secondary_contact_address_number), new.secondary_contact_address_number, new.secondary_contact_address1, new.secondary_contact_address2, new.secondary_contact_address3, new.secondary_contact_city, new.secondary_contact_state, new.secondary_contact_postalcode, new.secondary_contact_country, new.secondary_contact_address_change), new.secondary_contact_honorific, new.secondary_contact_first, new.secondary_contact_middle, new.secondary_contact_last, new.secondary_contact_suffix, new.secondary_contact_voice, NULL::text, new.secondary_contact_fax, new.secondary_contact_email, NULL::text, new.secondary_contact_job_title, new.secondary_contact_change), new.notes);
116513
116514
116515 --
116516 -- TOC entry 8696 (class 2618 OID 146571888)
116517 -- Dependencies: 238 238 238 238 237 1680 1665 238 8894
116518 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116519 --
116520
116521 CREATE RULE "_INSERT" AS ON INSERT TO accountchar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('CRMACCT'::text, public.getcrmacctid((new.account_number)::text), public.getcharid((new.characteristic)::text, 'CRMACCT'::text), new.value, false);
116522
116523
116524 --
116525 -- TOC entry 8697 (class 2618 OID 146571889)
116526 -- Dependencies: 241 241 241 241 241 241 240 1680 1669 910 241 8894
116527 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116528 --
116529
116530 CREATE RULE "_INSERT" AS ON INSERT TO accountcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'CRMA'::text, public.getcrmacctid((new.account_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116531
116532
116533 --
116534 -- TOC entry 8698 (class 2618 OID 146571890)
116535 -- Dependencies: 246 246 246 246 245 1680 246 8894
116536 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116537 --
116538
116539 CREATE RULE "_INSERT" AS ON INSERT TO accountfile DO INSTEAD INSERT INTO public.url (url_source_id, url_source, url_title, url_url) VALUES (public.getcrmacctid(new.account_number), 'CRMA'::text, new.title, new.url);
116540
116541
116542 --
116543 -- TOC entry 8699 (class 2618 OID 146571891)
116544 -- Dependencies: 250 250 250 2165 1702 1680 250 8894
116545 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116546 --
116547
116548 CREATE RULE "_INSERT" AS ON INSERT TO accountimage DO INSTEAD SELECT public.saveimageass('CRMA'::text, public.getcrmacctid(new.account_number), 'M'::bpchar, public.getimageid(new.image_name)) AS saveimageass;
116549
116550
116551 --
116552 -- TOC entry 8700 (class 2618 OID 146571892)
116553 -- Dependencies: 251 251 251 251 251 251 251 251 251 251 251 2157 251 8894
116554 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116555 --
116556
116557 CREATE RULE "_INSERT" AS ON INSERT TO address DO INSTEAD SELECT public.saveaddr(NULL::integer, (new.address_number)::text, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, COALESCE(new.active, true), new.notes, NULL::text) AS saveaddr;
116558
116559
116560 --
116561 -- TOC entry 8701 (class 2618 OID 146571893)
116562 -- Dependencies: 252 252 252 252 237 1665 1658 252 8894
116563 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116564 --
116565
116566 CREATE RULE "_INSERT" AS ON INSERT TO addresschar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('ADDR'::text, public.getaddrid((new.address_number)::text), public.getcharid((new.characteristic)::text, 'ADDR'::text), new.value, false);
116567
116568
116569 --
116570 -- TOC entry 8702 (class 2618 OID 146571894)
116571 -- Dependencies: 253 253 253 253 253 253 240 1669 1658 910 253 8894
116572 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116573 --
116574
116575 CREATE RULE "_INSERT" AS ON INSERT TO addresscomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'ADDR'::text, public.getaddrid((new.address_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116576
116577
116578 --
116579 -- TOC entry 8703 (class 2618 OID 146571895)
116580 -- Dependencies: 255 255 255 255 255 255 255 2160 1714 255 8894
116581 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116582 --
116583
116584 CREATE RULE "_INSERT" AS ON INSERT TO bom DO INSTEAD SELECT public.savebomhead(public.getitemid((new.item_number)::text), (new.revision)::text, new.revision_date, new.document_number, COALESCE(new.batch_size, (0)::numeric), new.total_qty_per) AS savebomhead;
116585
116586
116587 --
116588 -- TOC entry 8704 (class 2618 OID 146571897)
116589 -- Dependencies: 256 467 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 191 191 2233 1771 1742 1714 1665 1650 1546 1519 1311 1148 256 8894
116590 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116591 --
116592
116593 CREATE RULE "_INSERT" AS ON INSERT TO bomitem DO INSTEAD SELECT public.createbomitem(COALESCE(new.id, (nextval('public.bomitem_bomitem_id_seq'::regclass))::integer), public.getitemid((new.bom_item_number)::text), public.getitemid(new.item_number), COALESCE(new.sequence_number, (SELECT (max(bomitem.bomitem_seqnumber) + 10) FROM public.bomitem(public.getitemid((new.bom_item_number)::text), COALESCE(public.getrevid('BOM'::text, (new.bom_item_number)::text, (new.bom_revision)::text))) bomitem(bomitem_id, bomitem_parent_item_id, bomitem_seqnumber, bomitem_item_id, bomitem_qtyper, bomitem_scrap, bomitem_status, bomitem_effective, bomitem_expires, bomitem_createwo, bomitem_issuemethod, bomitem_schedatwooper, bomitem_ecn, bomitem_moddate, bomitem_subtype, bomitem_uom_id, bomitem_rev_id, bomitem_booitem_seq_id, bomitem_char_id, bomitem_value, bomitem_notes, bomitem_ref, bomitem_qtyfxd, bomitem_issuewo)), 10), (CASE WHEN (new.issue_method = 'Mixed'::text) THEN 'M'::text WHEN (new.issue_method = 'Push'::text) THEN 'S'::text WHEN (new.issue_method = 'Pull'::text) THEN 'L'::text ELSE public.fetchmetrictext('DefaultWomatlIssueMethod'::text) END)::bpchar, COALESCE(public.getuomid(new.issue_uom), (SELECT item.item_inv_uom_id FROM public.item WHERE (item.item_id = public.getitemid(new.item_number)))), new.qty_per, new.scrap, CASE WHEN (new.effective = 'Always'::text) THEN public.startoftime() ELSE COALESCE((new.effective)::date, public.startoftime()) END, CASE WHEN (new.expires = 'Never'::text) THEN public.endoftime() ELSE COALESCE((new.expires)::date, public.endoftime()) END, COALESCE(new.create_child_wo, false), COALESCE(public.getbooitemseqid((new.bom_item_number)::text, new.used_at), (-1)), COALESCE(new.schedule_at_wo_operation, false), new.ecn_number, (CASE WHEN (new.substitutions = 'No'::text) THEN 'N'::text WHEN (new.substitutions = 'BOM-Defined'::text) THEN 'B'::text ELSE 'I'::text END)::bpchar, COALESCE(public.getrevid('BOM'::text, (new.bom_item_number)::text, (new.bom_revision)::text)), public.getcharid(new.characteristic, 'I'::text), new.value, new.notes, new.reference) AS createbomitem;
116594
116595
116596 --
116597 -- TOC entry 8705 (class 2618 OID 146571899)
116598 -- Dependencies: 257 257 257 257 257 257 240 1669 910 257 8894
116599 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116600 --
116601
116602 CREATE RULE "_INSERT" AS ON INSERT TO bomitemcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'BMI'::text, new.bomitem_id, COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116603
116604
116605 --
116606 -- TOC entry 8706 (class 2618 OID 146571900)
116607 -- Dependencies: 259 259 259 259 259 258 1714 259 8894
116608 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116609 --
116610
116611 CREATE RULE "_INSERT" AS ON INSERT TO bomitemsubstitute DO INSTEAD INSERT INTO public.bomitemsub (bomitemsub_bomitem_id, bomitemsub_item_id, bomitemsub_uomratio, bomitemsub_rank) VALUES (new.bomitem_id, public.getitemid((new.substitute_item_number)::text), COALESCE(new.sub_parent_uom_ratio, (1)::numeric), COALESCE(new.ranking, 1));
116612
116613
116614 --
116615 -- TOC entry 8707 (class 2618 OID 146571901)
116616 -- Dependencies: 261 261 261 260 261 8894
116617 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116618 --
116619
116620 CREATE RULE "_INSERT" AS ON INSERT TO budget DO INSTEAD INSERT INTO public.budghead (budghead_name, budghead_descrip) VALUES (new.name, new.description);
116621
116622
116623 --
116624 -- TOC entry 8708 (class 2618 OID 146571902)
116625 -- Dependencies: 265 265 265 265 265 263 1730 1700 1663 265 8894
116626 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116627 --
116628
116629 CREATE RULE "_INSERT" AS ON INSERT TO budgetentry DO INSTEAD INSERT INTO public.budgitem (budgitem_budghead_id, budgitem_period_id, budgitem_accnt_id, budgitem_amount) VALUES (public.getbudgheadid(new.name), public.getperiodid(new.period_start), public.getglaccntid(new.account), new.amount);
116630
116631
116632 --
116633 -- TOC entry 8709 (class 2618 OID 146571903)
116634 -- Dependencies: 268 268 268 268 268 268 268 268 268 268 268 267 1744 1682 1681 1661 1535 268 8894
116635 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116636 --
116637
116638 CREATE RULE "_INSERT" AS ON INSERT TO cashreceipt DO INSTEAD INSERT INTO public.cashrcpt (cashrcpt_cust_id, cashrcpt_number, cashrcpt_amount, cashrcpt_fundstype, cashrcpt_docnumber, cashrcpt_bankaccnt_id, cashrcpt_notes, cashrcpt_distdate, cashrcpt_salescat_id, cashrcpt_curr_id, cashrcpt_usecustdeposit) VALUES (public.getcustid((new.customer_number)::text), (SELECT public.fetchcashrcptnumber() AS fetchcashrcptnumber), COALESCE(new.amount_received, (0)::numeric), CASE WHEN ((new.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((new.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((new.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((new.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((new.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((new.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((new.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((new.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((new.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, COALESCE(new.check_document_number, ''::character varying), public.getbankaccntid(new.post_to), COALESCE(new.notes, ''::text), CASE WHEN (new.distribution_date > ''::text) THEN ((new.distribution_date)::date)::timestamp with time zone ELSE now() END, COALESCE(public.getsalescatid(new.sales_category), (-1)), public.getcurrid((new.currency)::text), CASE WHEN (new.apply_balance_as = 'Customer Deposit'::text) THEN true ELSE false END);
116639
116640
116641 --
116642 -- TOC entry 8710 (class 2618 OID 146571905)
116643 -- Dependencies: 270 270 270 270 270 270 270 270 269 1664 1660 270 8894
116644 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116645 --
116646
116647 CREATE RULE "_INSERT" AS ON INSERT TO cashreceiptapply DO INSTEAD INSERT INTO public.cashrcptitem (cashrcptitem_cashrcpt_id, cashrcptitem_aropen_id, cashrcptitem_amount, cashrcptitem_discount) VALUES (public.getcashrcptid((new.customer_number)::text, CASE WHEN ((new.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((new.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((new.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((new.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((new.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((new.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((new.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((new.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((new.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (new.check_document_number)::text), public.getaropenid((new.customer_number)::text, (new.doc_type)::bpchar, (new.doc_number)::text), COALESCE(new.amount_to_apply, (0)::numeric), COALESCE(new.cashrcptitem_discount, (0)::numeric));
116648
116649
116650 --
116651 -- TOC entry 8711 (class 2618 OID 146571907)
116652 -- Dependencies: 272 272 272 272 272 272 272 271 1700 1664 272 8894
116653 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116654 --
116655
116656 CREATE RULE "_INSERT" AS ON INSERT TO cashreceiptapplymisc DO INSTEAD INSERT INTO public.cashrcptmisc (cashrcptmisc_cashrcpt_id, cashrcptmisc_accnt_id, cashrcptmisc_amount, cashrcptmisc_notes) VALUES (public.getcashrcptid((new.customer_number)::text, CASE WHEN ((new.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((new.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((new.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((new.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((new.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((new.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((new.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((new.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((new.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (new.check_document_number)::text), public.getglaccntid((new.account)::text), COALESCE(new.amount_to_distribute, (0)::numeric), COALESCE(new.notes, ''::text));
116657
116658
116659 --
116660 -- TOC entry 8712 (class 2618 OID 146571909)
116661 -- Dependencies: 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 2161 2158 1680 1658 273 8894
116662 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116663 --
116664
116665 CREATE RULE "_INSERT" AS ON INSERT TO contact DO INSTEAD SELECT public.savecntct(NULL::integer, (new.contact_number)::text, public.getcrmacctid(new.crm_account), public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.address_change), new.honorific, new.first, new.middle, new.last, new.suffix, new.initials, COALESCE(new.active, true), new.voice, new.alternate, new.fax, new.email, new.web, new.notes, new.job_title, new.contact_change) AS savecntct;
116666
116667
116668 --
116669 -- TOC entry 8713 (class 2618 OID 146571910)
116670 -- Dependencies: 274 274 274 274 237 1670 1665 274 8894
116671 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116672 --
116673
116674 CREATE RULE "_INSERT" AS ON INSERT TO contactchar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('CNTCT'::text, public.getcntctid(new.contact_number), public.getcharid((new.characteristic)::text, 'CNTCT'::text), new.value, false);
116675
116676
116677 --
116678 -- TOC entry 8714 (class 2618 OID 146571911)
116679 -- Dependencies: 275 275 275 275 275 275 240 1670 1669 910 275 8894
116680 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116681 --
116682
116683 CREATE RULE "_INSERT" AS ON INSERT TO contactcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'T'::text, public.getcntctid(new.contact_number), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116684
116685
116686 --
116687 -- TOC entry 8715 (class 2618 OID 146571912)
116688 -- Dependencies: 221 221 1816 221 8894
116689 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116690 --
116691
116692 CREATE RULE "_INSERT" AS ON INSERT TO creditmemo DO INSTEAD SELECT public.insertcreditmemo(new.*) AS insertcreditmemo;
116693
116694
116695 --
116696 -- TOC entry 8716 (class 2618 OID 146571913)
116697 -- Dependencies: 223 223 1817 223 8894
116698 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116699 --
116700
116701 CREATE RULE "_INSERT" AS ON INSERT TO creditmemoline DO INSTEAD SELECT public.insertcreditmemoline(new.*) AS insertcreditmemoline;
116702
116703
116704 --
116705 -- TOC entry 8717 (class 2618 OID 146571914)
116706 -- Dependencies: 276 276 276 276 237 1682 1665 276 8894
116707 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116708 --
116709
116710 CREATE RULE "_INSERT" AS ON INSERT TO custchar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('C'::text, public.getcustid((new.customer_number)::text), public.getcharid((new.characteristic)::text, 'C'::text), new.value, false);
116711
116712
116713 --
116714 -- TOC entry 8718 (class 2618 OID 146571915)
116715 -- Dependencies: 277 277 277 277 277 277 240 1682 1669 910 277 8894
116716 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116717 --
116718
116719 CREATE RULE "_INSERT" AS ON INSERT TO custcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'C'::text, public.getcustid((new.customer_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116720
116721
116722 --
116723 -- TOC entry 8719 (class 2618 OID 146571916)
116724 -- Dependencies: 279 279 279 279 279 279 279 279 279 279 279 279 279 279 279 1815 279 8894
116725 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116726 --
116727
116728 CREATE RULE "_INSERT" AS ON INSERT TO custcreditcard DO INSTEAD SELECT public.insertccard((new.customer_number)::text, new.active, new.credit_card_type, new.credit_card_number, new.name, new.street_address1, new.street_address2, new.city, new.state, new.postal_code, new.country, new.expiration_month, new.expiration_year, new.key) AS insertccard;
116729
116730
116731 --
116732 -- TOC entry 8720 (class 2618 OID 146571917)
116733 -- Dependencies: 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 216 216 213 2162 2158 1780 1769 1768 1754 1753 1749 1686 1681 1671 1658 1547 1546 1545 1539 1537 907 283 8894
116734 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116735 --
116736
116737 CREATE RULE "_INSERT" AS ON INSERT TO customer DO INSTEAD INSERT INTO public.custinfo (cust_active, cust_custtype_id, cust_salesrep_id, cust_commprcnt, cust_name, cust_creditlmt, cust_creditrating, cust_backorder, cust_partialship, cust_terms_id, cust_discntprcnt, cust_balmethod, cust_ffshipto, cust_shipform_id, cust_shipvia, cust_blanketpos, cust_shipchrg_id, cust_creditstatus, cust_comments, cust_ffbillto, cust_usespos, cust_number, cust_autoupdatestatus, cust_autoholdorders, cust_preferred_warehous_id, cust_curr_id, cust_creditlmt_curr_id, cust_cntct_id, cust_corrcntct_id, cust_taxzone_id, cust_gracedays) VALUES (COALESCE(new.active, true), COALESCE((public.getcusttypeid(new.customer_type))::numeric, public.fetchmetricvalue('DefaultCustType'::text)), COALESCE((public.getsalesrepid(new.sales_rep))::numeric, public.fetchmetricvalue('DefaultSalesRep'::text)), COALESCE((new.commission * 0.01), (SELECT salesrep.salesrep_commission FROM public.salesrep WHERE (salesrep.salesrep_id = public.getsalesrepid(new.sales_rep)))), COALESCE(new.customer_name, ''::text), COALESCE((new.credit_limit)::numeric, public.fetchmetricvalue('SOCreditLimit'::text)), COALESCE(new.credit_rating, public.fetchmetrictext('SOCreditRate'::text)), COALESCE(new.accepts_backorders, public.fetchmetricbool('DefaultBackOrders'::text), false), COALESCE(new.accepts_partial_shipments, public.fetchmetricbool('DefaultPartialShipments'::text), false), COALESCE((public.gettermsid(new.default_terms))::numeric, public.fetchmetricvalue('DefaultTerms'::text)), COALESCE(new.default_discount, (0)::numeric), CASE WHEN (new.balance_method = 'Balance Forward'::text) THEN 'B'::text WHEN (new.balance_method = 'Open Items'::text) THEN 'O'::text ELSE COALESCE(public.fetchmetrictext('DefaultBalanceMethod'::text), 'B'::text) END, COALESCE(new.allow_free_form_shipto, public.fetchmetricbool('DefaultFreeFormShiptos'::text), false), COALESCE((public.getshipformid(new.ship_form))::numeric, public.fetchmetricvalue('DefaultShipFormId'::text)), COALESCE(new.ship_via, public.fetchdefaultshipvia()), COALESCE(new.uses_blanket_pos, false), COALESCE(public.getshipchrgid(new.shipping_charges), (-1)), CASE WHEN (new.credit_status = 'On Credit Warning'::text) THEN 'W'::text WHEN (new.credit_status = 'On Credit Hold'::text) THEN 'H'::text ELSE 'G'::text END, COALESCE(new.notes, ''::text), COALESCE(new.allow_free_form_billto, false), COALESCE(new.uses_purchase_orders, false), COALESCE(upper((new.customer_number)::text), (public.fetchcrmaccountnumber())::text), COALESCE(new.credit_status_exceed_warn, false), COALESCE(new.credit_status_exceed_hold, false), COALESCE(public.getwarehousid(new.preferred_selling_site, 'ACTIVE'::text), (-1)), COALESCE(public.getcurrid((new.default_currency)::text), public.basecurrid()), COALESCE(public.getcurrid((new.credit_limit_currency)::text), public.basecurrid()), public.savecntct(public.getcntctid(new.billing_contact_number, false), new.billing_contact_number, public.saveaddr(public.getaddrid(new.billing_contact_address_number), new.billing_contact_address_number, new.billing_contact_address1, new.billing_contact_address2, new.billing_contact_address3, new.billing_contact_city, new.billing_contact_state, new.billing_contact_postalcode, new.billing_contact_country, new.billing_contact_address_change), new.billing_contact_honorific, new.billing_contact_first, new.billing_contact_middle, new.billing_contact_last, new.billing_contact_suffix, new.billing_contact_voice, new.billing_contact_alternate, new.billing_contact_fax, new.billing_contact_email, new.billing_contact_web, new.billing_contact_job_title, new.billing_contact_change), public.savecntct(public.getcntctid(new.correspond_contact_number, false), new.correspond_contact_number, public.saveaddr(public.getaddrid(new.correspond_contact_address_number), new.correspond_contact_address_number, new.correspond_contact_address1, new.correspond_contact_address2, new.correspond_contact_address3, new.correspond_contact_city, new.correspond_contact_state, new.correspond_contact_postalcode, new.correspond_contact_country, new.correspond_contact_address_change), new.correspond_contact_honorific, new.correspond_contact_first, new.correspond_contact_middle, new.correspond_contact_last, new.correspond_contact_suffix, new.correspond_contact_voice, new.correspond_contact_alternate, new.correspond_contact_fax, new.correspond_contact_email, new.correspond_contact_web, new.correspond_contact_job_title, new.correspond_contact_change), public.gettaxzoneid(new.default_tax_zone), CASE WHEN (COALESCE(new.alternate_grace_days, 0) > 0) THEN new.alternate_grace_days ELSE NULL::integer END);
116738
116739
116740 --
116741 -- TOC entry 8721 (class 2618 OID 146571919)
116742 -- Dependencies: 286 286 286 286 286 286 286 285 213 213 2233 1765 1682 1519 286 8894
116743 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116744 --
116745
116746 CREATE RULE "_INSERT" AS ON INSERT TO customertaxreg DO INSTEAD INSERT INTO public.taxreg (taxreg_rel_id, taxreg_rel_type, taxreg_taxauth_id, taxreg_taxzone_id, taxreg_number, taxreg_effective, taxreg_expires, taxreg_notes) VALUES (public.getcustid((new.customer_number)::text), 'C'::bpchar, public.gettaxauthid((new.tax_authority)::text), (SELECT custinfo.cust_taxzone_id FROM public.custinfo WHERE (custinfo.cust_id = public.getcustid((new.customer_number)::text))), COALESCE(new.registration_number, ''::text), CASE WHEN (new.start_date = 'Always'::text) THEN public.startoftime() ELSE COALESCE((new.start_date)::date, public.startoftime()) END, CASE WHEN (new.end_date = 'Never'::text) THEN public.endoftime() ELSE COALESCE((new.end_date)::date, public.endoftime()) END, new.notes);
116747
116748
116749 --
116750 -- TOC entry 8722 (class 2618 OID 146571921)
116751 -- Dependencies: 287 287 287 287 280 287 8894
116752 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116753 --
116754
116755 CREATE RULE "_INSERT" AS ON INSERT TO customertype DO INSTEAD INSERT INTO public.custtype (custtype_code, custtype_descrip, custtype_char) VALUES (new.code, COALESCE(new.description, ''::text), COALESCE(new.enable_characteristics_profile, false));
116756
116757
116758 --
116759 -- TOC entry 8723 (class 2618 OID 146571922)
116760 -- Dependencies: 288 288 288 288 288 237 1686 1665 288 8894
116761 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116762 --
116763
116764 CREATE RULE "_INSERT" AS ON INSERT TO customertypechar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('CT'::text, public.getcusttypeid((new.customer_type)::text), public.getcharid((new.characteristic)::text, 'CT'::text), new.value, COALESCE(new.is_default, false));
116765
116766
116767 --
116768 -- TOC entry 8724 (class 2618 OID 146571923)
116769 -- Dependencies: 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 219 219 213 213 213 213 213 213 2162 2158 1768 1759 1754 1753 1749 1688 1682 1670 1658 289 8894
116770 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116771 --
116772
116773 CREATE RULE "_INSERT" AS ON INSERT TO custshipto DO INSTEAD INSERT INTO public.shiptoinfo (shipto_cust_id, shipto_name, shipto_salesrep_id, shipto_comments, shipto_shipcomments, shipto_shipzone_id, shipto_shipvia, shipto_commission, shipto_shipform_id, shipto_shipchrg_id, shipto_active, shipto_default, shipto_num, shipto_ediprofile_id, shipto_cntct_id, shipto_addr_id, shipto_taxzone_id) VALUES (public.getcustid((new.customer_number)::text), COALESCE(new.name, ''::text), COALESCE(public.getsalesrepid(new.sales_rep), (SELECT custinfo.cust_salesrep_id FROM public.custinfo WHERE (custinfo.cust_id = public.getcustid((new.customer_number)::text)))), COALESCE(new.general_notes, ''::text), COALESCE(new.shipping_notes, ''::text), public.getshipzoneid(new.zone), COALESCE(new.ship_via, (SELECT custinfo.cust_shipvia FROM public.custinfo WHERE (custinfo.cust_id = public.getcustid((new.customer_number)::text)))), COALESCE((new.commission / 100.0), (0)::numeric), COALESCE(public.getshipformid(new.ship_form), (SELECT custinfo.cust_shipform_id FROM public.custinfo WHERE (custinfo.cust_id = public.getcustid((new.customer_number)::text)))), COALESCE(public.getshipchrgid(new.shipping_charges), (SELECT custinfo.cust_shipchrg_id FROM public.custinfo WHERE (custinfo.cust_id = public.getcustid((new.customer_number)::text)))), COALESCE(new.active, true), COALESCE(new.default_flag, false), COALESCE(new.shipto_number, (((SELECT (COALESCE(max((shiptoinfo.shipto_num)::integer), 0) + 1) FROM public.shiptoinfo WHERE ((shiptoinfo.shipto_cust_id = public.getcustid((new.customer_number)::text)) AND (shiptoinfo.shipto_num ~ '^[0-9]*$'::text))))::text)::character varying), CASE WHEN (new.edi_profile = 'No EDI'::text) THEN (-1) WHEN (new.edi_profile = 'Use Customer Master'::text) THEN (-2) ELSE public.getediprofileid(new.edi_profile) END, public.savecntct(public.getcntctid(new.contact_number), new.contact_number, NULL::integer, new.honorific, new.first, new.middle, new.last, new.suffix, new.phone, NULL::text, new.fax, new.email, NULL::text, new.job_title, new.contact_change), public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.address_change), COALESCE(public.gettaxzoneid(new.tax_zone), (SELECT custinfo.cust_taxzone_id FROM public.custinfo WHERE (custinfo.cust_id = public.getcustid((new.customer_number)::text)))));
116774
116775
116776 --
116777 -- TOC entry 8725 (class 2618 OID 146571925)
116778 -- Dependencies: 290 290 290 290 285 1765 1682 290 8894
116779 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116780 --
116781
116782 CREATE RULE "_INSERT" AS ON INSERT TO custtax DO INSTEAD INSERT INTO public.taxreg (taxreg_rel_type, taxreg_rel_id, taxreg_taxauth_id, taxreg_number) VALUES ('C'::bpchar, public.getcustid((new.customer_number)::text), public.gettaxauthid((new.tax_authority)::text), new.registration_number);
116783
116784
116785 --
116786 -- TOC entry 8726 (class 2618 OID 146571926)
116787 -- Dependencies: 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 292 292 2162 2158 1780 1752 1702 1687 1681 1670 1658 907 294 8894
116788 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116789 --
116790
116791 CREATE RULE "_INSERT" AS ON INSERT TO employee DO INSTEAD INSERT INTO public.emp (emp_code, emp_number, emp_active, emp_cntct_id, emp_warehous_id, emp_mgr_emp_id, emp_wage_type, emp_wage, emp_wage_curr_id, emp_wage_period, emp_dept_id, emp_shift_id, emp_image_id, emp_extrate, emp_extrate_period, emp_startdate, emp_notes) VALUES (new.code, new.number, COALESCE(new.active, true), public.savecntct(public.getcntctid(new.contact_number), new.contact_number, public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change), new.honorific, new.first, new.middle, new.last, new.suffix, new.voice, new.alternate, new.fax, new.email, new.web, new.job_title, new.contact_change), public.getwarehousid(new.site, 'ALL'::text), (SELECT emp.emp_id FROM public.emp WHERE (emp.emp_code = new.manager_code)), CASE WHEN (new.wage_type = 'Hourly'::text) THEN 'H'::text WHEN (new.wage_type = 'Salaried'::text) THEN 'S'::text ELSE NULL::text END, new.wage, COALESCE(public.getcurrid((new.wage_currency)::text), public.basecurrid()), CASE WHEN (new.wage_period = 'Hour'::text) THEN 'H'::text WHEN (new.wage_period = 'Day'::text) THEN 'D'::text WHEN (new.wage_period = 'Week'::text) THEN 'W'::text WHEN (new.wage_period = 'Biweek'::text) THEN 'BW'::text WHEN (new.wage_period = 'Month'::text) THEN 'M'::text WHEN (new.wage_period = 'Year'::text) THEN 'Y'::text ELSE NULL::text END, public.getdeptid(new.department), public.getshiftid(new.shift), public.getimageid(new.image), new.rate, CASE WHEN (new.billing_period = 'Hour'::text) THEN 'H'::text WHEN (new.billing_period = 'Day'::text) THEN 'D'::text WHEN (new.billing_period = 'Week'::text) THEN 'W'::text WHEN (new.billing_period = 'Biweek'::text) THEN 'BW'::text WHEN (new.billing_period = 'Month'::text) THEN 'M'::text WHEN (new.billing_period = 'Year'::text) THEN 'Y'::text ELSE NULL::text END, new.start_date, COALESCE(new.notes, ''::text));
116792
116793
116794 --
116795 -- TOC entry 8727 (class 2618 OID 146571928)
116796 -- Dependencies: 295 295 295 295 237 1690 1665 295 8894
116797 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116798 --
116799
116800 CREATE RULE "_INSERT" AS ON INSERT TO employeechar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('EMP'::text, public.getempid((new.employee_code)::text), public.getcharid((new.characteristic)::text, 'EMP'::text), new.value, false);
116801
116802
116803 --
116804 -- TOC entry 8728 (class 2618 OID 146571929)
116805 -- Dependencies: 296 296 296 296 296 296 240 1690 1669 910 296 8894
116806 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116807 --
116808
116809 CREATE RULE "_INSERT" AS ON INSERT TO employeecomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'EMP'::text, public.getempid((new.code)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid((new.type)::text), new.text);
116810
116811
116812 --
116813 -- TOC entry 8729 (class 2618 OID 146571930)
116814 -- Dependencies: 298 298 298 298 298 298 298 298 298 298 298 298 298 298 298 297 1681 298 8894
116815 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116816 --
116817
116818 CREATE RULE "_INSERT" AS ON INSERT TO extshipmaint DO INSTEAD INSERT INTO public.shipdata (shipdata_cohead_number, shipdata_shiphead_number, shipdata_void_ind, shipdata_shipper, shipdata_billing_option, shipdata_weight, shipdata_base_freight, shipdata_base_freight_curr_id, shipdata_total_freight, shipdata_total_freight_curr_id, shipdata_package_type, shipdata_cosmisc_tracknum, shipdata_cosmisc_packnum_tracknum, shipdata_lastupdated) VALUES (new.so_number, new.shipment_number, new.void, new.shipper, new.billing_option, new.weight, new.base_freight, public.getcurrid((new.base_freight_currency)::text), new.total_freight, public.getcurrid((new.total_freight_currency)::text), new.package_type, new.tracking_number, new.package_tracking_number, new.last_updated);
116819
116820
116821 --
116822 -- TOC entry 8730 (class 2618 OID 146571931)
116823 -- Dependencies: 302 302 302 302 302 302 302 302 302 300 1780 1759 1684 1697 302 8894
116824 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116825 --
116826
116827 CREATE RULE "_INSERT" AS ON INSERT TO freightpricingscheduleitem DO INSTEAD INSERT INTO public.ipsfreight (ipsfreight_ipshead_id, ipsfreight_qtybreak, ipsfreight_price, ipsfreight_type, ipsfreight_warehous_id, ipsfreight_shipzone_id, ipsfreight_freightclass_id, ipsfreight_shipvia) VALUES (public.getipsheadid((new.pricing_schedule)::text), new.qty_break, new.price, CASE WHEN (new.price_type = 'Flat Rate'::text) THEN 'F'::text ELSE 'P'::text END, CASE WHEN (new.from_site = 'Any'::text) THEN NULL::integer ELSE public.getwarehousid(new.from_site, 'All'::text) END, CASE WHEN (new.to_shipzone = 'Any'::text) THEN NULL::integer ELSE public.getshipzoneid(new.to_shipzone) END, CASE WHEN (new.freight_class = 'Any'::text) THEN NULL::integer ELSE public.getfreightclassid(new.freight_class) END, CASE WHEN (new.ship_via = 'Any'::text) THEN NULL::text ELSE new.ship_via END);
116828
116829
116830 --
116831 -- TOC entry 8731 (class 2618 OID 146571932)
116832 -- Dependencies: 303 303 303 303 303 303 303 303 303 303 303 262 303 8894
116833 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116834 --
116835
116836 CREATE RULE "_INSERT" AS ON INSERT TO glaccount DO INSTEAD INSERT INTO public.accnt (accnt_number, accnt_descrip, accnt_comments, accnt_profit, accnt_sub, accnt_type, accnt_extref, accnt_company, accnt_forwardupdate, accnt_subaccnttype_code) VALUES (COALESCE(new.account_number, ''::character varying), COALESCE(new.description, ''::text), COALESCE(new.notes, ''::text), new.profit_center, new.sub_account, CASE WHEN (new.type = 'Asset'::text) THEN 'A'::text WHEN (new.type = 'Liability'::text) THEN 'L'::text WHEN (new.type = 'Expense'::text) THEN 'E'::text WHEN (new.type = 'Revenue'::text) THEN 'R'::text WHEN (new.type = 'Equity'::text) THEN 'Q'::text ELSE NULL::text END, COALESCE(new.ext_reference, ''::text), new.company, COALESCE(new.forward_update_trial_balances, false), COALESCE(new.sub_type, ''::text));
116837
116838
116839 --
116840 -- TOC entry 8732 (class 2618 OID 146571934)
116841 -- Dependencies: 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 206 2162 1721 1714 1707 1706 1705 1703 1680 1670 308 8894
116842 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116843 --
116844
116845 CREATE RULE "_INSERT" AS ON INSERT TO incident DO INSTEAD INSERT INTO public.incdt (incdt_number, incdt_crmacct_id, incdt_cntct_id, incdt_summary, incdt_descrip, incdt_item_id, incdt_status, incdt_assigned_username, incdt_incdtcat_id, incdt_incdtseverity_id, incdt_incdtpriority_id, incdt_incdtresolution_id, incdt_lotserial, incdt_ls_id) VALUES (new.incident_number, public.getcrmacctid(new.crm_account), public.savecntct(public.getcntctid(new.contact_number), new.contact_number, NULL::integer, new.honorific, new.first, new.middle, new.last, new.suffix, new.phone, NULL::text, new.fax, new.email, NULL::text, new.job_title, new.contact_change), COALESCE(new.description, ''::text), COALESCE(new.notes, ''::text), public.getitemid(new.item_number), CASE WHEN (new.status = 'New'::text) THEN 'N'::text WHEN (new.status = 'Feedback'::text) THEN 'F'::text WHEN (new.status = 'Confirmed'::text) THEN 'C'::text WHEN (new.status = 'Assigned'::text) THEN 'A'::text WHEN (new.status = 'Resolved'::text) THEN 'R'::text WHEN (new.status = 'Closed'::text) THEN 'L'::text ELSE ''::text END, COALESCE(new.assigned_to, ''::text), public.getincdtcatid(new.category), public.getincdtseverityid(new.severity), public.getincdtpriorityid(new.priority), public.getincdtresolutionid(new.resolution), COALESCE(new.lot_serial_number, ''::text), public.getlotserialid(new.item_number, new.lot_serial_number));
116846
116847
116848 --
116849 -- TOC entry 8733 (class 2618 OID 146571936)
116850 -- Dependencies: 309 309 309 309 237 1708 1665 309 8894
116851 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116852 --
116853
116854 CREATE RULE "_INSERT" AS ON INSERT TO incidentchar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('INCDT'::text, public.getincidentid(new.incident_number), public.getcharid((new.characteristic)::text, 'INCDT'::text), new.value, false);
116855
116856
116857 --
116858 -- TOC entry 8734 (class 2618 OID 146571937)
116859 -- Dependencies: 310 310 310 310 310 310 310 240 1708 1669 910 310 8894
116860 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116861 --
116862
116863 CREATE RULE "_INSERT" AS ON INSERT TO incidentcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text, comment_public) VALUES (COALESCE(new.date, now()), 'INCDT'::text, public.getincidentid(new.incident_number), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text, COALESCE(new.public, true));
116864
116865
116866 --
116867 -- TOC entry 8735 (class 2618 OID 146571938)
116868 -- Dependencies: 311 311 311 311 245 1708 311 8894
116869 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116870 --
116871
116872 CREATE RULE "_INSERT" AS ON INSERT TO incidentfile DO INSTEAD INSERT INTO public.url (url_source_id, url_source, url_title, url_url) VALUES (public.getincidentid(new.incident_number), 'INCDT'::text, new.title, new.url);
116873
116874
116875 --
116876 -- TOC entry 8736 (class 2618 OID 146571939)
116877 -- Dependencies: 312 312 312 2165 1708 1702 312 8894
116878 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116879 --
116880
116881 CREATE RULE "_INSERT" AS ON INSERT TO incidentimage DO INSTEAD SELECT public.saveimageass('INCDT'::text, public.getincidentid(new.incident_number), 'M'::bpchar, public.getimageid(new.image_name)) AS saveimageass;
116882
116883
116884 --
116885 -- TOC entry 8737 (class 2618 OID 146571940)
116886 -- Dependencies: 228 228 1829 228 8894
116887 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116888 --
116889
116890 CREATE RULE "_INSERT" AS ON INSERT TO invoice DO INSTEAD SELECT public.insertinvoice(new.*) AS insertinvoice;
116891
116892
116893 --
116894 -- TOC entry 8738 (class 2618 OID 146571941)
116895 -- Dependencies: 230 230 1830 230 8894
116896 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116897 --
116898
116899 CREATE RULE "_INSERT" AS ON INSERT TO invoiceline DO INSTEAD SELECT public.insertinvoicelineitem(new.*) AS insertinvoicelineitem;
116900
116901
116902 --
116903 -- TOC entry 8739 (class 2618 OID 146571942)
116904 -- Dependencies: 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 191 1771 1738 1666 315 8894
116905 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116906 --
116907
116908 CREATE RULE "_INSERT" AS ON INSERT TO item DO INSTEAD INSERT INTO public.item (item_number, item_active, item_descrip1, item_descrip2, item_type, item_maxcost, item_classcode_id, item_inv_uom_id, item_picklist, item_fractional, item_config, item_sold, item_prodcat_id, item_exclusive, item_listprice, item_listcost, item_price_uom_id, item_upccode, item_prodweight, item_packweight, item_comments, item_extdescrip) VALUES (upper((new.item_number)::text), COALESCE(new.active, true), COALESCE(new.description1, ''::text), COALESCE(new.description2, ''::text), CASE WHEN (new.item_type = 'Purchased'::text) THEN 'P'::text WHEN (new.item_type = 'Manufactured'::text) THEN 'M'::text WHEN (new.item_type = 'Job'::text) THEN 'J'::text WHEN (new.item_type = 'Kit'::text) THEN 'K'::text WHEN (new.item_type = 'Phantom'::text) THEN 'F'::text WHEN (new.item_type = 'Reference'::text) THEN 'R'::text WHEN (new.item_type = 'Costing'::text) THEN 'S'::text WHEN (new.item_type = 'Tooling'::text) THEN 'T'::text WHEN (new.item_type = 'Outside Process'::text) THEN 'O'::text WHEN (new.item_type = 'Planning'::text) THEN 'L'::text WHEN (new.item_type = 'Breeder'::text) THEN 'B'::text WHEN (new.item_type = 'Co-Product'::text) THEN 'C'::text WHEN (new.item_type = 'By-Product'::text) THEN 'Y'::text ELSE NULL::text END, COALESCE(new.maximum_desired_cost, (0)::numeric), public.getclasscodeid(new.class_code), public.getuomid(new.inventory_uom), COALESCE(new.pick_list_item, true), COALESCE(new.fractional, false), COALESCE(new.configured, false), COALESCE(new.item_is_sold, true), COALESCE(public.getprodcatid(new.product_category), (-1)), COALESCE(new.exclusive, false), COALESCE(new.list_price, (0)::numeric), COALESCE(new.list_cost, (0)::numeric), COALESCE(public.getuomid(new.list_price_uom), public.getuomid(new.inventory_uom)), new.upc_code, COALESCE(new.product_weight, (0)::numeric), COALESCE(new.packaging_weight, (0)::numeric), new.notes, new.ext_description);
116909
116910
116911 --
116912 -- TOC entry 8740 (class 2618 OID 146571944)
116913 -- Dependencies: 317 317 317 317 317 317 317 316 1714 317 8894
116914 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116915 --
116916
116917 CREATE RULE "_INSERT" AS ON INSERT TO itemalias DO INSTEAD INSERT INTO public.itemalias (itemalias_item_id, itemalias_number, itemalias_usedescrip, itemalias_descrip1, itemalias_descrip2, itemalias_comments) VALUES (public.getitemid((new.item_number)::text), new.alias_number, COALESCE(new.use_description, false), COALESCE(new.description1, ''::text), COALESCE(new.description2, ''::text), new.comments);
116918
116919
116920 --
116921 -- TOC entry 8741 (class 2618 OID 146571945)
116922 -- Dependencies: 318 318 318 318 318 237 1714 1665 318 8894
116923 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116924 --
116925
116926 CREATE RULE "_INSERT" AS ON INSERT TO itemchar DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value, charass_default) VALUES ('I'::text, public.getitemid((new.item_number)::text), public.getcharid((new.characteristic)::text, 'I'::text), new.value, COALESCE(new.is_default, false));
116927
116928
116929 --
116930 -- TOC entry 8742 (class 2618 OID 146571946)
116931 -- Dependencies: 319 319 319 319 319 319 240 1714 1669 910 319 8894
116932 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116933 --
116934
116935 CREATE RULE "_INSERT" AS ON INSERT TO itemcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'IS'::text, public.getitemid((new.item_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116936
116937
116938 --
116939 -- TOC entry 8743 (class 2618 OID 146571947)
116940 -- Dependencies: 322 322 322 322 322 322 1831 1714 1681 1679 322 8894
116941 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116942 --
116943
116944 CREATE RULE "_INSERT" AS ON INSERT TO itemcost DO INSTEAD SELECT public.insertitemcost(public.getitemid((new.item_number)::text), public.getcostelemid((new.costing_element)::text), public.getcurrid((new.currency)::text), new.actual_cost, new.post_to_standard) AS insertitemcost;
116945
116946
116947 --
116948 -- TOC entry 8744 (class 2618 OID 146571948)
116949 -- Dependencies: 323 323 323 323 245 1714 323 8894
116950 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116951 --
116952
116953 CREATE RULE "_INSERT" AS ON INSERT TO itemfile DO INSTEAD INSERT INTO public.url (url_source_id, url_source, url_title, url_url) VALUES (public.getitemid((new.item_number)::text), 'I'::text, new.title, new.url);
116954
116955
116956 --
116957 -- TOC entry 8745 (class 2618 OID 146571949)
116958 -- Dependencies: 324 324 324 324 2165 1714 1702 324 8894
116959 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116960 --
116961
116962 CREATE RULE "_INSERT" AS ON INSERT TO itemimage DO INSTEAD SELECT public.saveimageass('I'::text, public.getitemid((new.item_number)::text), (CASE WHEN (new.purpose = 'Product Description'::text) THEN 'P'::text WHEN (new.purpose = 'Inventory Description'::text) THEN 'I'::text WHEN (new.purpose = 'Engineering Reference'::text) THEN 'E'::text WHEN (new.purpose = 'Miscellaneous'::text) THEN 'M'::text ELSE 'X'::text END)::bpchar, public.getimageid(new.image_name)) AS saveimageass;
116963
116964
116965 --
116966 -- TOC entry 8746 (class 2618 OID 146571950)
116967 -- Dependencies: 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 192 1780 1732 1693 1716 1714 1678 1547 327 8894
116968 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116969 --
116970
116971 CREATE RULE "_INSERT" AS ON INSERT TO itemsite DO INSTEAD INSERT INTO public.itemsite (itemsite_item_id, itemsite_warehous_id, itemsite_active, itemsite_dropship, itemsite_posupply, itemsite_createpr, itemsite_wosupply, itemsite_createwo, itemsite_createsopr, itemsite_createsopo, itemsite_sold, itemsite_soldranking, itemsite_costmethod, itemsite_controlmethod, itemsite_perishable, itemsite_plancode_id, itemsite_costcat_id, itemsite_loccntrl, itemsite_location_id, itemsite_recvlocation_id, itemsite_issuelocation_id, itemsite_location_dist, itemsite_recvlocation_dist, itemsite_issuelocation_dist, itemsite_location, itemsite_location_comments, itemsite_disallowblankwip, itemsite_stocked, itemsite_abcclass, itemsite_autoabcclass, itemsite_cyclecountfreq, itemsite_eventfence, itemsite_useparams, itemsite_reorderlevel, itemsite_ordertoqty, itemsite_minordqty, itemsite_maxordqty, itemsite_multordqty, itemsite_useparamsmanual, itemsite_ordergroup, itemsite_ordergroup_first, itemsite_mps_timefence, itemsite_leadtime, itemsite_safetystock, itemsite_supply_itemsite_id, itemsite_notes, itemsite_qtyonhand, itemsite_warrpurc, itemsite_autoreg, itemsite_freeze, itemsite_value, itemsite_planning_type) VALUES (public.getitemid((new.item_number)::text), public.getwarehousid((new.site)::text, 'ACTIVE'::text), COALESCE(new.active, true), COALESCE(new.dropship, false), COALESCE(new.po_supplied_at_site, false), COALESCE(new.create_prs, false), COALESCE(new.wo_supplied_at_site, false), COALESCE(new.create_wos, false), COALESCE(new.create_soprs, false), COALESCE(new.create_sopos, false), COALESCE(new.sold_from_site, true), COALESCE(new.ranking, 1), CASE WHEN (new.cost_method = 'None'::text) THEN 'N'::text WHEN (new.cost_method = 'Average'::text) THEN 'A'::text WHEN (new.cost_method = 'Standard'::text) THEN 'S'::text WHEN (new.cost_method = 'Job'::text) THEN 'J'::text ELSE NULL::text END, CASE WHEN (new.control_method = 'None'::text) THEN 'N'::text WHEN (new.control_method = 'Regular'::text) THEN 'R'::text WHEN (new.control_method = 'Serial #'::text) THEN 'S'::text WHEN (new.control_method = 'Lot #'::text) THEN 'L'::text ELSE NULL::text END, COALESCE(new.perishable, false), public.getplancodeid(new.planner_code), public.getcostcatid(new.cost_category), COALESCE(new.multiple_location_control, false), COALESCE(public.getlocationid((new.site)::text, new.location), (-1)), COALESCE(public.getlocationid((new.site)::text, new.receive_location), (-1)), COALESCE(public.getlocationid((new.site)::text, new.issue_location), (-1)), COALESCE(new.auto_distr_location, false), COALESCE(new.auto_distr_receive_location, false), COALESCE(new.auto_distr_issue_location, false), COALESCE(new.user_defined_location, ''::text), COALESCE(new.location_comment, ''::text), COALESCE(new.disallow_blank_wip_locations, false), COALESCE(new.stocked, false), COALESCE(new.abc_class, 'A'::bpchar), COALESCE(new.allow_automatic_updates, false), COALESCE(new.cycl_cnt_freq, 0), COALESCE((new.event_fence)::numeric, public.fetchmetricvalue('DefaultEventFence'::text)), COALESCE(new.enforce_order_parameters, false), COALESCE(new.reorder_level, (0)::numeric), COALESCE(new.order_up_to, (0)::numeric), COALESCE(new.minimum_order, (0)::numeric), COALESCE(new.maximum_order, (0)::numeric), COALESCE(new.order_multiple, (0)::numeric), COALESCE(new.enforce_on_manual_orders, false), COALESCE(new.group_mps_mrp_orders, 0), COALESCE(new.first_group, false), COALESCE(new.mps_time_fence, 0), COALESCE(new.lead_time, 0), COALESCE(new.safety_stock, (0)::numeric), CASE WHEN (new.supplied_from_site = 'None'::text) THEN NULL::integer WHEN (new.supplied_from_site = ''::text) THEN NULL::integer ELSE public.getitemsiteid(new.supplied_from_site, (new.item_number)::text) END, COALESCE(new.notes, ''::text), 0, COALESCE(new.require_warranty, false), COALESCE(new.auto_register, false), false, 0, CASE WHEN (new.planning_system = 'None'::text) THEN 'N'::text WHEN (new.planning_system = 'MPS'::text) THEN 'S'::text ELSE 'M'::text END);
116972
116973
116974 --
116975 -- TOC entry 8747 (class 2618 OID 146571952)
116976 -- Dependencies: 328 328 328 328 328 328 328 240 1716 1669 910 328 8894
116977 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116978 --
116979
116980 CREATE RULE "_INSERT" AS ON INSERT TO itemsitecomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'IS'::text, public.getitemsiteid((new.site)::text, (new.item_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
116981
116982
116983 --
116984 -- TOC entry 8748 (class 2618 OID 146571953)
116985 -- Dependencies: 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 330 1778 1714 1677 1676 1675 331 8894
116986 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116987 --
116988
116989 CREATE RULE "_INSERT" AS ON INSERT TO itemsource DO INSTEAD INSERT INTO public.itemsrc (itemsrc_item_id, itemsrc_vend_id, itemsrc_vend_item_number, itemsrc_vend_item_descrip, itemsrc_comments, itemsrc_vend_uom, itemsrc_invvendoruomratio, itemsrc_minordqty, itemsrc_multordqty, itemsrc_leadtime, itemsrc_ranking, itemsrc_active, itemsrc_default, itemsrc_manuf_name, itemsrc_manuf_item_number, itemsrc_manuf_item_descrip, itemsrc_upccode, itemsrc_contrct_id, itemsrc_effective, itemsrc_expires) VALUES (public.getitemid((new.item_number)::text), public.getvendid((new.vendor)::text), new.vendor_item_number, COALESCE(new.vendor_description, ''::text), COALESCE(new.notes, ''::text), new.vendor_uom, new.inventory_vendor_uom_ratio, new.minimum_order, new.order_multiple, new.lead_time, new.vendor_ranking, COALESCE(new.active, true), COALESCE(new.itemsrc_default, true), COALESCE(new.manufacturer_name, ''::text), COALESCE(new.manufacturer_item_number, ''::text), new.manufacturer_description, new.bar_code, public.getcontrctid(new.contract_number), COALESCE(public.getcontrcteffective(new.contract_number), new.effective_date), COALESCE(public.getcontrctexpires(new.contract_number), new.expires_date));
116990
116991
116992 --
116993 -- TOC entry 8749 (class 2618 OID 146571955)
116994 -- Dependencies: 333 333 333 333 333 333 333 333 333 333 333 332 1780 1718 1681 333 8894
116995 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
116996 --
116997
116998 CREATE RULE "_INSERT" AS ON INSERT TO itemsourceprice DO INSTEAD INSERT INTO public.itemsrcp (itemsrcp_itemsrc_id, itemsrcp_qtybreak, itemsrcp_price, itemsrcp_curr_id, itemsrcp_updated, itemsrcp_dropship, itemsrcp_warehous_id, itemsrcp_type, itemsrcp_discntprcnt, itemsrcp_fixedamtdiscount) VALUES (public.getitemsrcid((new.item_number)::text, (new.vendor)::text), new.qty_break, new.price_per_unit, public.getcurrid((new.currency)::text), now(), COALESCE(new.dropship_only, false), CASE WHEN (new.pricing_site = 'All'::text) THEN (-1) ELSE COALESCE(public.getwarehousid(new.pricing_site, 'ALL'::text), (-1)) END, CASE WHEN (new.pricing_type = 'Discount'::text) THEN 'D'::text ELSE 'N'::text END, (COALESCE(new.discount_percent, 0.0) / 100.0), new.discount_fixed_amount);
116999
117000
117001 --
117002 -- TOC entry 8750 (class 2618 OID 146571957)
117003 -- Dependencies: 335 335 335 335 335 334 1714 335 8894
117004 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117005 --
117006
117007 CREATE RULE "_INSERT" AS ON INSERT TO itemsubstitute DO INSTEAD INSERT INTO public.itemsub (itemsub_parent_item_id, itemsub_sub_item_id, itemsub_uomratio, itemsub_rank) VALUES (public.getitemid((new.root_item_number)::text), public.getitemid((new.substitute_item_number)::text), COALESCE(new.sub_parent_uom_ratio, (1)::numeric), COALESCE(new.ranking, 1));
117008
117009
117010 --
117011 -- TOC entry 8751 (class 2618 OID 146571958)
117012 -- Dependencies: 337 337 337 337 336 1768 1767 1714 337 8894
117013 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117014 --
117015
117016 CREATE RULE "_INSERT" AS ON INSERT TO itemtaxtype DO INSTEAD INSERT INTO public.itemtax (itemtax_item_id, itemtax_taxzone_id, itemtax_taxtype_id) VALUES (public.getitemid((new.item_number)::text), CASE WHEN ((new.tax_zone)::text = 'Any'::text) THEN NULL::integer ELSE public.gettaxzoneid((new.tax_zone)::text) END, public.gettaxtypeid(new.tax_type));
117017
117018
117019 --
117020 -- TOC entry 8752 (class 2618 OID 146571959)
117021 -- Dependencies: 339 339 339 339 339 339 339 339 191 191 2172 1774 1771 1714 339 8894
117022 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117023 --
117024
117025 CREATE RULE "_INSERT" AS ON INSERT TO itemuomconversion DO INSTEAD SELECT public.saveitemuomconv(public.getitemid((new.item_number)::text), COALESCE(public.getuomid((new.uom)::text), (SELECT item.item_inv_uom_id FROM public.item WHERE (item.item_id = public.getitemid((new.item_number)::text)))), COALESCE(new.uom_value, (1)::numeric), COALESCE(public.getuomid(new.per_uom), (SELECT item.item_inv_uom_id FROM public.item WHERE (item.item_id = public.getitemid((new.item_number)::text)))), COALESCE(new.per_uom_value, (1)::numeric), COALESCE(new.fractional, false), public.getuomtypeid(new.selected_types)) AS saveitemuomconv;
117026
117027
117028 --
117029 -- TOC entry 8753 (class 2618 OID 146571960)
117030 -- Dependencies: 341 341 341 341 341 341 341 341 1820 1700 1681 1384 341 8894
117031 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117032 --
117033
117034 CREATE RULE "_INSERT" AS ON INSERT TO journalentry DO INSTEAD SELECT public.insertgltransaction('G/L'::text, 'JE'::text, new.doc_number, new.notes, public.getglaccntid(new.credit), public.getglaccntid(new.debit), (-1), public.currtobase(public.getcurrid((new.currency)::text), new.amount, new.dist_date), new.dist_date) AS insertgltransaction;
117035
117036
117037 --
117038 -- TOC entry 8754 (class 2618 OID 146571961)
117039 -- Dependencies: 344 344 344 344 344 344 344 344 344 344 342 1781 1780 344 8894
117040 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117041 --
117042
117043 CREATE RULE "_INSERT" AS ON INSERT TO location DO INSTEAD INSERT INTO public.location (location_warehous_id, location_name, location_descrip, location_restrict, location_netable, location_whsezone_id, location_aisle, location_rack, location_bin) VALUES (public.getwarehousid((new.site)::text, 'ACTIVE'::text), COALESCE(new.location, ''::character varying), COALESCE(new.description, ''::text), COALESCE(new.restricted, false), COALESCE(new.netable, true), public.getwhsezoneid((new.site)::text, new.zone), COALESCE(new.aisle, ''::character varying), COALESCE(new.rack, ''::character varying), COALESCE(new.bin, ''::character varying));
117044
117045
117046 --
117047 -- TOC entry 8755 (class 2618 OID 146571962)
117048 -- Dependencies: 345 825 825 825 345 345 345 345 193 193 2030 1716 910 345 8894
117049 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117050 --
117051
117052 CREATE RULE "_INSERT" AS ON INSERT TO misccounttag DO INSTEAD SELECT public.postmisccount(public.getitemsiteid(COALESCE(new.site, (SELECT whsinfo.warehous_code FROM public.usrpref, public.whsinfo WHERE (((usrpref.usrpref_username = public.geteffectivextuser()) AND (usrpref.usrpref_name = 'PreferredWarehouse'::text)) AND (whsinfo.warehous_id = (usrpref.usrpref_value)::integer)))), new.item_number), new.quantity, new.comment) AS postmisccount;
117053
117054
117055 --
117056 -- TOC entry 8756 (class 2618 OID 146571963)
117057 -- Dependencies: 346 632 346 346 346 346 346 301 1681 907 346 8894
117058 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117059 --
117060
117061 CREATE RULE "_INSERT" AS ON INSERT TO pricingschedule DO INSTEAD INSERT INTO public.ipshead (ipshead_id, ipshead_name, ipshead_descrip, ipshead_effective, ipshead_expires, ipshead_curr_id, ipshead_updated) VALUES (nextval('public.ipshead_ipshead_id_seq'::regclass), new.name, new.description, CASE WHEN (new.effective = 'Always'::text) THEN '1970-01-01'::date ELSE (COALESCE(new.effective, '1970-01-01'::text))::date END, CASE WHEN (new.expires = 'Never'::text) THEN '2100-01-01'::date ELSE (COALESCE(new.expires, '2100-01-01'::text))::date END, COALESCE(public.getcurrid((new.currency)::text), public.basecurrid()), now());
117062
117063
117064 --
117065 -- TOC entry 8757 (class 2618 OID 146571964)
117066 -- Dependencies: 348 348 348 348 348 348 348 347 1756 1684 1686 1682 348 8894
117067 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117068 --
117069
117070 CREATE RULE "_INSERT" AS ON INSERT TO pricingscheduleassign DO INSTEAD INSERT INTO public.ipsass (ipsass_ipshead_id, ipsass_cust_id, ipsass_custtype_id, ipsass_custtype_pattern, ipsass_shipto_id, ipsass_shipto_pattern) VALUES (public.getipsheadid((new.pricing_schedule)::text), CASE WHEN ((new.customer_number)::text = 'Any'::text) THEN (-1) ELSE public.getcustid((new.customer_number)::text) END, CASE WHEN ((new.customer_type)::text = 'N/A'::text) THEN (-1) ELSE public.getcusttypeid((new.customer_type)::text) END, new.customer_type_pattern, CASE WHEN (((new.customer_number)::text = 'Any'::text) OR ((new.customer_shipto)::text = 'Any'::text)) THEN (-1) ELSE public.getshiptoid((new.customer_number)::text, (new.customer_shipto)::text) END, new.customer_shipto_pattern);
117071
117072
117073 --
117074 -- TOC entry 8758 (class 2618 OID 146571965)
117075 -- Dependencies: 350 350 350 350 350 350 350 350 350 350 350 350 2164 2167 1771 1738 1714 1684 350 8894
117076 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117077 --
117078
117079 CREATE RULE "_INSERT" AS ON INSERT TO pricingscheduleitem DO INSTEAD SELECT CASE WHEN ((new.type)::text = 'Item'::text) THEN public.saveipsitem(NULL::integer, public.getipsheadid((new.pricing_schedule)::text), public.getitemid((new.item_number)::text), COALESCE(new.qty_break, (0)::numeric), COALESCE(new.price, (0)::numeric), public.getuomid((new.qty_uom)::text), public.getuomid((new.price_uom)::text), new.percent, new.fixedamt, CASE new.pricing_type WHEN 'Nominal'::text THEN 'N'::text WHEN 'Discount'::text THEN 'D'::text WHEN 'Markup'::text THEN 'M'::text ELSE '?'::text END) WHEN ((new.type)::text = 'Product Category'::text) THEN public.saveipsprodcat(NULL::integer, public.getipsheadid((new.pricing_schedule)::text), public.getprodcatid((new.product_category)::text), new.qty_break, new.percent, new.fixedamt, CASE new.pricing_type WHEN 'Nominal'::text THEN 'N'::text WHEN 'Discount'::text THEN 'D'::text WHEN 'Markup'::text THEN 'M'::text ELSE '?'::text END) ELSE NULL::integer END AS "case";
117080
117081
117082 --
117083 -- TOC entry 8759 (class 2618 OID 146571967)
117084 -- Dependencies: 352 352 352 352 352 352 352 352 352 351 1712 1665 352 8894
117085 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117086 --
117087
117088 CREATE RULE "_INSERT" AS ON INSERT TO pricingscheduleitemchar DO INSTEAD INSERT INTO public.ipsitemchar (ipsitemchar_ipsitem_id, ipsitemchar_char_id, ipsitemchar_value, ipsitemchar_price) VALUES (public.getipsitemid((new.pricing_schedule)::text, (new.item_number)::text, new.qty_break, (new.qty_uom)::text, (new.price_uom)::text), public.getcharid((new.characteristic)::text, 'I'::text), new.value, COALESCE(new.price, (0)::numeric));
117089
117090
117091 --
117092 -- TOC entry 8760 (class 2618 OID 146571968)
117093 -- Dependencies: 353 353 353 353 353 353 353 353 353 353 353 353 353 353 225 910 353 8894
117094 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117095 --
117096
117097 CREATE RULE "_INSERT" AS ON INSERT TO project DO INSTEAD INSERT INTO public.prj (prj_number, prj_name, prj_descrip, prj_owner_username, prj_username, prj_so, prj_wo, prj_po, prj_status, prj_due_date, prj_assigned_date, prj_start_date, prj_completed_date) VALUES (new.number, COALESCE(new.name, ''::text), COALESCE(new.description, ''::text), COALESCE(new.owner, public.geteffectivextuser()), COALESCE(new.assigned_to, public.geteffectivextuser()), COALESCE(new.sales_orders, true), COALESCE(new.work_orders, true), COALESCE(new.purchase_orders, true), CASE WHEN (new.status = 'In-Process'::text) THEN 'O'::text WHEN (new.status = 'Completed'::text) THEN 'C'::text ELSE 'P'::text END, new.due, new.assigned, new.started, new.completed);
117098
117099
117100 --
117101 -- TOC entry 8761 (class 2618 OID 146571970)
117102 -- Dependencies: 354 354 354 354 354 354 240 1736 1669 910 354 8894
117103 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117104 --
117105
117106 CREATE RULE "_INSERT" AS ON INSERT TO projectcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'J'::text, public.getprjid((new.project_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117107
117108
117109 --
117110 -- TOC entry 8762 (class 2618 OID 146571971)
117111 -- Dependencies: 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 357 356 2162 2158 1780 1768 1749 1670 1658 357 8894
117112 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117113 --
117114
117115 CREATE RULE "_INSERT" AS ON INSERT TO prospect DO INSTEAD INSERT INTO public.prospect (prospect_number, prospect_name, prospect_active, prospect_cntct_id, prospect_taxzone_id, prospect_salesrep_id, prospect_warehous_id, prospect_comments) VALUES (upper((new.prospect_number)::text), COALESCE(new.prospect_name, ''::text), COALESCE(new.active, true), public.savecntct(public.getcntctid(new.contact_number), new.contact_number, public.saveaddr(public.getaddrid(new.contact_address_number), new.contact_address_number, new.contact_address1, new.contact_address2, new.contact_address3, new.contact_city, new.contact_state, new.contact_postalcode, new.contact_country, new.contact_address_change), new.contact_honorific, new.contact_first, new.contact_middle, new.contact_last, new.contact_suffix, new.contact_voice, new.contact_alternate, new.contact_fax, new.contact_email, new.contact_web, new.contact_job_title, new.contact_change), public.gettaxzoneid(new.default_tax_zone), public.getsalesrepid(new.sales_rep), public.getwarehousid(new.site_code, 'ACTIVE'::text), COALESCE(new.notes, ''::text));
117116
117117
117118 --
117119 -- TOC entry 8763 (class 2618 OID 146571973)
117120 -- Dependencies: 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 198 197 197 193 193 1742 1736 1733 1716 1691 1551 360 8894
117121 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117122 --
117123
117124 CREATE RULE "_INSERT" AS ON INSERT TO purchaseline DO INSTEAD INSERT INTO public.poitem (poitem_pohead_id, poitem_linenumber, poitem_duedate, poitem_itemsite_id, poitem_vend_item_descrip, poitem_qty_ordered, poitem_unitprice, poitem_vend_item_number, poitem_manuf_name, poitem_manuf_item_number, poitem_manuf_item_descrip, poitem_comments, poitem_expcat_id, poitem_freight, poitem_prj_id, poitem_bom_rev_id, poitem_boo_rev_id) VALUES (public.getpoheadid((new.order_number)::text), new.line_number, new.due_date, public.getitemsiteid(COALESCE(new.site, (SELECT whsinfo.warehous_code FROM (public.pohead JOIN public.whsinfo ON ((whsinfo.warehous_id = pohead.pohead_warehous_id))) WHERE (pohead.pohead_id = public.getpoheadid((new.order_number)::text))), (SELECT whsinfo.warehous_code FROM public.whsinfo WHERE (whsinfo.warehous_id = public.fetchprefwarehousid()))), new.item_number), new.vendor_description, new.qty_ordered, new.unit_price, new.vend_item_number, new.manufacturer_name, new.manufacturer_item_number, new.manufacturer_description, new.notes, public.getexpcatid(new.expense_category), new.freight, public.getprjid(new.project_number), public.getrevid('BOM'::text, new.item_number, new.bill_of_materials_revision), public.getrevid('BOO'::text, new.item_number, new.bill_of_operations_revision));
117125
117126
117127 --
117128 -- TOC entry 8764 (class 2618 OID 146571975)
117129 -- Dependencies: 361 361 361 361 361 237 237 237 236 236 198 198 198 198 197 197 192 192 191 2281 361 8894
117130 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117131 --
117132
117133 CREATE RULE "_INSERT" AS ON INSERT TO purchaselinechar DO INSTEAD SELECT DISTINCT public.updatecharassignment('PI'::text, poitem.poitem_id, charass.charass_char_id, new.value) AS updatecharassignment FROM public.pohead, public.poitem, public.itemsite, public.item, public.charass, public."char" WHERE (((((((((pohead.pohead_number = (new.order_number)::text) AND (pohead.pohead_id = poitem.poitem_pohead_id)) AND (poitem.poitem_linenumber = new.line_number)) AND (poitem.poitem_itemsite_id = itemsite.itemsite_id)) AND (item.item_id = itemsite.itemsite_item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND ("char".char_id = charass.charass_char_id)) AND ("char".char_name = new.characteristic));
117134
117135
117136 --
117137 -- TOC entry 8765 (class 2618 OID 146571977)
117138 -- Dependencies: 362 362 362 362 362 362 362 240 198 198 198 197 197 1669 910 362 8894
117139 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117140 --
117141
117142 CREATE RULE "_INSERT" AS ON INSERT TO purchaselinecomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) SELECT COALESCE(new.date, (('now'::text)::date)::timestamp with time zone) AS "coalesce", 'PI', poitem.poitem_id, COALESCE(new.username, public.geteffectivextuser()) AS "coalesce", public.getcmnttypeid(new.type) AS getcmnttypeid, new.text FROM public.poitem, public.pohead WHERE (((pohead.pohead_number = (new.order_number)::text) AND (poitem.poitem_pohead_id = pohead.pohead_id)) AND (poitem.poitem_linenumber = new.line_number));
117143
117144
117145 --
117146 -- TOC entry 8766 (class 2618 OID 146571979)
117147 -- Dependencies: 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 210 210 210 210 210 210 210 197 193 193 1780 1778 1777 1769 1768 1681 1672 1670 1658 1551 910 365 8894
117148 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117149 --
117150
117151 CREATE RULE "_INSERT" AS ON INSERT TO purchaseorder DO INSTEAD INSERT INTO public.pohead (pohead_number, pohead_orderdate, pohead_status, pohead_terms_id, pohead_taxzone_id, pohead_warehous_id, pohead_agent_username, pohead_vend_id, pohead_vendaddr_id, pohead_fob, pohead_shipvia, pohead_curr_id, pohead_freight, pohead_comments, pohead_dropship, pohead_vend_cntct_id, pohead_vend_cntct_honorific, pohead_vend_cntct_first_name, pohead_vend_cntct_middle, pohead_vend_cntct_last_name, pohead_vend_cntct_suffix, pohead_vend_cntct_phone, pohead_vend_cntct_title, pohead_vend_cntct_fax, pohead_vend_cntct_email, pohead_vendaddress1, pohead_vendaddress2, pohead_vendaddress3, pohead_vendcity, pohead_vendstate, pohead_vendzipcode, pohead_vendcountry, pohead_shipto_cntct_id, pohead_shipto_cntct_honorific, pohead_shipto_cntct_first_name, pohead_shipto_cntct_middle, pohead_shipto_cntct_last_name, pohead_shipto_cntct_suffix, pohead_shipto_cntct_phone, pohead_shipto_cntct_title, pohead_shipto_cntct_fax, pohead_shipto_cntct_email, pohead_shiptoaddress_id, pohead_shiptoaddress1, pohead_shiptoaddress2, pohead_shiptoaddress3, pohead_shiptocity, pohead_shiptostate, pohead_shiptozipcode, pohead_shiptocountry, pohead_cohead_id) SELECT new.order_number, COALESCE(new.order_date, ('now'::text)::date) AS "coalesce", 'U', COALESCE(public.gettermsid(new.terms), vendinfo.vend_terms_id) AS "coalesce", COALESCE(public.gettaxzoneid(new.tax_zone), vendinfo.vend_taxzone_id) AS "coalesce", COALESCE(public.getwarehousid(new.receiving_site, 'ALL'::text), public.fetchprefwarehousid()) AS "coalesce", COALESCE(new.purchasing_agent, public.geteffectivextuser()) AS "coalesce", public.getvendid(new.vendor_number) AS getvendid, CASE WHEN (new.alt_address = 'MAIN'::text) THEN NULL::integer ELSE public.getvendaddrid(new.vendor_number, new.alt_address) END AS getvendaddrid, COALESCE(new.fob, CASE WHEN (vendinfo.vend_fobsource = 'W'::bpchar) THEN (SELECT whsinfo.warehous_fob FROM public.whsinfo WHERE (whsinfo.warehous_id = COALESCE(public.getwarehousid(new.receiving_site, 'ALL'::text), public.fetchprefwarehousid()))) ELSE vendinfo.vend_fob END) AS "coalesce", COALESCE(new.ship_via, vendinfo.vend_shipvia) AS "coalesce", COALESCE(public.getcurrid((new.currency)::text), vendinfo.vend_curr_id) AS "coalesce", COALESCE(new.freight, (0)::numeric) AS "coalesce", new.notes, COALESCE(new.dropship, false) AS "coalesce", public.getcntctid(new.vend_contact_number) AS getcntctid, COALESCE(new.vend_cntct_honorific, ''::text) AS "coalesce", COALESCE(new.vend_cntct_first_name, ''::text) AS "coalesce", COALESCE(new.vend_cntct_middle, ''::text) AS "coalesce", COALESCE(new.vend_cntct_last_name, ''::text) AS "coalesce", COALESCE(new.vend_cntct_suffix, ''::text) AS "coalesce", COALESCE(new.vend_cntct_phone, ''::text) AS "coalesce", COALESCE(new.vend_cntct_title, ''::text) AS "coalesce", COALESCE(new.vend_cntct_fax, ''::text) AS "coalesce", COALESCE(new.vend_cntct_email, ''::text) AS "coalesce", COALESCE(new.vendaddress1, ''::text) AS "coalesce", COALESCE(new.vendaddress2, ''::text) AS "coalesce", COALESCE(new.vendaddress3, ''::text) AS "coalesce", COALESCE(new.vendcity, ''::text) AS "coalesce", COALESCE(new.vendstate, ''::text) AS "coalesce", COALESCE(new.vendzipcode, ''::text) AS "coalesce", COALESCE(new.vendcountry, ''::text) AS "coalesce", public.getcntctid(new.shipto_contact_number) AS getcntctid, COALESCE(new.shipto_cntct_honorific, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_first_name, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_middle, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_last_name, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_suffix, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_phone, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_title, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_fax, ''::text) AS "coalesce", COALESCE(new.shipto_cntct_email, ''::text) AS "coalesce", public.getaddrid(new.shiptoaddress_number) AS getaddrid, COALESCE(new.shiptoaddress1, ''::text) AS "coalesce", COALESCE(new.shiptoaddress2, ''::text) AS "coalesce", COALESCE(new.shiptoaddress3, ''::text) AS "coalesce", COALESCE(new.shiptocity, ''::text) AS "coalesce", COALESCE(new.shiptostate, ''::text) AS "coalesce", COALESCE(new.shiptozipcode, ''::text) AS "coalesce", COALESCE(new.shiptocountry, ''::text) AS "coalesce", public.getcoheadid(new.sales_order_number) AS getcoheadid FROM public.vendinfo WHERE (vendinfo.vend_id = public.getvendid(new.vendor_number));
117152
117153
117154 --
117155 -- TOC entry 8767 (class 2618 OID 146571981)
117156 -- Dependencies: 366 366 366 366 366 366 240 1733 1669 910 366 8894
117157 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117158 --
117159
117160 CREATE RULE "_INSERT" AS ON INSERT TO purchaseordercomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, (('now'::text)::date)::timestamp with time zone), 'P'::text, public.getpoheadid((new.order_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117161
117162
117163 --
117164 -- TOC entry 8768 (class 2618 OID 146571982)
117165 -- Dependencies: 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 367 1780 1769 1768 1767 1759 1756 1751 1749 1736 1700 1683 1681 368 8894
117166 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117167 --
117168
117169 CREATE RULE "_INSERT" AS ON INSERT TO quote DO INSTEAD INSERT INTO public.quhead (quhead_number, quhead_cust_id, quhead_custponumber, quhead_quotedate, quhead_warehous_id, quhead_shipto_id, quhead_shiptoname, quhead_shiptoaddress1, quhead_shiptoaddress2, quhead_shiptoaddress3, quhead_salesrep_id, quhead_terms_id, quhead_fob, quhead_shipvia, quhead_shiptocity, quhead_shiptostate, quhead_shiptozipcode, quhead_freight, quhead_misc, quhead_ordercomments, quhead_shipcomments, quhead_shiptophone, quhead_billtoname, quhead_billtoaddress1, quhead_billtoaddress2, quhead_billtoaddress3, quhead_billtocity, quhead_billtostate, quhead_billtozip, quhead_misc_accnt_id, quhead_misc_descrip, quhead_commission, quhead_packdate, quhead_prj_id, quhead_billtocountry, quhead_shiptocountry, quhead_curr_id, quhead_taxzone_id, quhead_taxtype_id, quhead_imported, quhead_expire, quhead_status, quhead_saletype_id, quhead_shipzone_id) VALUES (new.quote_number, public.getcustid(new.customer_number, true), new.cust_po_number, new.quote_date, public.getwarehousid(new.site, 'SHIPPING'::text), public.getshiptoid(new.customer_number, new.shipto_number), new.shipto_name, new.shipto_address1, new.shipto_address2, new.shipto_address3, public.getsalesrepid(new.sales_rep), public.gettermsid(new.terms), new.fob, new.ship_via, new.shipto_city, new.shipto_state, new.shipto_postal_code, new.freight, new.misc_charge, new.order_notes, new.shipping_notes, new.shipto_phone, new.billto_name, new.billto_address1, new.billto_address2, new.billto_address3, new.billto_city, new.billto_state, new.billto_postal_code, public.getglaccntid(new.misc_account_number), new.misc_charge_description, new.commission, new.pack_date, public.getprjid(new.project_number), new.billto_country, new.shipto_country, public.getcurrid((new.currency)::text), public.gettaxzoneid(new.tax_zone), public.gettaxtypeid(new.tax_type), true, new.expire_date, CASE WHEN (new.status = 'Converted'::text) THEN 'C'::text ELSE 'O'::text END, public.getsaletypeid(new.sale_type), public.getshipzoneid(new.shipto_shipzone));
117170
117171
117172 --
117173 -- TOC entry 8769 (class 2618 OID 146571984)
117174 -- Dependencies: 369 369 369 369 369 369 240 1720 1669 910 369 8894
117175 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117176 --
117177
117178 CREATE RULE "_INSERT" AS ON INSERT TO quotecomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, (('now'::text)::date)::timestamp with time zone), 'Q'::text, public.getquoteid(new.quote_number), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117179
117180
117181 --
117182 -- TOC entry 8770 (class 2618 OID 146571985)
117183 -- Dependencies: 371 825 825 825 371 371 371 371 371 371 371 371 371 371 371 371 371 371 371 370 370 370 367 367 367 367 367 367 193 193 193 193 192 192 192 192 191 191 191 191 2234 1902 1888 1780 1771 1767 1720 1714 911 910 371 8894
117184 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117185 --
117186
117187 CREATE RULE "_INSERT" AS ON INSERT TO quoteline DO INSTEAD INSERT INTO public.quitem (quitem_quhead_id, quitem_linenumber, quitem_itemsite_id, quitem_scheddate, quitem_qtyord, quitem_unitcost, quitem_price, quitem_custprice, quitem_memo, quitem_imported, quitem_custpn, quitem_createorder, quitem_order_warehous_id, quitem_item_id, quitem_prcost, quitem_taxtype_id, quitem_qty_uom_id, quitem_qty_invuomratio, quitem_price_uom_id, quitem_price_invuomratio) SELECT public.getquoteid(new.quote_number) AS getquoteid, COALESCE(new.line_number, (SELECT (COALESCE(max(quitem.quitem_linenumber), 0) + 1) FROM public.quitem WHERE (quitem.quitem_quhead_id = public.getquoteid(new.quote_number)))) AS "coalesce", itemsite.itemsite_id, COALESCE(new.scheduled_date, (SELECT min(quitem.quitem_scheddate) AS min FROM public.quitem WHERE (quitem.quitem_quhead_id = public.getquoteid(new.quote_number)))) AS "coalesce", new.qty_ordered, public.stdcost(item.item_id) AS stdcost, COALESCE(new.net_unit_price, public.itemprice(public.getitemid(new.item_number), quhead.quhead_cust_id, quhead.quhead_shipto_id, new.qty_ordered, quhead.quhead_curr_id, quhead.quhead_quotedate)) AS "coalesce", public.itemprice(public.getitemid(new.item_number), quhead.quhead_cust_id, quhead.quhead_shipto_id, new.qty_ordered, quhead.quhead_curr_id, quhead.quhead_quotedate) AS itemprice, COALESCE(new.notes, ''::text) AS "coalesce", true AS bool, new.customer_pn, COALESCE(new.create_order, false) AS "coalesce", COALESCE(public.getwarehousid(new.supplying_site, 'SHIPPING'::text), itemsite.itemsite_warehous_id) AS "coalesce", public.getitemid(new.item_number) AS getitemid, COALESCE(new.overwrite_po_price, (0)::numeric) AS "coalesce", COALESCE(public.gettaxtypeid(new.tax_type), public.getitemtaxtype(itemsite.itemsite_item_id, quhead.quhead_taxzone_id)) AS "coalesce", COALESCE(public.getuomid(new.qty_uom), item.item_inv_uom_id) AS "coalesce", public.itemuomtouomratio(item.item_id, COALESCE(public.getuomid(new.qty_uom), item.item_inv_uom_id), item.item_inv_uom_id) AS itemuomtouomratio, COALESCE(public.getuomid(new.price_uom), item.item_price_uom_id) AS "coalesce", public.itemuomtouomratio(item.item_id, COALESCE(public.getuomid(new.price_uom), item.item_price_uom_id), item.item_price_uom_id) AS itemuomtouomratio FROM public.quhead, public.itemsite, public.item, public.whsinfo WHERE ((quhead.quhead_number = new.quote_number) AND (((((((itemsite.itemsite_warehous_id = whsinfo.warehous_id) AND (itemsite.itemsite_item_id = item.item_id)) AND itemsite.itemsite_active) AND (item.item_number = new.item_number)) AND whsinfo.warehous_active) AND whsinfo.warehous_shipping) AND (whsinfo.warehous_code = COALESCE(new.sold_from_site, (SELECT whsinfo.warehous_code FROM public.usrpref, public.whsinfo WHERE (((usrpref.usrpref_username = public.geteffectivextuser()) AND (usrpref.usrpref_name = 'PreferredWarehouse'::text)) AND (whsinfo.warehous_id = (usrpref.usrpref_value)::integer)))))));
117188
117189
117190 --
117191 -- TOC entry 8771 (class 2618 OID 146571987)
117192 -- Dependencies: 372 372 372 372 372 370 370 370 370 367 367 237 237 237 236 236 192 192 191 2281 372 8894
117193 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117194 --
117195
117196 CREATE RULE "_INSERT" AS ON INSERT TO quotelinechar DO INSTEAD SELECT DISTINCT public.updatecharassignment('QI'::text, quitem.quitem_id, charass.charass_char_id, new.value) AS updatecharassignment FROM public.quhead, public.quitem, public.itemsite, public.item, public.charass, public."char" WHERE (((((((((quhead.quhead_number = new.quote_number) AND (quhead.quhead_id = quitem.quitem_quhead_id)) AND (quitem.quitem_linenumber = new.line_number)) AND (quitem.quitem_itemsite_id = itemsite.itemsite_id)) AND (item.item_id = itemsite.itemsite_item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND ("char".char_id = charass.charass_char_id)) AND ("char".char_name = new.characteristic));
117197
117198
117199 --
117200 -- TOC entry 8772 (class 2618 OID 146571989)
117201 -- Dependencies: 373 373 373 373 373 373 373 240 1740 1669 910 373 8894
117202 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117203 --
117204
117205 CREATE RULE "_INSERT" AS ON INSERT TO quotelinecomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, (('now'::text)::date)::timestamp with time zone), 'QI'::text, public.getquotelineitemid(new.quote_number, new.line_number), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117206
117207
117208 --
117209 -- TOC entry 8773 (class 2618 OID 146571990)
117210 -- Dependencies: 375 375 375 375 375 375 374 1681 1672 1660 375 8894
117211 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117212 --
117213
117214 CREATE RULE "_INSERT" AS ON INSERT TO salescredit DO INSTEAD INSERT INTO public.aropenalloc (aropenalloc_aropen_id, aropenalloc_doctype, aropenalloc_doc_id, aropenalloc_amount, aropenalloc_curr_id) VALUES (public.getaropenid(new.customer_number, 'C'::bpchar, new.cm_number), 'S'::bpchar, public.getcoheadid(new.so_number), new.amount, public.getcurrid((new.currency)::text));
117215
117216
117217 --
117218 -- TOC entry 8774 (class 2618 OID 146571991)
117219 -- Dependencies: 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 380 376 1768 1767 1756 1749 1716 1700 1682 1681 907 380 8894
117220 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117221 --
117222
117223 CREATE RULE "_INSERT" AS ON INSERT TO saleshistory DO INSTEAD INSERT INTO public.cohist (cohist_cust_id, cohist_itemsite_id, cohist_shipdate, cohist_shipvia, cohist_ordernumber, cohist_orderdate, cohist_invcnumber, cohist_invcdate, cohist_qtyshipped, cohist_unitprice, cohist_shipto_id, cohist_salesrep_id, cohist_duedate, cohist_imported, cohist_billtoname, cohist_billtoaddress1, cohist_billtoaddress2, cohist_billtoaddress3, cohist_billtocity, cohist_billtostate, cohist_billtozip, cohist_shiptoname, cohist_shiptoaddress1, cohist_shiptoaddress2, cohist_shiptoaddress3, cohist_shiptocity, cohist_shiptostate, cohist_shiptozip, cohist_commission, cohist_commissionpaid, cohist_unitcost, cohist_misc_type, cohist_misc_descrip, cohist_misc_id, cohist_doctype, cohist_promisedate, cohist_ponumber, cohist_curr_id, cohist_sequence, cohist_taxzone_id, cohist_taxtype_id) VALUES (public.getcustid(new.customer_number), public.getitemsiteid(new.site_code, new.item_number), new.ship_date, new.ship_via, new.order_number, new.order_date, new.invoice_number, new.invoice_date, new.quantity_shipped, COALESCE(new.unit_price, (0)::numeric), public.getshiptoid(new.customer_number, new.shipto_number), public.getsalesrepid(new.sales_rep), new.due_date, true, new.billto_name, new.billto_address1, new.billto_address2, new.billto_address3, new.billto_city, new.billto_state, new.billto_zip, new.shipto_name, new.shipto_address1, new.shipto_address2, new.shipto_address3, new.shipto_city, new.shipto_state, new.shipto_zip, COALESCE(new.commission, (0)::numeric), COALESCE(new.commission_paid, false), COALESCE(new.unit_cost, (0)::numeric), CASE WHEN (new.misc_type = 'Misc. Charge'::text) THEN 'M'::text WHEN (new.misc_type = 'Freight'::text) THEN 'F'::text ELSE NULL::text END, new.misc_description, CASE WHEN (new.misc_type = 'Misc. Charge'::text) THEN public.getglaccntid(new.misc_info) ELSE NULL::integer END, CASE WHEN (new.document_type = 'Invoice'::text) THEN 'I'::text WHEN (new.document_type = 'Credit Memo'::text) THEN 'C'::text ELSE NULL::text END, new.promise_date, new.purchase_order_number, COALESCE(public.getcurrid((new.currency)::text), public.basecurrid()), new.gl_sequence, public.gettaxzoneid(new.tax_zone), public.gettaxtypeid(new.tax_type));
117224
117225
117226 --
117227 -- TOC entry 8775 (class 2618 OID 146571993)
117228 -- Dependencies: 381 381 381 381 381 237 237 237 236 236 196 196 196 196 195 195 195 195 195 195 192 192 191 2282 1876 1674 381 8894
117229 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117230 --
117231
117232 CREATE RULE "_INSERT" AS ON INSERT TO saleslinechar DO INSTEAD SELECT DISTINCT public.updatecharassignment('SI'::text, coitem.coitem_id, charass.charass_char_id, new.value, public.itemcharprice(item.item_id, "char".char_id, new.value, cohead.cohead_cust_id, cohead.cohead_shipto_id, coitem.coitem_qtyord, cohead.cohead_curr_id, cohead.cohead_orderdate)) AS updatecharassignment FROM public.cohead, public.coitem, public.itemsite, public.item, public.charass, public."char" WHERE (((((((((cohead.cohead_number = (new.order_number)::text) AND (cohead.cohead_id = coitem.coitem_cohead_id)) AND (coitem.coitem_id = public.getcoitemid((new.order_number)::text, new.line_number))) AND (coitem.coitem_itemsite_id = itemsite.itemsite_id)) AND (item.item_id = itemsite.itemsite_item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND ("char".char_id = charass.charass_char_id)) AND ("char".char_name = new.characteristic));
117233
117234
117235 --
117236 -- TOC entry 8776 (class 2618 OID 146571995)
117237 -- Dependencies: 382 382 382 382 382 382 382 240 1674 1669 910 382 8894
117238 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117239 --
117240
117241 CREATE RULE "_INSERT" AS ON INSERT TO saleslinecomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, (('now'::text)::date)::timestamp with time zone), 'SI'::text, public.getcoitemid((new.order_number)::text, new.line_number), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117242
117243
117244 --
117245 -- TOC entry 8777 (class 2618 OID 146571996)
117246 -- Dependencies: 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 213 195 1780 1769 1768 1759 1756 1754 1753 1751 1749 1736 1700 1682 1681 1670 1545 383 8894
117247 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117248 --
117249
117250 CREATE RULE "_INSERT" AS ON INSERT TO salesorder DO INSTEAD INSERT INTO public.cohead (cohead_number, cohead_cust_id, cohead_custponumber, cohead_orderdate, cohead_warehous_id, cohead_shipto_id, cohead_shiptoname, cohead_shiptoaddress1, cohead_shiptoaddress2, cohead_shiptoaddress3, cohead_salesrep_id, cohead_terms_id, cohead_fob, cohead_shipvia, cohead_shiptocity, cohead_shiptostate, cohead_shiptozipcode, cohead_freight, cohead_calcfreight, cohead_misc, cohead_imported, cohead_ordercomments, cohead_shipcomments, cohead_shiptophone, cohead_shipchrg_id, cohead_shipform_id, cohead_billtoname, cohead_billtoaddress1, cohead_billtoaddress2, cohead_billtoaddress3, cohead_billtocity, cohead_billtostate, cohead_billtozipcode, cohead_misc_accnt_id, cohead_misc_descrip, cohead_commission, cohead_holdtype, cohead_packdate, cohead_prj_id, cohead_shipcomplete, cohead_billtocountry, cohead_shiptocountry, cohead_curr_id, cohead_taxzone_id, cohead_shipto_cntct_id, cohead_shipto_cntct_honorific, cohead_shipto_cntct_first_name, cohead_shipto_cntct_middle, cohead_shipto_cntct_last_name, cohead_shipto_cntct_suffix, cohead_shipto_cntct_phone, cohead_shipto_cntct_title, cohead_shipto_cntct_fax, cohead_shipto_cntct_email, cohead_billto_cntct_id, cohead_billto_cntct_honorific, cohead_billto_cntct_first_name, cohead_billto_cntct_middle, cohead_billto_cntct_last_name, cohead_billto_cntct_suffix, cohead_billto_cntct_phone, cohead_billto_cntct_title, cohead_billto_cntct_fax, cohead_billto_cntct_email, cohead_saletype_id, cohead_shipzone_id) SELECT new.order_number, public.getcustid(new.customer_number) AS getcustid, new.cust_po_number, new.order_date, public.getwarehousid(new.site, 'SHIPPING'::text) AS getwarehousid, public.getshiptoid(new.customer_number, new.shipto_number) AS getshiptoid, new.shipto_name, new.shipto_address1, new.shipto_address2, new.shipto_address3, public.getsalesrepid(new.sales_rep) AS getsalesrepid, public.gettermsid(new.terms) AS gettermsid, new.fob, new.ship_via, new.shipto_city, new.shipto_state, new.shipto_postal_code, CASE WHEN COALESCE(new.calculate_freight, public.fetchmetricbool('CalculateFreight'::text)) THEN (0)::numeric ELSE new.freight END AS freight, COALESCE(new.calculate_freight, public.fetchmetricbool('CalculateFreight'::text)) AS "coalesce", new.misc_charge, true AS bool, new.order_notes, new.shipping_notes, new.shipto_phone, public.getshipchrgid(new.shipping_chgs) AS getshipchrgid, public.getshipformid(new.shipping_form) AS getshipformid, new.billto_name, new.billto_address1, new.billto_address2, new.billto_address3, new.billto_city, new.billto_state, new.billto_postal_code, public.getglaccntid(new.misc_account_number) AS getglaccntid, new.misc_charge_description, new.commission, CASE WHEN (new.hold_type = 'Credit'::text) THEN 'C'::text WHEN (new.hold_type = 'Shipping'::text) THEN 'S'::text WHEN (new.hold_type = 'Packing'::text) THEN 'P'::text ELSE 'N'::text END AS "case", new.pack_date, public.getprjid(new.project_number) AS getprjid, new.ship_complete, new.billto_country, new.shipto_country, public.getcurrid((new.currency)::text) AS getcurrid, CASE WHEN (new.tax_zone = 'None'::text) THEN (-1) ELSE public.gettaxzoneid(new.tax_zone) END AS gettaxzoneid, public.getcntctid(new.shipto_contact_number) AS getcntctid, new.shipto_contact_honorific, new.shipto_contact_first, new.shipto_contact_middle, new.shipto_contact_last, new.shipto_contact_suffix, new.shipto_contact_phone, new.shipto_contact_title, new.shipto_contact_fax, new.shipto_contact_email, public.getcntctid(new.billto_contact_number) AS getcntctid, new.billto_contact_name, new.billto_contact_first, new.billto_contact_middle, new.billto_contact_last, new.billto_contact_suffix, new.billto_contact_phone, new.billto_contact_title, new.billto_contct_fax, new.billto_contact_email, public.getsaletypeid(new.sale_type) AS getsaletypeid, public.getshipzoneid(new.shipto_shipzone) AS getshipzoneid FROM public.custinfo WHERE (custinfo.cust_number = new.customer_number);
117251
117252
117253 --
117254 -- TOC entry 8778 (class 2618 OID 146571998)
117255 -- Dependencies: 384 384 384 384 384 384 240 1748 1669 910 384 8894
117256 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117257 --
117258
117259 CREATE RULE "_INSERT" AS ON INSERT TO salesordercomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, (('now'::text)::date)::timestamp with time zone), 'S'::text, public.getsalesorderid((new.order_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117260
117261
117262 --
117263 -- TOC entry 8779 (class 2618 OID 146571999)
117264 -- Dependencies: 385 385 385 385 385 385 216 1690 385 8894
117265 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117266 --
117267
117268 CREATE RULE "_INSERT" AS ON INSERT TO salesrep DO INSTEAD INSERT INTO public.salesrep (salesrep_active, salesrep_number, salesrep_name, salesrep_commission, salesrep_method, salesrep_emp_id) VALUES (COALESCE(new.active, true), COALESCE(new.number, ''::character varying), COALESCE(new.name, ''::text), COALESCE((new.commission_percent * 0.01), (0)::numeric), ''::bpchar, public.getempid(new.employee));
117269
117270
117271 --
117272 -- TOC entry 8780 (class 2618 OID 146572000)
117273 -- Dependencies: 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 193 2162 2158 1768 1760 1758 1754 1700 1678 1670 1658 1547 388 8894
117274 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117275 --
117276
117277 CREATE RULE "_INSERT" AS ON INSERT TO site DO INSTEAD INSERT INTO public.whsinfo (warehous_code, warehous_descrip, warehous_fob, warehous_active, warehous_counttag_prefix, warehous_counttag_number, warehous_bol_prefix, warehous_bol_number, warehous_shipping, warehous_useslips, warehous_usezones, warehous_aislesize, warehous_aislealpha, warehous_racksize, warehous_rackalpha, warehous_binsize, warehous_binalpha, warehous_locationsize, warehous_locationalpha, warehous_enforcearbl, warehous_default_accnt_id, warehous_shipping_commission, warehous_cntct_id, warehous_addr_id, warehous_taxzone_id, warehous_transit, warehous_shipform_id, warehous_shipvia_id, warehous_shipcomments, warehous_costcat_id, warehous_sitetype_id, warehous_sequence) VALUES (COALESCE(new.code, ''::character varying), COALESCE(new.description, ''::text), CASE WHEN new.inventory_type THEN COALESCE(new.default_fob, ''::text) ELSE ''::text END, COALESCE(new.active, true), CASE WHEN new.inventory_type THEN COALESCE(new.next_count_tag_prefix, ''::text) ELSE ''::text END, CASE WHEN new.inventory_type THEN COALESCE(new.next_count_tag_number, 0) ELSE 0 END, CASE WHEN new.inventory_type THEN COALESCE(new.next_bill_of_lading_prefix, ''::text) ELSE ''::text END, CASE WHEN new.inventory_type THEN COALESCE(new.next_bill_of_lading_number, 0) ELSE 0 END, CASE WHEN new.inventory_type THEN COALESCE(new.shipping_site, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.force_the_use_of_count_slips, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.force_the_use_of_zones, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.aisle_size, 0) ELSE 0 END, CASE WHEN new.inventory_type THEN COALESCE(new.aisle_allow_alpha_characters, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.rack_size, 0) ELSE 0 END, CASE WHEN new.inventory_type THEN COALESCE(new.rack_allow_alpha_characters, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.bin_size, 0) ELSE 0 END, CASE WHEN new.inventory_type THEN COALESCE(new.bin_allow_alpha_characters, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.location_size, 0) ELSE 0 END, CASE WHEN new.inventory_type THEN COALESCE(new.location_allow_alpha_characters, false) ELSE false END, CASE WHEN new.inventory_type THEN COALESCE(new.enforce_arbl_naming_convention, false) ELSE false END, COALESCE(public.getglaccntid(new.post_unassigned_transactions_to), (-1)), CASE WHEN new.inventory_type THEN COALESCE((new.shipping_commission * 0.01), (0)::numeric) ELSE (0)::numeric END, public.savecntct(public.getcntctid(new.contact_number), new.contact_number, NULL::integer, new.honorific, new.first, new.middle, new.last, new.suffix, new.phone, NULL::text, new.fax, new.email, NULL::text, new.job_title, new.contact_change), public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.address_change), CASE WHEN new.inventory_type THEN COALESCE(public.gettaxzoneid(new.tax_zone), (-1)) ELSE NULL::integer END, CASE WHEN new.inventory_type THEN false WHEN new.transit_type THEN true ELSE false END, CASE WHEN new.transit_type THEN COALESCE((public.getshipformid(new.default_shipping_form))::numeric, public.fetchmetricvalue('DefaultShipFormId'::text)) ELSE NULL::numeric END, CASE WHEN new.transit_type THEN COALESCE((public.getshipviaid(new.default_ship_via))::numeric, public.fetchmetricvalue('DefaultShipViaId'::text)) ELSE NULL::numeric END, CASE WHEN new.transit_type THEN COALESCE(new.shipping_comments, ''::text) ELSE ''::text END, CASE WHEN new.transit_type THEN COALESCE(public.getcostcatid(new.default_cost_category), (-1)) ELSE NULL::integer END, COALESCE(public.getsitetypeid(new.type), (-1)), COALESCE(new.scheduling_sequence, 0));
117278
117279
117280 --
117281 -- TOC entry 8781 (class 2618 OID 146572002)
117282 -- Dependencies: 389 389 389 389 343 1780 389 8894
117283 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117284 --
117285
117286 CREATE RULE "_INSERT" AS ON INSERT TO sitezone DO INSTEAD INSERT INTO public.whsezone (whsezone_warehous_id, whsezone_name, whsezone_descrip) VALUES (public.getwarehousid((new.site)::text, 'ACTIVE'::text), COALESCE(new.name, ''::character varying), COALESCE(new.description, ''::text));
117287
117288
117289 --
117290 -- TOC entry 8782 (class 2618 OID 146572003)
117291 -- Dependencies: 390 390 390 390 390 390 390 390 390 390 390 390 390 390 390 390 232 1736 910 390 8894
117292 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117293 --
117294
117295 CREATE RULE "_INSERT" AS ON INSERT TO task DO INSTEAD INSERT INTO public.prjtask (prjtask_prj_id, prjtask_number, prjtask_name, prjtask_descrip, prjtask_owner_username, prjtask_username, prjtask_hours_budget, prjtask_hours_actual, prjtask_exp_budget, prjtask_exp_actual, prjtask_status, prjtask_due_date, prjtask_assigned_date, prjtask_start_date, prjtask_completed_date) VALUES (public.getprjid(new.project_number), new.number, COALESCE(new.name, ''::text), COALESCE(new.description, ''::text), COALESCE(new.owner, public.geteffectivextuser()), COALESCE(new.assigned_to, public.geteffectivextuser()), COALESCE(new.hours_budgeted, (0)::numeric), COALESCE(new.hours_actual, (0)::numeric), COALESCE(new.expenses_budgeted, (0)::numeric), COALESCE(new.expenses_actual, (0)::numeric), CASE WHEN (new.status = 'In-Process'::text) THEN 'O'::text WHEN (new.status = 'Completed'::text) THEN 'C'::text ELSE 'P'::text END, new.due, new.assigned, new.started, new.completed);
117296
117297
117298 --
117299 -- TOC entry 8783 (class 2618 OID 146572005)
117300 -- Dependencies: 391 391 391 391 391 391 391 240 1737 1669 910 391 8894
117301 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117302 --
117303
117304 CREATE RULE "_INSERT" AS ON INSERT TO taskcomment DO INSTEAD INSERT INTO public.comment (comment_date, comment_source, comment_source_id, comment_user, comment_cmnttype_id, comment_text) VALUES (COALESCE(new.date, now()), 'TA'::text, public.getprjtaskid((new.project_number)::text, (new.task_number)::text), COALESCE(new.username, public.geteffectivextuser()), public.getcmnttypeid(new.type), new.text);
117305
117306
117307 --
117308 -- TOC entry 8784 (class 2618 OID 146572006)
117309 -- Dependencies: 392 392 392 392 392 392 392 392 392 392 392 392 392 392 392 1724 1708 1705 1704 1680 1350 392 8894
117310 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117311 --
117312
117313 CREATE RULE "_INSERT" AS ON INSERT TO todo DO INSTEAD SELECT public.createtodoitem(NULL::integer, new.assigned_to, COALESCE(new.task_name, ''::text), COALESCE(new.description, ''::text), public.getincidentid(new.incident), COALESCE(public.getincdtcrmacctid(new.incident), public.getcrmacctid(new.account)), public.getopheadid(new.opportunity), CASE WHEN (new.date_started > ''::text) THEN (new.date_started)::date ELSE NULL::date END, CASE WHEN (new.date_due > ''::text) THEN (new.date_due)::date ELSE NULL::date END, (CASE WHEN (new.status = 'Pending Input'::text) THEN 'P'::text WHEN (new.status = 'Deferred'::text) THEN 'D'::text ELSE 'N'::text END)::bpchar, CASE WHEN (new.date_assigned > ''::text) THEN (new.date_assigned)::date ELSE NULL::date END, CASE WHEN (new.date_completed > ''::text) THEN (new.date_completed)::date ELSE NULL::date END, public.getincdtpriorityid(new.priority), COALESCE(new.notes, ''::text), new.owner) AS createtodoitem;
117314
117315
117316 --
117317 -- TOC entry 8785 (class 2618 OID 146572008)
117318 -- Dependencies: 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 210 2162 2158 1779 1769 1768 1766 1700 1691 1681 1670 1658 1547 1539 907 394 8894
117319 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117320 --
117321
117322 CREATE RULE "_INSERT" AS ON INSERT TO vendor DO INSTEAD INSERT INTO public.vendinfo (vend_name, vend_lastpurchdate, vend_active, vend_po, vend_comments, vend_pocomments, vend_number, vend_1099, vend_exported, vend_fobsource, vend_fob, vend_terms_id, vend_shipvia, vend_vendtype_id, vend_qualified, vend_ediemail, vend_ediemailbody, vend_edisubject, vend_edifilename, vend_accntnum, vend_emailpodelivery, vend_restrictpurch, vend_edicc, vend_curr_id, vend_cntct1_id, vend_cntct2_id, vend_addr_id, vend_match, vend_taxzone_id, vend_ach_routingnumber, vend_ach_accntnumber, vend_accnt_id, vend_expcat_id, vend_tax_id) VALUES (COALESCE(new.vendor_name, ''::text), NULL::date, COALESCE(new.active, true), COALESCE(new.sells_purchase_order_items, false), COALESCE(new.notes, ''::text), COALESCE(new.po_comments, ''::text), COALESCE(new.vendor_number, ''::character varying), COALESCE(new.receives_1099, false), false, CASE WHEN (new.default_fob = 'Receiving Site'::text) THEN 'W'::text ELSE 'V'::text END, CASE WHEN (new.default_fob = 'Receiving Site'::text) THEN ''::text ELSE new.default_fob END, COALESCE((public.gettermsid(new.default_terms))::numeric, public.fetchmetricvalue('DefaultTerms'::text)), COALESCE(new.ship_via, public.fetchdefaultshipvia()), public.getvendtypeid(new.vendor_type), COALESCE(new.qualified, false), COALESCE(new.po_edi_email, ''::text), COALESCE(new.po_edi_emailbody, ''::text), COALESCE(new.po_edi_subject, ''::text), COALESCE(new.po_edi_filename, ''::text), COALESCE(new.account_number, ''::text), COALESCE(new.allow_email_po_delivery, false), COALESCE(new.may_only_sell_item_source, false), COALESCE(new.po_edi_cc, ''::text), COALESCE(public.getcurrid((new.default_currency)::text), public.basecurrid()), public.savecntct(public.getcntctid(new.contact1_number), new.contact1_number, NULL::integer, new.contact1_honorific, new.contact1_first, new.contact1_middle, new.contact1_last, new.contact1_suffix, new.contact1_voice, new.contact1_alternate, new.contact1_fax, new.contact1_email, new.contact1_web, new.contact1_job_title, new.contact1_change), public.savecntct(public.getcntctid(new.contact2_number), new.contact2_number, NULL::integer, new.contact2_honorific, new.contact2_first, new.contact2_middle, new.contact2_last, new.contact2_suffix, new.contact2_voice, new.contact2_alternate, new.contact2_fax, new.contact2_email, new.contact2_web, new.contact2_job_title, new.contact2_change), public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change), COALESCE(new.matching_vo_po_amounts, false), public.gettaxzoneid(new.default_tax_zone), '\x'::bytea, '\x'::bytea, COALESCE(public.getglaccntid(new.default_dist_gl_account), (-1)), COALESCE(public.getexpcatid(new.default_dist_expense_category), (-1)), COALESCE(public.gettaxid(new.default_dist_tax_code), (-1)));
117323
117324
117325 --
117326 -- TOC entry 8786 (class 2618 OID 146572010)
117327 -- Dependencies: 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 364 2162 2158 1778 1670 1658 395 8894
117328 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117329 --
117330
117331 CREATE RULE "_INSERT" AS ON INSERT TO vendoraddress DO INSTEAD INSERT INTO public.vendaddrinfo (vendaddr_vend_id, vendaddr_code, vendaddr_name, vendaddr_comments, vendaddr_cntct_id, vendaddr_addr_id) VALUES (public.getvendid((new.vendor_number)::text), COALESCE(new.vendor_address_number, ''::character varying), COALESCE(new.vendor_address_name, ''::text), COALESCE(new.notes, ''::text), public.savecntct(public.getcntctid(new.contact_number), new.contact_number, public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change), new.contact_honorific, new.contact_first, new.contact_middle, new.contact_last, new.contact_suffix, new.contact_voice, new.contact_alternate, new.contact_fax, new.contact_email, new.contact_web, new.contact_job_title, new.contact_change), public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change));
117332
117333
117334 --
117335 -- TOC entry 8787 (class 2618 OID 146572012)
117336 -- Dependencies: 396 396 396 393 396 8894
117337 -- Name: _INSERT; Type: RULE; Schema: api; Owner: admin
117338 --
117339
117340 CREATE RULE "_INSERT" AS ON INSERT TO vendortype DO INSTEAD INSERT INTO public.vendtype (vendtype_code, vendtype_descrip) VALUES (new.code, COALESCE(new.description, ''::text));
117341
117342
117343 --
117344 -- TOC entry 8788 (class 2618 OID 146572013)
117345 -- Dependencies: 360 360 360 237 237 237 237 237 236 198 198 198 198 197 197 192 192 191 360 8894
117346 -- Name: _INSERT_CHAR; Type: RULE; Schema: api; Owner: admin
117347 --
117348
117349 CREATE RULE "_INSERT_CHAR" AS ON INSERT TO purchaseline DO INSTEAD INSERT INTO public.charass (charass_target_type, charass_target_id, charass_char_id, charass_value) SELECT 'PI', poitem.poitem_id, "char".char_id, charass.charass_value FROM public.pohead, public.poitem, public.charass, public."char", public.itemsite, public.item WHERE (((((((((pohead.pohead_number = (new.order_number)::text) AND (poitem.poitem_pohead_id = pohead.pohead_id)) AND (poitem.poitem_linenumber = new.line_number)) AND (itemsite.itemsite_id = poitem.poitem_itemsite_id)) AND (itemsite.itemsite_item_id = item.item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND charass.charass_default) AND ("char".char_id = charass.charass_char_id));
117350
117351
117352 --
117353 -- TOC entry 8789 (class 2618 OID 146572015)
117354 -- Dependencies: 201 201 201 201 201 201 201 201 201 201 201 201 201 201 201 201 201 201 201 196 196 196 192 192 191 191 191 191 191 1902 1771 1767 1714 1700 1674 1672 201 8894
117355 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117356 --
117357
117358 CREATE RULE "_UPDATE" AS ON UPDATE TO salesline DO INSTEAD UPDATE public.coitem SET coitem_status = new.status, coitem_scheddate = new.scheduled_date, coitem_promdate = new.promise_date, coitem_qtyord = new.qty_ordered, coitem_qty_uom_id = public.getuomid(new.qty_uom), coitem_qty_invuomratio = public.itemuomtouomratio(item.item_id, public.getuomid(new.qty_uom), item.item_inv_uom_id), coitem_price = new.net_unit_price, coitem_price_uom_id = public.getuomid(new.price_uom), coitem_price_invuomratio = public.itemuomtouomratio(item.item_id, public.getuomid(new.price_uom), item.item_price_uom_id), coitem_memo = new.notes, coitem_order_type = CASE WHEN (((NOT old.create_order) AND new.create_order) AND (item.item_type = 'M'::bpchar)) THEN 'W'::text WHEN ((((NOT old.create_order) AND new.create_order) AND (item.item_type = 'P'::bpchar)) AND itemsite.itemsite_createsopo) THEN 'P'::text WHEN (((NOT old.create_order) AND new.create_order) AND (item.item_type = 'P'::bpchar)) THEN 'R'::text ELSE NULL::text END, coitem_substitute_item_id = public.getitemid(new.substitute_for), coitem_prcost = new.overwrite_po_price, coitem_taxtype_id = CASE WHEN (new.tax_type = 'None'::text) THEN NULL::integer ELSE public.gettaxtypeid(new.tax_type) END, coitem_warranty = new.warranty, coitem_cos_accnt_id = public.getglaccntid(new.alternate_cos_account), coitem_rev_accnt_id = public.getglaccntid(new.alternate_rev_account) FROM (public.item JOIN public.itemsite ON ((item.item_id = itemsite.itemsite_item_id))) WHERE ((((item.item_number = old.item_number) AND (coitem.coitem_cohead_id = public.getcoheadid((old.order_number)::text))) AND (coitem.coitem_id = public.getcoitemid((old.order_number)::text, (old.line_number)::text))) AND (coitem.coitem_subnumber = 0));
117359
117360
117361 --
117362 -- TOC entry 8790 (class 2618 OID 146572017)
117363 -- Dependencies: 211 211 211 211 211 211 211 207 207 1769 211 8894
117364 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117365 --
117366
117367 CREATE RULE "_UPDATE" AS ON UPDATE TO apmemo DO INSTEAD UPDATE public.apopen SET apopen_duedate = new.due_date, apopen_terms_id = public.gettermsid(new.terms), apopen_amount = new.amount, apopen_notes = new.notes WHERE ((apopen.apopen_docnumber = old.document_number) AND ((apopen.apopen_doctype)::text = CASE WHEN (old.document_type = 'Credit Memo'::text) THEN 'C'::text WHEN (old.document_type = 'Debit Memo'::text) THEN 'D'::text ELSE ''::text END));
117368
117369
117370 --
117371 -- TOC entry 8791 (class 2618 OID 146572018)
117372 -- Dependencies: 217 217 217 217 217 217 217 217 217 217 212 212 1769 1749 1743 217 8894
117373 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117374 --
117375
117376 CREATE RULE "_UPDATE" AS ON UPDATE TO armemo DO INSTEAD UPDATE public.aropen SET aropen_duedate = new.due_date, aropen_terms_id = public.gettermsid(new.terms), aropen_salesrep_id = public.getsalesrepid(new.sales_rep), aropen_amount = new.amount, aropen_commission_due = new.commission_due, aropen_notes = new.notes, aropen_rsncode_id = public.getrsnid(new.reason_code) WHERE ((aropen.aropen_docnumber = old.document_number) AND ((aropen.aropen_doctype)::text = CASE WHEN (old.document_type = 'Credit Memo'::text) THEN 'C'::text WHEN (old.document_type = 'Debit Memo'::text) THEN 'D'::text ELSE ''::text END));
117377
117378
117379 --
117380 -- TOC entry 8792 (class 2618 OID 146572020)
117381 -- Dependencies: 194 194 194 8894
117382 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117383 --
117384
117385 CREATE RULE "_UPDATE" AS ON UPDATE TO physinvcount DO INSTEAD NOTHING;
117386
117387
117388 --
117389 -- TOC entry 8793 (class 2618 OID 146572021)
117390 -- Dependencies: 235 235 235 235 235 235 235 235 235 205 1680 1670 235 8894
117391 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117392 --
117393
117394 CREATE RULE "_UPDATE" AS ON UPDATE TO account DO INSTEAD UPDATE public.crmacct SET crmacct_number = new.account_number, crmacct_parent_id = public.getcrmacctid(new.parent_account), crmacct_name = new.account_name, crmacct_active = new.active, crmacct_type = CASE WHEN (new.type = 'Individual'::text) THEN 'I'::text ELSE 'O'::text END, crmacct_cntct_id_1 = public.getcntctid(new.primary_contact_number), crmacct_cntct_id_2 = public.getcntctid(new.secondary_contact_number), crmacct_notes = new.notes WHERE (crmacct.crmacct_number = (old.account_number)::text);
117395
117396
117397 --
117398 -- TOC entry 8794 (class 2618 OID 146572023)
117399 -- Dependencies: 238 238 238 238 237 237 237 1680 1665 238 8894
117400 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117401 --
117402
117403 CREATE RULE "_UPDATE" AS ON UPDATE TO accountchar DO INSTEAD UPDATE public.charass SET charass_value = new.value WHERE (((charass.charass_target_type = 'CRMACCT'::text) AND (charass.charass_target_id = public.getcrmacctid((old.account_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'CRMACCT'::text)));
117404
117405
117406 --
117407 -- TOC entry 8795 (class 2618 OID 146572024)
117408 -- Dependencies: 241 241 241 8894
117409 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117410 --
117411
117412 CREATE RULE "_UPDATE" AS ON UPDATE TO accountcomment DO INSTEAD NOTHING;
117413
117414
117415 --
117416 -- TOC entry 8796 (class 2618 OID 146572025)
117417 -- Dependencies: 246 246 246 246 245 245 245 245 1680 246 8894
117418 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117419 --
117420
117421 CREATE RULE "_UPDATE" AS ON UPDATE TO accountfile DO INSTEAD UPDATE public.url SET url_title = new.title, url_url = new.url WHERE ((((url.url_source_id = public.getcrmacctid(old.account_number)) AND (url.url_source = 'CRMA'::text)) AND (url.url_title = old.title)) AND (url.url_url = old.url));
117422
117423
117424 --
117425 -- TOC entry 8797 (class 2618 OID 146572026)
117426 -- Dependencies: 250 250 250 249 249 249 1702 1680 250 8894
117427 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117428 --
117429
117430 CREATE RULE "_UPDATE" AS ON UPDATE TO accountimage DO INSTEAD UPDATE public.imageass SET imageass_image_id = public.getimageid(new.image_name) WHERE (((imageass.imageass_source_id = public.getcrmacctid(old.account_number)) AND (imageass.imageass_source = 'CRMA'::text)) AND (imageass.imageass_image_id = public.getimageid(old.image_name)));
117431
117432
117433 --
117434 -- TOC entry 8798 (class 2618 OID 146572027)
117435 -- Dependencies: 251 251 251 251 251 251 251 251 251 251 251 251 2157 1658 251 8894
117436 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117437 --
117438
117439 CREATE RULE "_UPDATE" AS ON UPDATE TO address DO INSTEAD SELECT public.saveaddr(public.getaddrid((new.address_number)::text), (new.address_number)::text, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.active, new.notes, new.change) AS saveaddr;
117440
117441
117442 --
117443 -- TOC entry 8799 (class 2618 OID 146572028)
117444 -- Dependencies: 252 252 252 252 237 237 237 1665 1658 252 8894
117445 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117446 --
117447
117448 CREATE RULE "_UPDATE" AS ON UPDATE TO addresschar DO INSTEAD UPDATE public.charass SET charass_value = new.value WHERE (((charass.charass_target_type = 'ADDR'::text) AND (charass.charass_target_id = public.getaddrid((old.address_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'ADDR'::text)));
117449
117450
117451 --
117452 -- TOC entry 8800 (class 2618 OID 146572029)
117453 -- Dependencies: 253 253 253 8894
117454 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117455 --
117456
117457 CREATE RULE "_UPDATE" AS ON UPDATE TO addresscomment DO INSTEAD NOTHING;
117458
117459
117460 --
117461 -- TOC entry 8801 (class 2618 OID 146572030)
117462 -- Dependencies: 255 255 255 255 255 255 255 2160 1714 255 8894
117463 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117464 --
117465
117466 CREATE RULE "_UPDATE" AS ON UPDATE TO bom DO INSTEAD SELECT public.savebomhead(public.getitemid((new.item_number)::text), (new.revision)::text, new.revision_date, new.document_number, COALESCE(new.batch_size, (0)::numeric), new.total_qty_per) AS savebomhead;
117467
117468
117469 --
117470 -- TOC entry 8802 (class 2618 OID 146572031)
117471 -- Dependencies: 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 256 203 2233 1771 1742 1665 1650 1519 256 8894
117472 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117473 --
117474
117475 CREATE RULE "_UPDATE" AS ON UPDATE TO bomitem DO INSTEAD UPDATE public.bomitem SET bomitem_issuemethod = CASE WHEN (new.issue_method = 'Mixed'::text) THEN 'M'::text WHEN (new.issue_method = 'Push'::text) THEN 'S'::text WHEN (new.issue_method = 'Pull'::text) THEN 'L'::text ELSE NULL::text END, bomitem_uom_id = public.getuomid(new.issue_uom), bomitem_qtyper = new.qty_per, bomitem_scrap = new.scrap, bomitem_effective = CASE WHEN (new.effective = 'Always'::text) THEN public.startoftime() ELSE (new.effective)::date END, bomitem_expires = CASE WHEN (new.expires = 'Never'::text) THEN public.endoftime() ELSE (new.expires)::date END, bomitem_createwo = new.create_child_wo, bomitem_booitem_seq_id = COALESCE(public.getbooitemseqid((new.bom_item_number)::text, new.used_at), (-1)), bomitem_schedatwooper = new.schedule_at_wo_operation, bomitem_ecn = new.ecn_number, bomitem_subtype = CASE WHEN (new.substitutions = 'No'::text) THEN 'N'::text WHEN (new.substitutions = 'Item-Defined'::text) THEN 'I'::text WHEN (new.substitutions = 'BOM-Defined'::text) THEN 'B'::text ELSE NULL::text END, bomitem_rev_id = public.getrevid('BOM'::text, (new.bom_item_number)::text, (new.bom_revision)::text), bomitem_char_id = public.getcharid(new.characteristic, 'I'::text), bomitem_value = new.value, bomitem_notes = new.notes, bomitem_ref = new.reference WHERE (bomitem.bomitem_id = old.id);
117476
117477
117478 --
117479 -- TOC entry 8803 (class 2618 OID 146572033)
117480 -- Dependencies: 257 257 257 8894
117481 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117482 --
117483
117484 CREATE RULE "_UPDATE" AS ON UPDATE TO bomitemcomment DO INSTEAD NOTHING;
117485
117486
117487 --
117488 -- TOC entry 8804 (class 2618 OID 146572034)
117489 -- Dependencies: 259 259 259 259 259 258 258 1714 259 8894
117490 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117491 --
117492
117493 CREATE RULE "_UPDATE" AS ON UPDATE TO bomitemsubstitute DO INSTEAD UPDATE public.bomitemsub SET bomitemsub_uomratio = new.sub_parent_uom_ratio, bomitemsub_rank = new.ranking WHERE ((bomitemsub.bomitemsub_bomitem_id = old.bomitem_id) AND (bomitemsub.bomitemsub_item_id = public.getitemid((old.substitute_item_number)::text)));
117494
117495
117496 --
117497 -- TOC entry 8805 (class 2618 OID 146572035)
117498 -- Dependencies: 261 261 261 260 261 8894
117499 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117500 --
117501
117502 CREATE RULE "_UPDATE" AS ON UPDATE TO budget DO INSTEAD UPDATE public.budghead SET budghead_name = new.name, budghead_descrip = new.description WHERE (budghead.budghead_name = old.name);
117503
117504
117505 --
117506 -- TOC entry 8806 (class 2618 OID 146572036)
117507 -- Dependencies: 265 265 265 265 265 263 263 263 1730 1700 1663 265 8894
117508 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117509 --
117510
117511 CREATE RULE "_UPDATE" AS ON UPDATE TO budgetentry DO INSTEAD UPDATE public.budgitem SET budgitem_amount = new.amount WHERE (((budgitem.budgitem_budghead_id = public.getbudgheadid(old.name)) AND (budgitem.budgitem_period_id = public.getperiodid(old.period_start))) AND (budgitem.budgitem_accnt_id = public.getglaccntid(old.account)));
117512
117513
117514 --
117515 -- TOC entry 8807 (class 2618 OID 146572037)
117516 -- Dependencies: 268 268 268 268 268 268 268 268 268 268 268 268 267 1744 1681 1664 1661 268 8894
117517 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117518 --
117519
117520 CREATE RULE "_UPDATE" AS ON UPDATE TO cashreceipt DO INSTEAD UPDATE public.cashrcpt SET cashrcpt_amount = new.amount_received, cashrcpt_number = new.cashreceipt_number, cashrcpt_fundstype = CASE WHEN ((new.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((new.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((new.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((new.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((new.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((new.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((new.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((new.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((new.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, cashrcpt_docnumber = new.check_document_number, cashrcpt_bankaccnt_id = public.getbankaccntid(new.post_to), cashrcpt_notes = new.notes, cashrcpt_distdate = CASE WHEN (new.distribution_date > ''::text) THEN (new.distribution_date)::date ELSE NULL::date END, cashrcpt_salescat_id = public.getsalescatid(new.sales_category), cashrcpt_curr_id = public.getcurrid((new.currency)::text), cashrcpt_usecustdeposit = CASE WHEN (new.apply_balance_as = 'Customer Deposit'::text) THEN true ELSE false END WHERE (cashrcpt.cashrcpt_id = public.getcashrcptid((old.customer_number)::text, CASE WHEN ((old.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((old.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((old.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((old.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((old.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((old.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((old.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((old.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((old.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (old.check_document_number)::text));
117521
117522
117523 --
117524 -- TOC entry 8808 (class 2618 OID 146572039)
117525 -- Dependencies: 270 270 270 270 270 270 270 270 269 269 1664 1660 270 8894
117526 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117527 --
117528
117529 CREATE RULE "_UPDATE" AS ON UPDATE TO cashreceiptapply DO INSTEAD UPDATE public.cashrcptitem SET cashrcptitem_amount = new.amount_to_apply, cashrcptitem_discount = new.cashrcptitem_discount WHERE ((cashrcptitem.cashrcptitem_cashrcpt_id = public.getcashrcptid((old.customer_number)::text, CASE WHEN ((old.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((old.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((old.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((old.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((old.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((old.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((old.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((old.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((old.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (old.check_document_number)::text)) AND (cashrcptitem.cashrcptitem_aropen_id = public.getaropenid((old.customer_number)::text, (old.doc_type)::bpchar, (old.doc_number)::text)));
117530
117531
117532 --
117533 -- TOC entry 8809 (class 2618 OID 146572041)
117534 -- Dependencies: 272 272 272 272 272 272 272 271 271 1700 1664 272 8894
117535 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117536 --
117537
117538 CREATE RULE "_UPDATE" AS ON UPDATE TO cashreceiptapplymisc DO INSTEAD UPDATE public.cashrcptmisc SET cashrcptmisc_accnt_id = public.getglaccntid((new.account)::text), cashrcptmisc_amount = new.amount_to_distribute, cashrcptmisc_notes = new.notes WHERE ((cashrcptmisc.cashrcptmisc_cashrcpt_id = public.getcashrcptid((old.customer_number)::text, CASE WHEN ((old.funds_type)::text = 'Check'::text) THEN 'C'::text WHEN ((old.funds_type)::text = 'Certified Check'::text) THEN 'T'::text WHEN ((old.funds_type)::text = 'Master Card'::text) THEN 'M'::text WHEN ((old.funds_type)::text = 'Visa'::text) THEN 'V'::text WHEN ((old.funds_type)::text = 'American Express'::text) THEN 'A'::text WHEN ((old.funds_type)::text = 'Discover Card'::text) THEN 'D'::text WHEN ((old.funds_type)::text = 'Other Credit Card'::text) THEN 'R'::text WHEN ((old.funds_type)::text = 'Cash'::text) THEN 'K'::text WHEN ((old.funds_type)::text = 'Wire Transfer'::text) THEN 'W'::text ELSE 'O'::text END, (old.check_document_number)::text)) AND (cashrcptmisc.cashrcptmisc_accnt_id = public.getglaccntid((old.account)::text)));
117539
117540
117541 --
117542 -- TOC entry 8810 (class 2618 OID 146572043)
117543 -- Dependencies: 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 273 2161 2158 1680 1670 1658 273 8894
117544 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117545 --
117546
117547 CREATE RULE "_UPDATE" AS ON UPDATE TO contact DO INSTEAD SELECT public.savecntct(public.getcntctid((new.contact_number)::text), (new.contact_number)::text, public.getcrmacctid(new.crm_account), public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.address_change), new.honorific, new.first, new.middle, new.last, new.suffix, new.initials, new.active, new.voice, new.alternate, new.fax, new.email, new.web, new.notes, new.job_title, new.contact_change) AS savecntct;
117548
117549
117550 --
117551 -- TOC entry 8811 (class 2618 OID 146572044)
117552 -- Dependencies: 274 274 274 274 237 237 237 1670 1665 274 8894
117553 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117554 --
117555
117556 CREATE RULE "_UPDATE" AS ON UPDATE TO contactchar DO INSTEAD UPDATE public.charass SET charass_value = new.value WHERE (((charass.charass_target_type = 'CNTCT'::text) AND (charass.charass_target_id = public.getcntctid(old.contact_number))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'CNTCT'::text)));
117557
117558
117559 --
117560 -- TOC entry 8812 (class 2618 OID 146572045)
117561 -- Dependencies: 275 275 275 8894
117562 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117563 --
117564
117565 CREATE RULE "_UPDATE" AS ON UPDATE TO contactcomment DO INSTEAD NOTHING;
117566
117567
117568 --
117569 -- TOC entry 8813 (class 2618 OID 146572046)
117570 -- Dependencies: 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 221 218 218 214 214 1768 1756 1749 1700 1681 221 8894
117571 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117572 --
117573
117574 CREATE RULE "_UPDATE" AS ON UPDATE TO creditmemo DO INSTEAD UPDATE public.cmhead SET cmhead_custponumber = new.customer_po_number, cmhead_docdate = new.memo_date, cmhead_shipto_id = COALESCE(public.getshiptoid(new.customer_number, new.shipto_number), (-1)), cmhead_shipto_name = new.shipto_name, cmhead_shipto_address1 = new.shipto_address1, cmhead_shipto_address2 = new.shipto_address2, cmhead_shipto_address3 = new.shipto_address3, cmhead_shipto_city = new.shipto_city, cmhead_shipto_state = new.shipto_state, cmhead_shipto_zipcode = new.shipto_postal_code, cmhead_shipto_country = new.shipto_country, cmhead_salesrep_id = public.getsalesrepid(new.sales_rep), cmhead_freight = COALESCE(new.freight, (0)::numeric), cmhead_misc = COALESCE(new.misc_charge_amount, (0)::numeric), cmhead_comments = new.notes, cmhead_billtoname = new.billto_name, cmhead_billtoaddress1 = new.billto_address1, cmhead_billtoaddress2 = new.billto_address2, cmhead_billtoaddress3 = new.billto_address3, cmhead_billtocity = new.billto_city, cmhead_billtostate = new.billto_state, cmhead_billtozip = new.billto_postal_code, cmhead_billtocountry = new.billto_country, cmhead_hold = COALESCE(new.on_hold, false), cmhead_commission = COALESCE(new.commission, (0)::numeric), cmhead_misc_accnt_id = COALESCE(public.getglaccntid(new.misc_charge_credit_account), (-1)), cmhead_misc_descrip = new.misc_charge_description, cmhead_rsncode_id = (SELECT rsncode.rsncode_id FROM public.rsncode WHERE (rsncode.rsncode_code = new.reason_code)), cmhead_curr_id = COALESCE(public.getcurrid((new.currency)::text), (-1)), cmhead_taxzone_id = public.gettaxzoneid(NULLIF(new.tax_zone, 'None'::text)) WHERE ((cmhead.cmhead_number = old.memo_number) AND (cmhead.cmhead_posted = false));
117575
117576
117577 --
117578 -- TOC entry 8814 (class 2618 OID 146572048)
117579 -- Dependencies: 223 223 2287 223 8894
117580 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117581 --
117582
117583 CREATE RULE "_UPDATE" AS ON UPDATE TO creditmemoline DO INSTEAD SELECT public.updatecreditmemoline(new.*, old.*) AS updatecreditmemoline;
117584
117585
117586 --
117587 -- TOC entry 8815 (class 2618 OID 146572049)
117588 -- Dependencies: 276 276 276 276 237 237 237 1682 1665 276 8894
117589 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117590 --
117591
117592 CREATE RULE "_UPDATE" AS ON UPDATE TO custchar DO INSTEAD UPDATE public.charass SET charass_value = new.value WHERE (((charass.charass_target_type = 'C'::text) AND (charass.charass_target_id = public.getcustid((old.customer_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'C'::text)));
117593
117594
117595 --
117596 -- TOC entry 8816 (class 2618 OID 146572050)
117597 -- Dependencies: 277 277 277 8894
117598 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117599 --
117600
117601 CREATE RULE "_UPDATE" AS ON UPDATE TO custcomment DO INSTEAD NOTHING;
117602
117603
117604 --
117605 -- TOC entry 8817 (class 2618 OID 146572051)
117606 -- Dependencies: 279 279 279 8894
117607 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117608 --
117609
117610 CREATE RULE "_UPDATE" AS ON UPDATE TO custcreditcard DO INSTEAD NOTHING;
117611
117612
117613 --
117614 -- TOC entry 8818 (class 2618 OID 146572052)
117615 -- Dependencies: 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 283 213 2162 2158 1780 1769 1768 1754 1753 1749 1686 1682 1681 1671 1658 283 8894
117616 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117617 --
117618
117619 CREATE RULE "_UPDATE" AS ON UPDATE TO customer DO INSTEAD UPDATE public.custinfo SET cust_active = new.active, cust_custtype_id = public.getcusttypeid(new.customer_type), cust_salesrep_id = public.getsalesrepid(new.sales_rep), cust_commprcnt = (new.commission * 0.01), cust_name = new.customer_name, cust_creditlmt = new.credit_limit, cust_creditrating = new.credit_rating, cust_backorder = new.accepts_backorders, cust_partialship = new.accepts_partial_shipments, cust_terms_id = public.gettermsid(new.default_terms), cust_discntprcnt = new.default_discount, cust_balmethod = CASE WHEN (new.balance_method = 'Balance Forward'::text) THEN 'B'::text WHEN (new.balance_method = 'Open Items'::text) THEN 'O'::text ELSE NULL::text END, cust_ffshipto = new.allow_free_form_shipto, cust_shipform_id = public.getshipformid(new.ship_form), cust_shipvia = new.ship_via, cust_blanketpos = new.uses_blanket_pos, cust_shipchrg_id = COALESCE(public.getshipchrgid(new.shipping_charges), (-1)), cust_creditstatus = CASE WHEN (new.credit_status = 'On Credit Warning'::text) THEN 'W'::text WHEN (new.credit_status = 'On Credit Hold'::text) THEN 'H'::text ELSE 'G'::text END, cust_comments = new.notes, cust_ffbillto = new.allow_free_form_billto, cust_usespos = new.uses_purchase_orders, cust_number = new.customer_number, cust_autoupdatestatus = new.credit_status_exceed_warn, cust_autoholdorders = new.credit_status_exceed_hold, cust_preferred_warehous_id = COALESCE(public.getwarehousid(new.preferred_selling_site, 'ACTIVE'::text), (-1)), cust_curr_id = public.getcurrid((new.default_currency)::text), cust_creditlmt_curr_id = public.getcurrid((new.credit_limit_currency)::text), cust_cntct_id = public.savecntct(public.getcntctid(new.billing_contact_number, false), new.billing_contact_number, public.saveaddr(public.getaddrid(new.billing_contact_address_number), new.billing_contact_address_number, new.billing_contact_address1, new.billing_contact_address2, new.billing_contact_address3, new.billing_contact_city, new.billing_contact_state, new.billing_contact_postalcode, new.billing_contact_country, new.billing_contact_address_change), new.billing_contact_honorific, new.billing_contact_first, new.billing_contact_middle, new.billing_contact_last, new.billing_contact_suffix, new.billing_contact_voice, new.billing_contact_alternate, new.billing_contact_fax, new.billing_contact_email, new.billing_contact_web, new.billing_contact_job_title, new.billing_contact_change), cust_corrcntct_id = public.savecntct(public.getcntctid(new.correspond_contact_number, false), new.correspond_contact_number, public.saveaddr(public.getaddrid(new.correspond_contact_address_number), new.correspond_contact_address_number, new.correspond_contact_address1, new.correspond_contact_address2, new.correspond_contact_address3, new.correspond_contact_city, new.correspond_contact_state, new.correspond_contact_postalcode, new.correspond_contact_country, new.correspond_contact_address_change), new.correspond_contact_honorific, new.correspond_contact_first, new.correspond_contact_middle, new.correspond_contact_last, new.correspond_contact_suffix, new.correspond_contact_voice, new.correspond_contact_alternate, new.correspond_contact_fax, new.correspond_contact_email, new.correspond_contact_web, new.correspond_contact_job_title, new.correspond_contact_change), cust_taxzone_id = public.gettaxzoneid(new.default_tax_zone), cust_gracedays = CASE WHEN (COALESCE(new.alternate_grace_days, 0) > 0) THEN new.alternate_grace_days ELSE NULL::integer END WHERE (custinfo.cust_id = public.getcustid((old.customer_number)::text));
117620
117621
117622 --
117623 -- TOC entry 8819 (class 2618 OID 146572054)
117624 -- Dependencies: 287 287 287 287 280 287 8894
117625 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117626 --
117627
117628 CREATE RULE "_UPDATE" AS ON UPDATE TO customertype DO INSTEAD UPDATE public.custtype SET custtype_code = new.code, custtype_descrip = new.description, custtype_char = new.enable_characteristics_profile WHERE (custtype.custtype_code = (old.code)::text);
117629
117630
117631 --
117632 -- TOC entry 8820 (class 2618 OID 146572055)
117633 -- Dependencies: 288 288 288 288 288 237 237 237 1686 1665 288 8894
117634 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117635 --
117636
117637 CREATE RULE "_UPDATE" AS ON UPDATE TO customertypechar DO INSTEAD UPDATE public.charass SET charass_value = new.value, charass_default = new.is_default WHERE (((charass.charass_target_type = 'CT'::text) AND (charass.charass_target_id = public.getcusttypeid((old.customer_type)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'CT'::text)));
117638
117639
117640 --
117641 -- TOC entry 8821 (class 2618 OID 146572056)
117642 -- Dependencies: 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 289 219 2162 2158 1768 1759 1756 1754 1753 1749 1688 1682 1670 1658 289 8894
117643 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117644 --
117645
117646 CREATE RULE "_UPDATE" AS ON UPDATE TO custshipto DO INSTEAD UPDATE public.shiptoinfo SET shipto_cust_id = public.getcustid((new.customer_number)::text), shipto_name = new.name, shipto_salesrep_id = public.getsalesrepid(new.sales_rep), shipto_comments = new.general_notes, shipto_shipcomments = new.shipping_notes, shipto_shipzone_id = public.getshipzoneid(new.zone), shipto_shipvia = new.ship_via, shipto_commission = (new.commission / (100)::numeric), shipto_shipform_id = public.getshipformid(new.ship_form), shipto_shipchrg_id = public.getshipchrgid(new.shipping_charges), shipto_active = new.active, shipto_default = new.default_flag, shipto_num = old.shipto_number, shipto_ediprofile_id = CASE WHEN (new.edi_profile = 'No EDI'::text) THEN (-1) WHEN (new.edi_profile = 'Use Customer Master'::text) THEN (-2) ELSE public.getediprofileid(new.edi_profile) END, shipto_cntct_id = public.savecntct(public.getcntctid(new.contact_number), new.contact_number, NULL::integer, new.honorific, new.first, new.middle, new.last, new.suffix, new.phone, NULL::text, new.fax, new.email, NULL::text, new.job_title, new.contact_change), shipto_addr_id = public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.address_change), shipto_taxzone_id = public.gettaxzoneid(new.tax_zone) WHERE (shiptoinfo.shipto_id = public.getshiptoid((old.customer_number)::text, (old.shipto_number)::text));
117647
117648
117649 --
117650 -- TOC entry 8822 (class 2618 OID 146572058)
117651 -- Dependencies: 290 290 290 290 285 285 285 1765 1682 290 8894
117652 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117653 --
117654
117655 CREATE RULE "_UPDATE" AS ON UPDATE TO custtax DO INSTEAD UPDATE public.taxreg SET taxreg_number = new.registration_number WHERE (((taxreg.taxreg_rel_type = 'C'::bpchar) AND (taxreg.taxreg_rel_id = public.getcustid((old.customer_number)::text))) AND (taxreg.taxreg_taxauth_id = public.gettaxauthid((old.tax_authority)::text)));
117656
117657
117658 --
117659 -- TOC entry 8823 (class 2618 OID 146572059)
117660 -- Dependencies: 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 294 292 292 2162 2158 1780 1752 1702 1687 1681 1670 1658 907 294 8894
117661 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117662 --
117663
117664 CREATE RULE "_UPDATE" AS ON UPDATE TO employee DO INSTEAD UPDATE public.emp SET emp_code = new.code, emp_number = new.number, emp_active = new.active, emp_startdate = new.start_date, emp_cntct_id = public.savecntct(public.getcntctid(new.contact_number), new.contact_number, public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change), new.honorific, new.first, new.middle, new.last, new.suffix, new.voice, new.alternate, new.fax, new.email, new.web, new.job_title, new.contact_change), emp_warehous_id = public.getwarehousid(new.site, 'ALL'::text), emp_mgr_emp_id = (SELECT emp.emp_id FROM public.emp WHERE (emp.emp_code = new.manager_code)), emp_wage_type = CASE WHEN (new.wage_type = 'Hourly'::text) THEN 'H'::text WHEN (new.wage_type = 'Salaried'::text) THEN 'S'::text ELSE NULL::text END, emp_wage = new.wage, emp_wage_curr_id = COALESCE(public.getcurrid((new.wage_currency)::text), public.basecurrid()), emp_wage_period = CASE WHEN (new.wage_period = 'Hour'::text) THEN 'H'::text WHEN (new.wage_period = 'Day'::text) THEN 'D'::text WHEN (new.wage_period = 'Week'::text) THEN 'W'::text WHEN (new.wage_period = 'Biweek'::text) THEN 'BW'::text WHEN (new.wage_period = 'Month'::text) THEN 'M'::text WHEN (new.wage_period = 'Year'::text) THEN 'Y'::text ELSE NULL::text END, emp_dept_id = public.getdeptid(new.department), emp_shift_id = public.getshiftid(new.shift), emp_image_id = public.getimageid(new.image), emp_extrate = new.rate, emp_extrate_period = CASE WHEN (new.billing_period = 'Hour'::text) THEN 'H'::text WHEN (new.billing_period = 'Day'::text) THEN 'D'::text WHEN (new.billing_period = 'Week'::text) THEN 'W'::text WHEN (new.billing_period = 'Biweek'::text) THEN 'BW'::text WHEN (new.billing_period = 'Month'::text) THEN 'M'::text WHEN (new.billing_period = 'Year'::text) THEN 'Y'::text ELSE NULL::text END, emp_notes = COALESCE(new.notes, ''::text) WHERE (emp.emp_code = (old.code)::text);
117665
117666
117667 --
117668 -- TOC entry 8824 (class 2618 OID 146572061)
117669 -- Dependencies: 295 295 295 295 237 237 237 1690 1665 295 8894
117670 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117671 --
117672
117673 CREATE RULE "_UPDATE" AS ON UPDATE TO employeechar DO INSTEAD UPDATE public.charass SET charass_value = new.value WHERE (((charass.charass_target_type = 'EMP'::text) AND (charass.charass_target_id = public.getempid((old.employee_code)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'EMP'::text)));
117674
117675
117676 --
117677 -- TOC entry 8825 (class 2618 OID 146572062)
117678 -- Dependencies: 296 296 296 8894
117679 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117680 --
117681
117682 CREATE RULE "_UPDATE" AS ON UPDATE TO employeecomment DO INSTEAD NOTHING;
117683
117684
117685 --
117686 -- TOC entry 8826 (class 2618 OID 146572063)
117687 -- Dependencies: 298 298 298 298 298 298 298 298 298 298 298 298 298 298 298 297 297 297 297 1681 298 8894
117688 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117689 --
117690
117691 CREATE RULE "_UPDATE" AS ON UPDATE TO extshipmaint DO INSTEAD UPDATE public.shipdata SET shipdata_cohead_number = new.so_number, shipdata_shiphead_number = new.shipment_number, shipdata_void_ind = new.void, shipdata_shipper = new.shipper, shipdata_billing_option = new.billing_option, shipdata_weight = new.weight, shipdata_base_freight = new.base_freight, shipdata_base_freight_curr_id = public.getcurrid((new.base_freight_currency)::text), shipdata_total_freight = new.total_freight, shipdata_total_freight_curr_id = public.getcurrid((new.total_freight_currency)::text), shipdata_package_type = new.package_type, shipdata_cosmisc_tracknum = new.tracking_number, shipdata_cosmisc_packnum_tracknum = new.package_tracking_number, shipdata_lastupdated = new.last_updated WHERE ((((shipdata.shipdata_cohead_number = (old.so_number)::text) AND (shipdata.shipdata_shiphead_number = (old.shipment_number)::text)) AND (shipdata.shipdata_shipper = (old.shipper)::text)) AND (shipdata.shipdata_cosmisc_packnum_tracknum = (old.package_tracking_number)::text));
117692
117693
117694 --
117695 -- TOC entry 8827 (class 2618 OID 146572064)
117696 -- Dependencies: 302 302 302 302 302 302 302 302 302 300 300 300 300 300 300 300 300 1780 1759 1684 1697 302 8894
117697 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117698 --
117699
117700 CREATE RULE "_UPDATE" AS ON UPDATE TO freightpricingscheduleitem DO INSTEAD UPDATE public.ipsfreight SET ipsfreight_ipshead_id = public.getipsheadid((old.pricing_schedule)::text), ipsfreight_qtybreak = new.qty_break, ipsfreight_price = new.price, ipsfreight_type = CASE WHEN (new.price_type = 'Flat Rate'::text) THEN 'F'::text WHEN (new.price_type = 'Price Per UOM'::text) THEN 'P'::text ELSE NULL::text END, ipsfreight_warehous_id = CASE WHEN (new.from_site = 'Any'::text) THEN NULL::integer ELSE public.getwarehousid(new.from_site, 'All'::text) END, ipsfreight_shipzone_id = CASE WHEN (new.to_shipzone = 'Any'::text) THEN NULL::integer ELSE public.getshipzoneid(new.to_shipzone) END, ipsfreight_freightclass_id = CASE WHEN (new.freight_class = 'Any'::text) THEN NULL::integer ELSE public.getfreightclassid(new.freight_class) END, ipsfreight_shipvia = CASE WHEN (new.ship_via = 'Any'::text) THEN NULL::text ELSE new.ship_via END WHERE (((((((((ipsfreight.ipsfreight_ipshead_id = public.getipsheadid((old.pricing_schedule)::text)) AND (ipsfreight.ipsfreight_qtybreak = old.qty_break)) AND (ipsfreight.ipsfreight_price = old.price)) AND ((ipsfreight.ipsfreight_type)::text = CASE WHEN (old.price_type = 'Flat Rate'::text) THEN 'F'::text WHEN (old.price_type = 'Price Per UOM'::text) THEN 'P'::text ELSE NULL::text END)) AND ((ipsfreight.ipsfreight_warehous_id IS NULL) AND (old.from_site = 'Any'::text))) OR ((ipsfreight.ipsfreight_warehous_id = CASE WHEN (old.from_site = 'Any'::text) THEN 0 ELSE public.getwarehousid(old.from_site, 'All'::text) END) AND ((ipsfreight.ipsfreight_shipzone_id IS NULL) AND (old.to_shipzone = 'Any'::text)))) OR ((ipsfreight.ipsfreight_shipzone_id = CASE WHEN (old.to_shipzone = 'Any'::text) THEN 0 ELSE public.getshipzoneid(old.to_shipzone) END) AND ((ipsfreight.ipsfreight_freightclass_id IS NULL) AND (old.freight_class = 'Any'::text)))) OR ((ipsfreight.ipsfreight_freightclass_id = CASE WHEN (old.freight_class = 'Any'::text) THEN 0 ELSE public.getfreightclassid(old.freight_class) END) AND ((ipsfreight.ipsfreight_shipvia IS NULL) AND (old.ship_via = 'Any'::text)))) OR (ipsfreight.ipsfreight_shipvia = old.ship_via));
117701
117702
117703 --
117704 -- TOC entry 8828 (class 2618 OID 146572066)
117705 -- Dependencies: 303 303 303 303 303 303 303 303 303 303 303 262 1701 303 8894
117706 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117707 --
117708
117709 CREATE RULE "_UPDATE" AS ON UPDATE TO glaccount DO INSTEAD UPDATE public.accnt SET accnt_number = new.account_number, accnt_descrip = new.description, accnt_comments = new.notes, accnt_profit = new.profit_center, accnt_sub = new.sub_account, accnt_type = CASE WHEN (new.type = 'Asset'::text) THEN 'A'::text WHEN (new.type = 'Liability'::text) THEN 'L'::text WHEN (new.type = 'Expense'::text) THEN 'E'::text WHEN (new.type = 'Revenue'::text) THEN 'R'::text WHEN (new.type = 'Equity'::text) THEN 'Q'::text ELSE NULL::text END, accnt_extref = new.ext_reference, accnt_company = new.company, accnt_forwardupdate = new.forward_update_trial_balances, accnt_subaccnttype_code = new.sub_type WHERE (accnt.accnt_id = public.getglaccntid((old.company)::text, (old.profit_center)::text, (old.account_number)::text, (old.sub_account)::text));
117710
117711
117712 --
117713 -- TOC entry 8829 (class 2618 OID 146572068)
117714 -- Dependencies: 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 308 206 2162 1721 1714 1708 1707 1706 1705 1703 1680 1670 308 8894
117715 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117716 --
117717
117718 CREATE RULE "_UPDATE" AS ON UPDATE TO incident DO INSTEAD UPDATE public.incdt SET incdt_crmacct_id = public.getcrmacctid(new.crm_account), incdt_cntct_id = public.savecntct(public.getcntctid(new.contact_number), new.contact_number, NULL::integer, new.honorific, new.first, new.middle, new.last, new.suffix, new.phone, NULL::text, new.fax, new.email, NULL::text, new.job_title, new.contact_change), incdt_descrip = new.notes, incdt_summary = new.description, incdt_item_id = public.getitemid(new.item_number), incdt_status = CASE WHEN (new.status = 'New'::text) THEN 'N'::text WHEN (new.status = 'Feedback'::text) THEN 'F'::text WHEN (new.status = 'Confirmed'::text) THEN 'C'::text WHEN (new.status = 'Assigned'::text) THEN 'A'::text WHEN (new.status = 'Resolved'::text) THEN 'R'::text WHEN (new.status = 'Closed'::text) THEN 'L'::text ELSE NULL::text END, incdt_assigned_username = new.assigned_to, incdt_incdtcat_id = public.getincdtcatid(new.category), incdt_incdtseverity_id = public.getincdtseverityid(new.severity), incdt_incdtpriority_id = public.getincdtpriorityid(new.priority), incdt_incdtresolution_id = public.getincdtresolutionid(new.resolution), incdt_lotserial = new.lot_serial_number, incdt_ls_id = public.getlotserialid(new.item_number, new.lot_serial_number) WHERE (incdt.incdt_id = public.getincidentid(old.incident_number));
117719
117720
117721 --
117722 -- TOC entry 8830 (class 2618 OID 146572070)
117723 -- Dependencies: 309 309 309 309 237 237 237 1708 1665 309 8894
117724 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117725 --
117726
117727 CREATE RULE "_UPDATE" AS ON UPDATE TO incidentchar DO INSTEAD UPDATE public.charass SET charass_value = new.value WHERE (((charass.charass_target_type = 'INCDT'::text) AND (charass.charass_target_id = public.getincidentid(old.incident_number))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'INCDT'::text)));
117728
117729
117730 --
117731 -- TOC entry 8831 (class 2618 OID 146572071)
117732 -- Dependencies: 310 310 310 8894
117733 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117734 --
117735
117736 CREATE RULE "_UPDATE" AS ON UPDATE TO incidentcomment DO INSTEAD NOTHING;
117737
117738
117739 --
117740 -- TOC entry 8832 (class 2618 OID 146572072)
117741 -- Dependencies: 311 311 311 311 245 245 245 245 1708 311 8894
117742 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117743 --
117744
117745 CREATE RULE "_UPDATE" AS ON UPDATE TO incidentfile DO INSTEAD UPDATE public.url SET url_title = new.title, url_url = new.url WHERE ((((url.url_source_id = public.getincidentid(old.incident_number)) AND (url.url_source = 'INCDT'::text)) AND (url.url_title = old.title)) AND (url.url_url = old.url));
117746
117747
117748 --
117749 -- TOC entry 8833 (class 2618 OID 146572073)
117750 -- Dependencies: 312 312 312 249 249 249 1708 1702 312 8894
117751 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117752 --
117753
117754 CREATE RULE "_UPDATE" AS ON UPDATE TO incidentimage DO INSTEAD UPDATE public.imageass SET imageass_image_id = public.getimageid(new.image_name) WHERE (((imageass.imageass_source_id = public.getincidentid(old.incident_number)) AND (imageass.imageass_source = 'INCDT'::text)) AND (imageass.imageass_image_id = public.getimageid(old.image_name)));
117755
117756
117757 --
117758 -- TOC entry 8834 (class 2618 OID 146572074)
117759 -- Dependencies: 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 228 224 224 1769 1768 1759 1756 1751 1749 1736 1700 1682 1681 228 8894
117760 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117761 --
117762
117763 CREATE RULE "_UPDATE" AS ON UPDATE TO invoice DO INSTEAD UPDATE public.invchead SET invchead_invcnumber = old.invoice_number, invchead_ordernumber = new.order_number, invchead_invcdate = new.invoice_date, invchead_shipdate = new.ship_date, invchead_orderdate = new.order_date, invchead_salesrep_id = public.getsalesrepid(new.sales_rep), invchead_commission = new.commission, invchead_taxzone_id = public.gettaxzoneid(NULLIF(new.tax_zone, 'None'::text)), invchead_terms_id = public.gettermsid(new.terms), invchead_cust_id = (SELECT public.getcustid(new.customer_number) AS getcustid), invchead_billto_name = new.billto_name, invchead_billto_address1 = new.billto_address1, invchead_billto_address2 = new.billto_address2, invchead_billto_address3 = new.billto_address3, invchead_billto_city = new.billto_city, invchead_billto_state = new.billto_state, invchead_billto_zipcode = new.billto_postal_code, invchead_billto_country = new.billto_country, invchead_billto_phone = new.billto_phone, invchead_shipto_id = COALESCE(public.getshiptoid(new.customer_number, new.shipto_number), (-1)), invchead_shipto_name = new.shipto_name, invchead_shipto_address1 = new.shipto_address1, invchead_shipto_address2 = new.shipto_address2, invchead_shipto_address3 = new.shipto_address3, invchead_shipto_city = new.shipto_city, invchead_shipto_state = new.shipto_state, invchead_shipto_zipcode = new.shipto_postal_code, invchead_shipto_country = new.shipto_country, invchead_shipto_phone = new.shipto_phone, invchead_ponumber = new.po_number, invchead_shipvia = new.ship_via, invchead_prj_id = COALESCE(public.getprjid(new.project_number), (-1)), invchead_fob = new.fob, invchead_misc_descrip = new.misc_charge_description, invchead_misc_amount = new.misc_charge, invchead_misc_accnt_id = COALESCE(public.getglaccntid(new.misc_charge_account_number), (-1)), invchead_freight = new.freight, invchead_curr_id = COALESCE(public.getcurrid((new.currency)::text), (-1)), invchead_payment = new.payment, invchead_notes = new.notes, invchead_saletype_id = public.getsaletypeid(new.sale_type), invchead_shipzone_id = public.getshipzoneid(new.shipto_shipzone) WHERE ((invchead.invchead_invcnumber = old.invoice_number) AND (invchead.invchead_posted = false));
117764
117765
117766 --
117767 -- TOC entry 8835 (class 2618 OID 146572076)
117768 -- Dependencies: 230 230 2291 230 8894
117769 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117770 --
117771
117772 CREATE RULE "_UPDATE" AS ON UPDATE TO invoiceline DO INSTEAD SELECT public.updateinvoicelineitem(new.*, old.*) AS updateinvoicelineitem;
117773
117774
117775 --
117776 -- TOC entry 8836 (class 2618 OID 146572077)
117777 -- Dependencies: 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 315 191 1771 1738 1714 1666 315 8894
117778 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117779 --
117780
117781 CREATE RULE "_UPDATE" AS ON UPDATE TO item DO INSTEAD UPDATE public.item SET item_active = new.active, item_descrip1 = new.description1, item_descrip2 = new.description2, item_type = CASE WHEN (new.item_type = 'Purchased'::text) THEN 'P'::text WHEN (new.item_type = 'Manufactured'::text) THEN 'M'::text WHEN (new.item_type = 'Job'::text) THEN 'J'::text WHEN (new.item_type = 'Kit'::text) THEN 'K'::text WHEN (new.item_type = 'Phantom'::text) THEN 'F'::text WHEN (new.item_type = 'Reference'::text) THEN 'R'::text WHEN (new.item_type = 'Costing'::text) THEN 'S'::text WHEN (new.item_type = 'Tooling'::text) THEN 'T'::text WHEN (new.item_type = 'Outside Process'::text) THEN 'O'::text WHEN (new.item_type = 'Planning'::text) THEN 'L'::text WHEN (new.item_type = 'Breeder'::text) THEN 'B'::text WHEN (new.item_type = 'Co-Product'::text) THEN 'C'::text WHEN (new.item_type = 'By-Product'::text) THEN 'Y'::text ELSE NULL::text END, item_maxcost = new.maximum_desired_cost, item_classcode_id = public.getclasscodeid(new.class_code), item_inv_uom_id = public.getuomid(new.inventory_uom), item_picklist = new.pick_list_item, item_fractional = new.fractional, item_config = new.configured, item_sold = new.item_is_sold, item_prodcat_id = COALESCE(public.getprodcatid(new.product_category), (-1)), item_exclusive = new.exclusive, item_listprice = new.list_price, item_listcost = new.list_cost, item_price_uom_id = public.getuomid(new.list_price_uom), item_upccode = new.upc_code, item_prodweight = new.product_weight, item_packweight = new.packaging_weight, item_comments = new.notes, item_extdescrip = new.ext_description WHERE (item.item_id = public.getitemid((old.item_number)::text));
117782
117783
117784 --
117785 -- TOC entry 8837 (class 2618 OID 146572079)
117786 -- Dependencies: 317 317 317 317 317 317 317 316 316 1714 317 8894
117787 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117788 --
117789
117790 CREATE RULE "_UPDATE" AS ON UPDATE TO itemalias DO INSTEAD UPDATE public.itemalias SET itemalias_number = new.alias_number, itemalias_usedescrip = new.use_description, itemalias_descrip1 = new.description1, itemalias_descrip2 = new.description2, itemalias_comments = new.comments WHERE ((itemalias.itemalias_item_id = public.getitemid((old.item_number)::text)) AND (itemalias.itemalias_number = old.alias_number));
117791
117792
117793 --
117794 -- TOC entry 8838 (class 2618 OID 146572080)
117795 -- Dependencies: 318 318 318 318 318 237 237 237 1714 1665 318 8894
117796 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117797 --
117798
117799 CREATE RULE "_UPDATE" AS ON UPDATE TO itemchar DO INSTEAD UPDATE public.charass SET charass_value = new.value, charass_default = new.is_default WHERE (((charass.charass_target_type = 'I'::text) AND (charass.charass_target_id = public.getitemid((old.item_number)::text))) AND (charass.charass_char_id = public.getcharid((old.characteristic)::text, 'I'::text)));
117800
117801
117802 --
117803 -- TOC entry 8839 (class 2618 OID 146572081)
117804 -- Dependencies: 319 319 319 8894
117805 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117806 --
117807
117808 CREATE RULE "_UPDATE" AS ON UPDATE TO itemcomment DO INSTEAD NOTHING;
117809
117810
117811 --
117812 -- TOC entry 8840 (class 2618 OID 146572082)
117813 -- Dependencies: 322 322 322 322 322 322 2292 1714 1681 1679 322 8894
117814 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117815 --
117816
117817 CREATE RULE "_UPDATE" AS ON UPDATE TO itemcost DO INSTEAD SELECT public.updateitemcost(public.getitemid((new.item_number)::text), public.getcostelemid((new.costing_element)::text), public.getcurrid((new.currency)::text), new.actual_cost, new.post_to_standard) AS updateitemcost;
117818
117819
117820 --
117821 -- TOC entry 8841 (class 2618 OID 146572083)
117822 -- Dependencies: 323 323 323 323 245 245 245 245 1714 323 8894
117823 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117824 --
117825
117826 CREATE RULE "_UPDATE" AS ON UPDATE TO itemfile DO INSTEAD UPDATE public.url SET url_title = new.title, url_url = new.url WHERE ((((url.url_source_id = public.getitemid((old.item_number)::text)) AND (url.url_source = 'I'::text)) AND (url.url_title = old.title)) AND (url.url_url = old.url));
117827
117828
117829 --
117830 -- TOC entry 8842 (class 2618 OID 146572084)
117831 -- Dependencies: 324 324 324 324 2165 1714 1702 324 8894
117832 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117833 --
117834
117835 CREATE RULE "_UPDATE" AS ON UPDATE TO itemimage DO INSTEAD SELECT public.saveimageass('I'::text, public.getitemid((new.item_number)::text), (CASE WHEN (new.purpose = 'Product Description'::text) THEN 'P'::text WHEN (new.purpose = 'Inventory Description'::text) THEN 'I'::text WHEN (new.purpose = 'Engineering Reference'::text) THEN 'E'::text WHEN (new.purpose = 'Miscellaneous'::text) THEN 'M'::text ELSE 'X'::text END)::bpchar, public.getimageid(new.image_name)) AS saveimageass;
117836
117837
117838 --
117839 -- TOC entry 8843 (class 2618 OID 146572085)
117840 -- Dependencies: 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 192 1732 1693 1716 1678 327 8894
117841 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117842 --
117843
117844 CREATE RULE "_UPDATE" AS ON UPDATE TO itemsite DO INSTEAD UPDATE public.itemsite SET itemsite_active = new.active, itemsite_dropship = new.dropship, itemsite_posupply = new.po_supplied_at_site, itemsite_createpr = new.create_prs, itemsite_wosupply = new.wo_supplied_at_site, itemsite_createwo = new.create_wos, itemsite_createsopr = new.create_soprs, itemsite_createsopo = new.create_sopos, itemsite_sold = new.sold_from_site, itemsite_soldranking = new.ranking, itemsite_costmethod = CASE WHEN (new.cost_method = 'None'::text) THEN 'N'::text WHEN (new.cost_method = 'Average'::text) THEN 'A'::text WHEN (new.cost_method = 'Standard'::text) THEN 'S'::text WHEN (new.cost_method = 'Job'::text) THEN 'J'::text ELSE NULL::text END, itemsite_controlmethod = CASE WHEN (new.control_method = 'None'::text) THEN 'N'::text WHEN (new.control_method = 'Regular'::text) THEN 'R'::text WHEN (new.control_method = 'Serial #'::text) THEN 'S'::text WHEN (new.control_method = 'Lot #'::text) THEN 'L'::text ELSE NULL::text END, itemsite_perishable = new.perishable, itemsite_plancode_id = public.getplancodeid(new.planner_code), itemsite_costcat_id = public.getcostcatid(new.cost_category), itemsite_loccntrl = new.multiple_location_control, itemsite_location_id = CASE WHEN (new.location = 'N/A'::text) THEN (-1) ELSE public.getlocationid((new.site)::text, new.location) END, itemsite_recvlocation_id = CASE WHEN (new.receive_location = 'N/A'::text) THEN (-1) ELSE public.getlocationid((new.site)::text, new.receive_location) END, itemsite_issuelocation_id = CASE WHEN (new.issue_location = 'N/A'::text) THEN (-1) ELSE public.getlocationid((new.site)::text, new.issue_location) END, itemsite_location_dist = new.auto_distr_location, itemsite_recvlocation_dist = new.auto_distr_receive_location, itemsite_issuelocation_dist = new.auto_distr_issue_location, itemsite_location = new.user_defined_location, itemsite_location_comments = new.user_defined_location, itemsite_disallowblankwip = new.disallow_blank_wip_locations, itemsite_stocked = new.stocked, itemsite_abcclass = new.abc_class, itemsite_autoabcclass = new.allow_automatic_updates, itemsite_cyclecountfreq = new.cycl_cnt_freq, itemsite_eventfence = new.event_fence, itemsite_useparams = new.enforce_order_parameters, itemsite_reorderlevel = new.reorder_level, itemsite_ordertoqty = new.order_up_to, itemsite_minordqty = new.minimum_order, itemsite_maxordqty = new.maximum_order, itemsite_multordqty = new.order_multiple, itemsite_useparamsmanual = new.enforce_on_manual_orders, itemsite_ordergroup = new.group_mps_mrp_orders, itemsite_ordergroup_first = new.first_group, itemsite_mps_timefence = new.mps_time_fence, itemsite_leadtime = new.lead_time, itemsite_safetystock = new.safety_stock, itemsite_supply_itemsite_id = CASE WHEN (new.supplied_from_site = 'None'::text) THEN NULL::integer WHEN (new.supplied_from_site = ''::text) THEN NULL::integer ELSE public.getitemsiteid(new.supplied_from_site, (new.item_number)::text) END, itemsite_notes = new.notes, itemsite_warrpurc = new.require_warranty, itemsite_autoreg = new.auto_register, itemsite_planning_type = CASE WHEN (new.planning_system = 'None'::text) THEN 'N'::text WHEN (new.planning_system = 'MPS'::text) THEN 'S'::text ELSE 'M'::text END WHERE (itemsite.itemsite_id = public.getitemsiteid((old.site)::text, (old.item_number)::text));
117845
117846
117847 --
117848 -- TOC entry 8844 (class 2618 OID 146572087)
117849 -- Dependencies: 328 328 328 8894
117850 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117851 --
117852
117853 CREATE RULE "_UPDATE" AS ON UPDATE TO itemsitecomment DO INSTEAD NOTHING;
117854
117855
117856 --
117857 -- TOC entry 8845 (class 2618 OID 146572088)
117858 -- Dependencies: 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 331 330 330 330 330 330 1778 1714 1677 1676 1675 331 8894
117859 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117860 --
117861
117862 CREATE RULE "_UPDATE" AS ON UPDATE TO itemsource DO INSTEAD UPDATE public.itemsrc SET itemsrc_vend_item_number = new.vendor_item_number, itemsrc_vend_item_descrip = new.vendor_description, itemsrc_comments = new.notes, itemsrc_vend_uom = new.vendor_uom, itemsrc_invvendoruomratio = new.inventory_vendor_uom_ratio, itemsrc_minordqty = new.minimum_order, itemsrc_multordqty = new.order_multiple, itemsrc_leadtime = new.lead_time, itemsrc_ranking = new.vendor_ranking, itemsrc_active = new.active, itemsrc_default = new.itemsrc_default, itemsrc_manuf_name = new.manufacturer_name, itemsrc_manuf_item_number = new.manufacturer_item_number, itemsrc_manuf_item_descrip = new.manufacturer_description, itemsrc_upccode = new.bar_code, itemsrc_contrct_id = public.getcontrctid(new.contract_number), itemsrc_effective = COALESCE(public.getcontrcteffective(new.contract_number), new.effective_date), itemsrc_expires = COALESCE(public.getcontrctexpires(new.contract_number), new.expires_date) WHERE (((((itemsrc.itemsrc_item_id = public.getitemid((old.item_number)::text)) AND (itemsrc.itemsrc_vend_id = public.getvendid((old.vendor)::text))) AND (itemsrc.itemsrc_vend_item_number = old.vendor_item_number)) AND (itemsrc.itemsrc_manuf_name = old.manufacturer_name)) AND (itemsrc.itemsrc_manuf_item_number = old.manufacturer_item_number));
117863
117864
117865 --
117866 -- TOC entry 8846 (class 2618 OID 146572090)
117867 -- Dependencies: 333 333 333 333 333 333 333 333 333 333 333 332 332 1780 1718 1681 333 8894
117868 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117869 --
117870
117871 CREATE RULE "_UPDATE" AS ON UPDATE TO itemsourceprice DO INSTEAD UPDATE public.itemsrcp SET itemsrcp_qtybreak = new.qty_break, itemsrcp_price = new.price_per_unit, itemsrcp_updated = now(), itemsrcp_curr_id = public.getcurrid((new.currency)::text), itemsrcp_dropship = COALESCE(new.dropship_only, false), itemsrcp_warehous_id = CASE WHEN (new.pricing_site = 'All'::text) THEN (-1) ELSE COALESCE(public.getwarehousid(new.pricing_site, 'ALL'::text), (-1)) END, itemsrcp_type = CASE WHEN (new.pricing_type = 'Discount'::text) THEN 'D'::text ELSE 'N'::text END, itemsrcp_discntprcnt = (COALESCE(new.discount_percent, 0.0) / 100.0), itemsrcp_fixedamtdiscount = new.discount_fixed_amount WHERE ((itemsrcp.itemsrcp_itemsrc_id = public.getitemsrcid((old.item_number)::text, (new.vendor)::text)) AND (itemsrcp.itemsrcp_qtybreak = old.qty_break));
117872
117873
117874 --
117875 -- TOC entry 8847 (class 2618 OID 146572092)
117876 -- Dependencies: 335 335 335 335 335 334 334 1714 335 8894
117877 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117878 --
117879
117880 CREATE RULE "_UPDATE" AS ON UPDATE TO itemsubstitute DO INSTEAD UPDATE public.itemsub SET itemsub_uomratio = new.sub_parent_uom_ratio, itemsub_rank = new.ranking WHERE ((itemsub.itemsub_parent_item_id = public.getitemid((old.root_item_number)::text)) AND (itemsub.itemsub_sub_item_id = public.getitemid((old.substitute_item_number)::text)));
117881
117882
117883 --
117884 -- TOC entry 8848 (class 2618 OID 146572093)
117885 -- Dependencies: 337 337 337 337 336 336 336 1768 1767 1714 337 8894
117886 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117887 --
117888
117889 CREATE RULE "_UPDATE" AS ON UPDATE TO itemtaxtype DO INSTEAD UPDATE public.itemtax SET itemtax_taxzone_id = CASE WHEN ((new.tax_zone)::text = 'Any'::text) THEN NULL::integer ELSE public.gettaxzoneid((new.tax_zone)::text) END, itemtax_taxtype_id = public.gettaxtypeid(new.tax_type) WHERE (((itemtax.itemtax_item_id = public.getitemid((old.item_number)::text)) AND CASE WHEN ((old.tax_zone)::text = 'Any'::text) THEN (itemtax.itemtax_taxzone_id IS NULL) ELSE (itemtax.itemtax_taxzone_id = public.gettaxzoneid((old.tax_zone)::text)) END) AND (itemtax.itemtax_taxtype_id = public.gettaxtypeid(old.tax_type)));
117890
117891
117892 --
117893 -- TOC entry 8849 (class 2618 OID 146572094)
117894 -- Dependencies: 339 339 339 339 339 339 339 339 191 191 2172 1774 1771 1714 339 8894
117895 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117896 --
117897
117898 CREATE RULE "_UPDATE" AS ON UPDATE TO itemuomconversion DO INSTEAD SELECT public.saveitemuomconv(public.getitemid((new.item_number)::text), COALESCE(public.getuomid((new.uom)::text), (SELECT item.item_inv_uom_id FROM public.item WHERE (item.item_id = public.getitemid((new.item_number)::text)))), COALESCE(new.uom_value, (1)::numeric), COALESCE(public.getuomid(new.per_uom), (SELECT item.item_inv_uom_id FROM public.item WHERE (item.item_id = public.getitemid((new.item_number)::text)))), COALESCE(new.per_uom_value, (1)::numeric), COALESCE(new.fractional, false), public.getuomtypeid(new.selected_types)) AS saveitemuomconv;
117899
117900
117901 --
117902 -- TOC entry 8850 (class 2618 OID 146572095)
117903 -- Dependencies: 341 341 341 8894
117904 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117905 --
117906
117907 CREATE RULE "_UPDATE" AS ON UPDATE TO journalentry DO INSTEAD NOTHING;
117908
117909
117910 --
117911 -- TOC entry 8851 (class 2618 OID 146572096)
117912 -- Dependencies: 344 344 344 344 344 344 344 344 344 344 342 342 1781 1780 344 8894
117913 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117914 --
117915
117916 CREATE RULE "_UPDATE" AS ON UPDATE TO location DO INSTEAD UPDATE public.location SET location_name = new.location, location_descrip = new.description, location_restrict = new.restricted, location_netable = new.netable, location_whsezone_id = public.getwhsezoneid((new.site)::text, new.zone), location_aisle = new.aisle, location_rack = new.rack, location_bin = new.bin WHERE ((location.location_warehous_id = public.getwarehousid((old.site)::text, 'ACTIVE'::text)) AND (location.location_name = (old.location)::text));
117917
117918
117919 --
117920 -- TOC entry 8852 (class 2618 OID 146572097)
117921 -- Dependencies: 345 345 345 8894
117922 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117923 --
117924
117925 CREATE RULE "_UPDATE" AS ON UPDATE TO misccounttag DO INSTEAD NOTHING;
117926
117927
117928 --
117929 -- TOC entry 8853 (class 2618 OID 146572098)
117930 -- Dependencies: 346 349 349 346 346 346 346 346 301 1684 1681 907 346 8894
117931 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117932 --
117933
117934 CREATE RULE "_UPDATE" AS ON UPDATE TO pricingschedule DO INSTEAD UPDATE public.ipshead SET ipshead_descrip = new.description, ipshead_effective = CASE WHEN (new.effective = 'Always'::text) THEN '1970-01-01'::date ELSE (new.effective)::date END, ipshead_expires = CASE WHEN (new.expires = 'Never'::text) THEN '2100-01-01'::date ELSE (new.expires)::date END, ipshead_updated = now(), ipshead_curr_id = CASE WHEN (SELECT (count(ipsiteminfo.ipsitem_id) = 0) FROM public.ipsiteminfo WHERE (ipsiteminfo.ipsitem_ipshead_id = public.getipsheadid((old.name)::text))) THEN COALESCE(public.getcurrid((new.currency)::text), public.basecurrid()) ELSE public.getcurrid((old.currency)::text) END WHERE (ipshead.ipshead_name = (old.name)::text);
117935
117936
117937 --
117938 -- TOC entry 8854 (class 2618 OID 146572100)
117939 -- Dependencies: 348 348 348 348 348 348 348 347 347 347 347 347 347 1756 1684 1686 1682 348 8894
117940 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117941 --
117942
117943 CREATE RULE "_UPDATE" AS ON UPDATE TO pricingscheduleassign DO INSTEAD UPDATE public.ipsass SET ipsass_ipshead_id = public.getipsheadid((new.pricing_schedule)::text), ipsass_cust_id = CASE WHEN ((new.customer_number)::text = 'Any'::text) THEN (-1) ELSE public.getcustid((new.customer_number)::text) END, ipsass_custtype_id = CASE WHEN ((new.customer_type)::text = 'N/A'::text) THEN (-1) ELSE public.getcusttypeid((new.customer_type)::text) END, ipsass_custtype_pattern = new.customer_type_pattern, ipsass_shipto_id = CASE WHEN (((new.customer_number)::text = 'Any'::text) OR ((new.customer_shipto)::text = 'Any'::text)) THEN (-1) ELSE public.getshiptoid((new.customer_number)::text, (new.customer_shipto)::text) END, ipsass_shipto_pattern = new.customer_shipto_pattern WHERE ((((((ipsass.ipsass_ipshead_id = public.getipsheadid((old.pricing_schedule)::text)) AND (ipsass.ipsass_cust_id = CASE WHEN ((old.customer_number)::text = 'Any'::text) THEN (-1) ELSE public.getcustid((old.customer_number)::text) END)) AND (ipsass.ipsass_custtype_id = CASE WHEN ((old.customer_type)::text = 'N/A'::text) THEN (-1) ELSE public.getcusttypeid((old.customer_type)::text) END)) AND (ipsass.ipsass_custtype_pattern = (old.customer_type_pattern)::text)) AND (ipsass.ipsass_shipto_id = CASE WHEN ((old.customer_shipto)::text = 'Any'::text) THEN (-1) ELSE public.getshiptoid((old.customer_number)::text, (old.customer_shipto)::text) END)) AND (ipsass.ipsass_shipto_pattern = (old.customer_shipto_pattern)::text));
117944
117945
117946 --
117947 -- TOC entry 8855 (class 2618 OID 146572102)
117948 -- Dependencies: 350 350 350 350 350 350 350 350 350 350 350 350 2164 2167 1771 1738 1714 1713 1712 1684 350 8894
117949 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117950 --
117951
117952 CREATE RULE "_UPDATE" AS ON UPDATE TO pricingscheduleitem DO INSTEAD SELECT CASE WHEN ((old.type)::text = 'Item'::text) THEN public.saveipsitem(public.getipsitemid((old.pricing_schedule)::text, (old.item_number)::text, old.qty_break, (old.qty_uom)::text, (old.price_uom)::text), public.getipsheadid((new.pricing_schedule)::text), public.getitemid((new.item_number)::text), new.qty_break, new.price, public.getuomid((new.qty_uom)::text), public.getuomid((new.price_uom)::text), new.percent, new.fixedamt, CASE new.pricing_type WHEN 'Nominal'::text THEN 'N'::text WHEN 'Discount'::text THEN 'D'::text WHEN 'Markup'::text THEN 'M'::text ELSE '?'::text END) WHEN ((old.type)::text = 'Product Category'::text) THEN public.saveipsprodcat(public.getipsprodcatid((old.pricing_schedule)::text, (old.product_category)::text, old.qty_break), public.getipsheadid((new.pricing_schedule)::text), public.getprodcatid((new.product_category)::text), new.qty_break, new.percent, new.fixedamt, CASE new.pricing_type WHEN 'Nominal'::text THEN 'N'::text WHEN 'Discount'::text THEN 'D'::text WHEN 'Markup'::text THEN 'M'::text ELSE '?'::text END) ELSE NULL::integer END AS result;
117953
117954
117955 --
117956 -- TOC entry 8856 (class 2618 OID 146572104)
117957 -- Dependencies: 352 352 352 352 352 352 352 352 352 351 351 351 1712 1665 352 8894
117958 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117959 --
117960
117961 CREATE RULE "_UPDATE" AS ON UPDATE TO pricingscheduleitemchar DO INSTEAD UPDATE public.ipsitemchar SET ipsitemchar_price = new.price WHERE (((ipsitemchar.ipsitemchar_ipsitem_id = public.getipsitemid((old.pricing_schedule)::text, (old.item_number)::text, old.qty_break, (old.qty_uom)::text, (old.price_uom)::text)) AND (ipsitemchar.ipsitemchar_char_id = public.getcharid((old.characteristic)::text, 'I'::text))) AND (ipsitemchar.ipsitemchar_value = (old.value)::text));
117962
117963
117964 --
117965 -- TOC entry 8857 (class 2618 OID 146572105)
117966 -- Dependencies: 353 353 353 353 353 353 353 353 353 353 353 353 353 353 225 353 8894
117967 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117968 --
117969
117970 CREATE RULE "_UPDATE" AS ON UPDATE TO project DO INSTEAD UPDATE public.prj SET prj_name = new.name, prj_descrip = new.description, prj_owner_username = new.owner, prj_username = new.assigned_to, prj_so = new.sales_orders, prj_wo = new.work_orders, prj_po = new.purchase_orders, prj_status = CASE WHEN (new.status = 'In-Process'::text) THEN 'O'::text WHEN (new.status = 'Completed'::text) THEN 'C'::text ELSE 'P'::text END, prj_due_date = new.due, prj_assigned_date = new.assigned, prj_start_date = new.started, prj_completed_date = new.completed WHERE (prj.prj_number = old.number);
117971
117972
117973 --
117974 -- TOC entry 8858 (class 2618 OID 146572106)
117975 -- Dependencies: 354 354 354 8894
117976 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117977 --
117978
117979 CREATE RULE "_UPDATE" AS ON UPDATE TO projectcomment DO INSTEAD NOTHING;
117980
117981
117982 --
117983 -- TOC entry 8859 (class 2618 OID 146572107)
117984 -- Dependencies: 357 357 357 357 357 357 357 357 357 356 1780 1768 1749 1739 1670 357 8894
117985 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117986 --
117987
117988 CREATE RULE "_UPDATE" AS ON UPDATE TO prospect DO INSTEAD UPDATE public.prospect SET prospect_number = upper((new.prospect_number)::text), prospect_name = new.prospect_name, prospect_active = new.active, prospect_cntct_id = public.getcntctid(new.contact_number), prospect_taxzone_id = public.gettaxzoneid(new.default_tax_zone), prospect_salesrep_id = public.getsalesrepid(new.sales_rep), prospect_warehous_id = public.getwarehousid(new.site_code, 'ACTIVE'::text), prospect_comments = new.notes WHERE (prospect.prospect_id = public.getprospectid((old.prospect_number)::text));
117989
117990
117991 --
117992 -- TOC entry 8860 (class 2618 OID 146572108)
117993 -- Dependencies: 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 360 198 1742 1736 1734 360 8894
117994 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
117995 --
117996
117997 CREATE RULE "_UPDATE" AS ON UPDATE TO purchaseline DO INSTEAD UPDATE public.poitem SET poitem_duedate = new.due_date, poitem_qty_ordered = new.qty_ordered, poitem_unitprice = new.unit_price, poitem_vend_item_number = new.vend_item_number, poitem_vend_item_descrip = new.vendor_description, poitem_manuf_name = new.manufacturer_name, poitem_manuf_item_number = new.manufacturer_item_number, poitem_manuf_item_descrip = new.manufacturer_description, poitem_comments = new.notes, poitem_freight = new.freight, poitem_prj_id = public.getprjid(new.project_number), poitem_bom_rev_id = public.getrevid('BOM'::text, old.item_number, new.bill_of_materials_revision), poitem_boo_rev_id = public.getrevid('BOO'::text, old.item_number, new.bill_of_operations_revision) WHERE (poitem.poitem_id = public.getpoitemid((old.order_number)::text, old.line_number));
117998
117999
118000 --
118001 -- TOC entry 8861 (class 2618 OID 146572110)
118002 -- Dependencies: 361 361 361 361 361 237 237 237 236 236 198 198 198 198 197 197 192 192 191 2281 361 8894
118003 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118004 --
118005
118006 CREATE RULE "_UPDATE" AS ON UPDATE TO purchaselinechar DO INSTEAD SELECT DISTINCT public.updatecharassignment('PI'::text, poitem.poitem_id, charass.charass_char_id, new.value) AS updatecharassignment FROM public.pohead, public.poitem, public.itemsite, public.item, public.charass, public."char" WHERE (((((((((pohead.pohead_number = (old.order_number)::text) AND (pohead.pohead_id = poitem.poitem_pohead_id)) AND (poitem.poitem_linenumber = old.line_number)) AND (poitem.poitem_itemsite_id = itemsite.itemsite_id)) AND (item.item_id = itemsite.itemsite_item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND ("char".char_id = charass.charass_char_id)) AND ("char".char_name = old.characteristic));
118007
118008
118009 --
118010 -- TOC entry 8862 (class 2618 OID 146572112)
118011 -- Dependencies: 362 362 362 8894
118012 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118013 --
118014
118015 CREATE RULE "_UPDATE" AS ON UPDATE TO purchaselinecomment DO INSTEAD NOTHING;
118016
118017
118018 --
118019 -- TOC entry 8863 (class 2618 OID 146572113)
118020 -- Dependencies: 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 365 197 1780 1777 1769 1768 1681 1672 1670 1658 365 8894
118021 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118022 --
118023
118024 CREATE RULE "_UPDATE" AS ON UPDATE TO purchaseorder DO INSTEAD UPDATE public.pohead SET pohead_terms_id = public.gettermsid(new.terms), pohead_taxzone_id = public.gettaxzoneid(new.tax_zone), pohead_warehous_id = public.getwarehousid(new.receiving_site, 'ALL'::text), pohead_agent_username = new.purchasing_agent, pohead_vendaddr_id = CASE WHEN (new.alt_address = 'MAIN'::text) THEN NULL::integer ELSE public.getvendaddrid(old.vendor_number, new.alt_address) END, pohead_fob = new.fob, pohead_shipvia = new.ship_via, pohead_curr_id = public.getcurrid((new.currency)::text), pohead_freight = new.freight, pohead_comments = new.notes, pohead_dropship = new.dropship, pohead_vend_cntct_id = public.getcntctid(new.vend_contact_number), pohead_vend_cntct_honorific = new.vend_cntct_honorific, pohead_vend_cntct_first_name = new.vend_cntct_first_name, pohead_vend_cntct_middle = new.vend_cntct_middle, pohead_vend_cntct_last_name = new.vend_cntct_last_name, pohead_vend_cntct_suffix = new.vend_cntct_suffix, pohead_vend_cntct_phone = new.vend_cntct_phone, pohead_vend_cntct_title = new.vend_cntct_title, pohead_vend_cntct_fax = new.vend_cntct_fax, pohead_vend_cntct_email = new.vend_cntct_email, pohead_vendaddress1 = new.vendaddress1, pohead_vendaddress2 = new.vendaddress2, pohead_vendaddress3 = new.vendaddress3, pohead_vendcity = new.vendcity, pohead_vendstate = new.vendstate, pohead_vendzipcode = new.vendzipcode, pohead_vendcountry = new.vendcountry, pohead_shipto_cntct_id = public.getcntctid(new.shipto_contact_number), pohead_shipto_cntct_honorific = new.shipto_cntct_honorific, pohead_shipto_cntct_first_name = new.shipto_cntct_first_name, pohead_shipto_cntct_middle = new.shipto_cntct_middle, pohead_shipto_cntct_last_name = new.shipto_cntct_last_name, pohead_shipto_cntct_suffix = new.shipto_cntct_suffix, pohead_shipto_cntct_phone = new.shipto_cntct_phone, pohead_shipto_cntct_title = new.shipto_cntct_title, pohead_shipto_cntct_fax = new.shipto_cntct_fax, pohead_shipto_cntct_email = new.shipto_cntct_email, pohead_shiptoaddress_id = public.getaddrid(new.shiptoaddress_number), pohead_shiptoaddress1 = new.shiptoaddress1, pohead_shiptoaddress2 = new.shiptoaddress2, pohead_shiptoaddress3 = new.shiptoaddress3, pohead_shiptocity = new.shiptocity, pohead_shiptostate = new.shiptostate, pohead_shiptozipcode = new.shiptozipcode, pohead_shiptocountry = new.shiptocountry, pohead_cohead_id = public.getcoheadid(new.sales_order_number) WHERE (pohead.pohead_number = (old.order_number)::text);
118025
118026
118027 --
118028 -- TOC entry 8864 (class 2618 OID 146572115)
118029 -- Dependencies: 366 366 366 8894
118030 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118031 --
118032
118033 CREATE RULE "_UPDATE" AS ON UPDATE TO purchaseordercomment DO INSTEAD NOTHING;
118034
118035
118036 --
118037 -- TOC entry 8865 (class 2618 OID 146572116)
118038 -- Dependencies: 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 368 367 1780 1769 1768 1767 1759 1756 1751 1749 1736 1700 1683 1681 368 8894
118039 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118040 --
118041
118042 CREATE RULE "_UPDATE" AS ON UPDATE TO quote DO INSTEAD UPDATE public.quhead SET quhead_number = old.quote_number, quhead_cust_id = public.getcustid(new.customer_number, true), quhead_custponumber = new.cust_po_number, quhead_quotedate = new.quote_date, quhead_warehous_id = public.getwarehousid(new.site, 'SHIPPING'::text), quhead_shipto_id = public.getshiptoid(new.customer_number, new.shipto_number), quhead_shiptoname = new.shipto_name, quhead_shiptoaddress1 = new.shipto_address1, quhead_shiptoaddress2 = new.shipto_address2, quhead_shiptoaddress3 = new.shipto_address3, quhead_salesrep_id = public.getsalesrepid(new.sales_rep), quhead_terms_id = public.gettermsid(new.terms), quhead_fob = new.fob, quhead_shipvia = new.ship_via, quhead_shiptocity = new.shipto_city, quhead_shiptostate = new.shipto_state, quhead_shiptozipcode = new.shipto_postal_code, quhead_freight = new.freight, quhead_misc = new.misc_charge, quhead_ordercomments = new.order_notes, quhead_shipcomments = new.shipping_notes, quhead_shiptophone = new.shipto_phone, quhead_billtoname = new.billto_name, quhead_billtoaddress1 = new.billto_address1, quhead_billtoaddress2 = new.billto_address2, quhead_billtoaddress3 = new.billto_address3, quhead_billtocity = new.billto_city, quhead_billtostate = new.billto_state, quhead_billtozip = new.billto_postal_code, quhead_misc_accnt_id = public.getglaccntid(new.misc_account_number), quhead_misc_descrip = new.misc_charge_description, quhead_commission = new.commission, quhead_packdate = new.pack_date, quhead_prj_id = public.getprjid(new.project_number), quhead_billtocountry = new.billto_country, quhead_shiptocountry = new.shipto_country, quhead_curr_id = public.getcurrid((new.currency)::text), quhead_taxzone_id = public.gettaxzoneid(new.tax_zone), quhead_taxtype_id = public.gettaxtypeid(new.tax_type), quhead_expire = new.expire_date, quhead_saletype_id = public.getsaletypeid(new.sale_type), quhead_shipzone_id = public.getshipzoneid(new.shipto_shipzone) WHERE (quhead.quhead_number = (old.quote_number)::text);
118043
118044
118045 --
118046 -- TOC entry 8866 (class 2618 OID 146572118)
118047 -- Dependencies: 369 369 369 8894
118048 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118049 --
118050
118051 CREATE RULE "_UPDATE" AS ON UPDATE TO quotecomment DO INSTEAD NOTHING;
118052
118053
118054 --
118055 -- TOC entry 8867 (class 2618 OID 146572119)
118056 -- Dependencies: 371 371 371 371 371 371 371 371 371 371 371 371 371 370 370 191 191 1902 1780 1771 1767 1720 371 8894
118057 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118058 --
118059
118060 CREATE RULE "_UPDATE" AS ON UPDATE TO quoteline DO INSTEAD UPDATE public.quitem SET quitem_scheddate = new.scheduled_date, quitem_qtyord = new.qty_ordered, quitem_qty_uom_id = public.getuomid(new.qty_uom), quitem_qty_invuomratio = public.itemuomtouomratio(item.item_id, COALESCE(public.getuomid(new.qty_uom), item.item_inv_uom_id), item.item_inv_uom_id), quitem_price = new.net_unit_price, quitem_price_uom_id = public.getuomid(new.price_uom), quitem_price_invuomratio = public.itemuomtouomratio(item.item_id, COALESCE(public.getuomid(new.price_uom), item.item_inv_uom_id), item.item_inv_uom_id), quitem_memo = new.notes, quitem_createorder = new.create_order, quitem_order_warehous_id = public.getwarehousid(new.supplying_site, 'SHIPPING'::text), quitem_prcost = new.overwrite_po_price, quitem_taxtype_id = public.gettaxtypeid(new.tax_type) FROM public.item WHERE ((quitem.quitem_quhead_id = public.getquoteid(old.quote_number)) AND (quitem.quitem_linenumber = old.line_number));
118061
118062
118063 --
118064 -- TOC entry 8868 (class 2618 OID 146572121)
118065 -- Dependencies: 372 372 372 372 372 370 370 370 370 367 367 237 237 237 236 236 192 192 191 2281 372 8894
118066 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118067 --
118068
118069 CREATE RULE "_UPDATE" AS ON UPDATE TO quotelinechar DO INSTEAD SELECT DISTINCT public.updatecharassignment('QI'::text, quitem.quitem_id, charass.charass_char_id, new.value) AS updatecharassignment FROM public.quhead, public.quitem, public.itemsite, public.item, public.charass, public."char" WHERE (((((((((quhead.quhead_number = old.quote_number) AND (quhead.quhead_id = quitem.quitem_quhead_id)) AND (quitem.quitem_linenumber = old.line_number)) AND (quitem.quitem_itemsite_id = itemsite.itemsite_id)) AND (item.item_id = itemsite.itemsite_item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND ("char".char_id = charass.charass_char_id)) AND ("char".char_name = old.characteristic));
118070
118071
118072 --
118073 -- TOC entry 8869 (class 2618 OID 146572123)
118074 -- Dependencies: 373 373 373 8894
118075 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118076 --
118077
118078 CREATE RULE "_UPDATE" AS ON UPDATE TO quotelinecomment DO INSTEAD NOTHING;
118079
118080
118081 --
118082 -- TOC entry 8870 (class 2618 OID 146572124)
118083 -- Dependencies: 380 380 380 8894
118084 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118085 --
118086
118087 CREATE RULE "_UPDATE" AS ON UPDATE TO saleshistory DO INSTEAD NOTHING;
118088
118089
118090 --
118091 -- TOC entry 8871 (class 2618 OID 146572125)
118092 -- Dependencies: 381 381 381 381 381 237 237 237 236 236 196 196 196 196 195 195 195 195 195 195 192 192 191 2282 1876 1674 381 8894
118093 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118094 --
118095
118096 CREATE RULE "_UPDATE" AS ON UPDATE TO saleslinechar DO INSTEAD SELECT DISTINCT public.updatecharassignment('SI'::text, coitem.coitem_id, charass.charass_char_id, new.value, public.itemcharprice(item.item_id, "char".char_id, new.value, cohead.cohead_cust_id, cohead.cohead_shipto_id, coitem.coitem_qtyord, cohead.cohead_curr_id, cohead.cohead_orderdate)) AS updatecharassignment FROM public.cohead, public.coitem, public.itemsite, public.item, public.charass, public."char" WHERE (((((((((cohead.cohead_number = (old.order_number)::text) AND (cohead.cohead_id = coitem.coitem_cohead_id)) AND (coitem.coitem_id = public.getcoitemid((old.order_number)::text, old.line_number))) AND (coitem.coitem_itemsite_id = itemsite.itemsite_id)) AND (item.item_id = itemsite.itemsite_item_id)) AND (charass.charass_target_type = 'I'::text)) AND (charass.charass_target_id = item.item_id)) AND ("char".char_id = charass.charass_char_id)) AND ("char".char_name = old.characteristic));
118097
118098
118099 --
118100 -- TOC entry 8872 (class 2618 OID 146572127)
118101 -- Dependencies: 382 382 382 8894
118102 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118103 --
118104
118105 CREATE RULE "_UPDATE" AS ON UPDATE TO saleslinecomment DO INSTEAD NOTHING;
118106
118107
118108 --
118109 -- TOC entry 8873 (class 2618 OID 146572128)
118110 -- Dependencies: 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 383 195 1780 1769 1768 1759 1756 1754 1753 1751 1749 1736 1700 1682 1681 1672 1670 1652 383 8894
118111 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118112 --
118113
118114 CREATE RULE "_UPDATE" AS ON UPDATE TO salesorder DO INSTEAD UPDATE public.cohead SET cohead_number = old.order_number, cohead_cust_id = public.getcustid(new.customer_number), cohead_custponumber = new.cust_po_number, cohead_orderdate = new.order_date, cohead_warehous_id = public.getwarehousid(new.site, 'SHIPPING'::text), cohead_shipto_id = public.getshiptoid(new.customer_number, new.shipto_number), cohead_shiptoname = new.shipto_name, cohead_shiptoaddress1 = new.shipto_address1, cohead_shiptoaddress2 = new.shipto_address2, cohead_shiptoaddress3 = new.shipto_address3, cohead_salesrep_id = public.getsalesrepid(new.sales_rep), cohead_terms_id = public.gettermsid(new.terms), cohead_fob = new.fob, cohead_shipvia = new.ship_via, cohead_shiptocity = new.shipto_city, cohead_shiptostate = new.shipto_state, cohead_shiptozipcode = new.shipto_postal_code, cohead_freight = CASE WHEN new.calculate_freight THEN COALESCE((SELECT sum(freightdetail.freightdata_total) AS sum FROM public.freightdetail('SO'::text, public.getcoheadid((old.order_number)::text), public.getcustid(new.customer_number), public.getshiptoid(new.customer_number, new.shipto_number), new.order_date, new.ship_via, public.getcurrid((new.currency)::text)) freightdetail(freightdata_schedule, freightdata_from, freightdata_to, freightdata_shipvia, freightdata_freightclass, freightdata_weight, freightdata_uom, freightdata_price, freightdata_type, freightdata_total, freightdata_currency)), (0)::numeric) ELSE new.freight END, cohead_calcfreight = new.calculate_freight, cohead_misc = new.misc_charge, cohead_ordercomments = new.order_notes, cohead_shipcomments = new.shipping_notes, cohead_shiptophone = new.shipto_phone, cohead_shipchrg_id = public.getshipchrgid(new.shipping_chgs), cohead_shipform_id = public.getshipformid(new.shipping_form), cohead_billtoname = new.billto_name, cohead_billtoaddress1 = new.billto_address1, cohead_billtoaddress2 = new.billto_address2, cohead_billtoaddress3 = new.billto_address3, cohead_billtocity = new.billto_city, cohead_billtostate = new.billto_state, cohead_billtozipcode = new.billto_postal_code, cohead_misc_accnt_id = public.getglaccntid(new.misc_account_number), cohead_misc_descrip = new.misc_charge_description, cohead_commission = new.commission, cohead_holdtype = CASE WHEN (new.hold_type = 'Credit'::text) THEN 'C'::text WHEN (new.hold_type = 'Shipping'::text) THEN 'S'::text WHEN (new.hold_type = 'Packing'::text) THEN 'P'::text ELSE 'N'::text END, cohead_packdate = new.pack_date, cohead_prj_id = public.getprjid(new.project_number), cohead_shipcomplete = new.ship_complete, cohead_billtocountry = new.billto_country, cohead_shiptocountry = new.shipto_country, cohead_curr_id = public.getcurrid((new.currency)::text), cohead_taxzone_id = public.gettaxzoneid(new.tax_zone), cohead_lastupdated = ('now'::text)::timestamp(6) with time zone, cohead_shipto_cntct_id = public.getcntctid(new.shipto_contact_number), cohead_shipto_cntct_honorific = new.shipto_contact_honorific, cohead_shipto_cntct_first_name = new.shipto_contact_first, cohead_shipto_cntct_middle = new.shipto_contact_middle, cohead_shipto_cntct_last_name = new.shipto_contact_last, cohead_shipto_cntct_suffix = new.shipto_contact_suffix, cohead_shipto_cntct_phone = new.shipto_contact_phone, cohead_shipto_cntct_title = new.shipto_contact_title, cohead_shipto_cntct_fax = new.shipto_contact_fax, cohead_shipto_cntct_email = new.shipto_contact_email, cohead_billto_cntct_id = public.getcntctid(new.billto_contact_number), cohead_billto_cntct_honorific = new.billto_contact_name, cohead_billto_cntct_first_name = new.billto_contact_first, cohead_billto_cntct_middle = new.billto_contact_middle, cohead_billto_cntct_last_name = new.billto_contact_last, cohead_billto_cntct_suffix = new.billto_contact_suffix, cohead_billto_cntct_phone = new.billto_contact_phone, cohead_billto_cntct_title = new.billto_contact_title, cohead_billto_cntct_fax = new.billto_contct_fax, cohead_billto_cntct_email = new.billto_contact_email, cohead_saletype_id = public.getsaletypeid(new.sale_type), cohead_shipzone_id = public.getshipzoneid(new.shipto_shipzone) WHERE (cohead.cohead_number = (old.order_number)::text);
118115
118116
118117 --
118118 -- TOC entry 8874 (class 2618 OID 146572130)
118119 -- Dependencies: 384 384 384 8894
118120 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118121 --
118122
118123 CREATE RULE "_UPDATE" AS ON UPDATE TO salesordercomment DO INSTEAD NOTHING;
118124
118125
118126 --
118127 -- TOC entry 8875 (class 2618 OID 146572131)
118128 -- Dependencies: 385 385 385 385 385 385 216 1690 385 8894
118129 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118130 --
118131
118132 CREATE RULE "_UPDATE" AS ON UPDATE TO salesrep DO INSTEAD UPDATE public.salesrep SET salesrep_active = new.active, salesrep_number = new.number, salesrep_name = new.name, salesrep_commission = (new.commission_percent * 0.01), salesrep_emp_id = public.getempid(new.employee) WHERE (salesrep.salesrep_number = (old.number)::text);
118133
118134
118135 --
118136 -- TOC entry 8876 (class 2618 OID 146572132)
118137 -- Dependencies: 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 388 193 2162 2158 1780 1768 1760 1758 1754 1700 1678 1670 1658 388 8894
118138 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118139 --
118140
118141 CREATE RULE "_UPDATE" AS ON UPDATE TO site DO INSTEAD UPDATE public.whsinfo SET warehous_descrip = new.description, warehous_fob = CASE WHEN new.inventory_type THEN new.default_fob ELSE NULL::text END, warehous_active = new.active, warehous_counttag_prefix = CASE WHEN new.inventory_type THEN new.next_count_tag_prefix ELSE NULL::text END, warehous_counttag_number = CASE WHEN new.inventory_type THEN new.next_count_tag_number ELSE NULL::integer END, warehous_bol_prefix = CASE WHEN new.inventory_type THEN new.next_bill_of_lading_prefix ELSE NULL::text END, warehous_bol_number = CASE WHEN new.inventory_type THEN new.next_bill_of_lading_number ELSE NULL::integer END, warehous_shipping = CASE WHEN new.inventory_type THEN new.shipping_site ELSE NULL::boolean END, warehous_useslips = CASE WHEN new.inventory_type THEN new.force_the_use_of_count_slips ELSE NULL::boolean END, warehous_usezones = CASE WHEN new.inventory_type THEN new.force_the_use_of_zones ELSE NULL::boolean END, warehous_aislesize = CASE WHEN new.inventory_type THEN new.aisle_size ELSE NULL::integer END, warehous_aislealpha = CASE WHEN new.inventory_type THEN new.aisle_allow_alpha_characters ELSE NULL::boolean END, warehous_racksize = CASE WHEN new.inventory_type THEN new.rack_size ELSE NULL::integer END, warehous_rackalpha = CASE WHEN new.inventory_type THEN new.rack_allow_alpha_characters ELSE NULL::boolean END, warehous_binsize = CASE WHEN new.inventory_type THEN new.bin_size ELSE NULL::integer END, warehous_binalpha = CASE WHEN new.inventory_type THEN new.bin_allow_alpha_characters ELSE NULL::boolean END, warehous_locationsize = CASE WHEN new.inventory_type THEN new.location_size ELSE NULL::integer END, warehous_locationalpha = CASE WHEN new.inventory_type THEN new.location_allow_alpha_characters ELSE NULL::boolean END, warehous_enforcearbl = CASE WHEN new.inventory_type THEN new.enforce_arbl_naming_convention ELSE NULL::boolean END, warehous_default_accnt_id = public.getglaccntid(new.post_unassigned_transactions_to), warehous_shipping_commission = CASE WHEN new.inventory_type THEN (new.shipping_commission * 0.01) ELSE NULL::numeric END, warehous_cntct_id = public.savecntct(public.getcntctid(new.contact_number), new.contact_number, NULL::integer, new.honorific, new.first, new.middle, new.last, new.suffix, new.phone, NULL::text, new.fax, new.email, NULL::text, new.job_title, new.contact_change), warehous_addr_id = public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postal_code, new.country, new.address_change), warehous_taxzone_id = CASE WHEN new.inventory_type THEN public.gettaxzoneid(new.tax_zone) ELSE NULL::integer END, warehous_transit = CASE WHEN new.inventory_type THEN false WHEN new.transit_type THEN true ELSE NULL::boolean END, warehous_shipform_id = CASE WHEN new.transit_type THEN public.getshipformid(new.default_shipping_form) ELSE NULL::integer END, warehous_shipvia_id = CASE WHEN new.transit_type THEN public.getshipviaid(new.default_ship_via) ELSE NULL::integer END, warehous_shipcomments = CASE WHEN new.transit_type THEN new.shipping_comments ELSE NULL::text END, warehous_costcat_id = CASE WHEN new.transit_type THEN public.getcostcatid(new.default_cost_category) ELSE NULL::integer END, warehous_sitetype_id = public.getsitetypeid(new.type), warehous_sequence = new.scheduling_sequence WHERE (whsinfo.warehous_id = public.getwarehousid((old.code)::text, 'ALL'::text));
118142
118143
118144 --
118145 -- TOC entry 8877 (class 2618 OID 146572134)
118146 -- Dependencies: 389 389 389 389 343 343 1780 389 8894
118147 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118148 --
118149
118150 CREATE RULE "_UPDATE" AS ON UPDATE TO sitezone DO INSTEAD UPDATE public.whsezone SET whsezone_descrip = new.description WHERE ((whsezone.whsezone_warehous_id = public.getwarehousid((old.site)::text, 'ACTIVE'::text)) AND (whsezone.whsezone_name = (old.name)::text));
118151
118152
118153 --
118154 -- TOC entry 8878 (class 2618 OID 146572135)
118155 -- Dependencies: 390 390 390 390 390 390 390 390 390 390 390 390 390 390 390 390 232 232 1736 390 8894
118156 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118157 --
118158
118159 CREATE RULE "_UPDATE" AS ON UPDATE TO task DO INSTEAD UPDATE public.prjtask SET prjtask_name = new.name, prjtask_descrip = new.description, prjtask_owner_username = new.owner, prjtask_username = new.assigned_to, prjtask_hours_budget = new.hours_budgeted, prjtask_hours_actual = new.hours_actual, prjtask_exp_budget = new.expenses_budgeted, prjtask_exp_actual = new.expenses_actual, prjtask_status = CASE WHEN (new.status = 'In-Process'::text) THEN 'O'::text WHEN (new.status = 'Completed'::text) THEN 'C'::text ELSE 'P'::text END, prjtask_due_date = new.due, prjtask_assigned_date = new.assigned, prjtask_start_date = new.started, prjtask_completed_date = new.completed WHERE ((prjtask.prjtask_prj_id = public.getprjid(old.project_number)) AND (prjtask.prjtask_number = old.number));
118160
118161
118162 --
118163 -- TOC entry 8879 (class 2618 OID 146572137)
118164 -- Dependencies: 391 391 391 8894
118165 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118166 --
118167
118168 CREATE RULE "_UPDATE" AS ON UPDATE TO taskcomment DO INSTEAD NOTHING;
118169
118170
118171 --
118172 -- TOC entry 8880 (class 2618 OID 146572138)
118173 -- Dependencies: 392 392 392 392 392 392 392 392 392 392 392 392 392 392 392 392 392 2310 1724 1708 1705 1704 1680 392 8894
118174 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118175 --
118176
118177 CREATE RULE "_UPDATE" AS ON UPDATE TO todo DO INSTEAD SELECT public.updatetodoitem(old.task_number, old.assigned_to, new.task_name, new.description, public.getincidentid(new.incident), COALESCE(public.getincdtcrmacctid(new.incident), public.getcrmacctid(new.account)), public.getopheadid(new.opportunity), CASE WHEN (new.date_started > ''::text) THEN (new.date_started)::date ELSE NULL::date END, CASE WHEN (new.date_due > ''::text) THEN (new.date_due)::date ELSE NULL::date END, (CASE WHEN (new.status = 'Pending Input'::text) THEN 'P'::text WHEN (new.status = 'Deferred'::text) THEN 'D'::text WHEN (new.status = 'Neither'::text) THEN 'N'::text ELSE NULL::text END)::bpchar, CASE WHEN (new.date_assigned > ''::text) THEN (new.date_assigned)::date ELSE NULL::date END, CASE WHEN (new.date_completed > ''::text) THEN (new.date_completed)::date ELSE NULL::date END, public.getincdtpriorityid(new.priority), new.notes, new.active, new.owner) AS updatetodoitem;
118178
118179
118180 --
118181 -- TOC entry 8881 (class 2618 OID 146572140)
118182 -- Dependencies: 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 394 210 2162 2158 1779 1778 1769 1768 1766 1700 1691 1681 1670 1658 394 8894
118183 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118184 --
118185
118186 CREATE RULE "_UPDATE" AS ON UPDATE TO vendor DO INSTEAD UPDATE public.vendinfo SET vend_name = new.vendor_name, vend_active = new.active, vend_po = new.sells_purchase_order_items, vend_comments = new.notes, vend_pocomments = new.po_comments, vend_1099 = new.receives_1099, vend_fobsource = CASE WHEN (new.default_fob IS NULL) THEN NULL::text WHEN (new.default_fob = 'Receiving Site'::text) THEN 'W'::text ELSE 'V'::text END, vend_fob = CASE WHEN (new.default_fob IS NULL) THEN NULL::text WHEN (new.default_fob = 'Receiving Site'::text) THEN ''::text ELSE new.default_fob END, vend_terms_id = public.gettermsid(new.default_terms), vend_shipvia = new.ship_via, vend_vendtype_id = public.getvendtypeid(new.vendor_type), vend_qualified = new.qualified, vend_ediemail = new.po_edi_email, vend_ediemailbody = new.po_edi_emailbody, vend_edisubject = new.po_edi_subject, vend_edifilename = new.po_edi_filename, vend_accntnum = new.account_number, vend_emailpodelivery = new.allow_email_po_delivery, vend_restrictpurch = new.may_only_sell_item_source, vend_edicc = new.po_edi_cc, vend_curr_id = public.getcurrid((new.default_currency)::text), vend_cntct1_id = public.savecntct(public.getcntctid(new.contact1_number), new.contact1_number, NULL::integer, new.contact1_honorific, new.contact1_first, new.contact1_middle, new.contact1_last, new.contact1_suffix, new.contact1_voice, new.contact1_alternate, new.contact1_fax, new.contact1_email, new.contact1_web, new.contact1_job_title, new.contact1_change), vend_cntct2_id = public.savecntct(public.getcntctid(new.contact2_number), new.contact2_number, NULL::integer, new.contact2_honorific, new.contact2_first, new.contact2_middle, new.contact2_last, new.contact2_suffix, new.contact2_voice, new.contact2_alternate, new.contact2_fax, new.contact2_email, new.contact2_web, new.contact2_job_title, new.contact2_change), vend_addr_id = public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change), vend_match = new.matching_vo_po_amounts, vend_taxzone_id = public.gettaxzoneid(new.default_tax_zone), vend_accnt_id = COALESCE(public.getglaccntid(NULLIF(new.default_dist_gl_account, 'N/A'::text)), (-1)), vend_expcat_id = COALESCE(public.getexpcatid(NULLIF(new.default_dist_expense_category, 'N/A'::text)), (-1)), vend_tax_id = COALESCE(public.gettaxid(NULLIF(new.default_dist_tax_code, 'N/A'::text)), (-1)) WHERE (vendinfo.vend_id = public.getvendid((old.vendor_number)::text));
118187
118188
118189 --
118190 -- TOC entry 8882 (class 2618 OID 146572142)
118191 -- Dependencies: 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 395 364 2162 2158 1778 1777 1670 1658 395 8894
118192 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118193 --
118194
118195 CREATE RULE "_UPDATE" AS ON UPDATE TO vendoraddress DO INSTEAD UPDATE public.vendaddrinfo SET vendaddr_vend_id = public.getvendid((new.vendor_number)::text), vendaddr_code = new.vendor_address_number, vendaddr_name = new.vendor_address_name, vendaddr_comments = new.notes, vendaddr_cntct_id = public.savecntct(public.getcntctid(new.contact_number), new.contact_number, public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change), new.contact_honorific, new.contact_first, new.contact_middle, new.contact_last, new.contact_suffix, new.contact_voice, new.contact_alternate, new.contact_fax, new.contact_email, new.contact_web, new.contact_job_title, new.contact_change), vendaddr_addr_id = public.saveaddr(public.getaddrid(new.address_number), new.address_number, new.address1, new.address2, new.address3, new.city, new.state, new.postalcode, new.country, new.address_change) WHERE (vendaddrinfo.vendaddr_id = public.getvendaddrid((old.vendor_number)::text, (old.vendor_address_number)::text));
118196
118197
118198 --
118199 -- TOC entry 8883 (class 2618 OID 146572144)
118200 -- Dependencies: 396 396 396 393 396 8894
118201 -- Name: _UPDATE; Type: RULE; Schema: api; Owner: admin
118202 --
118203
118204 CREATE RULE "_UPDATE" AS ON UPDATE TO vendortype DO INSTEAD UPDATE public.vendtype SET vendtype_code = new.code, vendtype_descrip = new.description WHERE (vendtype.vendtype_code = (old.code)::text);
118205
118206
118207 SET search_path = public, pg_catalog;
118208
118209 --
118210 -- TOC entry 8884 (class 2618 OID 146572145)
118211 -- Dependencies: 245 245 245 8894
118212 -- Name: _DELETE; Type: RULE; Schema: public; Owner: admin
118213 --
118214
118215 CREATE RULE "_DELETE" AS ON DELETE TO url DO INSTEAD NOTHING;
118216
118217
118218 --
118219 -- TOC entry 8885 (class 2618 OID 146572146)
118220 -- Dependencies: 245 245 245 1397 245 8894
118221 -- Name: _DELETE_FILE; Type: RULE; Schema: public; Owner: admin
118222 --
118223
118224 CREATE RULE "_DELETE_FILE" AS ON DELETE TO url WHERE (old.url_stream IS NOT NULL) DO INSTEAD SELECT deletefile(old.url_id) AS deletefile;
118225
118226
118227 --
118228 -- TOC entry 8886 (class 2618 OID 146572147)
118229 -- Dependencies: 245 245 245 1474 245 8894
118230 -- Name: _DELETE_URL; Type: RULE; Schema: public; Owner: admin
118231 --
118232
118233 CREATE RULE "_DELETE_URL" AS ON DELETE TO url WHERE (old.url_stream IS NULL) DO INSTEAD SELECT deleteurl(old.url_id) AS deleteurl;
118234
118235
118236 --
118237 -- TOC entry 8887 (class 2618 OID 146572148)
118238 -- Dependencies: 245 245 245 8894
118239 -- Name: _INSERT; Type: RULE; Schema: public; Owner: admin
118240 --
118241
118242 CREATE RULE "_INSERT" AS ON INSERT TO url DO INSTEAD NOTHING;
118243
118244
118245 --
118246 -- TOC entry 8888 (class 2618 OID 146572149)
118247 -- Dependencies: 245 245 247 245 245 245 245 245 245 242 1331 245 8894
118248 -- Name: _INSERT_FILE; Type: RULE; Schema: public; Owner: admin
118249 --
118250
118251 CREATE RULE "_INSERT_FILE" AS ON INSERT TO url WHERE (new.url_stream IS NOT NULL) DO INSTEAD INSERT INTO docass (docass_id, docass_source_id, docass_source_type, docass_target_id, docass_target_type, docass_purpose) VALUES (COALESCE((new.url_id)::bigint, nextval('docass_docass_id_seq'::regclass)), new.url_source_id, new.url_source, createfile(new.url_title, new.url_url, new.url_stream), 'FILE'::text, 'S'::bpchar);
118252
118253
118254 --
118255 -- TOC entry 8889 (class 2618 OID 146572150)
118256 -- Dependencies: 245 245 247 245 245 245 245 245 242 1353 245 8894
118257 -- Name: _INSERT_URL; Type: RULE; Schema: public; Owner: admin
118258 --
118259
118260 CREATE RULE "_INSERT_URL" AS ON INSERT TO url WHERE (new.url_stream IS NULL) DO INSTEAD INSERT INTO docass (docass_id, docass_source_id, docass_source_type, docass_target_id, docass_target_type, docass_purpose) VALUES (COALESCE((new.url_id)::bigint, nextval('docass_docass_id_seq'::regclass)), new.url_source_id, new.url_source, createurl(new.url_title, new.url_url), 'URL'::text, 'S'::bpchar);
118261
118262
118263 --
118264 -- TOC entry 8890 (class 2618 OID 146572151)
118265 -- Dependencies: 245 245 245 8894
118266 -- Name: _UPDATE; Type: RULE; Schema: public; Owner: admin
118267 --
118268
118269 CREATE RULE "_UPDATE" AS ON UPDATE TO url DO INSTEAD NOTHING;
118270
118271
118272 --
118273 -- TOC entry 8891 (class 2618 OID 146572152)
118274 -- Dependencies: 245 245 245 245 245 243 242 242 242 245 8894
118275 -- Name: _UPDATE_FILE; Type: RULE; Schema: public; Owner: admin
118276 --
118277
118278 CREATE RULE "_UPDATE_FILE" AS ON UPDATE TO url WHERE (new.url_stream IS NOT NULL) DO INSTEAD UPDATE file SET file_title = new.url_title, file_stream = new.url_stream FROM docass WHERE (((docass.docass_id = old.url_id) AND (docass.docass_target_id = file.file_id)) AND (docass.docass_target_type = 'FILE'::text));
118279
118280
118281 --
118282 -- TOC entry 8892 (class 2618 OID 146572153)
118283 -- Dependencies: 245 245 245 245 245 244 242 242 242 245 8894
118284 -- Name: _UPDATE_URL; Type: RULE; Schema: public; Owner: admin
118285 --
118286
118287 CREATE RULE "_UPDATE_URL" AS ON UPDATE TO url WHERE (new.url_stream IS NULL) DO INSTEAD UPDATE urlinfo SET url_title = new.url_title, url_url = new.url_url FROM docass WHERE (((docass.docass_id = old.url_id) AND (docass.docass_target_id = urlinfo.url_id)) AND (docass.docass_target_type = 'URL'::text));
118288
118289
118290 SET search_path = fixcountry, pg_catalog;
118291
118292 --
118293 -- TOC entry 8256 (class 2620 OID 146572154)
118294 -- Dependencies: 399 1008 8894
118295 -- Name: pkgcmdaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118296 --
118297
118298 CREATE TRIGGER pkgcmdaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdaftertrigger();
118299
118300
118301 --
118302 -- TOC entry 8257 (class 2620 OID 146572155)
118303 -- Dependencies: 399 1009 8894
118304 -- Name: pkgcmdaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118305 --
118306
118307 CREATE TRIGGER pkgcmdaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdaltertrigger();
118308
118309
118310 --
118311 -- TOC entry 8259 (class 2620 OID 146572156)
118312 -- Dependencies: 402 1010 8894
118313 -- Name: pkgcmdargaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118314 --
118315
118316 CREATE TRIGGER pkgcmdargaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargaftertrigger();
118317
118318
118319 --
118320 -- TOC entry 8260 (class 2620 OID 146572157)
118321 -- Dependencies: 402 1012 8894
118322 -- Name: pkgcmdargaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118323 --
118324
118325 CREATE TRIGGER pkgcmdargaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargaltertrigger();
118326
118327
118328 --
118329 -- TOC entry 8261 (class 2620 OID 146572158)
118330 -- Dependencies: 402 1013 8894
118331 -- Name: pkgcmdargbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118332 --
118333
118334 CREATE TRIGGER pkgcmdargbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargbeforetrigger();
118335
118336
118337 --
118338 -- TOC entry 8258 (class 2620 OID 146572159)
118339 -- Dependencies: 399 1014 8894
118340 -- Name: pkgcmdbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118341 --
118342
118343 CREATE TRIGGER pkgcmdbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdbeforetrigger();
118344
118345
118346 --
118347 -- TOC entry 8262 (class 2620 OID 146572160)
118348 -- Dependencies: 404 1016 8894
118349 -- Name: pkgimageaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118350 --
118351
118352 CREATE TRIGGER pkgimageaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimageaftertrigger();
118353
118354
118355 --
118356 -- TOC entry 8263 (class 2620 OID 146572161)
118357 -- Dependencies: 404 1017 8894
118358 -- Name: pkgimagealtertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118359 --
118360
118361 CREATE TRIGGER pkgimagealtertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimagealtertrigger();
118362
118363
118364 --
118365 -- TOC entry 8264 (class 2620 OID 146572162)
118366 -- Dependencies: 404 1018 8894
118367 -- Name: pkgimagebeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118368 --
118369
118370 CREATE TRIGGER pkgimagebeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimagebeforetrigger();
118371
118372
118373 --
118374 -- TOC entry 8267 (class 2620 OID 146572163)
118375 -- Dependencies: 407 1020 8894
118376 -- Name: pkgmetasqlaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118377 --
118378
118379 CREATE TRIGGER pkgmetasqlaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlaftertrigger();
118380
118381
118382 --
118383 -- TOC entry 8268 (class 2620 OID 146572164)
118384 -- Dependencies: 407 1022 8894
118385 -- Name: pkgmetasqlaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118386 --
118387
118388 CREATE TRIGGER pkgmetasqlaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlaltertrigger();
118389
118390
118391 --
118392 -- TOC entry 8269 (class 2620 OID 146572165)
118393 -- Dependencies: 407 1023 8894
118394 -- Name: pkgmetasqlbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118395 --
118396
118397 CREATE TRIGGER pkgmetasqlbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlbeforetrigger();
118398
118399
118400 --
118401 -- TOC entry 8270 (class 2620 OID 146572166)
118402 -- Dependencies: 410 1024 8894
118403 -- Name: pkgprivaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118404 --
118405
118406 CREATE TRIGGER pkgprivaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivaftertrigger();
118407
118408
118409 --
118410 -- TOC entry 8271 (class 2620 OID 146572167)
118411 -- Dependencies: 410 1025 8894
118412 -- Name: pkgprivaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118413 --
118414
118415 CREATE TRIGGER pkgprivaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivaltertrigger();
118416
118417
118418 --
118419 -- TOC entry 8272 (class 2620 OID 146572168)
118420 -- Dependencies: 410 1026 8894
118421 -- Name: pkgprivbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118422 --
118423
118424 CREATE TRIGGER pkgprivbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivbeforetrigger();
118425
118426
118427 --
118428 -- TOC entry 8274 (class 2620 OID 146572169)
118429 -- Dependencies: 413 1027 8894
118430 -- Name: pkgreportaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118431 --
118432
118433 CREATE TRIGGER pkgreportaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportaftertrigger();
118434
118435
118436 --
118437 -- TOC entry 8275 (class 2620 OID 146572170)
118438 -- Dependencies: 413 1028 8894
118439 -- Name: pkgreportaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118440 --
118441
118442 CREATE TRIGGER pkgreportaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportaltertrigger();
118443
118444
118445 --
118446 -- TOC entry 8276 (class 2620 OID 146572171)
118447 -- Dependencies: 413 1029 8894
118448 -- Name: pkgreportbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118449 --
118450
118451 CREATE TRIGGER pkgreportbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportbeforetrigger();
118452
118453
118454 --
118455 -- TOC entry 8277 (class 2620 OID 146572172)
118456 -- Dependencies: 416 959 8894
118457 -- Name: pkgscriptaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118458 --
118459
118460 CREATE TRIGGER pkgscriptaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptaftertrigger();
118461
118462
118463 --
118464 -- TOC entry 8278 (class 2620 OID 146572173)
118465 -- Dependencies: 416 983 8894
118466 -- Name: pkgscriptaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118467 --
118468
118469 CREATE TRIGGER pkgscriptaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptaltertrigger();
118470
118471
118472 --
118473 -- TOC entry 8279 (class 2620 OID 146572174)
118474 -- Dependencies: 416 1003 8894
118475 -- Name: pkgscriptbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118476 --
118477
118478 CREATE TRIGGER pkgscriptbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptbeforetrigger();
118479
118480
118481 --
118482 -- TOC entry 8280 (class 2620 OID 146572175)
118483 -- Dependencies: 419 1011 8894
118484 -- Name: pkguiformaftertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118485 --
118486
118487 CREATE TRIGGER pkguiformaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformaftertrigger();
118488
118489
118490 --
118491 -- TOC entry 8281 (class 2620 OID 146572176)
118492 -- Dependencies: 419 1021 8894
118493 -- Name: pkguiformaltertrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118494 --
118495
118496 CREATE TRIGGER pkguiformaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformaltertrigger();
118497
118498
118499 --
118500 -- TOC entry 8282 (class 2620 OID 146572177)
118501 -- Dependencies: 419 945 8894
118502 -- Name: pkguiformbeforetrigger; Type: TRIGGER; Schema: fixcountry; Owner: admin
118503 --
118504
118505 CREATE TRIGGER pkguiformbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformbeforetrigger();
118506
118507
118508 SET search_path = public, pg_catalog;
118509
118510 --
118511 -- TOC entry 8206 (class 2620 OID 146572178)
118512 -- Dependencies: 262 914 8894
118513 -- Name: accntdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118514 --
118515
118516 CREATE TRIGGER accntdeletetrigger BEFORE DELETE ON accnt FOR EACH ROW EXECUTE PROCEDURE _accntdeletetrigger();
118517
118518
118519 --
118520 -- TOC entry 8207 (class 2620 OID 146572179)
118521 -- Dependencies: 262 915 8894
118522 -- Name: accnttrigger; Type: TRIGGER; Schema: public; Owner: admin
118523 --
118524
118525 CREATE TRIGGER accnttrigger BEFORE INSERT OR UPDATE ON accnt FOR EACH ROW EXECUTE PROCEDURE _accnttrigger();
118526
118527
118528 --
118529 -- TOC entry 8208 (class 2620 OID 146572180)
118530 -- Dependencies: 262 916 8894
118531 -- Name: accntuniquetrigger; Type: TRIGGER; Schema: public; Owner: admin
118532 --
118533
118534 CREATE TRIGGER accntuniquetrigger BEFORE INSERT ON accnt FOR EACH ROW EXECUTE PROCEDURE _accntuniquetrigger();
118535
118536
118537 --
118538 -- TOC entry 8197 (class 2620 OID 146572181)
118539 -- Dependencies: 234 917 8894
118540 -- Name: addrtrigger; Type: TRIGGER; Schema: public; Owner: admin
118541 --
118542
118543 CREATE TRIGGER addrtrigger BEFORE INSERT OR DELETE OR UPDATE ON addr FOR EACH ROW EXECUTE PROCEDURE _addrtrigger();
118544
118545
118546 --
118547 -- TOC entry 8283 (class 2620 OID 146572182)
118548 -- Dependencies: 424 918 8894
118549 -- Name: alarmbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118550 --
118551
118552 CREATE TRIGGER alarmbeforetrigger BEFORE INSERT ON alarm FOR EACH ROW EXECUTE PROCEDURE _alarmbeforetrigger();
118553
118554
118555 --
118556 -- TOC entry 8284 (class 2620 OID 146572183)
118557 -- Dependencies: 428 919 8894
118558 -- Name: apapplytrigger; Type: TRIGGER; Schema: public; Owner: admin
118559 --
118560
118561 CREATE TRIGGER apapplytrigger BEFORE INSERT OR UPDATE ON apapply FOR EACH ROW EXECUTE PROCEDURE _apapplytrigger();
118562
118563
118564 --
118565 -- TOC entry 8163 (class 2620 OID 146572184)
118566 -- Dependencies: 207 920 8894
118567 -- Name: apopentrigger; Type: TRIGGER; Schema: public; Owner: admin
118568 --
118569
118570 CREATE TRIGGER apopentrigger BEFORE INSERT OR UPDATE ON apopen FOR EACH ROW EXECUTE PROCEDURE _apopentrigger();
118571
118572
118573 --
118574 -- TOC entry 8286 (class 2620 OID 146572185)
118575 -- Dependencies: 443 913 8894
118576 -- Name: arapplytrigger; Type: TRIGGER; Schema: public; Owner: admin
118577 --
118578
118579 CREATE TRIGGER arapplytrigger BEFORE INSERT OR UPDATE ON arapply FOR EACH ROW EXECUTE PROCEDURE _arapplytrigger();
118580
118581
118582 --
118583 -- TOC entry 8170 (class 2620 OID 146572186)
118584 -- Dependencies: 212 903 8894
118585 -- Name: aropenaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118586 --
118587
118588 CREATE TRIGGER aropenaftertrigger AFTER INSERT OR UPDATE ON aropen FOR EACH ROW EXECUTE PROCEDURE _aropenaftertrigger();
118589
118590
118591 --
118592 -- TOC entry 8171 (class 2620 OID 146572187)
118593 -- Dependencies: 212 904 8894
118594 -- Name: aropentrigger; Type: TRIGGER; Schema: public; Owner: admin
118595 --
118596
118597 CREATE TRIGGER aropentrigger BEFORE INSERT OR UPDATE ON aropen FOR EACH ROW EXECUTE PROCEDURE _aropentrigger();
118598
118599
118600 --
118601 -- TOC entry 8204 (class 2620 OID 146572188)
118602 -- Dependencies: 254 921 8894
118603 -- Name: bomheadtrigger; Type: TRIGGER; Schema: public; Owner: admin
118604 --
118605
118606 CREATE TRIGGER bomheadtrigger AFTER INSERT OR DELETE OR UPDATE ON bomhead FOR EACH ROW EXECUTE PROCEDURE _bomheadtrigger();
118607
118608
118609 --
118610 -- TOC entry 8152 (class 2620 OID 146572189)
118611 -- Dependencies: 203 922 8894
118612 -- Name: bomitemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118613 --
118614
118615 CREATE TRIGGER bomitemaftertrigger AFTER INSERT OR UPDATE ON bomitem FOR EACH ROW EXECUTE PROCEDURE _bomitemaftertrigger();
118616
118617
118618 --
118619 -- TOC entry 8153 (class 2620 OID 146572190)
118620 -- Dependencies: 203 923 8894
118621 -- Name: bomitembeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118622 --
118623
118624 CREATE TRIGGER bomitembeforedeletetrigger BEFORE DELETE ON bomitem FOR EACH ROW EXECUTE PROCEDURE _bomitembeforedeletetrigger();
118625
118626
118627 --
118628 -- TOC entry 8154 (class 2620 OID 146572191)
118629 -- Dependencies: 203 924 8894
118630 -- Name: bomitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118631 --
118632
118633 CREATE TRIGGER bomitembeforetrigger BEFORE INSERT OR UPDATE ON bomitem FOR EACH ROW EXECUTE PROCEDURE _bomitembeforetrigger();
118634
118635
118636 --
118637 -- TOC entry 8205 (class 2620 OID 146572192)
118638 -- Dependencies: 258 925 8894
118639 -- Name: bomitemsubtrigger; Type: TRIGGER; Schema: public; Owner: admin
118640 --
118641
118642 CREATE TRIGGER bomitemsubtrigger BEFORE INSERT OR DELETE OR UPDATE ON bomitemsub FOR EACH ROW EXECUTE PROCEDURE _bomitemsubtrigger();
118643
118644
118645 --
118646 -- TOC entry 8211 (class 2620 OID 146572193)
118647 -- Dependencies: 269 926 8894
118648 -- Name: cashrcptitemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118649 --
118650
118651 CREATE TRIGGER cashrcptitemaftertrigger AFTER INSERT OR UPDATE ON cashrcptitem FOR EACH ROW EXECUTE PROCEDURE _cashrcptitemaftertrigger();
118652
118653
118654 --
118655 -- TOC entry 8212 (class 2620 OID 146572194)
118656 -- Dependencies: 269 927 8894
118657 -- Name: cashrcptitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
118658 --
118659
118660 CREATE TRIGGER cashrcptitemtrigger BEFORE INSERT OR UPDATE ON cashrcptitem FOR EACH ROW EXECUTE PROCEDURE _cashrcptitemtrigger();
118661
118662
118663 --
118664 -- TOC entry 8213 (class 2620 OID 146572195)
118665 -- Dependencies: 271 928 8894
118666 -- Name: cashrcptmisctrigger; Type: TRIGGER; Schema: public; Owner: admin
118667 --
118668
118669 CREATE TRIGGER cashrcptmisctrigger BEFORE INSERT OR UPDATE ON cashrcptmisc FOR EACH ROW EXECUTE PROCEDURE _cashrcptmisctrigger();
118670
118671
118672 --
118673 -- TOC entry 8210 (class 2620 OID 146572196)
118674 -- Dependencies: 267 929 8894
118675 -- Name: cashrcpttrigger; Type: TRIGGER; Schema: public; Owner: admin
118676 --
118677
118678 CREATE TRIGGER cashrcpttrigger BEFORE INSERT OR UPDATE ON cashrcpt FOR EACH ROW EXECUTE PROCEDURE _cashrcpttrigger();
118679
118680
118681 --
118682 -- TOC entry 8214 (class 2620 OID 146572197)
118683 -- Dependencies: 278 931 8894
118684 -- Name: ccardtrigger; Type: TRIGGER; Schema: public; Owner: admin
118685 --
118686
118687 CREATE TRIGGER ccardtrigger BEFORE INSERT OR UPDATE ON ccard FOR EACH ROW EXECUTE PROCEDURE _ccardtrigger();
118688
118689
118690 --
118691 -- TOC entry 8199 (class 2620 OID 146572198)
118692 -- Dependencies: 237 932 8894
118693 -- Name: charasshistorytrigger; Type: TRIGGER; Schema: public; Owner: admin
118694 --
118695
118696 CREATE TRIGGER charasshistorytrigger BEFORE INSERT OR DELETE OR UPDATE ON charass FOR EACH ROW EXECUTE PROCEDURE _charasshistorytrigger();
118697
118698
118699 --
118700 -- TOC entry 8200 (class 2620 OID 146572199)
118701 -- Dependencies: 237 933 8894
118702 -- Name: charasstrigger; Type: TRIGGER; Schema: public; Owner: admin
118703 --
118704
118705 CREATE TRIGGER charasstrigger AFTER INSERT OR UPDATE ON charass FOR EACH ROW EXECUTE PROCEDURE _charasstrigger();
118706
118707
118708 --
118709 -- TOC entry 8198 (class 2620 OID 146572200)
118710 -- Dependencies: 236 934 8894
118711 -- Name: charbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118712 --
118713
118714 CREATE TRIGGER charbeforetrigger BEFORE INSERT OR UPDATE ON "char" FOR EACH ROW EXECUTE PROCEDURE _charbeforetrigger();
118715
118716
118717 --
118718 -- TOC entry 8287 (class 2620 OID 146572201)
118719 -- Dependencies: 490 935 8894
118720 -- Name: charopttrigger; Type: TRIGGER; Schema: public; Owner: admin
118721 --
118722
118723 CREATE TRIGGER charopttrigger AFTER DELETE OR UPDATE ON charopt FOR EACH ROW EXECUTE PROCEDURE _charopttrigger();
118724
118725
118726 --
118727 -- TOC entry 8285 (class 2620 OID 146572202)
118728 -- Dependencies: 430 938 8894
118729 -- Name: checkheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118730 --
118731
118732 CREATE TRIGGER checkheadbeforetrigger BEFORE INSERT OR UPDATE ON checkhead FOR EACH ROW EXECUTE PROCEDURE _checkheadbeforetrigger();
118733
118734
118735 --
118736 -- TOC entry 8179 (class 2620 OID 146572203)
118737 -- Dependencies: 218 939 8894
118738 -- Name: cmheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118739 --
118740
118741 CREATE TRIGGER cmheadbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON cmhead FOR EACH ROW EXECUTE PROCEDURE _cmheadbeforetrigger();
118742
118743
118744 --
118745 -- TOC entry 8180 (class 2620 OID 146572204)
118746 -- Dependencies: 218 940 8894
118747 -- Name: cmheadtrigger; Type: TRIGGER; Schema: public; Owner: admin
118748 --
118749
118750 CREATE TRIGGER cmheadtrigger AFTER INSERT OR DELETE OR UPDATE ON cmhead FOR EACH ROW EXECUTE PROCEDURE _cmheadtrigger();
118751
118752
118753 --
118754 -- TOC entry 8182 (class 2620 OID 146572205)
118755 -- Dependencies: 222 941 8894
118756 -- Name: cmitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118757 --
118758
118759 CREATE TRIGGER cmitembeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON cmitem FOR EACH ROW EXECUTE PROCEDURE _cmitembeforetrigger();
118760
118761
118762 --
118763 -- TOC entry 8183 (class 2620 OID 146572206)
118764 -- Dependencies: 222 942 8894
118765 -- Name: cmitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
118766 --
118767
118768 CREATE TRIGGER cmitemtrigger AFTER INSERT OR DELETE OR UPDATE ON cmitem FOR EACH ROW EXECUTE PROCEDURE _cmitemtrigger();
118769
118770
118771 --
118772 -- TOC entry 8155 (class 2620 OID 146572207)
118773 -- Dependencies: 204 943 8894
118774 -- Name: cntcttrigger; Type: TRIGGER; Schema: public; Owner: admin
118775 --
118776
118777 CREATE TRIGGER cntcttrigger BEFORE INSERT OR UPDATE ON cntct FOR EACH ROW EXECUTE PROCEDURE _cntcttrigger();
118778
118779
118780 --
118781 -- TOC entry 8156 (class 2620 OID 146572208)
118782 -- Dependencies: 204 947 8894
118783 -- Name: cntcttriggerafter; Type: TRIGGER; Schema: public; Owner: admin
118784 --
118785
118786 CREATE TRIGGER cntcttriggerafter AFTER INSERT OR DELETE OR UPDATE ON cntct FOR EACH ROW EXECUTE PROCEDURE _cntcttriggerafter();
118787
118788
118789 --
118790 -- TOC entry 8157 (class 2620 OID 146572209)
118791 -- Dependencies: 204 948 8894
118792 -- Name: cntcttriggerbeforedelete; Type: TRIGGER; Schema: public; Owner: admin
118793 --
118794
118795 CREATE TRIGGER cntcttriggerbeforedelete BEFORE DELETE ON cntct FOR EACH ROW EXECUTE PROCEDURE _cntcttriggerbeforedelete();
118796
118797
118798 --
118799 -- TOC entry 8133 (class 2620 OID 146572210)
118800 -- Dependencies: 189 949 8894
118801 -- Name: cntsliptrigger; Type: TRIGGER; Schema: public; Owner: admin
118802 --
118803
118804 CREATE TRIGGER cntsliptrigger BEFORE INSERT OR DELETE OR UPDATE ON cntslip FOR EACH ROW EXECUTE PROCEDURE _cntsliptrigger();
118805
118806
118807 --
118808 -- TOC entry 8288 (class 2620 OID 146572211)
118809 -- Dependencies: 513 950 8894
118810 -- Name: cobillbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118811 --
118812
118813 CREATE TRIGGER cobillbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON cobill FOR EACH ROW EXECUTE PROCEDURE _cobillbeforetrigger();
118814
118815
118816 --
118817 -- TOC entry 8289 (class 2620 OID 146572212)
118818 -- Dependencies: 513 951 8894
118819 -- Name: cobilltrigger; Type: TRIGGER; Schema: public; Owner: admin
118820 --
118821
118822 CREATE TRIGGER cobilltrigger AFTER INSERT OR DELETE OR UPDATE ON cobill FOR EACH ROW EXECUTE PROCEDURE _cobilltrigger();
118823
118824
118825 --
118826 -- TOC entry 8290 (class 2620 OID 146572213)
118827 -- Dependencies: 516 936 8894
118828 -- Name: cobmiscbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118829 --
118830
118831 CREATE TRIGGER cobmiscbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON cobmisc FOR EACH ROW EXECUTE PROCEDURE _cobmiscbeforetrigger();
118832
118833
118834 --
118835 -- TOC entry 8291 (class 2620 OID 146572214)
118836 -- Dependencies: 516 937 8894
118837 -- Name: cobmisctrigger; Type: TRIGGER; Schema: public; Owner: admin
118838 --
118839
118840 CREATE TRIGGER cobmisctrigger AFTER INSERT OR DELETE OR UPDATE ON cobmisc FOR EACH ROW EXECUTE PROCEDURE _cobmisctrigger();
118841
118842
118843 --
118844 -- TOC entry 8201 (class 2620 OID 146572215)
118845 -- Dependencies: 240 944 8894
118846 -- Name: commenttrigger; Type: TRIGGER; Schema: public; Owner: admin
118847 --
118848
118849 CREATE TRIGGER commenttrigger AFTER INSERT OR UPDATE ON comment FOR EACH ROW EXECUTE PROCEDURE _commenttrigger();
118850
118851
118852 --
118853 -- TOC entry 8292 (class 2620 OID 146572216)
118854 -- Dependencies: 523 952 8894
118855 -- Name: companytrigger; Type: TRIGGER; Schema: public; Owner: admin
118856 --
118857
118858 CREATE TRIGGER companytrigger BEFORE UPDATE ON company FOR EACH ROW EXECUTE PROCEDURE _companytrigger();
118859
118860
118861 --
118862 -- TOC entry 8230 (class 2620 OID 146572217)
118863 -- Dependencies: 329 953 8894
118864 -- Name: contrctaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118865 --
118866
118867 CREATE TRIGGER contrctaftertrigger AFTER UPDATE ON contrct FOR EACH ROW EXECUTE PROCEDURE _contrctaftertrigger();
118868
118869
118870 --
118871 -- TOC entry 8158 (class 2620 OID 146572218)
118872 -- Dependencies: 205 954 8894
118873 -- Name: crmacctaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118874 --
118875
118876 CREATE TRIGGER crmacctaftertrigger AFTER INSERT OR DELETE OR UPDATE ON crmacct FOR EACH ROW EXECUTE PROCEDURE _crmacctaftertrigger();
118877
118878
118879 --
118880 -- TOC entry 8159 (class 2620 OID 146572219)
118881 -- Dependencies: 205 955 8894
118882 -- Name: crmacctbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
118883 --
118884
118885 CREATE TRIGGER crmacctbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON crmacct FOR EACH ROW EXECUTE PROCEDURE _crmacctbeforetrigger();
118886
118887
118888 --
118889 -- TOC entry 8294 (class 2620 OID 146572220)
118890 -- Dependencies: 545 1379 8894
118891 -- Name: currexchangecheckoverlap; Type: TRIGGER; Schema: public; Owner: admin
118892 --
118893
118894 CREATE TRIGGER currexchangecheckoverlap BEFORE INSERT OR UPDATE ON curr_rate FOR EACH ROW EXECUTE PROCEDURE currexchangecheckoverlap();
118895
118896
118897 --
118898 -- TOC entry 8164 (class 2620 OID 146572221)
118899 -- Dependencies: 208 1381 8894
118900 -- Name: curronebase; Type: TRIGGER; Schema: public; Owner: admin
118901 --
118902
118903 CREATE TRIGGER curronebase AFTER INSERT OR UPDATE ON curr_symbol FOR EACH ROW EXECUTE PROCEDURE curronebase();
118904
118905
118906 --
118907 -- TOC entry 8172 (class 2620 OID 146572222)
118908 -- Dependencies: 213 956 8894
118909 -- Name: custaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118910 --
118911
118912 CREATE TRIGGER custaftertrigger AFTER INSERT OR UPDATE ON custinfo FOR EACH ROW EXECUTE PROCEDURE _custaftertrigger();
118913
118914
118915 --
118916 -- TOC entry 8173 (class 2620 OID 146572223)
118917 -- Dependencies: 213 957 8894
118918 -- Name: custinfoafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118919 --
118920
118921 CREATE TRIGGER custinfoafterdeletetrigger AFTER DELETE ON custinfo FOR EACH ROW EXECUTE PROCEDURE _custinfoafterdeletetrigger();
118922
118923
118924 --
118925 -- TOC entry 8174 (class 2620 OID 146572224)
118926 -- Dependencies: 213 958 8894
118927 -- Name: custinfobeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118928 --
118929
118930 CREATE TRIGGER custinfobeforedeletetrigger BEFORE DELETE ON custinfo FOR EACH ROW EXECUTE PROCEDURE _custinfobeforedeletetrigger();
118931
118932
118933 --
118934 -- TOC entry 8175 (class 2620 OID 146572225)
118935 -- Dependencies: 213 960 8894
118936 -- Name: custtrigger; Type: TRIGGER; Schema: public; Owner: admin
118937 --
118938
118939 CREATE TRIGGER custtrigger BEFORE INSERT OR UPDATE ON custinfo FOR EACH ROW EXECUTE PROCEDURE _custtrigger();
118940
118941
118942 --
118943 -- TOC entry 8215 (class 2620 OID 146572226)
118944 -- Dependencies: 280 961 8894
118945 -- Name: custtypeafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118946 --
118947
118948 CREATE TRIGGER custtypeafterdeletetrigger AFTER DELETE ON custtype FOR EACH ROW EXECUTE PROCEDURE _custtypeafterdeletetrigger();
118949
118950
118951 --
118952 -- TOC entry 8216 (class 2620 OID 146572227)
118953 -- Dependencies: 280 962 8894
118954 -- Name: custtypetrigger; Type: TRIGGER; Schema: public; Owner: admin
118955 --
118956
118957 CREATE TRIGGER custtypetrigger BEFORE INSERT OR UPDATE ON custtype FOR EACH ROW EXECUTE PROCEDURE _custtypetrigger();
118958
118959
118960 --
118961 -- TOC entry 8202 (class 2620 OID 146572228)
118962 -- Dependencies: 242 963 8894
118963 -- Name: docasstrigger; Type: TRIGGER; Schema: public; Owner: admin
118964 --
118965
118966 CREATE TRIGGER docasstrigger AFTER INSERT OR UPDATE ON docass FOR EACH ROW EXECUTE PROCEDURE _docasstrigger();
118967
118968
118969 --
118970 -- TOC entry 8222 (class 2620 OID 146572229)
118971 -- Dependencies: 292 964 8894
118972 -- Name: empafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118973 --
118974
118975 CREATE TRIGGER empafterdeletetrigger AFTER DELETE ON emp FOR EACH ROW EXECUTE PROCEDURE _empafterdeletetrigger();
118976
118977
118978 --
118979 -- TOC entry 8223 (class 2620 OID 146572230)
118980 -- Dependencies: 292 965 8894
118981 -- Name: empaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
118982 --
118983
118984 CREATE TRIGGER empaftertrigger AFTER INSERT OR UPDATE ON emp FOR EACH ROW EXECUTE PROCEDURE _empaftertrigger();
118985
118986
118987 --
118988 -- TOC entry 8224 (class 2620 OID 146572231)
118989 -- Dependencies: 292 966 8894
118990 -- Name: empbeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
118991 --
118992
118993 CREATE TRIGGER empbeforedeletetrigger BEFORE DELETE ON emp FOR EACH ROW EXECUTE PROCEDURE _empbeforedeletetrigger();
118994
118995
118996 --
118997 -- TOC entry 8225 (class 2620 OID 146572232)
118998 -- Dependencies: 292 967 8894
118999 -- Name: empbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119000 --
119001
119002 CREATE TRIGGER empbeforetrigger BEFORE INSERT OR UPDATE ON emp FOR EACH ROW EXECUTE PROCEDURE _empbeforetrigger();
119003
119004
119005 --
119006 -- TOC entry 8296 (class 2620 OID 146572233)
119007 -- Dependencies: 567 968 8894
119008 -- Name: evntlogafterinserttrigger; Type: TRIGGER; Schema: public; Owner: admin
119009 --
119010
119011 CREATE TRIGGER evntlogafterinserttrigger AFTER INSERT ON evntlog FOR EACH ROW EXECUTE PROCEDURE _evntlogafterinserttrigger();
119012
119013
119014 --
119015 -- TOC entry 8237 (class 2620 OID 146572234)
119016 -- Dependencies: 340 969 8894
119017 -- Name: gltransaltertrigger; Type: TRIGGER; Schema: public; Owner: admin
119018 --
119019
119020 CREATE TRIGGER gltransaltertrigger BEFORE DELETE OR UPDATE ON gltrans FOR EACH ROW EXECUTE PROCEDURE _gltransaltertrigger();
119021
119022
119023 --
119024 -- TOC entry 8238 (class 2620 OID 146572235)
119025 -- Dependencies: 340 970 8894
119026 -- Name: gltransinserttrigger; Type: TRIGGER; Schema: public; Owner: admin
119027 --
119028
119029 CREATE TRIGGER gltransinserttrigger BEFORE INSERT ON gltrans FOR EACH ROW EXECUTE PROCEDURE _gltransinserttrigger();
119030
119031
119032 --
119033 -- TOC entry 8297 (class 2620 OID 146572236)
119034 -- Dependencies: 603 971 8894
119035 -- Name: grpprivtrigger; Type: TRIGGER; Schema: public; Owner: admin
119036 --
119037
119038 CREATE TRIGGER grpprivtrigger BEFORE INSERT OR UPDATE ON grppriv FOR EACH ROW EXECUTE PROCEDURE _grpprivtrigger();
119039
119040
119041 --
119042 -- TOC entry 8203 (class 2620 OID 146572237)
119043 -- Dependencies: 249 972 8894
119044 -- Name: imageasstrigger; Type: TRIGGER; Schema: public; Owner: admin
119045 --
119046
119047 CREATE TRIGGER imageasstrigger AFTER INSERT OR UPDATE ON imageass FOR EACH ROW EXECUTE PROCEDURE _imageasstrigger();
119048
119049
119050 --
119051 -- TOC entry 8160 (class 2620 OID 146572238)
119052 -- Dependencies: 206 973 8894
119053 -- Name: incdtbeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119054 --
119055
119056 CREATE TRIGGER incdtbeforedeletetrigger BEFORE DELETE ON incdt FOR EACH ROW EXECUTE PROCEDURE _incdtbeforedeletetrigger();
119057
119058
119059 --
119060 -- TOC entry 8161 (class 2620 OID 146572239)
119061 -- Dependencies: 206 974 8894
119062 -- Name: incdtbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119063 --
119064
119065 CREATE TRIGGER incdtbeforetrigger BEFORE INSERT OR UPDATE ON incdt FOR EACH ROW EXECUTE PROCEDURE _incdtbeforetrigger();
119066
119067
119068 --
119069 -- TOC entry 8162 (class 2620 OID 146572240)
119070 -- Dependencies: 206 975 8894
119071 -- Name: incdttrigger; Type: TRIGGER; Schema: public; Owner: admin
119072 --
119073
119074 CREATE TRIGGER incdttrigger AFTER INSERT OR DELETE OR UPDATE ON incdt FOR EACH ROW EXECUTE PROCEDURE _incdttrigger();
119075
119076
119077 --
119078 -- TOC entry 8184 (class 2620 OID 146572241)
119079 -- Dependencies: 224 976 8894
119080 -- Name: invcheadaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119081 --
119082
119083 CREATE TRIGGER invcheadaftertrigger AFTER UPDATE ON invchead FOR EACH ROW EXECUTE PROCEDURE _invcheadaftertrigger();
119084
119085
119086 --
119087 -- TOC entry 8185 (class 2620 OID 146572242)
119088 -- Dependencies: 224 977 8894
119089 -- Name: invcheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119090 --
119091
119092 CREATE TRIGGER invcheadbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON invchead FOR EACH ROW EXECUTE PROCEDURE _invcheadbeforetrigger();
119093
119094
119095 --
119096 -- TOC entry 8186 (class 2620 OID 146572243)
119097 -- Dependencies: 224 978 8894
119098 -- Name: invcheadtrigger; Type: TRIGGER; Schema: public; Owner: admin
119099 --
119100
119101 CREATE TRIGGER invcheadtrigger AFTER INSERT OR DELETE OR UPDATE ON invchead FOR EACH ROW EXECUTE PROCEDURE _invcheadtrigger();
119102
119103
119104 --
119105 -- TOC entry 8190 (class 2620 OID 146572244)
119106 -- Dependencies: 229 979 8894
119107 -- Name: invcitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119108 --
119109
119110 CREATE TRIGGER invcitembeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON invcitem FOR EACH ROW EXECUTE PROCEDURE _invcitembeforetrigger();
119111
119112
119113 --
119114 -- TOC entry 8191 (class 2620 OID 146572245)
119115 -- Dependencies: 229 980 8894
119116 -- Name: invcitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
119117 --
119118
119119 CREATE TRIGGER invcitemtrigger AFTER INSERT OR DELETE OR UPDATE ON invcitem FOR EACH ROW EXECUTE PROCEDURE _invcitemtrigger();
119120
119121
119122 --
119123 -- TOC entry 8298 (class 2620 OID 146572246)
119124 -- Dependencies: 623 1840 8894
119125 -- Name: invhisttrigger; Type: TRIGGER; Schema: public; Owner: admin
119126 --
119127
119128 CREATE TRIGGER invhisttrigger BEFORE INSERT OR UPDATE ON invhist FOR EACH ROW EXECUTE PROCEDURE invhisttrig();
119129
119130
119131 --
119132 -- TOC entry 8242 (class 2620 OID 146572247)
119133 -- Dependencies: 347 981 8894
119134 -- Name: ipsassbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119135 --
119136
119137 CREATE TRIGGER ipsassbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON ipsass FOR EACH ROW EXECUTE PROCEDURE _ipsassbeforetrigger();
119138
119139
119140 --
119141 -- TOC entry 8227 (class 2620 OID 146572248)
119142 -- Dependencies: 301 982 8894
119143 -- Name: ipsheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119144 --
119145
119146 CREATE TRIGGER ipsheadbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON ipshead FOR EACH ROW EXECUTE PROCEDURE _ipsheadbeforetrigger();
119147
119148
119149 --
119150 -- TOC entry 8244 (class 2620 OID 146572249)
119151 -- Dependencies: 351 984 8894
119152 -- Name: ipsitemcharbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119153 --
119154
119155 CREATE TRIGGER ipsitemcharbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON ipsitemchar FOR EACH ROW EXECUTE PROCEDURE _ipsitemcharbeforetrigger();
119156
119157
119158 --
119159 -- TOC entry 8243 (class 2620 OID 146572250)
119160 -- Dependencies: 349 985 8894
119161 -- Name: ipsiteminfobeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119162 --
119163
119164 CREATE TRIGGER ipsiteminfobeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON ipsiteminfo FOR EACH ROW EXECUTE PROCEDURE _ipsiteminfobeforetrigger();
119165
119166
119167 --
119168 -- TOC entry 8134 (class 2620 OID 146572251)
119169 -- Dependencies: 191 986 8894
119170 -- Name: itemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119171 --
119172
119173 CREATE TRIGGER itemaftertrigger AFTER INSERT OR DELETE OR UPDATE ON item FOR EACH ROW EXECUTE PROCEDURE _itemaftertrigger();
119174
119175
119176 --
119177 -- TOC entry 8228 (class 2620 OID 146572252)
119178 -- Dependencies: 321 988 8894
119179 -- Name: itemcostaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119180 --
119181
119182 CREATE TRIGGER itemcostaftertrigger AFTER INSERT OR UPDATE ON itemcost FOR EACH ROW EXECUTE PROCEDURE _itemcostaftertrigger();
119183
119184
119185 --
119186 -- TOC entry 8229 (class 2620 OID 146572253)
119187 -- Dependencies: 321 989 8894
119188 -- Name: itemcosttrigger; Type: TRIGGER; Schema: public; Owner: admin
119189 --
119190
119191 CREATE TRIGGER itemcosttrigger BEFORE INSERT OR DELETE OR UPDATE ON itemcost FOR EACH ROW EXECUTE PROCEDURE _itemcosttrigger();
119192
119193
119194 --
119195 -- TOC entry 8136 (class 2620 OID 146572254)
119196 -- Dependencies: 192 990 8894
119197 -- Name: itemsiteaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119198 --
119199
119200 CREATE TRIGGER itemsiteaftertrigger AFTER INSERT OR UPDATE ON itemsite FOR EACH ROW EXECUTE PROCEDURE _itemsiteaftertrigger();
119201
119202
119203 --
119204 -- TOC entry 8137 (class 2620 OID 146572255)
119205 -- Dependencies: 192 991 8894
119206 -- Name: itemsitetrigger; Type: TRIGGER; Schema: public; Owner: admin
119207 --
119208
119209 CREATE TRIGGER itemsitetrigger BEFORE INSERT OR UPDATE ON itemsite FOR EACH ROW EXECUTE PROCEDURE _itemsitetrigger();
119210
119211
119212 --
119213 -- TOC entry 8231 (class 2620 OID 146572256)
119214 -- Dependencies: 330 992 8894
119215 -- Name: itemsrcaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119216 --
119217
119218 CREATE TRIGGER itemsrcaftertrigger AFTER INSERT OR UPDATE ON itemsrc FOR EACH ROW EXECUTE PROCEDURE _itemsrcaftertrigger();
119219
119220
119221 --
119222 -- TOC entry 8233 (class 2620 OID 146572257)
119223 -- Dependencies: 332 993 8894
119224 -- Name: itemsrcptrigger; Type: TRIGGER; Schema: public; Owner: admin
119225 --
119226
119227 CREATE TRIGGER itemsrcptrigger BEFORE INSERT OR UPDATE ON itemsrcp FOR EACH ROW EXECUTE PROCEDURE _itemsrcptrigger();
119228
119229
119230 --
119231 -- TOC entry 8232 (class 2620 OID 146572258)
119232 -- Dependencies: 330 994 8894
119233 -- Name: itemsrctrigger; Type: TRIGGER; Schema: public; Owner: admin
119234 --
119235
119236 CREATE TRIGGER itemsrctrigger BEFORE INSERT OR UPDATE ON itemsrc FOR EACH ROW EXECUTE PROCEDURE _itemsrctrigger();
119237
119238
119239 --
119240 -- TOC entry 8234 (class 2620 OID 146572259)
119241 -- Dependencies: 334 995 8894
119242 -- Name: itemsubtrigger; Type: TRIGGER; Schema: public; Owner: admin
119243 --
119244
119245 CREATE TRIGGER itemsubtrigger AFTER INSERT OR UPDATE ON itemsub FOR EACH ROW EXECUTE PROCEDURE _itemsubtrigger();
119246
119247
119248 --
119249 -- TOC entry 8235 (class 2620 OID 146572260)
119250 -- Dependencies: 336 996 8894
119251 -- Name: itemtaxtrigger; Type: TRIGGER; Schema: public; Owner: admin
119252 --
119253
119254 CREATE TRIGGER itemtaxtrigger AFTER INSERT OR UPDATE ON itemtax FOR EACH ROW EXECUTE PROCEDURE _itemtaxtrigger();
119255
119256
119257 --
119258 -- TOC entry 8135 (class 2620 OID 146572261)
119259 -- Dependencies: 191 997 8894
119260 -- Name: itemtrigger; Type: TRIGGER; Schema: public; Owner: admin
119261 --
119262
119263 CREATE TRIGGER itemtrigger BEFORE INSERT OR UPDATE ON item FOR EACH ROW EXECUTE PROCEDURE _itemtrigger();
119264
119265
119266 --
119267 -- TOC entry 8236 (class 2620 OID 146572262)
119268 -- Dependencies: 338 998 8894
119269 -- Name: itemuomconvtrigger; Type: TRIGGER; Schema: public; Owner: admin
119270 --
119271
119272 CREATE TRIGGER itemuomconvtrigger AFTER INSERT OR UPDATE ON itemuomconv FOR EACH ROW EXECUTE PROCEDURE _itemuomconvtrigger();
119273
119274
119275 --
119276 -- TOC entry 8239 (class 2620 OID 146572263)
119277 -- Dependencies: 342 999 8894
119278 -- Name: locationaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119279 --
119280
119281 CREATE TRIGGER locationaftertrigger AFTER INSERT OR UPDATE ON location FOR EACH ROW EXECUTE PROCEDURE _locationaftertrigger();
119282
119283
119284 --
119285 -- TOC entry 8240 (class 2620 OID 146572264)
119286 -- Dependencies: 342 1000 8894
119287 -- Name: locationtrigger; Type: TRIGGER; Schema: public; Owner: admin
119288 --
119289
119290 CREATE TRIGGER locationtrigger BEFORE INSERT OR UPDATE ON location FOR EACH ROW EXECUTE PROCEDURE _locationtrigger();
119291
119292
119293 --
119294 -- TOC entry 8265 (class 2620 OID 146572265)
119295 -- Dependencies: 405 1001 8894
119296 -- Name: metasqlaltertrigger; Type: TRIGGER; Schema: public; Owner: admin
119297 --
119298
119299 CREATE TRIGGER metasqlaltertrigger BEFORE INSERT OR UPDATE ON metasql FOR EACH ROW EXECUTE PROCEDURE _metasqlaltertrigger();
119300
119301
119302 --
119303 -- TOC entry 8266 (class 2620 OID 146572266)
119304 -- Dependencies: 405 1002 8894
119305 -- Name: metasqltrigger; Type: TRIGGER; Schema: public; Owner: admin
119306 --
119307
119308 CREATE TRIGGER metasqltrigger BEFORE INSERT OR UPDATE ON metasql FOR EACH ROW EXECUTE PROCEDURE _metasqltrigger();
119309
119310
119311 --
119312 -- TOC entry 8192 (class 2620 OID 146572267)
119313 -- Dependencies: 231 1004 8894
119314 -- Name: opheadaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119315 --
119316
119317 CREATE TRIGGER opheadaftertrigger AFTER INSERT OR DELETE OR UPDATE ON ophead FOR EACH ROW EXECUTE PROCEDURE _opheadaftertrigger();
119318
119319
119320 --
119321 -- TOC entry 8193 (class 2620 OID 146572268)
119322 -- Dependencies: 231 1005 8894
119323 -- Name: opheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119324 --
119325
119326 CREATE TRIGGER opheadbeforetrigger BEFORE INSERT OR UPDATE ON ophead FOR EACH ROW EXECUTE PROCEDURE _opheadbeforetrigger();
119327
119328
119329 --
119330 -- TOC entry 8299 (class 2620 OID 146572269)
119331 -- Dependencies: 706 1006 8894
119332 -- Name: packbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119333 --
119334
119335 CREATE TRIGGER packbeforetrigger BEFORE INSERT OR UPDATE ON pack FOR EACH ROW EXECUTE PROCEDURE _packbeforetrigger();
119336
119337
119338 --
119339 -- TOC entry 8209 (class 2620 OID 146572270)
119340 -- Dependencies: 264 1007 8894
119341 -- Name: periodaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119342 --
119343
119344 CREATE TRIGGER periodaftertrigger AFTER INSERT OR DELETE OR UPDATE ON period FOR EACH STATEMENT EXECUTE PROCEDURE _periodaftertrigger();
119345
119346
119347 --
119348 -- TOC entry 8300 (class 2620 OID 146572271)
119349 -- Dependencies: 713 1015 8894
119350 -- Name: pkgheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119351 --
119352
119353 CREATE TRIGGER pkgheadbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkghead FOR EACH ROW EXECUTE PROCEDURE _pkgheadbeforetrigger();
119354
119355
119356 --
119357 -- TOC entry 8301 (class 2620 OID 146572272)
119358 -- Dependencies: 715 1019 8894
119359 -- Name: pkgitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119360 --
119361
119362 CREATE TRIGGER pkgitembeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgitem FOR EACH ROW EXECUTE PROCEDURE _pkgitembeforetrigger();
119363
119364
119365 --
119366 -- TOC entry 8146 (class 2620 OID 146572273)
119367 -- Dependencies: 197 1030 8894
119368 -- Name: poheadtrigger; Type: TRIGGER; Schema: public; Owner: admin
119369 --
119370
119371 CREATE TRIGGER poheadtrigger BEFORE INSERT OR DELETE OR UPDATE ON pohead FOR EACH ROW EXECUTE PROCEDURE _poheadtrigger();
119372
119373
119374 --
119375 -- TOC entry 8147 (class 2620 OID 146572274)
119376 -- Dependencies: 197 1031 8894
119377 -- Name: poheadtriggerafter; Type: TRIGGER; Schema: public; Owner: admin
119378 --
119379
119380 CREATE TRIGGER poheadtriggerafter AFTER UPDATE ON pohead FOR EACH ROW EXECUTE PROCEDURE _poheadtriggerafter();
119381
119382
119383 --
119384 -- TOC entry 8148 (class 2620 OID 146572275)
119385 -- Dependencies: 198 1032 8894
119386 -- Name: poitemafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119387 --
119388
119389 CREATE TRIGGER poitemafterdeletetrigger AFTER DELETE ON poitem FOR EACH ROW EXECUTE PROCEDURE _poitemafterdeletetrigger();
119390
119391
119392 --
119393 -- TOC entry 8149 (class 2620 OID 146572276)
119394 -- Dependencies: 198 1033 8894
119395 -- Name: poitemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119396 --
119397
119398 CREATE TRIGGER poitemaftertrigger AFTER INSERT OR UPDATE ON poitem FOR EACH ROW EXECUTE PROCEDURE _poitemaftertrigger();
119399
119400
119401 --
119402 -- TOC entry 8150 (class 2620 OID 146572277)
119403 -- Dependencies: 198 1034 8894
119404 -- Name: poitemdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119405 --
119406
119407 CREATE TRIGGER poitemdeletetrigger BEFORE DELETE ON poitem FOR EACH ROW EXECUTE PROCEDURE _poitemdeletetrigger();
119408
119409
119410 --
119411 -- TOC entry 8151 (class 2620 OID 146572278)
119412 -- Dependencies: 198 1035 8894
119413 -- Name: poitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
119414 --
119415
119416 CREATE TRIGGER poitemtrigger BEFORE INSERT OR UPDATE ON poitem FOR EACH ROW EXECUTE PROCEDURE _poitemtrigger();
119417
119418
119419 --
119420 -- TOC entry 8187 (class 2620 OID 146572279)
119421 -- Dependencies: 225 1036 8894
119422 -- Name: prjaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119423 --
119424
119425 CREATE TRIGGER prjaftertrigger AFTER INSERT OR UPDATE ON prj FOR EACH ROW EXECUTE PROCEDURE _prjaftertrigger();
119426
119427
119428 --
119429 -- TOC entry 8188 (class 2620 OID 146572280)
119430 -- Dependencies: 225 1038 8894
119431 -- Name: prjbeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119432 --
119433
119434 CREATE TRIGGER prjbeforedeletetrigger BEFORE DELETE ON prj FOR EACH ROW EXECUTE PROCEDURE _prjbeforedeletetrigger();
119435
119436
119437 --
119438 -- TOC entry 8194 (class 2620 OID 146572281)
119439 -- Dependencies: 232 1039 8894
119440 -- Name: prjtaskaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119441 --
119442
119443 CREATE TRIGGER prjtaskaftertrigger AFTER INSERT OR UPDATE ON prjtask FOR EACH ROW EXECUTE PROCEDURE _prjtaskaftertrigger();
119444
119445
119446 --
119447 -- TOC entry 8195 (class 2620 OID 146572282)
119448 -- Dependencies: 232 1040 8894
119449 -- Name: prjtasktrigger; Type: TRIGGER; Schema: public; Owner: admin
119450 --
119451
119452 CREATE TRIGGER prjtasktrigger BEFORE INSERT OR UPDATE ON prjtask FOR EACH ROW EXECUTE PROCEDURE _prjtasktrigger();
119453
119454
119455 --
119456 -- TOC entry 8245 (class 2620 OID 146572283)
119457 -- Dependencies: 356 1041 8894
119458 -- Name: prospectafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119459 --
119460
119461 CREATE TRIGGER prospectafterdeletetrigger AFTER DELETE ON prospect FOR EACH ROW EXECUTE PROCEDURE _prospectafterdeletetrigger();
119462
119463
119464 --
119465 -- TOC entry 8246 (class 2620 OID 146572284)
119466 -- Dependencies: 356 1042 8894
119467 -- Name: prospectaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119468 --
119469
119470 CREATE TRIGGER prospectaftertrigger AFTER INSERT OR UPDATE ON prospect FOR EACH ROW EXECUTE PROCEDURE _prospectaftertrigger();
119471
119472
119473 --
119474 -- TOC entry 8247 (class 2620 OID 146572285)
119475 -- Dependencies: 356 1043 8894
119476 -- Name: prospectbeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119477 --
119478
119479 CREATE TRIGGER prospectbeforedeletetrigger BEFORE DELETE ON prospect FOR EACH ROW EXECUTE PROCEDURE _prospectbeforedeletetrigger();
119480
119481
119482 --
119483 -- TOC entry 8248 (class 2620 OID 146572286)
119484 -- Dependencies: 356 1044 8894
119485 -- Name: prospecttrigger; Type: TRIGGER; Schema: public; Owner: admin
119486 --
119487
119488 CREATE TRIGGER prospecttrigger BEFORE INSERT OR UPDATE ON prospect FOR EACH ROW EXECUTE PROCEDURE _prospecttrigger();
119489
119490
119491 --
119492 -- TOC entry 8302 (class 2620 OID 146572287)
119493 -- Dependencies: 728 1045 8894
119494 -- Name: prtrigger; Type: TRIGGER; Schema: public; Owner: admin
119495 --
119496
119497 CREATE TRIGGER prtrigger AFTER INSERT ON pr FOR EACH ROW EXECUTE PROCEDURE _prtrigger();
119498
119499
119500 --
119501 -- TOC entry 8251 (class 2620 OID 146572288)
119502 -- Dependencies: 367 1046 8894
119503 -- Name: quheadtrigger; Type: TRIGGER; Schema: public; Owner: admin
119504 --
119505
119506 CREATE TRIGGER quheadtrigger BEFORE INSERT OR DELETE OR UPDATE ON quhead FOR EACH ROW EXECUTE PROCEDURE _quheadtrigger();
119507
119508
119509 --
119510 -- TOC entry 8252 (class 2620 OID 146572289)
119511 -- Dependencies: 370 1048 8894
119512 -- Name: quitemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119513 --
119514
119515 CREATE TRIGGER quitemaftertrigger AFTER INSERT OR UPDATE ON quitem FOR EACH ROW EXECUTE PROCEDURE _quitemaftertrigger();
119516
119517
119518 --
119519 -- TOC entry 8253 (class 2620 OID 146572290)
119520 -- Dependencies: 370 1049 8894
119521 -- Name: quitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119522 --
119523
119524 CREATE TRIGGER quitembeforetrigger BEFORE INSERT OR UPDATE ON quitem FOR EACH ROW EXECUTE PROCEDURE _quitembeforetrigger();
119525
119526
119527 --
119528 -- TOC entry 8254 (class 2620 OID 146572291)
119529 -- Dependencies: 370 1050 8894
119530 -- Name: quitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
119531 --
119532
119533 CREATE TRIGGER quitemtrigger BEFORE INSERT OR DELETE OR UPDATE ON quitem FOR EACH ROW EXECUTE PROCEDURE _quitemtrigger();
119534
119535
119536 --
119537 -- TOC entry 8304 (class 2620 OID 146572292)
119538 -- Dependencies: 749 1051 8894
119539 -- Name: recuraftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119540 --
119541
119542 CREATE TRIGGER recuraftertrigger AFTER DELETE ON recur FOR EACH ROW EXECUTE PROCEDURE _recuraftertrigger();
119543
119544
119545 --
119546 -- TOC entry 8273 (class 2620 OID 146572293)
119547 -- Dependencies: 411 1052 8894
119548 -- Name: reporttrigger; Type: TRIGGER; Schema: public; Owner: admin
119549 --
119550
119551 CREATE TRIGGER reporttrigger BEFORE INSERT OR UPDATE ON report FOR EACH ROW EXECUTE PROCEDURE _reporttrigger();
119552
119553
119554 --
119555 -- TOC entry 8176 (class 2620 OID 146572294)
119556 -- Dependencies: 216 1053 8894
119557 -- Name: salesrepafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119558 --
119559
119560 CREATE TRIGGER salesrepafterdeletetrigger AFTER DELETE ON salesrep FOR EACH ROW EXECUTE PROCEDURE _salesrepafterdeletetrigger();
119561
119562
119563 --
119564 -- TOC entry 8177 (class 2620 OID 146572295)
119565 -- Dependencies: 216 1054 8894
119566 -- Name: salesrepaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119567 --
119568
119569 CREATE TRIGGER salesrepaftertrigger AFTER INSERT OR UPDATE ON salesrep FOR EACH ROW EXECUTE PROCEDURE _salesrepaftertrigger();
119570
119571
119572 --
119573 -- TOC entry 8178 (class 2620 OID 146572296)
119574 -- Dependencies: 216 1055 8894
119575 -- Name: salesrepbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119576 --
119577
119578 CREATE TRIGGER salesrepbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON salesrep FOR EACH ROW EXECUTE PROCEDURE _salesrepbeforetrigger();
119579
119580
119581 --
119582 -- TOC entry 8189 (class 2620 OID 146572297)
119583 -- Dependencies: 226 1058 8894
119584 -- Name: saletypebeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119585 --
119586
119587 CREATE TRIGGER saletypebeforedeletetrigger BEFORE DELETE ON saletype FOR EACH ROW EXECUTE PROCEDURE _saletypebeforedeletetrigger();
119588
119589
119590 --
119591 -- TOC entry 8305 (class 2620 OID 146572298)
119592 -- Dependencies: 771 1059 8894
119593 -- Name: shipdatasumtrigger; Type: TRIGGER; Schema: public; Owner: admin
119594 --
119595
119596 CREATE TRIGGER shipdatasumtrigger BEFORE INSERT OR UPDATE ON shipdatasum FOR EACH ROW EXECUTE PROCEDURE _shipdatasumtrigger();
119597
119598
119599 --
119600 -- TOC entry 8226 (class 2620 OID 146572299)
119601 -- Dependencies: 297 1060 8894
119602 -- Name: shipdatatrigger; Type: TRIGGER; Schema: public; Owner: admin
119603 --
119604
119605 CREATE TRIGGER shipdatatrigger BEFORE INSERT OR UPDATE ON shipdata FOR EACH ROW EXECUTE PROCEDURE _shipdatatrigger();
119606
119607
119608 --
119609 -- TOC entry 8217 (class 2620 OID 146572300)
119610 -- Dependencies: 282 1061 8894
119611 -- Name: shipformafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119612 --
119613
119614 CREATE TRIGGER shipformafterdeletetrigger AFTER DELETE ON shipform FOR EACH ROW EXECUTE PROCEDURE _shipformafterdeletetrigger();
119615
119616
119617 --
119618 -- TOC entry 8293 (class 2620 OID 146572301)
119619 -- Dependencies: 526 1062 8894
119620 -- Name: shipheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119621 --
119622
119623 CREATE TRIGGER shipheadbeforetrigger BEFORE INSERT OR UPDATE ON shiphead FOR EACH ROW EXECUTE PROCEDURE _shipheadbeforetrigger();
119624
119625
119626 --
119627 -- TOC entry 8181 (class 2620 OID 146572302)
119628 -- Dependencies: 219 1063 8894
119629 -- Name: shiptoinfoaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119630 --
119631
119632 CREATE TRIGGER shiptoinfoaftertrigger AFTER INSERT OR UPDATE ON shiptoinfo FOR EACH ROW EXECUTE PROCEDURE _shiptoinfoaftertrigger();
119633
119634
119635 --
119636 -- TOC entry 8255 (class 2620 OID 146572303)
119637 -- Dependencies: 386 1064 8894
119638 -- Name: shipviaafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119639 --
119640
119641 CREATE TRIGGER shipviaafterdeletetrigger AFTER DELETE ON shipvia FOR EACH ROW EXECUTE PROCEDURE _shipviaafterdeletetrigger();
119642
119643
119644 --
119645 -- TOC entry 8306 (class 2620 OID 146572304)
119646 -- Dependencies: 781 1065 8894
119647 -- Name: sltransaltertrigger; Type: TRIGGER; Schema: public; Owner: admin
119648 --
119649
119650 CREATE TRIGGER sltransaltertrigger BEFORE DELETE OR UPDATE ON sltrans FOR EACH ROW EXECUTE PROCEDURE _sltransaltertrigger();
119651
119652
119653 --
119654 -- TOC entry 8307 (class 2620 OID 146572305)
119655 -- Dependencies: 781 1047 8894
119656 -- Name: sltransinserttrigger; Type: TRIGGER; Schema: public; Owner: admin
119657 --
119658
119659 CREATE TRIGGER sltransinserttrigger BEFORE INSERT ON sltrans FOR EACH ROW EXECUTE PROCEDURE _sltransinserttrigger();
119660
119661
119662 --
119663 -- TOC entry 8139 (class 2620 OID 146572306)
119664 -- Dependencies: 195 1056 8894
119665 -- Name: soheadtrigger; Type: TRIGGER; Schema: public; Owner: admin
119666 --
119667
119668 CREATE TRIGGER soheadtrigger BEFORE INSERT OR DELETE OR UPDATE ON cohead FOR EACH ROW EXECUTE PROCEDURE _soheadtrigger();
119669
119670
119671 --
119672 -- TOC entry 8140 (class 2620 OID 146572307)
119673 -- Dependencies: 195 1066 8894
119674 -- Name: soheadtriggerafter; Type: TRIGGER; Schema: public; Owner: admin
119675 --
119676
119677 CREATE TRIGGER soheadtriggerafter AFTER UPDATE ON cohead FOR EACH ROW EXECUTE PROCEDURE _soheadtriggerafter();
119678
119679
119680 --
119681 -- TOC entry 8141 (class 2620 OID 146572308)
119682 -- Dependencies: 196 1067 8894
119683 -- Name: soitemafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119684 --
119685
119686 CREATE TRIGGER soitemafterdeletetrigger AFTER DELETE ON coitem FOR EACH ROW EXECUTE PROCEDURE _soitemafterdeletetrigger();
119687
119688
119689 --
119690 -- TOC entry 8142 (class 2620 OID 146572309)
119691 -- Dependencies: 196 1068 8894
119692 -- Name: soitemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119693 --
119694
119695 CREATE TRIGGER soitemaftertrigger AFTER INSERT OR UPDATE ON coitem FOR EACH ROW EXECUTE PROCEDURE _soitemaftertrigger();
119696
119697
119698 --
119699 -- TOC entry 8143 (class 2620 OID 146572310)
119700 -- Dependencies: 196 1069 8894
119701 -- Name: soitembeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119702 --
119703
119704 CREATE TRIGGER soitembeforedeletetrigger BEFORE DELETE ON coitem FOR EACH ROW EXECUTE PROCEDURE _soitembeforedeletetrigger();
119705
119706
119707 --
119708 -- TOC entry 8144 (class 2620 OID 146572311)
119709 -- Dependencies: 196 1070 8894
119710 -- Name: soitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119711 --
119712
119713 CREATE TRIGGER soitembeforetrigger BEFORE INSERT OR UPDATE ON coitem FOR EACH ROW EXECUTE PROCEDURE _soitembeforetrigger();
119714
119715
119716 --
119717 -- TOC entry 8145 (class 2620 OID 146572312)
119718 -- Dependencies: 196 1071 8894
119719 -- Name: soitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
119720 --
119721
119722 CREATE TRIGGER soitemtrigger BEFORE INSERT OR UPDATE ON coitem FOR EACH ROW EXECUTE PROCEDURE _soitemtrigger();
119723
119724
119725 --
119726 -- TOC entry 8218 (class 2620 OID 146572313)
119727 -- Dependencies: 284 1072 8894
119728 -- Name: taxauthafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119729 --
119730
119731 CREATE TRIGGER taxauthafterdeletetrigger AFTER DELETE ON taxauth FOR EACH ROW EXECUTE PROCEDURE _taxauthafterdeletetrigger();
119732
119733
119734 --
119735 -- TOC entry 8219 (class 2620 OID 146572314)
119736 -- Dependencies: 284 1073 8894
119737 -- Name: taxauthaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119738 --
119739
119740 CREATE TRIGGER taxauthaftertrigger AFTER INSERT OR UPDATE ON taxauth FOR EACH ROW EXECUTE PROCEDURE _taxauthaftertrigger();
119741
119742
119743 --
119744 -- TOC entry 8220 (class 2620 OID 146572315)
119745 -- Dependencies: 284 1074 8894
119746 -- Name: taxauthbeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119747 --
119748
119749 CREATE TRIGGER taxauthbeforedeletetrigger BEFORE DELETE ON taxauth FOR EACH ROW EXECUTE PROCEDURE _taxauthbeforedeletetrigger();
119750
119751
119752 --
119753 -- TOC entry 8221 (class 2620 OID 146572316)
119754 -- Dependencies: 284 1075 8894
119755 -- Name: taxauthbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119756 --
119757
119758 CREATE TRIGGER taxauthbeforetrigger BEFORE INSERT OR UPDATE ON taxauth FOR EACH ROW EXECUTE PROCEDURE _taxauthbeforetrigger();
119759
119760
119761 --
119762 -- TOC entry 8165 (class 2620 OID 146572317)
119763 -- Dependencies: 209 1037 8894
119764 -- Name: termsafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119765 --
119766
119767 CREATE TRIGGER termsafterdeletetrigger AFTER DELETE ON terms FOR EACH ROW EXECUTE PROCEDURE _termsafterdeletetrigger();
119768
119769
119770 --
119771 -- TOC entry 8196 (class 2620 OID 146572318)
119772 -- Dependencies: 233 1076 8894
119773 -- Name: todoitemtrigger; Type: TRIGGER; Schema: public; Owner: admin
119774 --
119775
119776 CREATE TRIGGER todoitemtrigger BEFORE DELETE ON todoitem FOR EACH ROW EXECUTE PROCEDURE _todoitemtrigger();
119777
119778
119779 --
119780 -- TOC entry 8308 (class 2620 OID 146572319)
119781 -- Dependencies: 820 1077 8894
119782 -- Name: uomconvupdate; Type: TRIGGER; Schema: public; Owner: admin
119783 --
119784
119785 CREATE TRIGGER uomconvupdate BEFORE UPDATE ON uomconv FOR EACH ROW EXECUTE PROCEDURE _uomconvupdate();
119786
119787
119788 --
119789 -- TOC entry 8309 (class 2620 OID 146572320)
119790 -- Dependencies: 825 1078 8894
119791 -- Name: usrprefaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119792 --
119793
119794 CREATE TRIGGER usrprefaftertrigger AFTER INSERT OR DELETE OR UPDATE ON usrpref FOR EACH ROW EXECUTE PROCEDURE _usrprefaftertrigger();
119795
119796
119797 --
119798 -- TOC entry 8310 (class 2620 OID 146572321)
119799 -- Dependencies: 825 1079 8894
119800 -- Name: usrprefbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119801 --
119802
119803 CREATE TRIGGER usrprefbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON usrpref FOR EACH ROW EXECUTE PROCEDURE _usrprefbeforetrigger();
119804
119805
119806 --
119807 -- TOC entry 8303 (class 2620 OID 146572322)
119808 -- Dependencies: 733 1080 8894
119809 -- Name: usrprivtrigger; Type: TRIGGER; Schema: public; Owner: admin
119810 --
119811
119812 CREATE TRIGGER usrprivtrigger BEFORE INSERT OR UPDATE ON usrpriv FOR EACH ROW EXECUTE PROCEDURE _usrprivtrigger();
119813
119814
119815 --
119816 -- TOC entry 8250 (class 2620 OID 146572323)
119817 -- Dependencies: 364 1082 8894
119818 -- Name: vendaddrtrigger; Type: TRIGGER; Schema: public; Owner: admin
119819 --
119820
119821 CREATE TRIGGER vendaddrtrigger BEFORE INSERT OR DELETE OR UPDATE ON vendaddrinfo FOR EACH ROW EXECUTE PROCEDURE _vendaddrtrigger();
119822
119823
119824 --
119825 -- TOC entry 8166 (class 2620 OID 146572324)
119826 -- Dependencies: 210 1083 8894
119827 -- Name: vendaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119828 --
119829
119830 CREATE TRIGGER vendaftertrigger AFTER INSERT OR UPDATE ON vendinfo FOR EACH ROW EXECUTE PROCEDURE _vendaftertrigger();
119831
119832
119833 --
119834 -- TOC entry 8167 (class 2620 OID 146572325)
119835 -- Dependencies: 210 1084 8894
119836 -- Name: vendinfoafterdeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119837 --
119838
119839 CREATE TRIGGER vendinfoafterdeletetrigger AFTER DELETE ON vendinfo FOR EACH ROW EXECUTE PROCEDURE _vendinfoafterdeletetrigger();
119840
119841
119842 --
119843 -- TOC entry 8168 (class 2620 OID 146572326)
119844 -- Dependencies: 210 1085 8894
119845 -- Name: vendinfobeforedeletetrigger; Type: TRIGGER; Schema: public; Owner: admin
119846 --
119847
119848 CREATE TRIGGER vendinfobeforedeletetrigger BEFORE DELETE ON vendinfo FOR EACH ROW EXECUTE PROCEDURE _vendinfobeforedeletetrigger();
119849
119850
119851 --
119852 -- TOC entry 8169 (class 2620 OID 146572327)
119853 -- Dependencies: 210 1086 8894
119854 -- Name: vendtrigger; Type: TRIGGER; Schema: public; Owner: admin
119855 --
119856
119857 CREATE TRIGGER vendtrigger BEFORE INSERT OR UPDATE ON vendinfo FOR EACH ROW EXECUTE PROCEDURE _vendtrigger();
119858
119859
119860 --
119861 -- TOC entry 8311 (class 2620 OID 146572328)
119862 -- Dependencies: 837 1087 8894
119863 -- Name: vodistaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119864 --
119865
119866 CREATE TRIGGER vodistaftertrigger AFTER INSERT OR DELETE OR UPDATE ON vodist FOR EACH ROW EXECUTE PROCEDURE _vodistaftertrigger();
119867
119868
119869 --
119870 -- TOC entry 8312 (class 2620 OID 146572329)
119871 -- Dependencies: 837 1088 8894
119872 -- Name: vodistbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119873 --
119874
119875 CREATE TRIGGER vodistbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON vodist FOR EACH ROW EXECUTE PROCEDURE _vodistbeforetrigger();
119876
119877
119878 --
119879 -- TOC entry 8313 (class 2620 OID 146572330)
119880 -- Dependencies: 839 1089 8894
119881 -- Name: voheadaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119882 --
119883
119884 CREATE TRIGGER voheadaftertrigger AFTER INSERT OR DELETE OR UPDATE ON vohead FOR EACH ROW EXECUTE PROCEDURE _voheadaftertrigger();
119885
119886
119887 --
119888 -- TOC entry 8314 (class 2620 OID 146572331)
119889 -- Dependencies: 839 1090 8894
119890 -- Name: voheadbeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119891 --
119892
119893 CREATE TRIGGER voheadbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON vohead FOR EACH ROW EXECUTE PROCEDURE _voheadbeforetrigger();
119894
119895
119896 --
119897 -- TOC entry 8315 (class 2620 OID 146572332)
119898 -- Dependencies: 842 1091 8894
119899 -- Name: voitemaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119900 --
119901
119902 CREATE TRIGGER voitemaftertrigger AFTER INSERT OR DELETE OR UPDATE ON voitem FOR EACH ROW EXECUTE PROCEDURE _voitemaftertrigger();
119903
119904
119905 --
119906 -- TOC entry 8316 (class 2620 OID 146572333)
119907 -- Dependencies: 842 1092 8894
119908 -- Name: voitembeforetrigger; Type: TRIGGER; Schema: public; Owner: admin
119909 --
119910
119911 CREATE TRIGGER voitembeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON voitem FOR EACH ROW EXECUTE PROCEDURE _voitembeforetrigger();
119912
119913
119914 --
119915 -- TOC entry 8138 (class 2620 OID 146572334)
119916 -- Dependencies: 193 1093 8894
119917 -- Name: warehoustrigger; Type: TRIGGER; Schema: public; Owner: admin
119918 --
119919
119920 CREATE TRIGGER warehoustrigger BEFORE INSERT OR UPDATE ON whsinfo FOR EACH ROW EXECUTE PROCEDURE _warehoustrigger();
119921
119922
119923 --
119924 -- TOC entry 8241 (class 2620 OID 146572335)
119925 -- Dependencies: 343 1094 8894
119926 -- Name: whsezonetrigger; Type: TRIGGER; Schema: public; Owner: admin
119927 --
119928
119929 CREATE TRIGGER whsezonetrigger BEFORE INSERT OR UPDATE ON whsezone FOR EACH ROW EXECUTE PROCEDURE _whsezonetrigger();
119930
119931
119932 --
119933 -- TOC entry 8249 (class 2620 OID 146572336)
119934 -- Dependencies: 359 1095 8894
119935 -- Name: womatlaftertrigger; Type: TRIGGER; Schema: public; Owner: admin
119936 --
119937
119938 CREATE TRIGGER womatlaftertrigger AFTER INSERT OR DELETE OR UPDATE ON womatl FOR EACH ROW EXECUTE PROCEDURE _womatlaftertrigger();
119939
119940
119941 --
119942 -- TOC entry 8295 (class 2620 OID 146572337)
119943 -- Dependencies: 560 1097 8894
119944 -- Name: wotrigger; Type: TRIGGER; Schema: public; Owner: admin
119945 --
119946
119947 CREATE TRIGGER wotrigger BEFORE INSERT OR DELETE OR UPDATE ON wo FOR EACH ROW EXECUTE PROCEDURE _wotrigger();
119948
119949
119950 SET search_path = te, pg_catalog;
119951
119952 --
119953 -- TOC entry 8317 (class 2620 OID 146572338)
119954 -- Dependencies: 859 1008 8894
119955 -- Name: pkgcmdaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
119956 --
119957
119958 CREATE TRIGGER pkgcmdaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdaftertrigger();
119959
119960
119961 --
119962 -- TOC entry 8318 (class 2620 OID 146572339)
119963 -- Dependencies: 859 1009 8894
119964 -- Name: pkgcmdaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
119965 --
119966
119967 CREATE TRIGGER pkgcmdaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdaltertrigger();
119968
119969
119970 --
119971 -- TOC entry 8320 (class 2620 OID 146572340)
119972 -- Dependencies: 860 1010 8894
119973 -- Name: pkgcmdargaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
119974 --
119975
119976 CREATE TRIGGER pkgcmdargaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargaftertrigger();
119977
119978
119979 --
119980 -- TOC entry 8321 (class 2620 OID 146572341)
119981 -- Dependencies: 860 1012 8894
119982 -- Name: pkgcmdargaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
119983 --
119984
119985 CREATE TRIGGER pkgcmdargaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargaltertrigger();
119986
119987
119988 --
119989 -- TOC entry 8322 (class 2620 OID 146572342)
119990 -- Dependencies: 860 1013 8894
119991 -- Name: pkgcmdargbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
119992 --
119993
119994 CREATE TRIGGER pkgcmdargbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargbeforetrigger();
119995
119996
119997 --
119998 -- TOC entry 8319 (class 2620 OID 146572343)
119999 -- Dependencies: 859 1014 8894
120000 -- Name: pkgcmdbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120001 --
120002
120003 CREATE TRIGGER pkgcmdbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdbeforetrigger();
120004
120005
120006 --
120007 -- TOC entry 8323 (class 2620 OID 146572344)
120008 -- Dependencies: 861 1016 8894
120009 -- Name: pkgimageaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
120010 --
120011
120012 CREATE TRIGGER pkgimageaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimageaftertrigger();
120013
120014
120015 --
120016 -- TOC entry 8324 (class 2620 OID 146572345)
120017 -- Dependencies: 861 1017 8894
120018 -- Name: pkgimagealtertrigger; Type: TRIGGER; Schema: te; Owner: admin
120019 --
120020
120021 CREATE TRIGGER pkgimagealtertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimagealtertrigger();
120022
120023
120024 --
120025 -- TOC entry 8325 (class 2620 OID 146572346)
120026 -- Dependencies: 861 1018 8894
120027 -- Name: pkgimagebeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120028 --
120029
120030 CREATE TRIGGER pkgimagebeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimagebeforetrigger();
120031
120032
120033 --
120034 -- TOC entry 8326 (class 2620 OID 146572347)
120035 -- Dependencies: 862 1020 8894
120036 -- Name: pkgmetasqlaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
120037 --
120038
120039 CREATE TRIGGER pkgmetasqlaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlaftertrigger();
120040
120041
120042 --
120043 -- TOC entry 8327 (class 2620 OID 146572348)
120044 -- Dependencies: 862 1022 8894
120045 -- Name: pkgmetasqlaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
120046 --
120047
120048 CREATE TRIGGER pkgmetasqlaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlaltertrigger();
120049
120050
120051 --
120052 -- TOC entry 8328 (class 2620 OID 146572349)
120053 -- Dependencies: 862 1023 8894
120054 -- Name: pkgmetasqlbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120055 --
120056
120057 CREATE TRIGGER pkgmetasqlbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlbeforetrigger();
120058
120059
120060 --
120061 -- TOC entry 8329 (class 2620 OID 146572350)
120062 -- Dependencies: 863 1024 8894
120063 -- Name: pkgprivaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
120064 --
120065
120066 CREATE TRIGGER pkgprivaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivaftertrigger();
120067
120068
120069 --
120070 -- TOC entry 8330 (class 2620 OID 146572351)
120071 -- Dependencies: 863 1025 8894
120072 -- Name: pkgprivaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
120073 --
120074
120075 CREATE TRIGGER pkgprivaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivaltertrigger();
120076
120077
120078 --
120079 -- TOC entry 8331 (class 2620 OID 146572352)
120080 -- Dependencies: 863 1026 8894
120081 -- Name: pkgprivbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120082 --
120083
120084 CREATE TRIGGER pkgprivbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivbeforetrigger();
120085
120086
120087 --
120088 -- TOC entry 8332 (class 2620 OID 146572353)
120089 -- Dependencies: 864 1027 8894
120090 -- Name: pkgreportaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
120091 --
120092
120093 CREATE TRIGGER pkgreportaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportaftertrigger();
120094
120095
120096 --
120097 -- TOC entry 8333 (class 2620 OID 146572354)
120098 -- Dependencies: 864 1028 8894
120099 -- Name: pkgreportaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
120100 --
120101
120102 CREATE TRIGGER pkgreportaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportaltertrigger();
120103
120104
120105 --
120106 -- TOC entry 8334 (class 2620 OID 146572355)
120107 -- Dependencies: 864 1029 8894
120108 -- Name: pkgreportbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120109 --
120110
120111 CREATE TRIGGER pkgreportbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportbeforetrigger();
120112
120113
120114 --
120115 -- TOC entry 8335 (class 2620 OID 146572356)
120116 -- Dependencies: 865 959 8894
120117 -- Name: pkgscriptaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
120118 --
120119
120120 CREATE TRIGGER pkgscriptaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptaftertrigger();
120121
120122
120123 --
120124 -- TOC entry 8336 (class 2620 OID 146572357)
120125 -- Dependencies: 865 983 8894
120126 -- Name: pkgscriptaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
120127 --
120128
120129 CREATE TRIGGER pkgscriptaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptaltertrigger();
120130
120131
120132 --
120133 -- TOC entry 8337 (class 2620 OID 146572358)
120134 -- Dependencies: 865 1003 8894
120135 -- Name: pkgscriptbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120136 --
120137
120138 CREATE TRIGGER pkgscriptbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptbeforetrigger();
120139
120140
120141 --
120142 -- TOC entry 8338 (class 2620 OID 146572359)
120143 -- Dependencies: 866 1011 8894
120144 -- Name: pkguiformaftertrigger; Type: TRIGGER; Schema: te; Owner: admin
120145 --
120146
120147 CREATE TRIGGER pkguiformaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformaftertrigger();
120148
120149
120150 --
120151 -- TOC entry 8339 (class 2620 OID 146572360)
120152 -- Dependencies: 866 1021 8894
120153 -- Name: pkguiformaltertrigger; Type: TRIGGER; Schema: te; Owner: admin
120154 --
120155
120156 CREATE TRIGGER pkguiformaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformaltertrigger();
120157
120158
120159 --
120160 -- TOC entry 8340 (class 2620 OID 146572361)
120161 -- Dependencies: 866 945 8894
120162 -- Name: pkguiformbeforetrigger; Type: TRIGGER; Schema: te; Owner: admin
120163 --
120164
120165 CREATE TRIGGER pkguiformbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformbeforetrigger();
120166
120167
120168 --
120169 -- TOC entry 8341 (class 2620 OID 146572362)
120170 -- Dependencies: 873 2335 8894
120171 -- Name: teheadtrigger; Type: TRIGGER; Schema: te; Owner: admin
120172 --
120173
120174 CREATE TRIGGER teheadtrigger AFTER INSERT OR UPDATE ON tehead FOR EACH ROW EXECUTE PROCEDURE triggertehead();
120175
120176
120177 --
120178 -- TOC entry 8342 (class 2620 OID 146572363)
120179 -- Dependencies: 875 2336 8894
120180 -- Name: teitemtrigger; Type: TRIGGER; Schema: te; Owner: admin
120181 --
120182
120183 CREATE TRIGGER teitemtrigger AFTER INSERT OR DELETE OR UPDATE ON teitem FOR EACH ROW EXECUTE PROCEDURE triggerteitem();
120184
120185
120186 --
120187 -- TOC entry 8343 (class 2620 OID 146572364)
120188 -- Dependencies: 877 2329 8894
120189 -- Name: teprjtrigger; Type: TRIGGER; Schema: te; Owner: admin
120190 --
120191
120192 CREATE TRIGGER teprjtrigger AFTER INSERT OR UPDATE ON teprj FOR EACH ROW EXECUTE PROCEDURE triggerteprj();
120193
120194
120195 SET search_path = xtdesktop, pg_catalog;
120196
120197 --
120198 -- TOC entry 8344 (class 2620 OID 146572365)
120199 -- Dependencies: 881 1008 8894
120200 -- Name: pkgcmdaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120201 --
120202
120203 CREATE TRIGGER pkgcmdaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdaftertrigger();
120204
120205
120206 --
120207 -- TOC entry 8345 (class 2620 OID 146572366)
120208 -- Dependencies: 881 1009 8894
120209 -- Name: pkgcmdaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120210 --
120211
120212 CREATE TRIGGER pkgcmdaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdaltertrigger();
120213
120214
120215 --
120216 -- TOC entry 8347 (class 2620 OID 146572367)
120217 -- Dependencies: 882 1010 8894
120218 -- Name: pkgcmdargaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120219 --
120220
120221 CREATE TRIGGER pkgcmdargaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargaftertrigger();
120222
120223
120224 --
120225 -- TOC entry 8348 (class 2620 OID 146572368)
120226 -- Dependencies: 882 1012 8894
120227 -- Name: pkgcmdargaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120228 --
120229
120230 CREATE TRIGGER pkgcmdargaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargaltertrigger();
120231
120232
120233 --
120234 -- TOC entry 8349 (class 2620 OID 146572369)
120235 -- Dependencies: 882 1013 8894
120236 -- Name: pkgcmdargbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120237 --
120238
120239 CREATE TRIGGER pkgcmdargbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmdarg FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdargbeforetrigger();
120240
120241
120242 --
120243 -- TOC entry 8346 (class 2620 OID 146572370)
120244 -- Dependencies: 881 1014 8894
120245 -- Name: pkgcmdbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120246 --
120247
120248 CREATE TRIGGER pkgcmdbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgcmd FOR EACH ROW EXECUTE PROCEDURE public._pkgcmdbeforetrigger();
120249
120250
120251 --
120252 -- TOC entry 8350 (class 2620 OID 146572371)
120253 -- Dependencies: 883 1016 8894
120254 -- Name: pkgimageaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120255 --
120256
120257 CREATE TRIGGER pkgimageaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimageaftertrigger();
120258
120259
120260 --
120261 -- TOC entry 8351 (class 2620 OID 146572372)
120262 -- Dependencies: 883 1017 8894
120263 -- Name: pkgimagealtertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120264 --
120265
120266 CREATE TRIGGER pkgimagealtertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimagealtertrigger();
120267
120268
120269 --
120270 -- TOC entry 8352 (class 2620 OID 146572373)
120271 -- Dependencies: 883 1018 8894
120272 -- Name: pkgimagebeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120273 --
120274
120275 CREATE TRIGGER pkgimagebeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgimage FOR EACH ROW EXECUTE PROCEDURE public._pkgimagebeforetrigger();
120276
120277
120278 --
120279 -- TOC entry 8353 (class 2620 OID 146572374)
120280 -- Dependencies: 884 1020 8894
120281 -- Name: pkgmetasqlaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120282 --
120283
120284 CREATE TRIGGER pkgmetasqlaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlaftertrigger();
120285
120286
120287 --
120288 -- TOC entry 8354 (class 2620 OID 146572375)
120289 -- Dependencies: 884 1022 8894
120290 -- Name: pkgmetasqlaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120291 --
120292
120293 CREATE TRIGGER pkgmetasqlaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlaltertrigger();
120294
120295
120296 --
120297 -- TOC entry 8355 (class 2620 OID 146572376)
120298 -- Dependencies: 884 1023 8894
120299 -- Name: pkgmetasqlbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120300 --
120301
120302 CREATE TRIGGER pkgmetasqlbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgmetasql FOR EACH ROW EXECUTE PROCEDURE public._pkgmetasqlbeforetrigger();
120303
120304
120305 --
120306 -- TOC entry 8356 (class 2620 OID 146572377)
120307 -- Dependencies: 885 1024 8894
120308 -- Name: pkgprivaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120309 --
120310
120311 CREATE TRIGGER pkgprivaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivaftertrigger();
120312
120313
120314 --
120315 -- TOC entry 8357 (class 2620 OID 146572378)
120316 -- Dependencies: 885 1025 8894
120317 -- Name: pkgprivaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120318 --
120319
120320 CREATE TRIGGER pkgprivaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivaltertrigger();
120321
120322
120323 --
120324 -- TOC entry 8358 (class 2620 OID 146572379)
120325 -- Dependencies: 885 1026 8894
120326 -- Name: pkgprivbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120327 --
120328
120329 CREATE TRIGGER pkgprivbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgpriv FOR EACH ROW EXECUTE PROCEDURE public._pkgprivbeforetrigger();
120330
120331
120332 --
120333 -- TOC entry 8359 (class 2620 OID 146572380)
120334 -- Dependencies: 886 1027 8894
120335 -- Name: pkgreportaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120336 --
120337
120338 CREATE TRIGGER pkgreportaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportaftertrigger();
120339
120340
120341 --
120342 -- TOC entry 8360 (class 2620 OID 146572381)
120343 -- Dependencies: 886 1028 8894
120344 -- Name: pkgreportaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120345 --
120346
120347 CREATE TRIGGER pkgreportaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportaltertrigger();
120348
120349
120350 --
120351 -- TOC entry 8361 (class 2620 OID 146572382)
120352 -- Dependencies: 886 1029 8894
120353 -- Name: pkgreportbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120354 --
120355
120356 CREATE TRIGGER pkgreportbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgreport FOR EACH ROW EXECUTE PROCEDURE public._pkgreportbeforetrigger();
120357
120358
120359 --
120360 -- TOC entry 8362 (class 2620 OID 146572383)
120361 -- Dependencies: 887 959 8894
120362 -- Name: pkgscriptaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120363 --
120364
120365 CREATE TRIGGER pkgscriptaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptaftertrigger();
120366
120367
120368 --
120369 -- TOC entry 8363 (class 2620 OID 146572384)
120370 -- Dependencies: 887 983 8894
120371 -- Name: pkgscriptaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120372 --
120373
120374 CREATE TRIGGER pkgscriptaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptaltertrigger();
120375
120376
120377 --
120378 -- TOC entry 8364 (class 2620 OID 146572385)
120379 -- Dependencies: 887 1003 8894
120380 -- Name: pkgscriptbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120381 --
120382
120383 CREATE TRIGGER pkgscriptbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkgscript FOR EACH ROW EXECUTE PROCEDURE public._pkgscriptbeforetrigger();
120384
120385
120386 --
120387 -- TOC entry 8365 (class 2620 OID 146572386)
120388 -- Dependencies: 888 1011 8894
120389 -- Name: pkguiformaftertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120390 --
120391
120392 CREATE TRIGGER pkguiformaftertrigger AFTER INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformaftertrigger();
120393
120394
120395 --
120396 -- TOC entry 8366 (class 2620 OID 146572387)
120397 -- Dependencies: 888 1021 8894
120398 -- Name: pkguiformaltertrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120399 --
120400
120401 CREATE TRIGGER pkguiformaltertrigger BEFORE INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformaltertrigger();
120402
120403
120404 --
120405 -- TOC entry 8367 (class 2620 OID 146572388)
120406 -- Dependencies: 888 945 8894
120407 -- Name: pkguiformbeforetrigger; Type: TRIGGER; Schema: xtdesktop; Owner: admin
120408 --
120409
120410 CREATE TRIGGER pkguiformbeforetrigger BEFORE INSERT OR DELETE OR UPDATE ON pkguiform FOR EACH ROW EXECUTE PROCEDURE public._pkguiformbeforetrigger();
120411
120412
120413 SET search_path = fixcountry, pg_catalog;
120414
120415 --
120416 -- TOC entry 7968 (class 2606 OID 146572389)
120417 -- Dependencies: 7164 399 402 8894
120418 -- Name: pkgcmdarg_cmdarg_cmd_id_fkey; Type: FK CONSTRAINT; Schema: fixcountry; Owner: admin
120419 --
120420
120421 ALTER TABLE ONLY pkgcmdarg
120422     ADD CONSTRAINT pkgcmdarg_cmdarg_cmd_id_fkey FOREIGN KEY (cmdarg_cmd_id) REFERENCES pkgcmd(cmd_id);
120423
120424
120425 SET search_path = public, pg_catalog;
120426
120427 --
120428 -- TOC entry 7863 (class 2606 OID 146572394)
120429 -- Dependencies: 7298 523 262 8894
120430 -- Name: accnt_accnt_company_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120431 --
120432
120433 ALTER TABLE ONLY accnt
120434     ADD CONSTRAINT accnt_accnt_company_fkey FOREIGN KEY (accnt_company) REFERENCES company(company_number) ON UPDATE CASCADE;
120435
120436
120437 --
120438 -- TOC entry 7864 (class 2606 OID 146572399)
120439 -- Dependencies: 6834 208 262 8894
120440 -- Name: accnt_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120441 --
120442
120443 ALTER TABLE ONLY accnt
120444     ADD CONSTRAINT accnt_to_curr_symbol FOREIGN KEY (accnt_curr_id) REFERENCES curr_symbol(curr_id);
120445
120446
120447 --
120448 -- TOC entry 7969 (class 2606 OID 146572404)
120449 -- Dependencies: 7204 430 428 8894
120450 -- Name: apapply_apapply_checkhead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120451 --
120452
120453 ALTER TABLE ONLY apapply
120454     ADD CONSTRAINT apapply_apapply_checkhead_id_fkey FOREIGN KEY (apapply_checkhead_id) REFERENCES checkhead(checkhead_id);
120455
120456
120457 --
120458 -- TOC entry 7970 (class 2606 OID 146572409)
120459 -- Dependencies: 6841 210 428 8894
120460 -- Name: apapply_apapply_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120461 --
120462
120463 ALTER TABLE ONLY apapply
120464     ADD CONSTRAINT apapply_apapply_vend_id_fkey FOREIGN KEY (apapply_vend_id) REFERENCES vendinfo(vend_id);
120465
120466
120467 --
120468 -- TOC entry 7971 (class 2606 OID 146572414)
120469 -- Dependencies: 6834 208 428 8894
120470 -- Name: apapply_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120471 --
120472
120473 ALTER TABLE ONLY apapply
120474     ADD CONSTRAINT apapply_to_curr_symbol FOREIGN KEY (apapply_curr_id) REFERENCES curr_symbol(curr_id);
120475
120476
120477 --
120478 -- TOC entry 7979 (class 2606 OID 146572419)
120479 -- Dependencies: 6834 208 434 8894
120480 -- Name: apcreditapply_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120481 --
120482
120483 ALTER TABLE ONLY apcreditapply
120484     ADD CONSTRAINT apcreditapply_curr_symbol FOREIGN KEY (apcreditapply_curr_id) REFERENCES curr_symbol(curr_id);
120485
120486
120487 --
120488 -- TOC entry 7792 (class 2606 OID 146572424)
120489 -- Dependencies: 6841 210 207 8894
120490 -- Name: apopen_apopen_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120491 --
120492
120493 ALTER TABLE ONLY apopen
120494     ADD CONSTRAINT apopen_apopen_vend_id_fkey FOREIGN KEY (apopen_vend_id) REFERENCES vendinfo(vend_id);
120495
120496
120497 --
120498 -- TOC entry 7793 (class 2606 OID 146572429)
120499 -- Dependencies: 6834 208 207 8894
120500 -- Name: apopen_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120501 --
120502
120503 ALTER TABLE ONLY apopen
120504     ADD CONSTRAINT apopen_to_curr_symbol FOREIGN KEY (apopen_curr_id) REFERENCES curr_symbol(curr_id);
120505
120506
120507 --
120508 -- TOC entry 7980 (class 2606 OID 146572434)
120509 -- Dependencies: 7124 363 438 8894
120510 -- Name: apopentax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120511 --
120512
120513 ALTER TABLE ONLY apopentax
120514     ADD CONSTRAINT apopentax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
120515
120516
120517 --
120518 -- TOC entry 7981 (class 2606 OID 146572439)
120519 -- Dependencies: 6828 207 438 8894
120520 -- Name: apopentax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120521 --
120522
120523 ALTER TABLE ONLY apopentax
120524     ADD CONSTRAINT apopentax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES apopen(apopen_id) ON DELETE CASCADE;
120525
120526
120527 --
120528 -- TOC entry 7982 (class 2606 OID 146572444)
120529 -- Dependencies: 7124 363 438 8894
120530 -- Name: apopentax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120531 --
120532
120533 ALTER TABLE ONLY apopentax
120534     ADD CONSTRAINT apopentax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
120535
120536
120537 --
120538 -- TOC entry 7983 (class 2606 OID 146572449)
120539 -- Dependencies: 6796 199 438 8894
120540 -- Name: apopentax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120541 --
120542
120543 ALTER TABLE ONLY apopentax
120544     ADD CONSTRAINT apopentax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
120545
120546
120547 --
120548 -- TOC entry 7984 (class 2606 OID 146572454)
120549 -- Dependencies: 6834 208 439 8894
120550 -- Name: apselect_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120551 --
120552
120553 ALTER TABLE ONLY apselect
120554     ADD CONSTRAINT apselect_to_curr_symbol FOREIGN KEY (apselect_curr_id) REFERENCES curr_symbol(curr_id);
120555
120556
120557 --
120558 -- TOC entry 7985 (class 2606 OID 146572459)
120559 -- Dependencies: 6834 208 443 8894
120560 -- Name: arapply_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120561 --
120562
120563 ALTER TABLE ONLY arapply
120564     ADD CONSTRAINT arapply_to_curr_symbol FOREIGN KEY (arapply_curr_id) REFERENCES curr_symbol(curr_id);
120565
120566
120567 --
120568 -- TOC entry 7986 (class 2606 OID 146572464)
120569 -- Dependencies: 6834 208 446 8894
120570 -- Name: arcreditapply_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120571 --
120572
120573 ALTER TABLE ONLY arcreditapply
120574     ADD CONSTRAINT arcreditapply_curr_symbol FOREIGN KEY (arcreditapply_curr_id) REFERENCES curr_symbol(curr_id);
120575
120576
120577 --
120578 -- TOC entry 7800 (class 2606 OID 146572469)
120579 -- Dependencies: 6853 213 212 8894
120580 -- Name: aropen_aropen_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120581 --
120582
120583 ALTER TABLE ONLY aropen
120584     ADD CONSTRAINT aropen_aropen_cust_id_fkey FOREIGN KEY (aropen_cust_id) REFERENCES custinfo(cust_id);
120585
120586
120587 --
120588 -- TOC entry 7801 (class 2606 OID 146572474)
120589 -- Dependencies: 6865 216 212 8894
120590 -- Name: aropen_aropen_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120591 --
120592
120593 ALTER TABLE ONLY aropen
120594     ADD CONSTRAINT aropen_aropen_salesrep_id_fkey FOREIGN KEY (aropen_salesrep_id) REFERENCES salesrep(salesrep_id);
120595
120596
120597 --
120598 -- TOC entry 7802 (class 2606 OID 146572479)
120599 -- Dependencies: 6834 208 212 8894
120600 -- Name: aropen_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120601 --
120602
120603 ALTER TABLE ONLY aropen
120604     ADD CONSTRAINT aropen_to_curr_symbol FOREIGN KEY (aropen_curr_id) REFERENCES curr_symbol(curr_id);
120605
120606
120607 --
120608 -- TOC entry 7987 (class 2606 OID 146572484)
120609 -- Dependencies: 7124 363 450 8894
120610 -- Name: aropentax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120611 --
120612
120613 ALTER TABLE ONLY aropentax
120614     ADD CONSTRAINT aropentax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
120615
120616
120617 --
120618 -- TOC entry 7988 (class 2606 OID 146572489)
120619 -- Dependencies: 6849 212 450 8894
120620 -- Name: aropentax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120621 --
120622
120623 ALTER TABLE ONLY aropentax
120624     ADD CONSTRAINT aropentax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES aropen(aropen_id) ON DELETE CASCADE;
120625
120626
120627 --
120628 -- TOC entry 7989 (class 2606 OID 146572494)
120629 -- Dependencies: 7124 363 450 8894
120630 -- Name: aropentax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120631 --
120632
120633 ALTER TABLE ONLY aropentax
120634     ADD CONSTRAINT aropentax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
120635
120636
120637 --
120638 -- TOC entry 7990 (class 2606 OID 146572499)
120639 -- Dependencies: 6796 199 450 8894
120640 -- Name: aropentax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120641 --
120642
120643 ALTER TABLE ONLY aropentax
120644     ADD CONSTRAINT aropentax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
120645
120646
120647 --
120648 -- TOC entry 7991 (class 2606 OID 146572504)
120649 -- Dependencies: 6796 199 451 8894
120650 -- Name: asohist_asohist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120651 --
120652
120653 ALTER TABLE ONLY asohist
120654     ADD CONSTRAINT asohist_asohist_taxtype_id_fkey FOREIGN KEY (asohist_taxtype_id) REFERENCES taxtype(taxtype_id);
120655
120656
120657 --
120658 -- TOC entry 7992 (class 2606 OID 146572509)
120659 -- Dependencies: 6878 220 451 8894
120660 -- Name: asohist_asohist_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120661 --
120662
120663 ALTER TABLE ONLY asohist
120664     ADD CONSTRAINT asohist_asohist_taxzone_id_fkey FOREIGN KEY (asohist_taxzone_id) REFERENCES taxzone(taxzone_id);
120665
120666
120667 --
120668 -- TOC entry 7993 (class 2606 OID 146572514)
120669 -- Dependencies: 6834 208 451 8894
120670 -- Name: asohist_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120671 --
120672
120673 ALTER TABLE ONLY asohist
120674     ADD CONSTRAINT asohist_to_curr_symbol FOREIGN KEY (asohist_curr_id) REFERENCES curr_symbol(curr_id);
120675
120676
120677 --
120678 -- TOC entry 7994 (class 2606 OID 146572519)
120679 -- Dependencies: 7124 363 453 8894
120680 -- Name: asohisttax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120681 --
120682
120683 ALTER TABLE ONLY asohisttax
120684     ADD CONSTRAINT asohisttax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
120685
120686
120687 --
120688 -- TOC entry 7995 (class 2606 OID 146572524)
120689 -- Dependencies: 7229 451 453 8894
120690 -- Name: asohisttax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120691 --
120692
120693 ALTER TABLE ONLY asohisttax
120694     ADD CONSTRAINT asohisttax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES asohist(asohist_id) ON DELETE CASCADE;
120695
120696
120697 --
120698 -- TOC entry 7996 (class 2606 OID 146572529)
120699 -- Dependencies: 7124 363 453 8894
120700 -- Name: asohisttax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120701 --
120702
120703 ALTER TABLE ONLY asohisttax
120704     ADD CONSTRAINT asohisttax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
120705
120706
120707 --
120708 -- TOC entry 7997 (class 2606 OID 146572534)
120709 -- Dependencies: 6796 199 453 8894
120710 -- Name: asohisttax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120711 --
120712
120713 ALTER TABLE ONLY asohisttax
120714     ADD CONSTRAINT asohisttax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
120715
120716
120717 --
120718 -- TOC entry 7867 (class 2606 OID 146572539)
120719 -- Dependencies: 6834 208 266 8894
120720 -- Name: bankaccnt_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120721 --
120722
120723 ALTER TABLE ONLY bankaccnt
120724     ADD CONSTRAINT bankaccnt_to_curr_symbol FOREIGN KEY (bankaccnt_curr_id) REFERENCES curr_symbol(curr_id);
120725
120726
120727 --
120728 -- TOC entry 7998 (class 2606 OID 146572544)
120729 -- Dependencies: 6834 208 458 8894
120730 -- Name: bankadj_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120731 --
120732
120733 ALTER TABLE ONLY bankadj
120734     ADD CONSTRAINT bankadj_to_curr_symbol FOREIGN KEY (bankadj_curr_id) REFERENCES curr_symbol(curr_id);
120735
120736
120737 --
120738 -- TOC entry 7860 (class 2606 OID 146572549)
120739 -- Dependencies: 6751 191 254 8894
120740 -- Name: bomhead_bomhead_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120741 --
120742
120743 ALTER TABLE ONLY bomhead
120744     ADD CONSTRAINT bomhead_bomhead_item_id_fkey FOREIGN KEY (bomhead_item_id) REFERENCES item(item_id) ON UPDATE RESTRICT ON DELETE CASCADE;
120745
120746
120747 --
120748 -- TOC entry 7767 (class 2606 OID 146572554)
120749 -- Dependencies: 6924 236 203 8894
120750 -- Name: bomitem_bomitem_char_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120751 --
120752
120753 ALTER TABLE ONLY bomitem
120754     ADD CONSTRAINT bomitem_bomitem_char_id_fkey FOREIGN KEY (bomitem_char_id) REFERENCES "char"(char_id);
120755
120756
120757 --
120758 -- TOC entry 7768 (class 2606 OID 146572559)
120759 -- Dependencies: 6751 191 203 8894
120760 -- Name: bomitem_bomitem_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120761 --
120762
120763 ALTER TABLE ONLY bomitem
120764     ADD CONSTRAINT bomitem_bomitem_item_id_fkey FOREIGN KEY (bomitem_item_id) REFERENCES item(item_id);
120765
120766
120767 --
120768 -- TOC entry 7769 (class 2606 OID 146572564)
120769 -- Dependencies: 6751 191 203 8894
120770 -- Name: bomitem_bomitem_parent_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120771 --
120772
120773 ALTER TABLE ONLY bomitem
120774     ADD CONSTRAINT bomitem_bomitem_parent_item_id_fkey FOREIGN KEY (bomitem_parent_item_id) REFERENCES item(item_id) ON UPDATE RESTRICT ON DELETE CASCADE;
120775
120776
120777 --
120778 -- TOC entry 7770 (class 2606 OID 146572569)
120779 -- Dependencies: 6800 200 203 8894
120780 -- Name: bomitem_bomitem_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120781 --
120782
120783 ALTER TABLE ONLY bomitem
120784     ADD CONSTRAINT bomitem_bomitem_uom_id_fkey FOREIGN KEY (bomitem_uom_id) REFERENCES uom(uom_id);
120785
120786
120787 --
120788 -- TOC entry 7999 (class 2606 OID 146572574)
120789 -- Dependencies: 6810 203 468 8894
120790 -- Name: bomitemcost_bomitemcost_bomitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120791 --
120792
120793 ALTER TABLE ONLY bomitemcost
120794     ADD CONSTRAINT bomitemcost_bomitemcost_bomitem_id_fkey FOREIGN KEY (bomitemcost_bomitem_id) REFERENCES bomitem(bomitem_id);
120795
120796
120797 --
120798 -- TOC entry 8000 (class 2606 OID 146572579)
120799 -- Dependencies: 7049 320 468 8894
120800 -- Name: bomitemcost_bomitemcost_costelem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120801 --
120802
120803 ALTER TABLE ONLY bomitemcost
120804     ADD CONSTRAINT bomitemcost_bomitemcost_costelem_id_fkey FOREIGN KEY (bomitemcost_costelem_id) REFERENCES costelem(costelem_id);
120805
120806
120807 --
120808 -- TOC entry 8001 (class 2606 OID 146572584)
120809 -- Dependencies: 6834 208 468 8894
120810 -- Name: bomitemcost_bomitemcost_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120811 --
120812
120813 ALTER TABLE ONLY bomitemcost
120814     ADD CONSTRAINT bomitemcost_bomitemcost_curr_id_fkey FOREIGN KEY (bomitemcost_curr_id) REFERENCES curr_symbol(curr_id);
120815
120816
120817 --
120818 -- TOC entry 7861 (class 2606 OID 146572589)
120819 -- Dependencies: 6810 203 258 8894
120820 -- Name: bomitemsub_bomitemsub_bomitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120821 --
120822
120823 ALTER TABLE ONLY bomitemsub
120824     ADD CONSTRAINT bomitemsub_bomitemsub_bomitem_id_fkey FOREIGN KEY (bomitemsub_bomitem_id) REFERENCES bomitem(bomitem_id) ON UPDATE RESTRICT ON DELETE CASCADE;
120825
120826
120827 --
120828 -- TOC entry 7862 (class 2606 OID 146572594)
120829 -- Dependencies: 6751 191 258 8894
120830 -- Name: bomitemsub_bomitemsub_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120831 --
120832
120833 ALTER TABLE ONLY bomitemsub
120834     ADD CONSTRAINT bomitemsub_bomitemsub_item_id_fkey FOREIGN KEY (bomitemsub_item_id) REFERENCES item(item_id) ON UPDATE RESTRICT ON DELETE CASCADE;
120835
120836
120837 --
120838 -- TOC entry 8002 (class 2606 OID 146572599)
120839 -- Dependencies: 6924 236 471 8894
120840 -- Name: bomwork_bomwork_char_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120841 --
120842
120843 ALTER TABLE ONLY bomwork
120844     ADD CONSTRAINT bomwork_bomwork_char_id_fkey FOREIGN KEY (bomwork_char_id) REFERENCES "char"(char_id);
120845
120846
120847 --
120848 -- TOC entry 7865 (class 2606 OID 146572604)
120849 -- Dependencies: 6952 260 263 8894
120850 -- Name: budgitem_budgitem_budghead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120851 --
120852
120853 ALTER TABLE ONLY budgitem
120854     ADD CONSTRAINT budgitem_budgitem_budghead_id_fkey FOREIGN KEY (budgitem_budghead_id) REFERENCES budghead(budghead_id);
120855
120856
120857 --
120858 -- TOC entry 7866 (class 2606 OID 146572609)
120859 -- Dependencies: 6959 264 263 8894
120860 -- Name: budgitem_budgitem_period_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120861 --
120862
120863 ALTER TABLE ONLY budgitem
120864     ADD CONSTRAINT budgitem_budgitem_period_id_fkey FOREIGN KEY (budgitem_period_id) REFERENCES period(period_id);
120865
120866
120867 --
120868 -- TOC entry 7868 (class 2606 OID 146572614)
120869 -- Dependencies: 6963 266 267 8894
120870 -- Name: cashrcpt_bankaccnt_bankaccnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120871 --
120872
120873 ALTER TABLE ONLY cashrcpt
120874     ADD CONSTRAINT cashrcpt_bankaccnt_bankaccnt_id_fkey FOREIGN KEY (cashrcpt_bankaccnt_id) REFERENCES bankaccnt(bankaccnt_id);
120875
120876
120877 --
120878 -- TOC entry 7869 (class 2606 OID 146572619)
120879 -- Dependencies: 6853 213 267 8894
120880 -- Name: cashrcpt_cust_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120881 --
120882
120883 ALTER TABLE ONLY cashrcpt
120884     ADD CONSTRAINT cashrcpt_cust_cust_id_fkey FOREIGN KEY (cashrcpt_cust_id) REFERENCES custinfo(cust_id);
120885
120886
120887 --
120888 -- TOC entry 7870 (class 2606 OID 146572624)
120889 -- Dependencies: 6834 208 267 8894
120890 -- Name: cashrcpt_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
120891 --
120892
120893 ALTER TABLE ONLY cashrcpt
120894     ADD CONSTRAINT cashrcpt_to_curr_symbol FOREIGN KEY (cashrcpt_curr_id) REFERENCES curr_symbol(curr_id);
120895
120896
120897 --
120898 -- TOC entry 7871 (class 2606 OID 146572629)
120899 -- Dependencies: 6849 212 269 8894
120900 -- Name: cashrcptitem_aropen_aropen_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120901 --
120902
120903 ALTER TABLE ONLY cashrcptitem
120904     ADD CONSTRAINT cashrcptitem_aropen_aropen_id_fkey FOREIGN KEY (cashrcptitem_aropen_id) REFERENCES aropen(aropen_id);
120905
120906
120907 --
120908 -- TOC entry 7872 (class 2606 OID 146572634)
120909 -- Dependencies: 6967 267 269 8894
120910 -- Name: cashrcptitem_cashrcpt_cashrcpt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120911 --
120912
120913 ALTER TABLE ONLY cashrcptitem
120914     ADD CONSTRAINT cashrcptitem_cashrcpt_cashrcpt_id_fkey FOREIGN KEY (cashrcptitem_cashrcpt_id) REFERENCES cashrcpt(cashrcpt_id);
120915
120916
120917 --
120918 -- TOC entry 7873 (class 2606 OID 146572639)
120919 -- Dependencies: 6954 262 271 8894
120920 -- Name: cashrcptmisc_accnt_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120921 --
120922
120923 ALTER TABLE ONLY cashrcptmisc
120924     ADD CONSTRAINT cashrcptmisc_accnt_accnt_id_fkey FOREIGN KEY (cashrcptmisc_accnt_id) REFERENCES accnt(accnt_id);
120925
120926
120927 --
120928 -- TOC entry 7874 (class 2606 OID 146572644)
120929 -- Dependencies: 6967 267 271 8894
120930 -- Name: cashrcptmisc_cashrcpt_cashrcpt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120931 --
120932
120933 ALTER TABLE ONLY cashrcptmisc
120934     ADD CONSTRAINT cashrcptmisc_cashrcpt_cashrcpt_id_fkey FOREIGN KEY (cashrcptmisc_cashrcpt_id) REFERENCES cashrcpt(cashrcpt_id);
120935
120936
120937 --
120938 -- TOC entry 7875 (class 2606 OID 146572649)
120939 -- Dependencies: 6853 213 278 8894
120940 -- Name: ccard_ccard_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120941 --
120942
120943 ALTER TABLE ONLY ccard
120944     ADD CONSTRAINT ccard_ccard_cust_id_fkey FOREIGN KEY (ccard_cust_id) REFERENCES custinfo(cust_id);
120945
120946
120947 --
120948 -- TOC entry 8003 (class 2606 OID 146572654)
120949 -- Dependencies: 6963 266 484 8894
120950 -- Name: ccbank_ccbank_bankaccnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120951 --
120952
120953 ALTER TABLE ONLY ccbank
120954     ADD CONSTRAINT ccbank_ccbank_bankaccnt_id_fkey FOREIGN KEY (ccbank_bankaccnt_id) REFERENCES bankaccnt(bankaccnt_id);
120955
120956
120957 --
120958 -- TOC entry 8004 (class 2606 OID 146572659)
120959 -- Dependencies: 6924 236 490 8894
120960 -- Name: charopt_charopt_char_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120961 --
120962
120963 ALTER TABLE ONLY charopt
120964     ADD CONSTRAINT charopt_charopt_char_id_fkey FOREIGN KEY (charopt_char_id) REFERENCES "char"(char_id) ON DELETE CASCADE;
120965
120966
120967 --
120968 -- TOC entry 7972 (class 2606 OID 146572664)
120969 -- Dependencies: 6963 266 430 8894
120970 -- Name: checkhead_checkhead_bankaccnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120971 --
120972
120973 ALTER TABLE ONLY checkhead
120974     ADD CONSTRAINT checkhead_checkhead_bankaccnt_id_fkey FOREIGN KEY (checkhead_bankaccnt_id) REFERENCES bankaccnt(bankaccnt_id);
120975
120976
120977 --
120978 -- TOC entry 7973 (class 2606 OID 146572669)
120979 -- Dependencies: 6834 208 430 8894
120980 -- Name: checkhead_checkhead_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120981 --
120982
120983 ALTER TABLE ONLY checkhead
120984     ADD CONSTRAINT checkhead_checkhead_curr_id_fkey FOREIGN KEY (checkhead_curr_id) REFERENCES curr_symbol(curr_id);
120985
120986
120987 --
120988 -- TOC entry 7974 (class 2606 OID 146572674)
120989 -- Dependencies: 7118 358 430 8894
120990 -- Name: checkhead_checkhead_expcat_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
120991 --
120992
120993 ALTER TABLE ONLY checkhead
120994     ADD CONSTRAINT checkhead_checkhead_expcat_id_fkey FOREIGN KEY (checkhead_expcat_id) REFERENCES expcat(expcat_id);
120995
120996
120997 --
120998 -- TOC entry 7975 (class 2606 OID 146572679)
120999 -- Dependencies: 6828 207 432 8894
121000 -- Name: checkitem_checkitem_apopen_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121001 --
121002
121003 ALTER TABLE ONLY checkitem
121004     ADD CONSTRAINT checkitem_checkitem_apopen_id_fkey FOREIGN KEY (checkitem_apopen_id) REFERENCES apopen(apopen_id);
121005
121006
121007 --
121008 -- TOC entry 7976 (class 2606 OID 146572684)
121009 -- Dependencies: 6849 212 432 8894
121010 -- Name: checkitem_checkitem_aropen_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121011 --
121012
121013 ALTER TABLE ONLY checkitem
121014     ADD CONSTRAINT checkitem_checkitem_aropen_id_fkey FOREIGN KEY (checkitem_aropen_id) REFERENCES aropen(aropen_id);
121015
121016
121017 --
121018 -- TOC entry 7977 (class 2606 OID 146572689)
121019 -- Dependencies: 7204 430 432 8894
121020 -- Name: checkitem_checkitem_checkhead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121021 --
121022
121023 ALTER TABLE ONLY checkitem
121024     ADD CONSTRAINT checkitem_checkitem_checkhead_id_fkey FOREIGN KEY (checkitem_checkhead_id) REFERENCES checkhead(checkhead_id);
121025
121026
121027 --
121028 -- TOC entry 7978 (class 2606 OID 146572694)
121029 -- Dependencies: 6834 208 432 8894
121030 -- Name: checkitem_checkitem_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121031 --
121032
121033 ALTER TABLE ONLY checkitem
121034     ADD CONSTRAINT checkitem_checkitem_curr_id_fkey FOREIGN KEY (checkitem_curr_id) REFERENCES curr_symbol(curr_id);
121035
121036
121037 --
121038 -- TOC entry 7967 (class 2606 OID 146572699)
121039 -- Dependencies: 7162 397 400 8894
121040 -- Name: cmdarg_cmdarg_cmd_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121041 --
121042
121043 ALTER TABLE ONLY cmdarg
121044     ADD CONSTRAINT cmdarg_cmdarg_cmd_id_fkey FOREIGN KEY (cmdarg_cmd_id) REFERENCES cmd(cmd_id) ON DELETE CASCADE;
121045
121046
121047 --
121048 -- TOC entry 7813 (class 2606 OID 146572704)
121049 -- Dependencies: 6853 213 218 8894
121050 -- Name: cmhead_cmhead_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121051 --
121052
121053 ALTER TABLE ONLY cmhead
121054     ADD CONSTRAINT cmhead_cmhead_cust_id_fkey FOREIGN KEY (cmhead_cust_id) REFERENCES custinfo(cust_id);
121055
121056
121057 --
121058 -- TOC entry 7814 (class 2606 OID 146572709)
121059 -- Dependencies: 6796 199 218 8894
121060 -- Name: cmhead_cmhead_freighttaxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121061 --
121062
121063 ALTER TABLE ONLY cmhead
121064     ADD CONSTRAINT cmhead_cmhead_freighttaxtype_id_fkey FOREIGN KEY (cmhead_freighttaxtype_id) REFERENCES taxtype(taxtype_id);
121065
121066
121067 --
121068 -- TOC entry 7815 (class 2606 OID 146572714)
121069 -- Dependencies: 6891 225 218 8894
121070 -- Name: cmhead_cmhead_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121071 --
121072
121073 ALTER TABLE ONLY cmhead
121074     ADD CONSTRAINT cmhead_cmhead_prj_id_fkey FOREIGN KEY (cmhead_prj_id) REFERENCES prj(prj_id);
121075
121076
121077 --
121078 -- TOC entry 7816 (class 2606 OID 146572719)
121079 -- Dependencies: 6865 216 218 8894
121080 -- Name: cmhead_cmhead_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121081 --
121082
121083 ALTER TABLE ONLY cmhead
121084     ADD CONSTRAINT cmhead_cmhead_salesrep_id_fkey FOREIGN KEY (cmhead_salesrep_id) REFERENCES salesrep(salesrep_id);
121085
121086
121087 --
121088 -- TOC entry 7817 (class 2606 OID 146572724)
121089 -- Dependencies: 6895 226 218 8894
121090 -- Name: cmhead_cmhead_saletype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121091 --
121092
121093 ALTER TABLE ONLY cmhead
121094     ADD CONSTRAINT cmhead_cmhead_saletype_id_fkey FOREIGN KEY (cmhead_saletype_id) REFERENCES saletype(saletype_id);
121095
121096
121097 --
121098 -- TOC entry 7818 (class 2606 OID 146572729)
121099 -- Dependencies: 6897 227 218 8894
121100 -- Name: cmhead_cmhead_shipzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121101 --
121102
121103 ALTER TABLE ONLY cmhead
121104     ADD CONSTRAINT cmhead_cmhead_shipzone_id_fkey FOREIGN KEY (cmhead_shipzone_id) REFERENCES shipzone(shipzone_id);
121105
121106
121107 --
121108 -- TOC entry 7819 (class 2606 OID 146572734)
121109 -- Dependencies: 6878 220 218 8894
121110 -- Name: cmhead_cmhead_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121111 --
121112
121113 ALTER TABLE ONLY cmhead
121114     ADD CONSTRAINT cmhead_cmhead_taxzone_id_fkey FOREIGN KEY (cmhead_taxzone_id) REFERENCES taxzone(taxzone_id);
121115
121116
121117 --
121118 -- TOC entry 7820 (class 2606 OID 146572739)
121119 -- Dependencies: 6834 208 218 8894
121120 -- Name: cmhead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
121121 --
121122
121123 ALTER TABLE ONLY cmhead
121124     ADD CONSTRAINT cmhead_to_curr_symbol FOREIGN KEY (cmhead_curr_id) REFERENCES curr_symbol(curr_id);
121125
121126
121127 --
121128 -- TOC entry 8005 (class 2606 OID 146572744)
121129 -- Dependencies: 7124 363 497 8894
121130 -- Name: cmheadtax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121131 --
121132
121133 ALTER TABLE ONLY cmheadtax
121134     ADD CONSTRAINT cmheadtax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
121135
121136
121137 --
121138 -- TOC entry 8006 (class 2606 OID 146572749)
121139 -- Dependencies: 6872 218 497 8894
121140 -- Name: cmheadtax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121141 --
121142
121143 ALTER TABLE ONLY cmheadtax
121144     ADD CONSTRAINT cmheadtax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES cmhead(cmhead_id) ON DELETE CASCADE;
121145
121146
121147 --
121148 -- TOC entry 8007 (class 2606 OID 146572754)
121149 -- Dependencies: 7124 363 497 8894
121150 -- Name: cmheadtax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121151 --
121152
121153 ALTER TABLE ONLY cmheadtax
121154     ADD CONSTRAINT cmheadtax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
121155
121156
121157 --
121158 -- TOC entry 8008 (class 2606 OID 146572759)
121159 -- Dependencies: 6796 199 497 8894
121160 -- Name: cmheadtax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121161 --
121162
121163 ALTER TABLE ONLY cmheadtax
121164     ADD CONSTRAINT cmheadtax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
121165
121166
121167 --
121168 -- TOC entry 7830 (class 2606 OID 146572764)
121169 -- Dependencies: 6872 218 222 8894
121170 -- Name: cmitem_cmhead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121171 --
121172
121173 ALTER TABLE ONLY cmitem
121174     ADD CONSTRAINT cmitem_cmhead_id_fkey FOREIGN KEY (cmitem_cmhead_id) REFERENCES cmhead(cmhead_id) ON UPDATE CASCADE ON DELETE CASCADE;
121175
121176
121177 --
121178 -- TOC entry 7831 (class 2606 OID 146572769)
121179 -- Dependencies: 6800 200 222 8894
121180 -- Name: cmitem_cmitem_price_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121181 --
121182
121183 ALTER TABLE ONLY cmitem
121184     ADD CONSTRAINT cmitem_cmitem_price_uom_id_fkey FOREIGN KEY (cmitem_price_uom_id) REFERENCES uom(uom_id);
121185
121186
121187 --
121188 -- TOC entry 7832 (class 2606 OID 146572774)
121189 -- Dependencies: 6800 200 222 8894
121190 -- Name: cmitem_cmitem_qty_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121191 --
121192
121193 ALTER TABLE ONLY cmitem
121194     ADD CONSTRAINT cmitem_cmitem_qty_uom_id_fkey FOREIGN KEY (cmitem_qty_uom_id) REFERENCES uom(uom_id);
121195
121196
121197 --
121198 -- TOC entry 7833 (class 2606 OID 146572779)
121199 -- Dependencies: 6796 199 222 8894
121200 -- Name: cmitem_cmitem_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121201 --
121202
121203 ALTER TABLE ONLY cmitem
121204     ADD CONSTRAINT cmitem_cmitem_taxtype_id_fkey FOREIGN KEY (cmitem_taxtype_id) REFERENCES taxtype(taxtype_id);
121205
121206
121207 --
121208 -- TOC entry 8009 (class 2606 OID 146572784)
121209 -- Dependencies: 7124 363 499 8894
121210 -- Name: cmitemtax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121211 --
121212
121213 ALTER TABLE ONLY cmitemtax
121214     ADD CONSTRAINT cmitemtax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
121215
121216
121217 --
121218 -- TOC entry 8010 (class 2606 OID 146572789)
121219 -- Dependencies: 6884 222 499 8894
121220 -- Name: cmitemtax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121221 --
121222
121223 ALTER TABLE ONLY cmitemtax
121224     ADD CONSTRAINT cmitemtax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES cmitem(cmitem_id) ON DELETE CASCADE;
121225
121226
121227 --
121228 -- TOC entry 8011 (class 2606 OID 146572794)
121229 -- Dependencies: 7124 363 499 8894
121230 -- Name: cmitemtax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121231 --
121232
121233 ALTER TABLE ONLY cmitemtax
121234     ADD CONSTRAINT cmitemtax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
121235
121236
121237 --
121238 -- TOC entry 8012 (class 2606 OID 146572799)
121239 -- Dependencies: 6796 199 499 8894
121240 -- Name: cmitemtax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121241 --
121242
121243 ALTER TABLE ONLY cmitemtax
121244     ADD CONSTRAINT cmitemtax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
121245
121246
121247 --
121248 -- TOC entry 7771 (class 2606 OID 146572804)
121249 -- Dependencies: 6920 234 204 8894
121250 -- Name: cntct_cntct_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121251 --
121252
121253 ALTER TABLE ONLY cntct
121254     ADD CONSTRAINT cntct_cntct_addr_id_fkey FOREIGN KEY (cntct_addr_id) REFERENCES addr(addr_id);
121255
121256
121257 --
121258 -- TOC entry 7772 (class 2606 OID 146572809)
121259 -- Dependencies: 6820 205 204 8894
121260 -- Name: cntct_cntct_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121261 --
121262
121263 ALTER TABLE ONLY cntct
121264     ADD CONSTRAINT cntct_cntct_crmacct_id_fkey FOREIGN KEY (cntct_crmacct_id) REFERENCES crmacct(crmacct_id);
121265
121266
121267 --
121268 -- TOC entry 8013 (class 2606 OID 146572814)
121269 -- Dependencies: 6920 234 504 8894
121270 -- Name: cntctaddr_cntctaddr_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121271 --
121272
121273 ALTER TABLE ONLY cntctaddr
121274     ADD CONSTRAINT cntctaddr_cntctaddr_addr_id_fkey FOREIGN KEY (cntctaddr_addr_id) REFERENCES addr(addr_id);
121275
121276
121277 --
121278 -- TOC entry 8014 (class 2606 OID 146572819)
121279 -- Dependencies: 6816 204 504 8894
121280 -- Name: cntctaddr_cntctaddr_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121281 --
121282
121283 ALTER TABLE ONLY cntctaddr
121284     ADD CONSTRAINT cntctaddr_cntctaddr_cntct_id_fkey FOREIGN KEY (cntctaddr_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
121285
121286
121287 --
121288 -- TOC entry 8015 (class 2606 OID 146572824)
121289 -- Dependencies: 6816 204 506 8894
121290 -- Name: cntctdata_cntctdata_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121291 --
121292
121293 ALTER TABLE ONLY cntctdata
121294     ADD CONSTRAINT cntctdata_cntctdata_cntct_id_fkey FOREIGN KEY (cntctdata_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
121295
121296
121297 --
121298 -- TOC entry 8016 (class 2606 OID 146572829)
121299 -- Dependencies: 6816 204 508 8894
121300 -- Name: cntcteml_cntcteml_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121301 --
121302
121303 ALTER TABLE ONLY cntcteml
121304     ADD CONSTRAINT cntcteml_cntcteml_cntct_id_fkey FOREIGN KEY (cntcteml_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
121305
121306
121307 --
121308 -- TOC entry 8017 (class 2606 OID 146572834)
121309 -- Dependencies: 6816 204 510 8894
121310 -- Name: cntctmrgd_cntctmrgd_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121311 --
121312
121313 ALTER TABLE ONLY cntctmrgd
121314     ADD CONSTRAINT cntctmrgd_cntctmrgd_cntct_id_fkey FOREIGN KEY (cntctmrgd_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
121315
121316
121317 --
121318 -- TOC entry 8018 (class 2606 OID 146572839)
121319 -- Dependencies: 6816 204 511 8894
121320 -- Name: cntctsel_cntctsel_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121321 --
121322
121323 ALTER TABLE ONLY cntctsel
121324     ADD CONSTRAINT cntctsel_cntctsel_cntct_id_fkey FOREIGN KEY (cntctsel_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
121325
121326
121327 --
121328 -- TOC entry 8019 (class 2606 OID 146572844)
121329 -- Dependencies: 6905 229 513 8894
121330 -- Name: cobill_cobill_invcitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121331 --
121332
121333 ALTER TABLE ONLY cobill
121334     ADD CONSTRAINT cobill_cobill_invcitem_id_fkey FOREIGN KEY (cobill_invcitem_id) REFERENCES invcitem(invcitem_id);
121335
121336
121337 --
121338 -- TOC entry 8020 (class 2606 OID 146572849)
121339 -- Dependencies: 6796 199 513 8894
121340 -- Name: cobill_cobill_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121341 --
121342
121343 ALTER TABLE ONLY cobill
121344     ADD CONSTRAINT cobill_cobill_taxtype_id_fkey FOREIGN KEY (cobill_taxtype_id) REFERENCES taxtype(taxtype_id);
121345
121346
121347 --
121348 -- TOC entry 8021 (class 2606 OID 146572854)
121349 -- Dependencies: 7124 363 515 8894
121350 -- Name: cobilltax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121351 --
121352
121353 ALTER TABLE ONLY cobilltax
121354     ADD CONSTRAINT cobilltax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
121355
121356
121357 --
121358 -- TOC entry 8022 (class 2606 OID 146572859)
121359 -- Dependencies: 7288 513 515 8894
121360 -- Name: cobilltax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121361 --
121362
121363 ALTER TABLE ONLY cobilltax
121364     ADD CONSTRAINT cobilltax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES cobill(cobill_id) ON DELETE CASCADE;
121365
121366
121367 --
121368 -- TOC entry 8023 (class 2606 OID 146572864)
121369 -- Dependencies: 7124 363 515 8894
121370 -- Name: cobilltax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121371 --
121372
121373 ALTER TABLE ONLY cobilltax
121374     ADD CONSTRAINT cobilltax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
121375
121376
121377 --
121378 -- TOC entry 8024 (class 2606 OID 146572869)
121379 -- Dependencies: 6796 199 515 8894
121380 -- Name: cobilltax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121381 --
121382
121383 ALTER TABLE ONLY cobilltax
121384     ADD CONSTRAINT cobilltax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
121385
121386
121387 --
121388 -- TOC entry 8025 (class 2606 OID 146572874)
121389 -- Dependencies: 6889 224 516 8894
121390 -- Name: cobmisc_cobmisc_invchead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121391 --
121392
121393 ALTER TABLE ONLY cobmisc
121394     ADD CONSTRAINT cobmisc_cobmisc_invchead_id_fkey FOREIGN KEY (cobmisc_invchead_id) REFERENCES invchead(invchead_id);
121395
121396
121397 --
121398 -- TOC entry 8026 (class 2606 OID 146572879)
121399 -- Dependencies: 6796 199 516 8894
121400 -- Name: cobmisc_cobmisc_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121401 --
121402
121403 ALTER TABLE ONLY cobmisc
121404     ADD CONSTRAINT cobmisc_cobmisc_taxtype_id_fkey FOREIGN KEY (cobmisc_taxtype_id) REFERENCES taxtype(taxtype_id);
121405
121406
121407 --
121408 -- TOC entry 8027 (class 2606 OID 146572884)
121409 -- Dependencies: 6878 220 516 8894
121410 -- Name: cobmisc_cobmisc_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121411 --
121412
121413 ALTER TABLE ONLY cobmisc
121414     ADD CONSTRAINT cobmisc_cobmisc_taxzone_id_fkey FOREIGN KEY (cobmisc_taxzone_id) REFERENCES taxzone(taxzone_id);
121415
121416
121417 --
121418 -- TOC entry 8028 (class 2606 OID 146572889)
121419 -- Dependencies: 6834 208 516 8894
121420 -- Name: cobmisc_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
121421 --
121422
121423 ALTER TABLE ONLY cobmisc
121424     ADD CONSTRAINT cobmisc_to_curr_symbol FOREIGN KEY (cobmisc_curr_id) REFERENCES curr_symbol(curr_id);
121425
121426
121427 --
121428 -- TOC entry 8029 (class 2606 OID 146572894)
121429 -- Dependencies: 7124 363 518 8894
121430 -- Name: cobmisctax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121431 --
121432
121433 ALTER TABLE ONLY cobmisctax
121434     ADD CONSTRAINT cobmisctax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
121435
121436
121437 --
121438 -- TOC entry 8030 (class 2606 OID 146572899)
121439 -- Dependencies: 7293 516 518 8894
121440 -- Name: cobmisctax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121441 --
121442
121443 ALTER TABLE ONLY cobmisctax
121444     ADD CONSTRAINT cobmisctax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES cobmisc(cobmisc_id) ON DELETE CASCADE;
121445
121446
121447 --
121448 -- TOC entry 8031 (class 2606 OID 146572904)
121449 -- Dependencies: 7124 363 518 8894
121450 -- Name: cobmisctax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121451 --
121452
121453 ALTER TABLE ONLY cobmisctax
121454     ADD CONSTRAINT cobmisctax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
121455
121456
121457 --
121458 -- TOC entry 8032 (class 2606 OID 146572909)
121459 -- Dependencies: 6796 199 518 8894
121460 -- Name: cobmisctax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121461 --
121462
121463 ALTER TABLE ONLY cobmisctax
121464     ADD CONSTRAINT cobmisctax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
121465
121466
121467 --
121468 -- TOC entry 7725 (class 2606 OID 146572914)
121469 -- Dependencies: 6816 204 195 8894
121470 -- Name: cohead_cohead_billto_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121471 --
121472
121473 ALTER TABLE ONLY cohead
121474     ADD CONSTRAINT cohead_cohead_billto_cntct_id_fkey FOREIGN KEY (cohead_billto_cntct_id) REFERENCES cntct(cntct_id);
121475
121476
121477 --
121478 -- TOC entry 7726 (class 2606 OID 146572919)
121479 -- Dependencies: 6853 213 195 8894
121480 -- Name: cohead_cohead_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121481 --
121482
121483 ALTER TABLE ONLY cohead
121484     ADD CONSTRAINT cohead_cohead_cust_id_fkey FOREIGN KEY (cohead_cust_id) REFERENCES custinfo(cust_id);
121485
121486
121487 --
121488 -- TOC entry 7727 (class 2606 OID 146572924)
121489 -- Dependencies: 6954 262 195 8894
121490 -- Name: cohead_cohead_misc_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121491 --
121492
121493 ALTER TABLE ONLY cohead
121494     ADD CONSTRAINT cohead_cohead_misc_accnt_id_fkey FOREIGN KEY (cohead_misc_accnt_id) REFERENCES accnt(accnt_id);
121495
121496
121497 --
121498 -- TOC entry 7728 (class 2606 OID 146572929)
121499 -- Dependencies: 6909 231 195 8894
121500 -- Name: cohead_cohead_ophead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121501 --
121502
121503 ALTER TABLE ONLY cohead
121504     ADD CONSTRAINT cohead_cohead_ophead_id_fkey FOREIGN KEY (cohead_ophead_id) REFERENCES ophead(ophead_id);
121505
121506
121507 --
121508 -- TOC entry 7729 (class 2606 OID 146572934)
121509 -- Dependencies: 6891 225 195 8894
121510 -- Name: cohead_cohead_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121511 --
121512
121513 ALTER TABLE ONLY cohead
121514     ADD CONSTRAINT cohead_cohead_prj_id_fkey FOREIGN KEY (cohead_prj_id) REFERENCES prj(prj_id);
121515
121516
121517 --
121518 -- TOC entry 7730 (class 2606 OID 146572939)
121519 -- Dependencies: 6865 216 195 8894
121520 -- Name: cohead_cohead_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121521 --
121522
121523 ALTER TABLE ONLY cohead
121524     ADD CONSTRAINT cohead_cohead_salesrep_id_fkey FOREIGN KEY (cohead_salesrep_id) REFERENCES salesrep(salesrep_id);
121525
121526
121527 --
121528 -- TOC entry 7731 (class 2606 OID 146572944)
121529 -- Dependencies: 6895 226 195 8894
121530 -- Name: cohead_cohead_saletype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121531 --
121532
121533 ALTER TABLE ONLY cohead
121534     ADD CONSTRAINT cohead_cohead_saletype_id_fkey FOREIGN KEY (cohead_saletype_id) REFERENCES saletype(saletype_id);
121535
121536
121537 --
121538 -- TOC entry 7732 (class 2606 OID 146572949)
121539 -- Dependencies: 6984 282 195 8894
121540 -- Name: cohead_cohead_shipform_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121541 --
121542
121543 ALTER TABLE ONLY cohead
121544     ADD CONSTRAINT cohead_cohead_shipform_id_fkey FOREIGN KEY (cohead_shipform_id) REFERENCES shipform(shipform_id);
121545
121546
121547 --
121548 -- TOC entry 7733 (class 2606 OID 146572954)
121549 -- Dependencies: 6816 204 195 8894
121550 -- Name: cohead_cohead_shipto_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121551 --
121552
121553 ALTER TABLE ONLY cohead
121554     ADD CONSTRAINT cohead_cohead_shipto_cntct_id_fkey FOREIGN KEY (cohead_shipto_cntct_id) REFERENCES cntct(cntct_id);
121555
121556
121557 --
121558 -- TOC entry 7734 (class 2606 OID 146572959)
121559 -- Dependencies: 6876 219 195 8894
121560 -- Name: cohead_cohead_shipto_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121561 --
121562
121563 ALTER TABLE ONLY cohead
121564     ADD CONSTRAINT cohead_cohead_shipto_id_fkey FOREIGN KEY (cohead_shipto_id) REFERENCES shiptoinfo(shipto_id);
121565
121566
121567 --
121568 -- TOC entry 7735 (class 2606 OID 146572964)
121569 -- Dependencies: 6897 227 195 8894
121570 -- Name: cohead_cohead_shipzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121571 --
121572
121573 ALTER TABLE ONLY cohead
121574     ADD CONSTRAINT cohead_cohead_shipzone_id_fkey FOREIGN KEY (cohead_shipzone_id) REFERENCES shipzone(shipzone_id);
121575
121576
121577 --
121578 -- TOC entry 7736 (class 2606 OID 146572969)
121579 -- Dependencies: 6796 199 195 8894
121580 -- Name: cohead_cohead_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121581 --
121582
121583 ALTER TABLE ONLY cohead
121584     ADD CONSTRAINT cohead_cohead_taxtype_id_fkey FOREIGN KEY (cohead_taxtype_id) REFERENCES taxtype(taxtype_id);
121585
121586
121587 --
121588 -- TOC entry 7737 (class 2606 OID 146572974)
121589 -- Dependencies: 6878 220 195 8894
121590 -- Name: cohead_cohead_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121591 --
121592
121593 ALTER TABLE ONLY cohead
121594     ADD CONSTRAINT cohead_cohead_taxzone_id_fkey FOREIGN KEY (cohead_taxzone_id) REFERENCES taxzone(taxzone_id);
121595
121596
121597 --
121598 -- TOC entry 7738 (class 2606 OID 146572979)
121599 -- Dependencies: 6836 209 195 8894
121600 -- Name: cohead_cohead_terms_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121601 --
121602
121603 ALTER TABLE ONLY cohead
121604     ADD CONSTRAINT cohead_cohead_terms_id_fkey FOREIGN KEY (cohead_terms_id) REFERENCES terms(terms_id);
121605
121606
121607 --
121608 -- TOC entry 7739 (class 2606 OID 146572984)
121609 -- Dependencies: 6763 193 195 8894
121610 -- Name: cohead_cohead_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121611 --
121612
121613 ALTER TABLE ONLY cohead
121614     ADD CONSTRAINT cohead_cohead_warehous_id_fkey FOREIGN KEY (cohead_warehous_id) REFERENCES whsinfo(warehous_id);
121615
121616
121617 --
121618 -- TOC entry 7740 (class 2606 OID 146572989)
121619 -- Dependencies: 6834 208 195 8894
121620 -- Name: cohead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
121621 --
121622
121623 ALTER TABLE ONLY cohead
121624     ADD CONSTRAINT cohead_to_curr_symbol FOREIGN KEY (cohead_curr_id) REFERENCES curr_symbol(curr_id);
121625
121626
121627 --
121628 -- TOC entry 7954 (class 2606 OID 146572994)
121629 -- Dependencies: 7266 486 376 8894
121630 -- Name: cohist_cohist_cohead_ccpay_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121631 --
121632
121633 ALTER TABLE ONLY cohist
121634     ADD CONSTRAINT cohist_cohist_cohead_ccpay_id_fkey FOREIGN KEY (cohist_cohead_ccpay_id) REFERENCES ccpay(ccpay_id);
121635
121636
121637 --
121638 -- TOC entry 7955 (class 2606 OID 146572999)
121639 -- Dependencies: 6853 213 376 8894
121640 -- Name: cohist_cohist_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121641 --
121642
121643 ALTER TABLE ONLY cohist
121644     ADD CONSTRAINT cohist_cohist_cust_id_fkey FOREIGN KEY (cohist_cust_id) REFERENCES custinfo(cust_id);
121645
121646
121647 --
121648 -- TOC entry 7956 (class 2606 OID 146573004)
121649 -- Dependencies: 6865 216 376 8894
121650 -- Name: cohist_cohist_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121651 --
121652
121653 ALTER TABLE ONLY cohist
121654     ADD CONSTRAINT cohist_cohist_salesrep_id_fkey FOREIGN KEY (cohist_salesrep_id) REFERENCES salesrep(salesrep_id);
121655
121656
121657 --
121658 -- TOC entry 7957 (class 2606 OID 146573009)
121659 -- Dependencies: 6796 199 376 8894
121660 -- Name: cohist_cohist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121661 --
121662
121663 ALTER TABLE ONLY cohist
121664     ADD CONSTRAINT cohist_cohist_taxtype_id_fkey FOREIGN KEY (cohist_taxtype_id) REFERENCES taxtype(taxtype_id);
121665
121666
121667 --
121668 -- TOC entry 7958 (class 2606 OID 146573014)
121669 -- Dependencies: 6878 220 376 8894
121670 -- Name: cohist_cohist_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121671 --
121672
121673 ALTER TABLE ONLY cohist
121674     ADD CONSTRAINT cohist_cohist_taxzone_id_fkey FOREIGN KEY (cohist_taxzone_id) REFERENCES taxzone(taxzone_id);
121675
121676
121677 --
121678 -- TOC entry 7959 (class 2606 OID 146573019)
121679 -- Dependencies: 6834 208 376 8894
121680 -- Name: cohist_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
121681 --
121682
121683 ALTER TABLE ONLY cohist
121684     ADD CONSTRAINT cohist_to_curr_symbol FOREIGN KEY (cohist_curr_id) REFERENCES curr_symbol(curr_id);
121685
121686
121687 --
121688 -- TOC entry 7963 (class 2606 OID 146573024)
121689 -- Dependencies: 7124 363 379 8894
121690 -- Name: cohisttax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121691 --
121692
121693 ALTER TABLE ONLY cohisttax
121694     ADD CONSTRAINT cohisttax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
121695
121696
121697 --
121698 -- TOC entry 7964 (class 2606 OID 146573029)
121699 -- Dependencies: 7142 376 379 8894
121700 -- Name: cohisttax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121701 --
121702
121703 ALTER TABLE ONLY cohisttax
121704     ADD CONSTRAINT cohisttax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES cohist(cohist_id) ON DELETE CASCADE;
121705
121706
121707 --
121708 -- TOC entry 7965 (class 2606 OID 146573034)
121709 -- Dependencies: 7124 363 379 8894
121710 -- Name: cohisttax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121711 --
121712
121713 ALTER TABLE ONLY cohisttax
121714     ADD CONSTRAINT cohisttax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
121715
121716
121717 --
121718 -- TOC entry 7966 (class 2606 OID 146573039)
121719 -- Dependencies: 6796 199 379 8894
121720 -- Name: cohisttax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121721 --
121722
121723 ALTER TABLE ONLY cohisttax
121724     ADD CONSTRAINT cohisttax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
121725
121726
121727 --
121728 -- TOC entry 7741 (class 2606 OID 146573044)
121729 -- Dependencies: 6773 195 196 8894
121730 -- Name: coitem_coitem_cohead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121731 --
121732
121733 ALTER TABLE ONLY coitem
121734     ADD CONSTRAINT coitem_coitem_cohead_id_fkey FOREIGN KEY (coitem_cohead_id) REFERENCES cohead(cohead_id) ON DELETE CASCADE;
121735
121736
121737 --
121738 -- TOC entry 7742 (class 2606 OID 146573049)
121739 -- Dependencies: 6954 262 196 8894
121740 -- Name: coitem_coitem_cos_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121741 --
121742
121743 ALTER TABLE ONLY coitem
121744     ADD CONSTRAINT coitem_coitem_cos_accnt_id_fkey FOREIGN KEY (coitem_cos_accnt_id) REFERENCES accnt(accnt_id);
121745
121746
121747 --
121748 -- TOC entry 7743 (class 2606 OID 146573054)
121749 -- Dependencies: 6758 192 196 8894
121750 -- Name: coitem_coitem_itemsite_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121751 --
121752
121753 ALTER TABLE ONLY coitem
121754     ADD CONSTRAINT coitem_coitem_itemsite_id_fkey FOREIGN KEY (coitem_itemsite_id) REFERENCES itemsite(itemsite_id);
121755
121756
121757 --
121758 -- TOC entry 7744 (class 2606 OID 146573059)
121759 -- Dependencies: 6800 200 196 8894
121760 -- Name: coitem_coitem_price_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121761 --
121762
121763 ALTER TABLE ONLY coitem
121764     ADD CONSTRAINT coitem_coitem_price_uom_id_fkey FOREIGN KEY (coitem_price_uom_id) REFERENCES uom(uom_id);
121765
121766
121767 --
121768 -- TOC entry 7745 (class 2606 OID 146573064)
121769 -- Dependencies: 6800 200 196 8894
121770 -- Name: coitem_coitem_qty_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121771 --
121772
121773 ALTER TABLE ONLY coitem
121774     ADD CONSTRAINT coitem_coitem_qty_uom_id_fkey FOREIGN KEY (coitem_qty_uom_id) REFERENCES uom(uom_id);
121775
121776
121777 --
121778 -- TOC entry 7746 (class 2606 OID 146573069)
121779 -- Dependencies: 6954 262 196 8894
121780 -- Name: coitem_coitem_rev_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121781 --
121782
121783 ALTER TABLE ONLY coitem
121784     ADD CONSTRAINT coitem_coitem_rev_accnt_id_fkey FOREIGN KEY (coitem_rev_accnt_id) REFERENCES accnt(accnt_id);
121785
121786
121787 --
121788 -- TOC entry 7747 (class 2606 OID 146573074)
121789 -- Dependencies: 6751 191 196 8894
121790 -- Name: coitem_coitem_substitute_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121791 --
121792
121793 ALTER TABLE ONLY coitem
121794     ADD CONSTRAINT coitem_coitem_substitute_item_id_fkey FOREIGN KEY (coitem_substitute_item_id) REFERENCES item(item_id);
121795
121796
121797 --
121798 -- TOC entry 7748 (class 2606 OID 146573079)
121799 -- Dependencies: 6796 199 196 8894
121800 -- Name: coitem_coitem_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121801 --
121802
121803 ALTER TABLE ONLY coitem
121804     ADD CONSTRAINT coitem_coitem_taxtype_id_fkey FOREIGN KEY (coitem_taxtype_id) REFERENCES taxtype(taxtype_id);
121805
121806
121807 --
121808 -- TOC entry 7859 (class 2606 OID 146573084)
121809 -- Dependencies: 6931 239 240 8894
121810 -- Name: comment_comment_cmnttype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121811 --
121812
121813 ALTER TABLE ONLY comment
121814     ADD CONSTRAINT comment_comment_cmnttype_id_fkey FOREIGN KEY (comment_cmnttype_id) REFERENCES cmnttype(cmnttype_id);
121815
121816
121817 --
121818 -- TOC entry 8033 (class 2606 OID 146573089)
121819 -- Dependencies: 6834 208 523 8894
121820 -- Name: company_company_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121821 --
121822
121823 ALTER TABLE ONLY company
121824     ADD CONSTRAINT company_company_curr_id_fkey FOREIGN KEY (company_curr_id) REFERENCES curr_symbol(curr_id);
121825
121826
121827 --
121828 -- TOC entry 8034 (class 2606 OID 146573094)
121829 -- Dependencies: 6954 262 523 8894
121830 -- Name: company_company_dscrp_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121831 --
121832
121833 ALTER TABLE ONLY company
121834     ADD CONSTRAINT company_company_dscrp_accnt_id_fkey FOREIGN KEY (company_dscrp_accnt_id) REFERENCES accnt(accnt_id);
121835
121836
121837 --
121838 -- TOC entry 8035 (class 2606 OID 146573099)
121839 -- Dependencies: 6954 262 523 8894
121840 -- Name: company_company_gainloss_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121841 --
121842
121843 ALTER TABLE ONLY company
121844     ADD CONSTRAINT company_company_gainloss_accnt_id_fkey FOREIGN KEY (company_gainloss_accnt_id) REFERENCES accnt(accnt_id);
121845
121846
121847 --
121848 -- TOC entry 8036 (class 2606 OID 146573104)
121849 -- Dependencies: 6954 262 523 8894
121850 -- Name: company_company_unrlzgainloss_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121851 --
121852
121853 ALTER TABLE ONLY company
121854     ADD CONSTRAINT company_company_unrlzgainloss_accnt_id_fkey FOREIGN KEY (company_unrlzgainloss_accnt_id) REFERENCES accnt(accnt_id);
121855
121856
121857 --
121858 -- TOC entry 8037 (class 2606 OID 146573109)
121859 -- Dependencies: 6954 262 523 8894
121860 -- Name: company_company_yearend_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121861 --
121862
121863 ALTER TABLE ONLY company
121864     ADD CONSTRAINT company_company_yearend_accnt_id_fkey FOREIGN KEY (company_yearend_accnt_id) REFERENCES accnt(accnt_id);
121865
121866
121867 --
121868 -- TOC entry 7902 (class 2606 OID 146573114)
121869 -- Dependencies: 6841 210 329 8894
121870 -- Name: contrct_contrct_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121871 --
121872
121873 ALTER TABLE ONLY contrct
121874     ADD CONSTRAINT contrct_contrct_vend_id_fkey FOREIGN KEY (contrct_vend_id) REFERENCES vendinfo(vend_id);
121875
121876
121877 --
121878 -- TOC entry 8044 (class 2606 OID 146573119)
121879 -- Dependencies: 6834 208 535 8894
121880 -- Name: costhist_new_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
121881 --
121882
121883 ALTER TABLE ONLY costhist
121884     ADD CONSTRAINT costhist_new_to_curr_symbol FOREIGN KEY (costhist_newcurr_id) REFERENCES curr_symbol(curr_id);
121885
121886
121887 --
121888 -- TOC entry 8045 (class 2606 OID 146573124)
121889 -- Dependencies: 6834 208 535 8894
121890 -- Name: costhist_old_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
121891 --
121892
121893 ALTER TABLE ONLY costhist
121894     ADD CONSTRAINT costhist_old_to_curr_symbol FOREIGN KEY (costhist_oldcurr_id) REFERENCES curr_symbol(curr_id);
121895
121896
121897 --
121898 -- TOC entry 7773 (class 2606 OID 146573129)
121899 -- Dependencies: 6816 204 205 8894
121900 -- Name: crmacct_crmacct_cntct_id_1_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121901 --
121902
121903 ALTER TABLE ONLY crmacct
121904     ADD CONSTRAINT crmacct_crmacct_cntct_id_1_fkey FOREIGN KEY (crmacct_cntct_id_1) REFERENCES cntct(cntct_id);
121905
121906
121907 --
121908 -- TOC entry 7774 (class 2606 OID 146573134)
121909 -- Dependencies: 6816 204 205 8894
121910 -- Name: crmacct_crmacct_cntct_id_2_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121911 --
121912
121913 ALTER TABLE ONLY crmacct
121914     ADD CONSTRAINT crmacct_crmacct_cntct_id_2_fkey FOREIGN KEY (crmacct_cntct_id_2) REFERENCES cntct(cntct_id);
121915
121916
121917 --
121918 -- TOC entry 7775 (class 2606 OID 146573139)
121919 -- Dependencies: 6853 213 205 8894
121920 -- Name: crmacct_crmacct_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121921 --
121922
121923 ALTER TABLE ONLY crmacct
121924     ADD CONSTRAINT crmacct_crmacct_cust_id_fkey FOREIGN KEY (crmacct_cust_id) REFERENCES custinfo(cust_id);
121925
121926
121927 --
121928 -- TOC entry 7776 (class 2606 OID 146573144)
121929 -- Dependencies: 7002 292 205 8894
121930 -- Name: crmacct_crmacct_emp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121931 --
121932
121933 ALTER TABLE ONLY crmacct
121934     ADD CONSTRAINT crmacct_crmacct_emp_id_fkey FOREIGN KEY (crmacct_emp_id) REFERENCES emp(emp_id);
121935
121936
121937 --
121938 -- TOC entry 7777 (class 2606 OID 146573149)
121939 -- Dependencies: 6820 205 205 8894
121940 -- Name: crmacct_crmacct_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121941 --
121942
121943 ALTER TABLE ONLY crmacct
121944     ADD CONSTRAINT crmacct_crmacct_parent_id_fkey FOREIGN KEY (crmacct_parent_id) REFERENCES crmacct(crmacct_id);
121945
121946
121947 --
121948 -- TOC entry 7778 (class 2606 OID 146573154)
121949 -- Dependencies: 7112 356 205 8894
121950 -- Name: crmacct_crmacct_prospect_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121951 --
121952
121953 ALTER TABLE ONLY crmacct
121954     ADD CONSTRAINT crmacct_crmacct_prospect_id_fkey FOREIGN KEY (crmacct_prospect_id) REFERENCES prospect(prospect_id);
121955
121956
121957 --
121958 -- TOC entry 7779 (class 2606 OID 146573159)
121959 -- Dependencies: 6865 216 205 8894
121960 -- Name: crmacct_crmacct_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121961 --
121962
121963 ALTER TABLE ONLY crmacct
121964     ADD CONSTRAINT crmacct_crmacct_salesrep_id_fkey FOREIGN KEY (crmacct_salesrep_id) REFERENCES salesrep(salesrep_id);
121965
121966
121967 --
121968 -- TOC entry 7780 (class 2606 OID 146573164)
121969 -- Dependencies: 6988 284 205 8894
121970 -- Name: crmacct_crmacct_taxauth_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121971 --
121972
121973 ALTER TABLE ONLY crmacct
121974     ADD CONSTRAINT crmacct_crmacct_taxauth_id_fkey FOREIGN KEY (crmacct_taxauth_id) REFERENCES taxauth(taxauth_id);
121975
121976
121977 --
121978 -- TOC entry 7781 (class 2606 OID 146573169)
121979 -- Dependencies: 6841 210 205 8894
121980 -- Name: crmacct_crmacct_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121981 --
121982
121983 ALTER TABLE ONLY crmacct
121984     ADD CONSTRAINT crmacct_crmacct_vend_id_fkey FOREIGN KEY (crmacct_vend_id) REFERENCES vendinfo(vend_id);
121985
121986
121987 --
121988 -- TOC entry 8046 (class 2606 OID 146573174)
121989 -- Dependencies: 6820 205 544 8894
121990 -- Name: crmacctsel_crmacctsel_dest_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
121991 --
121992
121993 ALTER TABLE ONLY crmacctsel
121994     ADD CONSTRAINT crmacctsel_crmacctsel_dest_crmacct_id_fkey FOREIGN KEY (crmacctsel_dest_crmacct_id) REFERENCES crmacct(crmacct_id) ON DELETE CASCADE;
121995
121996
121997 --
121998 -- TOC entry 8047 (class 2606 OID 146573179)
121999 -- Dependencies: 6820 205 544 8894
122000 -- Name: crmacctsel_crmacctsel_src_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122001 --
122002
122003 ALTER TABLE ONLY crmacctsel
122004     ADD CONSTRAINT crmacctsel_crmacctsel_src_crmacct_id_fkey FOREIGN KEY (crmacctsel_src_crmacct_id) REFERENCES crmacct(crmacct_id) ON DELETE CASCADE;
122005
122006
122007 --
122008 -- TOC entry 8048 (class 2606 OID 146573184)
122009 -- Dependencies: 6834 208 545 8894
122010 -- Name: curr_rate_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122011 --
122012
122013 ALTER TABLE ONLY curr_rate
122014     ADD CONSTRAINT curr_rate_to_curr_symbol FOREIGN KEY (curr_id) REFERENCES curr_symbol(curr_id);
122015
122016
122017 --
122018 -- TOC entry 7803 (class 2606 OID 146573189)
122019 -- Dependencies: 6834 208 213 8894
122020 -- Name: cust_creditlmt_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122021 --
122022
122023 ALTER TABLE ONLY custinfo
122024     ADD CONSTRAINT cust_creditlmt_to_curr_symbol FOREIGN KEY (cust_creditlmt_curr_id) REFERENCES curr_symbol(curr_id);
122025
122026
122027 --
122028 -- TOC entry 7804 (class 2606 OID 146573194)
122029 -- Dependencies: 6834 208 213 8894
122030 -- Name: cust_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122031 --
122032
122033 ALTER TABLE ONLY custinfo
122034     ADD CONSTRAINT cust_to_curr_symbol FOREIGN KEY (cust_curr_id) REFERENCES curr_symbol(curr_id);
122035
122036
122037 --
122038 -- TOC entry 7805 (class 2606 OID 146573199)
122039 -- Dependencies: 6816 204 213 8894
122040 -- Name: custinfo_cust_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122041 --
122042
122043 ALTER TABLE ONLY custinfo
122044     ADD CONSTRAINT custinfo_cust_cntct_id_fkey FOREIGN KEY (cust_cntct_id) REFERENCES cntct(cntct_id);
122045
122046
122047 --
122048 -- TOC entry 7806 (class 2606 OID 146573204)
122049 -- Dependencies: 6816 204 213 8894
122050 -- Name: custinfo_cust_corrcntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122051 --
122052
122053 ALTER TABLE ONLY custinfo
122054     ADD CONSTRAINT custinfo_cust_corrcntct_id_fkey FOREIGN KEY (cust_corrcntct_id) REFERENCES cntct(cntct_id);
122055
122056
122057 --
122058 -- TOC entry 7807 (class 2606 OID 146573209)
122059 -- Dependencies: 6980 280 213 8894
122060 -- Name: custinfo_cust_custtype_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122061 --
122062
122063 ALTER TABLE ONLY custinfo
122064     ADD CONSTRAINT custinfo_cust_custtype_fkey FOREIGN KEY (cust_custtype_id) REFERENCES custtype(custtype_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
122065
122066
122067 --
122068 -- TOC entry 7808 (class 2606 OID 146573214)
122069 -- Dependencies: 6865 216 213 8894
122070 -- Name: custinfo_cust_salesrep_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122071 --
122072
122073 ALTER TABLE ONLY custinfo
122074     ADD CONSTRAINT custinfo_cust_salesrep_fkey FOREIGN KEY (cust_salesrep_id) REFERENCES salesrep(salesrep_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
122075
122076
122077 --
122078 -- TOC entry 7809 (class 2606 OID 146573219)
122079 -- Dependencies: 6984 282 213 8894
122080 -- Name: custinfo_cust_shipform_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122081 --
122082
122083 ALTER TABLE ONLY custinfo
122084     ADD CONSTRAINT custinfo_cust_shipform_fkey FOREIGN KEY (cust_shipform_id) REFERENCES shipform(shipform_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
122085
122086
122087 --
122088 -- TOC entry 7810 (class 2606 OID 146573224)
122089 -- Dependencies: 6878 220 213 8894
122090 -- Name: custinfo_cust_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122091 --
122092
122093 ALTER TABLE ONLY custinfo
122094     ADD CONSTRAINT custinfo_cust_taxzone_id_fkey FOREIGN KEY (cust_taxzone_id) REFERENCES taxzone(taxzone_id);
122095
122096
122097 --
122098 -- TOC entry 7811 (class 2606 OID 146573229)
122099 -- Dependencies: 6836 209 213 8894
122100 -- Name: custinfo_cust_terms_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122101 --
122102
122103 ALTER TABLE ONLY custinfo
122104     ADD CONSTRAINT custinfo_cust_terms_fkey FOREIGN KEY (cust_terms_id) REFERENCES terms(terms_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
122105
122106
122107 --
122108 -- TOC entry 7881 (class 2606 OID 146573234)
122109 -- Dependencies: 6816 204 292 8894
122110 -- Name: emp_emp_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122111 --
122112
122113 ALTER TABLE ONLY emp
122114     ADD CONSTRAINT emp_emp_cntct_id_fkey FOREIGN KEY (emp_cntct_id) REFERENCES cntct(cntct_id);
122115
122116
122117 --
122118 -- TOC entry 7882 (class 2606 OID 146573239)
122119 -- Dependencies: 6996 291 292 8894
122120 -- Name: emp_emp_dept_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122121 --
122122
122123 ALTER TABLE ONLY emp
122124     ADD CONSTRAINT emp_emp_dept_id_fkey FOREIGN KEY (emp_dept_id) REFERENCES dept(dept_id);
122125
122126
122127 --
122128 -- TOC entry 7883 (class 2606 OID 146573244)
122129 -- Dependencies: 6942 248 292 8894
122130 -- Name: emp_emp_image_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122131 --
122132
122133 ALTER TABLE ONLY emp
122134     ADD CONSTRAINT emp_emp_image_id_fkey FOREIGN KEY (emp_image_id) REFERENCES image(image_id);
122135
122136
122137 --
122138 -- TOC entry 7884 (class 2606 OID 146573249)
122139 -- Dependencies: 7002 292 292 8894
122140 -- Name: emp_emp_mgr_emp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122141 --
122142
122143 ALTER TABLE ONLY emp
122144     ADD CONSTRAINT emp_emp_mgr_emp_id_fkey FOREIGN KEY (emp_mgr_emp_id) REFERENCES emp(emp_id);
122145
122146
122147 --
122148 -- TOC entry 7885 (class 2606 OID 146573254)
122149 -- Dependencies: 7004 293 292 8894
122150 -- Name: emp_emp_shift_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122151 --
122152
122153 ALTER TABLE ONLY emp
122154     ADD CONSTRAINT emp_emp_shift_id_fkey FOREIGN KEY (emp_shift_id) REFERENCES shift(shift_id);
122155
122156
122157 --
122158 -- TOC entry 7886 (class 2606 OID 146573259)
122159 -- Dependencies: 6834 208 292 8894
122160 -- Name: emp_emp_wage_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122161 --
122162
122163 ALTER TABLE ONLY emp
122164     ADD CONSTRAINT emp_emp_wage_curr_id_fkey FOREIGN KEY (emp_wage_curr_id) REFERENCES curr_symbol(curr_id);
122165
122166
122167 --
122168 -- TOC entry 7887 (class 2606 OID 146573264)
122169 -- Dependencies: 6763 193 292 8894
122170 -- Name: emp_emp_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122171 --
122172
122173 ALTER TABLE ONLY emp
122174     ADD CONSTRAINT emp_emp_warehous_id_fkey FOREIGN KEY (emp_warehous_id) REFERENCES whsinfo(warehous_id);
122175
122176
122177 --
122178 -- TOC entry 8050 (class 2606 OID 146573269)
122179 -- Dependencies: 7002 292 565 8894
122180 -- Name: empgrpitem_empgrpitem_emp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122181 --
122182
122183 ALTER TABLE ONLY empgrpitem
122184     ADD CONSTRAINT empgrpitem_empgrpitem_emp_id_fkey FOREIGN KEY (empgrpitem_emp_id) REFERENCES emp(emp_id);
122185
122186
122187 --
122188 -- TOC entry 8051 (class 2606 OID 146573274)
122189 -- Dependencies: 7350 563 565 8894
122190 -- Name: empgrpitem_empgrpitem_empgrp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122191 --
122192
122193 ALTER TABLE ONLY empgrpitem
122194     ADD CONSTRAINT empgrpitem_empgrpitem_empgrp_id_fkey FOREIGN KEY (empgrpitem_empgrp_id) REFERENCES empgrp(empgrp_id);
122195
122196
122197 --
122198 -- TOC entry 8052 (class 2606 OID 146573279)
122199 -- Dependencies: 7373 579 588 8894
122200 -- Name: flnotes_flnotes_flhead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122201 --
122202
122203 ALTER TABLE ONLY flnotes
122204     ADD CONSTRAINT flnotes_flnotes_flhead_id_fkey FOREIGN KEY (flnotes_flhead_id) REFERENCES flhead(flhead_id) ON DELETE CASCADE;
122205
122206
122207 --
122208 -- TOC entry 8053 (class 2606 OID 146573284)
122209 -- Dependencies: 6959 264 588 8894
122210 -- Name: flnotes_flnotes_period_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122211 --
122212
122213 ALTER TABLE ONLY flnotes
122214     ADD CONSTRAINT flnotes_flnotes_period_id_fkey FOREIGN KEY (flnotes_period_id) REFERENCES period(period_id) ON DELETE CASCADE;
122215
122216
122217 --
122218 -- TOC entry 8054 (class 2606 OID 146573289)
122219 -- Dependencies: 7395 601 603 8894
122220 -- Name: grppriv_grppriv_grp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122221 --
122222
122223 ALTER TABLE ONLY grppriv
122224     ADD CONSTRAINT grppriv_grppriv_grp_id_fkey FOREIGN KEY (grppriv_grp_id) REFERENCES grp(grp_id);
122225
122226
122227 --
122228 -- TOC entry 7782 (class 2606 OID 146573294)
122229 -- Dependencies: 6849 212 206 8894
122230 -- Name: incdt_incdt_aropen_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122231 --
122232
122233 ALTER TABLE ONLY incdt
122234     ADD CONSTRAINT incdt_incdt_aropen_id_fkey FOREIGN KEY (incdt_aropen_id) REFERENCES aropen(aropen_id);
122235
122236
122237 --
122238 -- TOC entry 7783 (class 2606 OID 146573299)
122239 -- Dependencies: 6816 204 206 8894
122240 -- Name: incdt_incdt_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122241 --
122242
122243 ALTER TABLE ONLY incdt
122244     ADD CONSTRAINT incdt_incdt_cntct_id_fkey FOREIGN KEY (incdt_cntct_id) REFERENCES cntct(cntct_id);
122245
122246
122247 --
122248 -- TOC entry 7784 (class 2606 OID 146573304)
122249 -- Dependencies: 6820 205 206 8894
122250 -- Name: incdt_incdt_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122251 --
122252
122253 ALTER TABLE ONLY incdt
122254     ADD CONSTRAINT incdt_incdt_crmacct_id_fkey FOREIGN KEY (incdt_crmacct_id) REFERENCES crmacct(crmacct_id);
122255
122256
122257 --
122258 -- TOC entry 7785 (class 2606 OID 146573309)
122259 -- Dependencies: 7021 304 206 8894
122260 -- Name: incdt_incdt_incdtcat_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122261 --
122262
122263 ALTER TABLE ONLY incdt
122264     ADD CONSTRAINT incdt_incdt_incdtcat_id_fkey FOREIGN KEY (incdt_incdtcat_id) REFERENCES incdtcat(incdtcat_id);
122265
122266
122267 --
122268 -- TOC entry 7786 (class 2606 OID 146573314)
122269 -- Dependencies: 7025 305 206 8894
122270 -- Name: incdt_incdt_incdtpriority_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122271 --
122272
122273 ALTER TABLE ONLY incdt
122274     ADD CONSTRAINT incdt_incdt_incdtpriority_id_fkey FOREIGN KEY (incdt_incdtpriority_id) REFERENCES incdtpriority(incdtpriority_id);
122275
122276
122277 --
122278 -- TOC entry 7787 (class 2606 OID 146573319)
122279 -- Dependencies: 7029 306 206 8894
122280 -- Name: incdt_incdt_incdtresolution_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122281 --
122282
122283 ALTER TABLE ONLY incdt
122284     ADD CONSTRAINT incdt_incdt_incdtresolution_id_fkey FOREIGN KEY (incdt_incdtresolution_id) REFERENCES incdtresolution(incdtresolution_id);
122285
122286
122287 --
122288 -- TOC entry 7788 (class 2606 OID 146573324)
122289 -- Dependencies: 7033 307 206 8894
122290 -- Name: incdt_incdt_incdtseverity_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122291 --
122292
122293 ALTER TABLE ONLY incdt
122294     ADD CONSTRAINT incdt_incdt_incdtseverity_id_fkey FOREIGN KEY (incdt_incdtseverity_id) REFERENCES incdtseverity(incdtseverity_id);
122295
122296
122297 --
122298 -- TOC entry 7789 (class 2606 OID 146573329)
122299 -- Dependencies: 6751 191 206 8894
122300 -- Name: incdt_incdt_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122301 --
122302
122303 ALTER TABLE ONLY incdt
122304     ADD CONSTRAINT incdt_incdt_item_id_fkey FOREIGN KEY (incdt_item_id) REFERENCES item(item_id);
122305
122306
122307 --
122308 -- TOC entry 7790 (class 2606 OID 146573334)
122309 -- Dependencies: 6891 225 206 8894
122310 -- Name: incdt_incdt_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122311 --
122312
122313 ALTER TABLE ONLY incdt
122314     ADD CONSTRAINT incdt_incdt_prj_id_fkey FOREIGN KEY (incdt_prj_id) REFERENCES prj(prj_id);
122315
122316
122317 --
122318 -- TOC entry 7791 (class 2606 OID 146573339)
122319 -- Dependencies: 6824 206 206 8894
122320 -- Name: incdt_incdt_recurring_incdt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122321 --
122322
122323 ALTER TABLE ONLY incdt
122324     ADD CONSTRAINT incdt_incdt_recurring_incdt_id_fkey FOREIGN KEY (incdt_recurring_incdt_id) REFERENCES incdt(incdt_id);
122325
122326
122327 --
122328 -- TOC entry 8055 (class 2606 OID 146573344)
122329 -- Dependencies: 6824 206 609 8894
122330 -- Name: incdthist_incdthist_incdt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122331 --
122332
122333 ALTER TABLE ONLY incdthist
122334     ADD CONSTRAINT incdthist_incdthist_incdt_id_fkey FOREIGN KEY (incdthist_incdt_id) REFERENCES incdt(incdt_id);
122335
122336
122337 --
122338 -- TOC entry 7765 (class 2606 OID 146573349)
122339 -- Dependencies: 6758 192 202 8894
122340 -- Name: invbal_invbal_itemsite_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122341 --
122342
122343 ALTER TABLE ONLY invbal
122344     ADD CONSTRAINT invbal_invbal_itemsite_id_fkey FOREIGN KEY (invbal_itemsite_id) REFERENCES itemsite(itemsite_id) ON DELETE CASCADE;
122345
122346
122347 --
122348 -- TOC entry 7766 (class 2606 OID 146573354)
122349 -- Dependencies: 6959 264 202 8894
122350 -- Name: invbal_invbal_period_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122351 --
122352
122353 ALTER TABLE ONLY invbal
122354     ADD CONSTRAINT invbal_invbal_period_id_fkey FOREIGN KEY (invbal_period_id) REFERENCES period(period_id) ON DELETE CASCADE;
122355
122356
122357 --
122358 -- TOC entry 7834 (class 2606 OID 146573359)
122359 -- Dependencies: 6895 226 224 8894
122360 -- Name: invchead_invchead_saletype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122361 --
122362
122363 ALTER TABLE ONLY invchead
122364     ADD CONSTRAINT invchead_invchead_saletype_id_fkey FOREIGN KEY (invchead_saletype_id) REFERENCES saletype(saletype_id);
122365
122366
122367 --
122368 -- TOC entry 7835 (class 2606 OID 146573364)
122369 -- Dependencies: 6897 227 224 8894
122370 -- Name: invchead_invchead_shipzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122371 --
122372
122373 ALTER TABLE ONLY invchead
122374     ADD CONSTRAINT invchead_invchead_shipzone_id_fkey FOREIGN KEY (invchead_shipzone_id) REFERENCES shipzone(shipzone_id);
122375
122376
122377 --
122378 -- TOC entry 7836 (class 2606 OID 146573369)
122379 -- Dependencies: 6878 220 224 8894
122380 -- Name: invchead_invchead_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122381 --
122382
122383 ALTER TABLE ONLY invchead
122384     ADD CONSTRAINT invchead_invchead_taxzone_id_fkey FOREIGN KEY (invchead_taxzone_id) REFERENCES taxzone(taxzone_id);
122385
122386
122387 --
122388 -- TOC entry 7837 (class 2606 OID 146573374)
122389 -- Dependencies: 6834 208 224 8894
122390 -- Name: invchead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122391 --
122392
122393 ALTER TABLE ONLY invchead
122394     ADD CONSTRAINT invchead_to_curr_symbol FOREIGN KEY (invchead_curr_id) REFERENCES curr_symbol(curr_id);
122395
122396
122397 --
122398 -- TOC entry 8056 (class 2606 OID 146573379)
122399 -- Dependencies: 7124 363 617 8894
122400 -- Name: invcheadtax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122401 --
122402
122403 ALTER TABLE ONLY invcheadtax
122404     ADD CONSTRAINT invcheadtax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
122405
122406
122407 --
122408 -- TOC entry 8057 (class 2606 OID 146573384)
122409 -- Dependencies: 6889 224 617 8894
122410 -- Name: invcheadtax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122411 --
122412
122413 ALTER TABLE ONLY invcheadtax
122414     ADD CONSTRAINT invcheadtax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES invchead(invchead_id) ON DELETE CASCADE;
122415
122416
122417 --
122418 -- TOC entry 8058 (class 2606 OID 146573389)
122419 -- Dependencies: 7124 363 617 8894
122420 -- Name: invcheadtax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122421 --
122422
122423 ALTER TABLE ONLY invcheadtax
122424     ADD CONSTRAINT invcheadtax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
122425
122426
122427 --
122428 -- TOC entry 8059 (class 2606 OID 146573394)
122429 -- Dependencies: 6796 199 617 8894
122430 -- Name: invcheadtax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122431 --
122432
122433 ALTER TABLE ONLY invcheadtax
122434     ADD CONSTRAINT invcheadtax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
122435
122436
122437 --
122438 -- TOC entry 7842 (class 2606 OID 146573399)
122439 -- Dependencies: 6889 224 229 8894
122440 -- Name: invcitem_invchead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122441 --
122442
122443 ALTER TABLE ONLY invcitem
122444     ADD CONSTRAINT invcitem_invchead_id_fkey FOREIGN KEY (invcitem_invchead_id) REFERENCES invchead(invchead_id) ON UPDATE CASCADE ON DELETE CASCADE;
122445
122446
122447 --
122448 -- TOC entry 7843 (class 2606 OID 146573404)
122449 -- Dependencies: 6800 200 229 8894
122450 -- Name: invcitem_invcitem_price_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122451 --
122452
122453 ALTER TABLE ONLY invcitem
122454     ADD CONSTRAINT invcitem_invcitem_price_uom_id_fkey FOREIGN KEY (invcitem_price_uom_id) REFERENCES uom(uom_id);
122455
122456
122457 --
122458 -- TOC entry 7844 (class 2606 OID 146573409)
122459 -- Dependencies: 6800 200 229 8894
122460 -- Name: invcitem_invcitem_qty_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122461 --
122462
122463 ALTER TABLE ONLY invcitem
122464     ADD CONSTRAINT invcitem_invcitem_qty_uom_id_fkey FOREIGN KEY (invcitem_qty_uom_id) REFERENCES uom(uom_id);
122465
122466
122467 --
122468 -- TOC entry 7845 (class 2606 OID 146573414)
122469 -- Dependencies: 6954 262 229 8894
122470 -- Name: invcitem_invcitem_rev_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122471 --
122472
122473 ALTER TABLE ONLY invcitem
122474     ADD CONSTRAINT invcitem_invcitem_rev_accnt_id_fkey FOREIGN KEY (invcitem_rev_accnt_id) REFERENCES accnt(accnt_id);
122475
122476
122477 --
122478 -- TOC entry 7846 (class 2606 OID 146573419)
122479 -- Dependencies: 6796 199 229 8894
122480 -- Name: invcitem_invcitem_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122481 --
122482
122483 ALTER TABLE ONLY invcitem
122484     ADD CONSTRAINT invcitem_invcitem_taxtype_id_fkey FOREIGN KEY (invcitem_taxtype_id) REFERENCES taxtype(taxtype_id);
122485
122486
122487 --
122488 -- TOC entry 8060 (class 2606 OID 146573424)
122489 -- Dependencies: 7124 363 619 8894
122490 -- Name: invcitemtax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122491 --
122492
122493 ALTER TABLE ONLY invcitemtax
122494     ADD CONSTRAINT invcitemtax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
122495
122496
122497 --
122498 -- TOC entry 8061 (class 2606 OID 146573429)
122499 -- Dependencies: 6905 229 619 8894
122500 -- Name: invcitemtax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122501 --
122502
122503 ALTER TABLE ONLY invcitemtax
122504     ADD CONSTRAINT invcitemtax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES invcitem(invcitem_id) ON DELETE CASCADE;
122505
122506
122507 --
122508 -- TOC entry 8062 (class 2606 OID 146573434)
122509 -- Dependencies: 7124 363 619 8894
122510 -- Name: invcitemtax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122511 --
122512
122513 ALTER TABLE ONLY invcitemtax
122514     ADD CONSTRAINT invcitemtax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
122515
122516
122517 --
122518 -- TOC entry 8063 (class 2606 OID 146573439)
122519 -- Dependencies: 6796 199 619 8894
122520 -- Name: invcitemtax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122521 --
122522
122523 ALTER TABLE ONLY invcitemtax
122524     ADD CONSTRAINT invcitemtax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
122525
122526
122527 --
122528 -- TOC entry 8064 (class 2606 OID 146573444)
122529 -- Dependencies: 7118 358 625 8894
122530 -- Name: invhistexpcat_invhistexpcat_expcat_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122531 --
122532
122533 ALTER TABLE ONLY invhistexpcat
122534     ADD CONSTRAINT invhistexpcat_invhistexpcat_expcat_id_fkey FOREIGN KEY (invhistexpcat_expcat_id) REFERENCES expcat(expcat_id) ON UPDATE CASCADE ON DELETE CASCADE;
122535
122536
122537 --
122538 -- TOC entry 8065 (class 2606 OID 146573449)
122539 -- Dependencies: 7417 623 625 8894
122540 -- Name: invhistexpcat_invhistexpcat_invhist_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122541 --
122542
122543 ALTER TABLE ONLY invhistexpcat
122544     ADD CONSTRAINT invhistexpcat_invhistexpcat_invhist_id_fkey FOREIGN KEY (invhistexpcat_invhist_id) REFERENCES invhist(invhist_id) ON UPDATE CASCADE ON DELETE CASCADE;
122545
122546
122547 --
122548 -- TOC entry 7916 (class 2606 OID 146573454)
122549 -- Dependencies: 7017 301 347 8894
122550 -- Name: ipsass_ipsass_ipshead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122551 --
122552
122553 ALTER TABLE ONLY ipsass
122554     ADD CONSTRAINT ipsass_ipsass_ipshead_id_fkey FOREIGN KEY (ipsass_ipshead_id) REFERENCES ipshead(ipshead_id);
122555
122556
122557 --
122558 -- TOC entry 7891 (class 2606 OID 146573459)
122559 -- Dependencies: 7011 299 300 8894
122560 -- Name: ipsfreight_ipsfreight_freightclass_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122561 --
122562
122563 ALTER TABLE ONLY ipsfreight
122564     ADD CONSTRAINT ipsfreight_ipsfreight_freightclass_id_fkey FOREIGN KEY (ipsfreight_freightclass_id) REFERENCES freightclass(freightclass_id);
122565
122566
122567 --
122568 -- TOC entry 7892 (class 2606 OID 146573464)
122569 -- Dependencies: 7017 301 300 8894
122570 -- Name: ipsfreight_ipsfreight_ipshead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122571 --
122572
122573 ALTER TABLE ONLY ipsfreight
122574     ADD CONSTRAINT ipsfreight_ipsfreight_ipshead_id_fkey FOREIGN KEY (ipsfreight_ipshead_id) REFERENCES ipshead(ipshead_id);
122575
122576
122577 --
122578 -- TOC entry 7893 (class 2606 OID 146573469)
122579 -- Dependencies: 6897 227 300 8894
122580 -- Name: ipsfreight_ipsfreight_shipzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122581 --
122582
122583 ALTER TABLE ONLY ipsfreight
122584     ADD CONSTRAINT ipsfreight_ipsfreight_shipzone_id_fkey FOREIGN KEY (ipsfreight_shipzone_id) REFERENCES shipzone(shipzone_id);
122585
122586
122587 --
122588 -- TOC entry 7894 (class 2606 OID 146573474)
122589 -- Dependencies: 6763 193 300 8894
122590 -- Name: ipsfreight_ipsfreight_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122591 --
122592
122593 ALTER TABLE ONLY ipsfreight
122594     ADD CONSTRAINT ipsfreight_ipsfreight_warehous_id_fkey FOREIGN KEY (ipsfreight_warehous_id) REFERENCES whsinfo(warehous_id);
122595
122596
122597 --
122598 -- TOC entry 7895 (class 2606 OID 146573479)
122599 -- Dependencies: 6834 208 301 8894
122600 -- Name: ipshead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122601 --
122602
122603 ALTER TABLE ONLY ipshead
122604     ADD CONSTRAINT ipshead_to_curr_symbol FOREIGN KEY (ipshead_curr_id) REFERENCES curr_symbol(curr_id);
122605
122606
122607 --
122608 -- TOC entry 7917 (class 2606 OID 146573484)
122609 -- Dependencies: 7017 301 349 8894
122610 -- Name: ipsitem_ipshead_id_fk; Type: FK CONSTRAINT; Schema: public; Owner: admin
122611 --
122612
122613 ALTER TABLE ONLY ipsiteminfo
122614     ADD CONSTRAINT ipsitem_ipshead_id_fk FOREIGN KEY (ipsitem_ipshead_id) REFERENCES ipshead(ipshead_id) ON DELETE CASCADE;
122615
122616
122617 --
122618 -- TOC entry 7918 (class 2606 OID 146573489)
122619 -- Dependencies: 6800 200 349 8894
122620 -- Name: ipsitem_ipsitem_price_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122621 --
122622
122623 ALTER TABLE ONLY ipsiteminfo
122624     ADD CONSTRAINT ipsitem_ipsitem_price_uom_id_fkey FOREIGN KEY (ipsitem_price_uom_id) REFERENCES uom(uom_id);
122625
122626
122627 --
122628 -- TOC entry 7919 (class 2606 OID 146573494)
122629 -- Dependencies: 6800 200 349 8894
122630 -- Name: ipsitem_ipsitem_qty_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122631 --
122632
122633 ALTER TABLE ONLY ipsiteminfo
122634     ADD CONSTRAINT ipsitem_ipsitem_qty_uom_id_fkey FOREIGN KEY (ipsitem_qty_uom_id) REFERENCES uom(uom_id);
122635
122636
122637 --
122638 -- TOC entry 7920 (class 2606 OID 146573499)
122639 -- Dependencies: 6763 193 349 8894
122640 -- Name: ipsitem_ipsitem_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122641 --
122642
122643 ALTER TABLE ONLY ipsiteminfo
122644     ADD CONSTRAINT ipsitem_ipsitem_warehous_id_fkey FOREIGN KEY (ipsitem_warehous_id) REFERENCES whsinfo(warehous_id);
122645
122646
122647 --
122648 -- TOC entry 7921 (class 2606 OID 146573504)
122649 -- Dependencies: 6751 191 349 8894
122650 -- Name: ipsitem_item_id_fk; Type: FK CONSTRAINT; Schema: public; Owner: admin
122651 --
122652
122653 ALTER TABLE ONLY ipsiteminfo
122654     ADD CONSTRAINT ipsitem_item_id_fk FOREIGN KEY (ipsitem_item_id) REFERENCES item(item_id);
122655
122656
122657 --
122658 -- TOC entry 7922 (class 2606 OID 146573509)
122659 -- Dependencies: 6924 236 351 8894
122660 -- Name: ipsitemchar_ipsitemchar_char_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122661 --
122662
122663 ALTER TABLE ONLY ipsitemchar
122664     ADD CONSTRAINT ipsitemchar_ipsitemchar_char_id_fkey FOREIGN KEY (ipsitemchar_char_id) REFERENCES "char"(char_id);
122665
122666
122667 --
122668 -- TOC entry 7923 (class 2606 OID 146573514)
122669 -- Dependencies: 7104 349 351 8894
122670 -- Name: ipsitemchar_ipsitemchar_ipsitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122671 --
122672
122673 ALTER TABLE ONLY ipsitemchar
122674     ADD CONSTRAINT ipsitemchar_ipsitemchar_ipsitem_id_fkey FOREIGN KEY (ipsitemchar_ipsitem_id) REFERENCES ipsiteminfo(ipsitem_id) ON DELETE CASCADE;
122675
122676
122677 --
122678 -- TOC entry 7709 (class 2606 OID 146573519)
122679 -- Dependencies: 7037 313 191 8894
122680 -- Name: item_item_classcode_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122681 --
122682
122683 ALTER TABLE ONLY item
122684     ADD CONSTRAINT item_item_classcode_id_fkey FOREIGN KEY (item_classcode_id) REFERENCES classcode(classcode_id);
122685
122686
122687 --
122688 -- TOC entry 7710 (class 2606 OID 146573524)
122689 -- Dependencies: 7011 299 191 8894
122690 -- Name: item_item_freightclass_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122691 --
122692
122693 ALTER TABLE ONLY item
122694     ADD CONSTRAINT item_item_freightclass_id_fkey FOREIGN KEY (item_freightclass_id) REFERENCES freightclass(freightclass_id);
122695
122696
122697 --
122698 -- TOC entry 7711 (class 2606 OID 146573529)
122699 -- Dependencies: 6800 200 191 8894
122700 -- Name: item_item_inv_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122701 --
122702
122703 ALTER TABLE ONLY item
122704     ADD CONSTRAINT item_item_inv_uom_id_fkey FOREIGN KEY (item_inv_uom_id) REFERENCES uom(uom_id);
122705
122706
122707 --
122708 -- TOC entry 7712 (class 2606 OID 146573534)
122709 -- Dependencies: 6800 200 191 8894
122710 -- Name: item_item_price_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122711 --
122712
122713 ALTER TABLE ONLY item
122714     ADD CONSTRAINT item_item_price_uom_id_fkey FOREIGN KEY (item_price_uom_id) REFERENCES uom(uom_id);
122715
122716
122717 --
122718 -- TOC entry 7896 (class 2606 OID 146573539)
122719 -- Dependencies: 6820 205 316 8894
122720 -- Name: itemalias_itemalias_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122721 --
122722
122723 ALTER TABLE ONLY itemalias
122724     ADD CONSTRAINT itemalias_itemalias_crmacct_id_fkey FOREIGN KEY (itemalias_crmacct_id) REFERENCES crmacct(crmacct_id);
122725
122726
122727 --
122728 -- TOC entry 7897 (class 2606 OID 146573544)
122729 -- Dependencies: 6751 191 316 8894
122730 -- Name: itemalias_itemalias_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122731 --
122732
122733 ALTER TABLE ONLY itemalias
122734     ADD CONSTRAINT itemalias_itemalias_item_id_fkey FOREIGN KEY (itemalias_item_id) REFERENCES item(item_id);
122735
122736
122737 --
122738 -- TOC entry 7898 (class 2606 OID 146573549)
122739 -- Dependencies: 7049 320 321 8894
122740 -- Name: itemcost_itemcost_costelem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122741 --
122742
122743 ALTER TABLE ONLY itemcost
122744     ADD CONSTRAINT itemcost_itemcost_costelem_id_fkey FOREIGN KEY (itemcost_costelem_id) REFERENCES costelem(costelem_id);
122745
122746
122747 --
122748 -- TOC entry 7899 (class 2606 OID 146573554)
122749 -- Dependencies: 6834 208 321 8894
122750 -- Name: itemcost_itemcost_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122751 --
122752
122753 ALTER TABLE ONLY itemcost
122754     ADD CONSTRAINT itemcost_itemcost_curr_id_fkey FOREIGN KEY (itemcost_curr_id) REFERENCES curr_symbol(curr_id);
122755
122756
122757 --
122758 -- TOC entry 7900 (class 2606 OID 146573559)
122759 -- Dependencies: 6751 191 321 8894
122760 -- Name: itemcost_itemcost_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122761 --
122762
122763 ALTER TABLE ONLY itemcost
122764     ADD CONSTRAINT itemcost_itemcost_item_id_fkey FOREIGN KEY (itemcost_item_id) REFERENCES item(item_id);
122765
122766
122767 --
122768 -- TOC entry 7901 (class 2606 OID 146573564)
122769 -- Dependencies: 6834 208 321 8894
122770 -- Name: itemcost_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122771 --
122772
122773 ALTER TABLE ONLY itemcost
122774     ADD CONSTRAINT itemcost_to_curr_symbol FOREIGN KEY (itemcost_curr_id) REFERENCES curr_symbol(curr_id);
122775
122776
122777 --
122778 -- TOC entry 7713 (class 2606 OID 146573569)
122779 -- Dependencies: 7057 325 192 8894
122780 -- Name: itemsite_itemsite_costcat_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122781 --
122782
122783 ALTER TABLE ONLY itemsite
122784     ADD CONSTRAINT itemsite_itemsite_costcat_id_fkey FOREIGN KEY (itemsite_costcat_id) REFERENCES costcat(costcat_id);
122785
122786
122787 --
122788 -- TOC entry 7714 (class 2606 OID 146573574)
122789 -- Dependencies: 6751 191 192 8894
122790 -- Name: itemsite_itemsite_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122791 --
122792
122793 ALTER TABLE ONLY itemsite
122794     ADD CONSTRAINT itemsite_itemsite_item_id_fkey FOREIGN KEY (itemsite_item_id) REFERENCES item(item_id);
122795
122796
122797 --
122798 -- TOC entry 7715 (class 2606 OID 146573579)
122799 -- Dependencies: 7059 326 192 8894
122800 -- Name: itemsite_itemsite_plancode_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122801 --
122802
122803 ALTER TABLE ONLY itemsite
122804     ADD CONSTRAINT itemsite_itemsite_plancode_id_fkey FOREIGN KEY (itemsite_plancode_id) REFERENCES plancode(plancode_id);
122805
122806
122807 --
122808 -- TOC entry 7716 (class 2606 OID 146573584)
122809 -- Dependencies: 6763 193 192 8894
122810 -- Name: itemsite_itemsite_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122811 --
122812
122813 ALTER TABLE ONLY itemsite
122814     ADD CONSTRAINT itemsite_itemsite_warehous_id_fkey FOREIGN KEY (itemsite_warehous_id) REFERENCES whsinfo(warehous_id);
122815
122816
122817 --
122818 -- TOC entry 7903 (class 2606 OID 146573589)
122819 -- Dependencies: 7064 329 330 8894
122820 -- Name: itemsrc_itemsrc_contrct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122821 --
122822
122823 ALTER TABLE ONLY itemsrc
122824     ADD CONSTRAINT itemsrc_itemsrc_contrct_id_fkey FOREIGN KEY (itemsrc_contrct_id) REFERENCES contrct(contrct_id);
122825
122826
122827 --
122828 -- TOC entry 7904 (class 2606 OID 146573594)
122829 -- Dependencies: 6751 191 330 8894
122830 -- Name: itemsrc_itemsrc_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122831 --
122832
122833 ALTER TABLE ONLY itemsrc
122834     ADD CONSTRAINT itemsrc_itemsrc_item_id_fkey FOREIGN KEY (itemsrc_item_id) REFERENCES item(item_id) ON DELETE CASCADE;
122835
122836
122837 --
122838 -- TOC entry 7905 (class 2606 OID 146573599)
122839 -- Dependencies: 6841 210 330 8894
122840 -- Name: itemsrc_itemsrc_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122841 --
122842
122843 ALTER TABLE ONLY itemsrc
122844     ADD CONSTRAINT itemsrc_itemsrc_vend_id_fkey FOREIGN KEY (itemsrc_vend_id) REFERENCES vendinfo(vend_id) ON DELETE CASCADE;
122845
122846
122847 --
122848 -- TOC entry 7906 (class 2606 OID 146573604)
122849 -- Dependencies: 7068 330 332 8894
122850 -- Name: itemsrcp_itemsrcp_itemsrc_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122851 --
122852
122853 ALTER TABLE ONLY itemsrcp
122854     ADD CONSTRAINT itemsrcp_itemsrcp_itemsrc_id_fkey FOREIGN KEY (itemsrcp_itemsrc_id) REFERENCES itemsrc(itemsrc_id) ON DELETE CASCADE;
122855
122856
122857 --
122858 -- TOC entry 7907 (class 2606 OID 146573609)
122859 -- Dependencies: 6834 208 332 8894
122860 -- Name: itemsrcp_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
122861 --
122862
122863 ALTER TABLE ONLY itemsrcp
122864     ADD CONSTRAINT itemsrcp_to_curr_symbol FOREIGN KEY (itemsrcp_curr_id) REFERENCES curr_symbol(curr_id);
122865
122866
122867 --
122868 -- TOC entry 7908 (class 2606 OID 146573614)
122869 -- Dependencies: 6751 191 334 8894
122870 -- Name: itemsub_itemsub_parent_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122871 --
122872
122873 ALTER TABLE ONLY itemsub
122874     ADD CONSTRAINT itemsub_itemsub_parent_item_id_fkey FOREIGN KEY (itemsub_parent_item_id) REFERENCES item(item_id);
122875
122876
122877 --
122878 -- TOC entry 7909 (class 2606 OID 146573619)
122879 -- Dependencies: 6751 191 334 8894
122880 -- Name: itemsub_itemsub_sub_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122881 --
122882
122883 ALTER TABLE ONLY itemsub
122884     ADD CONSTRAINT itemsub_itemsub_sub_item_id_fkey FOREIGN KEY (itemsub_sub_item_id) REFERENCES item(item_id);
122885
122886
122887 --
122888 -- TOC entry 7910 (class 2606 OID 146573624)
122889 -- Dependencies: 6751 191 336 8894
122890 -- Name: itemtax_itemtax_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122891 --
122892
122893 ALTER TABLE ONLY itemtax
122894     ADD CONSTRAINT itemtax_itemtax_item_id_fkey FOREIGN KEY (itemtax_item_id) REFERENCES item(item_id);
122895
122896
122897 --
122898 -- TOC entry 7911 (class 2606 OID 146573629)
122899 -- Dependencies: 6796 199 336 8894
122900 -- Name: itemtax_itemtax_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122901 --
122902
122903 ALTER TABLE ONLY itemtax
122904     ADD CONSTRAINT itemtax_itemtax_taxtype_id_fkey FOREIGN KEY (itemtax_taxtype_id) REFERENCES taxtype(taxtype_id);
122905
122906
122907 --
122908 -- TOC entry 7912 (class 2606 OID 146573634)
122909 -- Dependencies: 6878 220 336 8894
122910 -- Name: itemtax_itemtax_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122911 --
122912
122913 ALTER TABLE ONLY itemtax
122914     ADD CONSTRAINT itemtax_itemtax_taxzone_id_fkey FOREIGN KEY (itemtax_taxzone_id) REFERENCES taxzone(taxzone_id);
122915
122916
122917 --
122918 -- TOC entry 8066 (class 2606 OID 146573639)
122919 -- Dependencies: 6751 191 662 8894
122920 -- Name: itemtrans_itemtrans_source_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122921 --
122922
122923 ALTER TABLE ONLY itemtrans
122924     ADD CONSTRAINT itemtrans_itemtrans_source_item_id_fkey FOREIGN KEY (itemtrans_source_item_id) REFERENCES item(item_id);
122925
122926
122927 --
122928 -- TOC entry 8067 (class 2606 OID 146573644)
122929 -- Dependencies: 6751 191 662 8894
122930 -- Name: itemtrans_itemtrans_target_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122931 --
122932
122933 ALTER TABLE ONLY itemtrans
122934     ADD CONSTRAINT itemtrans_itemtrans_target_item_id_fkey FOREIGN KEY (itemtrans_target_item_id) REFERENCES item(item_id);
122935
122936
122937 --
122938 -- TOC entry 8068 (class 2606 OID 146573649)
122939 -- Dependencies: 7084 338 664 8894
122940 -- Name: itemuom_itemuom_itemuomconv_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122941 --
122942
122943 ALTER TABLE ONLY itemuom
122944     ADD CONSTRAINT itemuom_itemuom_itemuomconv_id_fkey FOREIGN KEY (itemuom_itemuomconv_id) REFERENCES itemuomconv(itemuomconv_id);
122945
122946
122947 --
122948 -- TOC entry 8069 (class 2606 OID 146573654)
122949 -- Dependencies: 7629 822 664 8894
122950 -- Name: itemuom_itemuom_uomtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122951 --
122952
122953 ALTER TABLE ONLY itemuom
122954     ADD CONSTRAINT itemuom_itemuom_uomtype_id_fkey FOREIGN KEY (itemuom_uomtype_id) REFERENCES uomtype(uomtype_id);
122955
122956
122957 --
122958 -- TOC entry 7913 (class 2606 OID 146573659)
122959 -- Dependencies: 6800 200 338 8894
122960 -- Name: itemuomconv_itemuomconv_from_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122961 --
122962
122963 ALTER TABLE ONLY itemuomconv
122964     ADD CONSTRAINT itemuomconv_itemuomconv_from_uom_id_fkey FOREIGN KEY (itemuomconv_from_uom_id) REFERENCES uom(uom_id);
122965
122966
122967 --
122968 -- TOC entry 7914 (class 2606 OID 146573664)
122969 -- Dependencies: 6751 191 338 8894
122970 -- Name: itemuomconv_itemuomconv_item_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122971 --
122972
122973 ALTER TABLE ONLY itemuomconv
122974     ADD CONSTRAINT itemuomconv_itemuomconv_item_id_fkey FOREIGN KEY (itemuomconv_item_id) REFERENCES item(item_id);
122975
122976
122977 --
122978 -- TOC entry 7915 (class 2606 OID 146573669)
122979 -- Dependencies: 6800 200 338 8894
122980 -- Name: itemuomconv_itemuomconv_to_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122981 --
122982
122983 ALTER TABLE ONLY itemuomconv
122984     ADD CONSTRAINT itemuomconv_itemuomconv_to_uom_id_fkey FOREIGN KEY (itemuomconv_to_uom_id) REFERENCES uom(uom_id);
122985
122986
122987 --
122988 -- TOC entry 8070 (class 2606 OID 146573674)
122989 -- Dependencies: 6816 204 687 8894
122990 -- Name: mrghist_mrghist_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
122991 --
122992
122993 ALTER TABLE ONLY mrghist
122994     ADD CONSTRAINT mrghist_mrghist_cntct_id_fkey FOREIGN KEY (mrghist_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
122995
122996
122997 --
122998 -- TOC entry 7847 (class 2606 OID 146573679)
122999 -- Dependencies: 6816 204 231 8894
123000 -- Name: ophead_ophead_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123001 --
123002
123003 ALTER TABLE ONLY ophead
123004     ADD CONSTRAINT ophead_ophead_cntct_id_fkey FOREIGN KEY (ophead_cntct_id) REFERENCES cntct(cntct_id);
123005
123006
123007 --
123008 -- TOC entry 7848 (class 2606 OID 146573684)
123009 -- Dependencies: 6820 205 231 8894
123010 -- Name: ophead_ophead_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123011 --
123012
123013 ALTER TABLE ONLY ophead
123014     ADD CONSTRAINT ophead_ophead_crmacct_id_fkey FOREIGN KEY (ophead_crmacct_id) REFERENCES crmacct(crmacct_id);
123015
123016
123017 --
123018 -- TOC entry 7849 (class 2606 OID 146573689)
123019 -- Dependencies: 7486 696 231 8894
123020 -- Name: ophead_ophead_opsource_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123021 --
123022
123023 ALTER TABLE ONLY ophead
123024     ADD CONSTRAINT ophead_ophead_opsource_id_fkey FOREIGN KEY (ophead_opsource_id) REFERENCES opsource(opsource_id);
123025
123026
123027 --
123028 -- TOC entry 7850 (class 2606 OID 146573694)
123029 -- Dependencies: 7490 698 231 8894
123030 -- Name: ophead_ophead_opstage_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123031 --
123032
123033 ALTER TABLE ONLY ophead
123034     ADD CONSTRAINT ophead_ophead_opstage_id_fkey FOREIGN KEY (ophead_opstage_id) REFERENCES opstage(opstage_id);
123035
123036
123037 --
123038 -- TOC entry 7851 (class 2606 OID 146573699)
123039 -- Dependencies: 7494 700 231 8894
123040 -- Name: ophead_ophead_optype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123041 --
123042
123043 ALTER TABLE ONLY ophead
123044     ADD CONSTRAINT ophead_ophead_optype_id_fkey FOREIGN KEY (ophead_optype_id) REFERENCES optype(optype_id);
123045
123046
123047 --
123048 -- TOC entry 7852 (class 2606 OID 146573704)
123049 -- Dependencies: 7025 305 231 8894
123050 -- Name: ophead_ophead_priority_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123051 --
123052
123053 ALTER TABLE ONLY ophead
123054     ADD CONSTRAINT ophead_ophead_priority_id_fkey FOREIGN KEY (ophead_priority_id) REFERENCES incdtpriority(incdtpriority_id);
123055
123056
123057 --
123058 -- TOC entry 8071 (class 2606 OID 146573709)
123059 -- Dependencies: 7303 526 706 8894
123060 -- Name: pack_pack_shiphead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123061 --
123062
123063 ALTER TABLE ONLY pack
123064     ADD CONSTRAINT pack_pack_shiphead_id_fkey FOREIGN KEY (pack_shiphead_id) REFERENCES shiphead(shiphead_id);
123065
123066
123067 --
123068 -- TOC entry 8072 (class 2606 OID 146573714)
123069 -- Dependencies: 7266 486 709 8894
123070 -- Name: payco_payco_ccpay_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123071 --
123072
123073 ALTER TABLE ONLY payco
123074     ADD CONSTRAINT payco_payco_ccpay_id_fkey FOREIGN KEY (payco_ccpay_id) REFERENCES ccpay(ccpay_id);
123075
123076
123077 --
123078 -- TOC entry 8073 (class 2606 OID 146573719)
123079 -- Dependencies: 6773 195 709 8894
123080 -- Name: payco_payco_cohead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123081 --
123082
123083 ALTER TABLE ONLY payco
123084     ADD CONSTRAINT payco_payco_cohead_id_fkey FOREIGN KEY (payco_cohead_id) REFERENCES cohead(cohead_id);
123085
123086
123087 --
123088 -- TOC entry 8074 (class 2606 OID 146573724)
123089 -- Dependencies: 7510 713 711 8894
123090 -- Name: pkgdep_pkgdep_parent_pkghead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123091 --
123092
123093 ALTER TABLE ONLY pkgdep
123094     ADD CONSTRAINT pkgdep_pkgdep_parent_pkghead_id_fkey FOREIGN KEY (pkgdep_parent_pkghead_id) REFERENCES pkghead(pkghead_id);
123095
123096
123097 --
123098 -- TOC entry 8075 (class 2606 OID 146573729)
123099 -- Dependencies: 7510 713 711 8894
123100 -- Name: pkgdep_pkgdep_pkghead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123101 --
123102
123103 ALTER TABLE ONLY pkgdep
123104     ADD CONSTRAINT pkgdep_pkgdep_pkghead_id_fkey FOREIGN KEY (pkgdep_pkghead_id) REFERENCES pkghead(pkghead_id);
123105
123106
123107 --
123108 -- TOC entry 8076 (class 2606 OID 146573734)
123109 -- Dependencies: 7510 713 715 8894
123110 -- Name: pkgitem_pkgitem_pkghead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123111 --
123112
123113 ALTER TABLE ONLY pkgitem
123114     ADD CONSTRAINT pkgitem_pkgitem_pkghead_id_fkey FOREIGN KEY (pkgitem_pkghead_id) REFERENCES pkghead(pkghead_id) ON DELETE CASCADE;
123115
123116
123117 --
123118 -- TOC entry 7749 (class 2606 OID 146573739)
123119 -- Dependencies: 6773 195 197 8894
123120 -- Name: pohead_pohead_cohead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123121 --
123122
123123 ALTER TABLE ONLY pohead
123124     ADD CONSTRAINT pohead_pohead_cohead_id_fkey FOREIGN KEY (pohead_cohead_id) REFERENCES cohead(cohead_id) ON DELETE SET NULL;
123125
123126
123127 --
123128 -- TOC entry 7750 (class 2606 OID 146573744)
123129 -- Dependencies: 6816 204 197 8894
123130 -- Name: pohead_pohead_shipto_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123131 --
123132
123133 ALTER TABLE ONLY pohead
123134     ADD CONSTRAINT pohead_pohead_shipto_cntct_id_fkey FOREIGN KEY (pohead_shipto_cntct_id) REFERENCES cntct(cntct_id);
123135
123136
123137 --
123138 -- TOC entry 7751 (class 2606 OID 146573749)
123139 -- Dependencies: 6920 234 197 8894
123140 -- Name: pohead_pohead_shiptoddress_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123141 --
123142
123143 ALTER TABLE ONLY pohead
123144     ADD CONSTRAINT pohead_pohead_shiptoddress_id_fkey FOREIGN KEY (pohead_shiptoaddress_id) REFERENCES addr(addr_id);
123145
123146
123147 --
123148 -- TOC entry 7752 (class 2606 OID 146573754)
123149 -- Dependencies: 6796 199 197 8894
123150 -- Name: pohead_pohead_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123151 --
123152
123153 ALTER TABLE ONLY pohead
123154     ADD CONSTRAINT pohead_pohead_taxtype_id_fkey FOREIGN KEY (pohead_taxtype_id) REFERENCES taxtype(taxtype_id);
123155
123156
123157 --
123158 -- TOC entry 7753 (class 2606 OID 146573759)
123159 -- Dependencies: 6878 220 197 8894
123160 -- Name: pohead_pohead_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123161 --
123162
123163 ALTER TABLE ONLY pohead
123164     ADD CONSTRAINT pohead_pohead_taxzone_id_fkey FOREIGN KEY (pohead_taxzone_id) REFERENCES taxzone(taxzone_id);
123165
123166
123167 --
123168 -- TOC entry 7754 (class 2606 OID 146573764)
123169 -- Dependencies: 6836 209 197 8894
123170 -- Name: pohead_pohead_terms_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123171 --
123172
123173 ALTER TABLE ONLY pohead
123174     ADD CONSTRAINT pohead_pohead_terms_id_fkey FOREIGN KEY (pohead_terms_id) REFERENCES terms(terms_id);
123175
123176
123177 --
123178 -- TOC entry 7755 (class 2606 OID 146573769)
123179 -- Dependencies: 6816 204 197 8894
123180 -- Name: pohead_pohead_vend_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123181 --
123182
123183 ALTER TABLE ONLY pohead
123184     ADD CONSTRAINT pohead_pohead_vend_cntct_id_fkey FOREIGN KEY (pohead_vend_cntct_id) REFERENCES cntct(cntct_id);
123185
123186
123187 --
123188 -- TOC entry 7756 (class 2606 OID 146573774)
123189 -- Dependencies: 6841 210 197 8894
123190 -- Name: pohead_pohead_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123191 --
123192
123193 ALTER TABLE ONLY pohead
123194     ADD CONSTRAINT pohead_pohead_vend_id_fkey FOREIGN KEY (pohead_vend_id) REFERENCES vendinfo(vend_id);
123195
123196
123197 --
123198 -- TOC entry 7757 (class 2606 OID 146573779)
123199 -- Dependencies: 7126 364 197 8894
123200 -- Name: pohead_pohead_vendaddr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123201 --
123202
123203 ALTER TABLE ONLY pohead
123204     ADD CONSTRAINT pohead_pohead_vendaddr_id_fkey FOREIGN KEY (pohead_vendaddr_id) REFERENCES vendaddrinfo(vendaddr_id);
123205
123206
123207 --
123208 -- TOC entry 7758 (class 2606 OID 146573784)
123209 -- Dependencies: 6763 193 197 8894
123210 -- Name: pohead_pohead_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123211 --
123212
123213 ALTER TABLE ONLY pohead
123214     ADD CONSTRAINT pohead_pohead_warehous_id_fkey FOREIGN KEY (pohead_warehous_id) REFERENCES whsinfo(warehous_id);
123215
123216
123217 --
123218 -- TOC entry 7759 (class 2606 OID 146573789)
123219 -- Dependencies: 6834 208 197 8894
123220 -- Name: pohead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
123221 --
123222
123223 ALTER TABLE ONLY pohead
123224     ADD CONSTRAINT pohead_to_curr_symbol FOREIGN KEY (pohead_curr_id) REFERENCES curr_symbol(curr_id);
123225
123226
123227 --
123228 -- TOC entry 7760 (class 2606 OID 146573794)
123229 -- Dependencies: 7118 358 198 8894
123230 -- Name: poitem_poitem_expcat_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123231 --
123232
123233 ALTER TABLE ONLY poitem
123234     ADD CONSTRAINT poitem_poitem_expcat_id_fkey FOREIGN KEY (poitem_expcat_id) REFERENCES expcat(expcat_id);
123235
123236
123237 --
123238 -- TOC entry 7761 (class 2606 OID 146573799)
123239 -- Dependencies: 6758 192 198 8894
123240 -- Name: poitem_poitem_itemsite_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123241 --
123242
123243 ALTER TABLE ONLY poitem
123244     ADD CONSTRAINT poitem_poitem_itemsite_id_fkey FOREIGN KEY (poitem_itemsite_id) REFERENCES itemsite(itemsite_id);
123245
123246
123247 --
123248 -- TOC entry 7762 (class 2606 OID 146573804)
123249 -- Dependencies: 7068 330 198 8894
123250 -- Name: poitem_poitem_itemsrc_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123251 --
123252
123253 ALTER TABLE ONLY poitem
123254     ADD CONSTRAINT poitem_poitem_itemsrc_id_fkey FOREIGN KEY (poitem_itemsrc_id) REFERENCES itemsrc(itemsrc_id);
123255
123256
123257 --
123258 -- TOC entry 7763 (class 2606 OID 146573809)
123259 -- Dependencies: 6891 225 198 8894
123260 -- Name: poitem_poitem_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123261 --
123262
123263 ALTER TABLE ONLY poitem
123264     ADD CONSTRAINT poitem_poitem_prj_id_fkey FOREIGN KEY (poitem_prj_id) REFERENCES prj(prj_id);
123265
123266
123267 --
123268 -- TOC entry 7764 (class 2606 OID 146573814)
123269 -- Dependencies: 6796 199 198 8894
123270 -- Name: poitem_poitem_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123271 --
123272
123273 ALTER TABLE ONLY poitem
123274     ADD CONSTRAINT poitem_poitem_taxtype_id_fkey FOREIGN KEY (poitem_taxtype_id) REFERENCES taxtype(taxtype_id);
123275
123276
123277 --
123278 -- TOC entry 8085 (class 2606 OID 146573819)
123279 -- Dependencies: 7519 721 724 8894
123280 -- Name: poreject_poreject_recv_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123281 --
123282
123283 ALTER TABLE ONLY poreject
123284     ADD CONSTRAINT poreject_poreject_recv_id_fkey FOREIGN KEY (poreject_recv_id) REFERENCES recv(recv_id);
123285
123286
123287 --
123288 -- TOC entry 8086 (class 2606 OID 146573824)
123289 -- Dependencies: 6841 210 724 8894
123290 -- Name: poreject_poreject_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123291 --
123292
123293 ALTER TABLE ONLY poreject
123294     ADD CONSTRAINT poreject_poreject_vend_id_fkey FOREIGN KEY (poreject_vend_id) REFERENCES vendinfo(vend_id);
123295
123296
123297 --
123298 -- TOC entry 7838 (class 2606 OID 146573829)
123299 -- Dependencies: 6816 204 225 8894
123300 -- Name: prj_prj_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123301 --
123302
123303 ALTER TABLE ONLY prj
123304     ADD CONSTRAINT prj_prj_cntct_id_fkey FOREIGN KEY (prj_cntct_id) REFERENCES cntct(cntct_id);
123305
123306
123307 --
123308 -- TOC entry 7839 (class 2606 OID 146573834)
123309 -- Dependencies: 6820 205 225 8894
123310 -- Name: prj_prj_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123311 --
123312
123313 ALTER TABLE ONLY prj
123314     ADD CONSTRAINT prj_prj_crmacct_id_fkey FOREIGN KEY (prj_crmacct_id) REFERENCES crmacct(crmacct_id);
123315
123316
123317 --
123318 -- TOC entry 7840 (class 2606 OID 146573839)
123319 -- Dependencies: 7537 739 225 8894
123320 -- Name: prj_prj_prjtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123321 --
123322
123323 ALTER TABLE ONLY prj
123324     ADD CONSTRAINT prj_prj_prjtype_id_fkey FOREIGN KEY (prj_prjtype_id) REFERENCES prjtype(prjtype_id);
123325
123326
123327 --
123328 -- TOC entry 7841 (class 2606 OID 146573844)
123329 -- Dependencies: 6891 225 225 8894
123330 -- Name: prj_prj_recurring_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123331 --
123332
123333 ALTER TABLE ONLY prj
123334     ADD CONSTRAINT prj_prj_recurring_prj_id_fkey FOREIGN KEY (prj_recurring_prj_id) REFERENCES prj(prj_id);
123335
123336
123337 --
123338 -- TOC entry 7853 (class 2606 OID 146573849)
123339 -- Dependencies: 6891 225 232 8894
123340 -- Name: prjtask_prjtask_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123341 --
123342
123343 ALTER TABLE ONLY prjtask
123344     ADD CONSTRAINT prjtask_prjtask_prj_id_fkey FOREIGN KEY (prjtask_prj_id) REFERENCES prj(prj_id);
123345
123346
123347 --
123348 -- TOC entry 7924 (class 2606 OID 146573854)
123349 -- Dependencies: 6816 204 356 8894
123350 -- Name: prospect_prospect_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123351 --
123352
123353 ALTER TABLE ONLY prospect
123354     ADD CONSTRAINT prospect_prospect_cntct_id_fkey FOREIGN KEY (prospect_cntct_id) REFERENCES cntct(cntct_id);
123355
123356
123357 --
123358 -- TOC entry 7925 (class 2606 OID 146573859)
123359 -- Dependencies: 6865 216 356 8894
123360 -- Name: prospect_prospect_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123361 --
123362
123363 ALTER TABLE ONLY prospect
123364     ADD CONSTRAINT prospect_prospect_salesrep_id_fkey FOREIGN KEY (prospect_salesrep_id) REFERENCES salesrep(salesrep_id);
123365
123366
123367 --
123368 -- TOC entry 7926 (class 2606 OID 146573864)
123369 -- Dependencies: 6878 220 356 8894
123370 -- Name: prospect_prospect_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123371 --
123372
123373 ALTER TABLE ONLY prospect
123374     ADD CONSTRAINT prospect_prospect_taxzone_id_fkey FOREIGN KEY (prospect_taxzone_id) REFERENCES taxzone(taxzone_id);
123375
123376
123377 --
123378 -- TOC entry 7927 (class 2606 OID 146573869)
123379 -- Dependencies: 6763 193 356 8894
123380 -- Name: prospect_prospect_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123381 --
123382
123383 ALTER TABLE ONLY prospect
123384     ADD CONSTRAINT prospect_prospect_warehous_id_fkey FOREIGN KEY (prospect_warehous_id) REFERENCES whsinfo(warehous_id);
123385
123386
123387 --
123388 -- TOC entry 8088 (class 2606 OID 146573874)
123389 -- Dependencies: 7541 742 744 8894
123390 -- Name: qryitem_qryitem_qryhead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123391 --
123392
123393 ALTER TABLE ONLY qryitem
123394     ADD CONSTRAINT qryitem_qryitem_qryhead_id_fkey FOREIGN KEY (qryitem_qryhead_id) REFERENCES qryhead(qryhead_id);
123395
123396
123397 --
123398 -- TOC entry 7936 (class 2606 OID 146573879)
123399 -- Dependencies: 6816 204 367 8894
123400 -- Name: quhead_quhead_billto_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123401 --
123402
123403 ALTER TABLE ONLY quhead
123404     ADD CONSTRAINT quhead_quhead_billto_cntct_id_fkey FOREIGN KEY (quhead_billto_cntct_id) REFERENCES cntct(cntct_id);
123405
123406
123407 --
123408 -- TOC entry 7937 (class 2606 OID 146573884)
123409 -- Dependencies: 6954 262 367 8894
123410 -- Name: quhead_quhead_misc_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123411 --
123412
123413 ALTER TABLE ONLY quhead
123414     ADD CONSTRAINT quhead_quhead_misc_accnt_id_fkey FOREIGN KEY (quhead_misc_accnt_id) REFERENCES accnt(accnt_id);
123415
123416
123417 --
123418 -- TOC entry 7938 (class 2606 OID 146573889)
123419 -- Dependencies: 6909 231 367 8894
123420 -- Name: quhead_quhead_ophead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123421 --
123422
123423 ALTER TABLE ONLY quhead
123424     ADD CONSTRAINT quhead_quhead_ophead_id_fkey FOREIGN KEY (quhead_ophead_id) REFERENCES ophead(ophead_id);
123425
123426
123427 --
123428 -- TOC entry 7939 (class 2606 OID 146573894)
123429 -- Dependencies: 6891 225 367 8894
123430 -- Name: quhead_quhead_prj_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123431 --
123432
123433 ALTER TABLE ONLY quhead
123434     ADD CONSTRAINT quhead_quhead_prj_id_fkey FOREIGN KEY (quhead_prj_id) REFERENCES prj(prj_id);
123435
123436
123437 --
123438 -- TOC entry 7940 (class 2606 OID 146573899)
123439 -- Dependencies: 6865 216 367 8894
123440 -- Name: quhead_quhead_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123441 --
123442
123443 ALTER TABLE ONLY quhead
123444     ADD CONSTRAINT quhead_quhead_salesrep_id_fkey FOREIGN KEY (quhead_salesrep_id) REFERENCES salesrep(salesrep_id);
123445
123446
123447 --
123448 -- TOC entry 7941 (class 2606 OID 146573904)
123449 -- Dependencies: 6895 226 367 8894
123450 -- Name: quhead_quhead_saletype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123451 --
123452
123453 ALTER TABLE ONLY quhead
123454     ADD CONSTRAINT quhead_quhead_saletype_id_fkey FOREIGN KEY (quhead_saletype_id) REFERENCES saletype(saletype_id);
123455
123456
123457 --
123458 -- TOC entry 7942 (class 2606 OID 146573909)
123459 -- Dependencies: 6816 204 367 8894
123460 -- Name: quhead_quhead_shipto_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123461 --
123462
123463 ALTER TABLE ONLY quhead
123464     ADD CONSTRAINT quhead_quhead_shipto_cntct_id_fkey FOREIGN KEY (quhead_shipto_cntct_id) REFERENCES cntct(cntct_id);
123465
123466
123467 --
123468 -- TOC entry 7943 (class 2606 OID 146573914)
123469 -- Dependencies: 6876 219 367 8894
123470 -- Name: quhead_quhead_shipto_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123471 --
123472
123473 ALTER TABLE ONLY quhead
123474     ADD CONSTRAINT quhead_quhead_shipto_id_fkey FOREIGN KEY (quhead_shipto_id) REFERENCES shiptoinfo(shipto_id);
123475
123476
123477 --
123478 -- TOC entry 7944 (class 2606 OID 146573919)
123479 -- Dependencies: 6897 227 367 8894
123480 -- Name: quhead_quhead_shipzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123481 --
123482
123483 ALTER TABLE ONLY quhead
123484     ADD CONSTRAINT quhead_quhead_shipzone_id_fkey FOREIGN KEY (quhead_shipzone_id) REFERENCES shipzone(shipzone_id);
123485
123486
123487 --
123488 -- TOC entry 7945 (class 2606 OID 146573924)
123489 -- Dependencies: 6796 199 367 8894
123490 -- Name: quhead_quhead_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123491 --
123492
123493 ALTER TABLE ONLY quhead
123494     ADD CONSTRAINT quhead_quhead_taxtype_id_fkey FOREIGN KEY (quhead_taxtype_id) REFERENCES taxtype(taxtype_id);
123495
123496
123497 --
123498 -- TOC entry 7946 (class 2606 OID 146573929)
123499 -- Dependencies: 6878 220 367 8894
123500 -- Name: quhead_quhead_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123501 --
123502
123503 ALTER TABLE ONLY quhead
123504     ADD CONSTRAINT quhead_quhead_taxzone_id_fkey FOREIGN KEY (quhead_taxzone_id) REFERENCES taxzone(taxzone_id);
123505
123506
123507 --
123508 -- TOC entry 7947 (class 2606 OID 146573934)
123509 -- Dependencies: 6836 209 367 8894
123510 -- Name: quhead_quhead_terms_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123511 --
123512
123513 ALTER TABLE ONLY quhead
123514     ADD CONSTRAINT quhead_quhead_terms_id_fkey FOREIGN KEY (quhead_terms_id) REFERENCES terms(terms_id);
123515
123516
123517 --
123518 -- TOC entry 7948 (class 2606 OID 146573939)
123519 -- Dependencies: 6763 193 367 8894
123520 -- Name: quhead_quhead_warehous_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123521 --
123522
123523 ALTER TABLE ONLY quhead
123524     ADD CONSTRAINT quhead_quhead_warehous_id_fkey FOREIGN KEY (quhead_warehous_id) REFERENCES whsinfo(warehous_id);
123525
123526
123527 --
123528 -- TOC entry 7949 (class 2606 OID 146573944)
123529 -- Dependencies: 6834 208 367 8894
123530 -- Name: quhead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
123531 --
123532
123533 ALTER TABLE ONLY quhead
123534     ADD CONSTRAINT quhead_to_curr_symbol FOREIGN KEY (quhead_curr_id) REFERENCES curr_symbol(curr_id);
123535
123536
123537 --
123538 -- TOC entry 7950 (class 2606 OID 146573949)
123539 -- Dependencies: 7068 330 370 8894
123540 -- Name: quitem_quitem_itemsrc_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123541 --
123542
123543 ALTER TABLE ONLY quitem
123544     ADD CONSTRAINT quitem_quitem_itemsrc_id_fkey FOREIGN KEY (quitem_itemsrc_id) REFERENCES itemsrc(itemsrc_id);
123545
123546
123547 --
123548 -- TOC entry 7951 (class 2606 OID 146573954)
123549 -- Dependencies: 6800 200 370 8894
123550 -- Name: quitem_quitem_price_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123551 --
123552
123553 ALTER TABLE ONLY quitem
123554     ADD CONSTRAINT quitem_quitem_price_uom_id_fkey FOREIGN KEY (quitem_price_uom_id) REFERENCES uom(uom_id);
123555
123556
123557 --
123558 -- TOC entry 7952 (class 2606 OID 146573959)
123559 -- Dependencies: 6800 200 370 8894
123560 -- Name: quitem_quitem_qty_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123561 --
123562
123563 ALTER TABLE ONLY quitem
123564     ADD CONSTRAINT quitem_quitem_qty_uom_id_fkey FOREIGN KEY (quitem_qty_uom_id) REFERENCES uom(uom_id);
123565
123566
123567 --
123568 -- TOC entry 7953 (class 2606 OID 146573964)
123569 -- Dependencies: 6796 199 370 8894
123570 -- Name: quitem_quitem_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123571 --
123572
123573 ALTER TABLE ONLY quitem
123574     ADD CONSTRAINT quitem_quitem_taxtype_id_fkey FOREIGN KEY (quitem_taxtype_id) REFERENCES taxtype(taxtype_id);
123575
123576
123577 --
123578 -- TOC entry 8077 (class 2606 OID 146573969)
123579 -- Dependencies: 6834 208 721 8894
123580 -- Name: recv_recv_freight_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123581 --
123582
123583 ALTER TABLE ONLY recv
123584     ADD CONSTRAINT recv_recv_freight_curr_id_fkey FOREIGN KEY (recv_freight_curr_id) REFERENCES curr_symbol(curr_id);
123585
123586
123587 --
123588 -- TOC entry 8078 (class 2606 OID 146573974)
123589 -- Dependencies: 6758 192 721 8894
123590 -- Name: recv_recv_itemsite_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123591 --
123592
123593 ALTER TABLE ONLY recv
123594     ADD CONSTRAINT recv_recv_itemsite_id_fkey FOREIGN KEY (recv_itemsite_id) REFERENCES itemsite(itemsite_id);
123595
123596
123597 --
123598 -- TOC entry 8079 (class 2606 OID 146573979)
123599 -- Dependencies: 6834 208 721 8894
123600 -- Name: recv_recv_purchcost_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123601 --
123602
123603 ALTER TABLE ONLY recv
123604     ADD CONSTRAINT recv_recv_purchcost_curr_id_fkey FOREIGN KEY (recv_purchcost_curr_id) REFERENCES curr_symbol(curr_id);
123605
123606
123607 --
123608 -- TOC entry 8080 (class 2606 OID 146573984)
123609 -- Dependencies: 6834 208 721 8894
123610 -- Name: recv_recv_recvcost_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123611 --
123612
123613 ALTER TABLE ONLY recv
123614     ADD CONSTRAINT recv_recv_recvcost_curr_id_fkey FOREIGN KEY (recv_recvcost_curr_id) REFERENCES curr_symbol(curr_id);
123615
123616
123617 --
123618 -- TOC entry 8081 (class 2606 OID 146573989)
123619 -- Dependencies: 7519 721 721 8894
123620 -- Name: recv_recv_splitfrom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123621 --
123622
123623 ALTER TABLE ONLY recv
123624     ADD CONSTRAINT recv_recv_splitfrom_id_fkey FOREIGN KEY (recv_splitfrom_id) REFERENCES recv(recv_id);
123625
123626
123627 --
123628 -- TOC entry 8082 (class 2606 OID 146573994)
123629 -- Dependencies: 6841 210 721 8894
123630 -- Name: recv_recv_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123631 --
123632
123633 ALTER TABLE ONLY recv
123634     ADD CONSTRAINT recv_recv_vend_id_fkey FOREIGN KEY (recv_vend_id) REFERENCES vendinfo(vend_id);
123635
123636
123637 --
123638 -- TOC entry 8083 (class 2606 OID 146573999)
123639 -- Dependencies: 7642 839 721 8894
123640 -- Name: recv_recv_vohead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123641 --
123642
123643 ALTER TABLE ONLY recv
123644     ADD CONSTRAINT recv_recv_vohead_id_fkey FOREIGN KEY (recv_vohead_id) REFERENCES vohead(vohead_id);
123645
123646
123647 --
123648 -- TOC entry 8084 (class 2606 OID 146574004)
123649 -- Dependencies: 7648 842 721 8894
123650 -- Name: recv_recv_voitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123651 --
123652
123653 ALTER TABLE ONLY recv
123654     ADD CONSTRAINT recv_recv_voitem_id_fkey FOREIGN KEY (recv_voitem_id) REFERENCES voitem(voitem_id);
123655
123656
123657 --
123658 -- TOC entry 7812 (class 2606 OID 146574009)
123659 -- Dependencies: 7002 292 216 8894
123660 -- Name: salesrep_salesrep_emp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123661 --
123662
123663 ALTER TABLE ONLY salesrep
123664     ADD CONSTRAINT salesrep_salesrep_emp_id_fkey FOREIGN KEY (salesrep_emp_id) REFERENCES emp(emp_id);
123665
123666
123667 --
123668 -- TOC entry 7888 (class 2606 OID 146574014)
123669 -- Dependencies: 6834 208 297 8894
123670 -- Name: shipdata_shipdata_base_freight_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123671 --
123672
123673 ALTER TABLE ONLY shipdata
123674     ADD CONSTRAINT shipdata_shipdata_base_freight_curr_id_fkey FOREIGN KEY (shipdata_base_freight_curr_id) REFERENCES curr_symbol(curr_id);
123675
123676
123677 --
123678 -- TOC entry 7889 (class 2606 OID 146574019)
123679 -- Dependencies: 7305 526 297 8894
123680 -- Name: shipdata_shipdata_shiphead_number_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123681 --
123682
123683 ALTER TABLE ONLY shipdata
123684     ADD CONSTRAINT shipdata_shipdata_shiphead_number_fkey FOREIGN KEY (shipdata_shiphead_number) REFERENCES shiphead(shiphead_number);
123685
123686
123687 --
123688 -- TOC entry 7890 (class 2606 OID 146574024)
123689 -- Dependencies: 6834 208 297 8894
123690 -- Name: shipdata_shipdata_total_freight_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123691 --
123692
123693 ALTER TABLE ONLY shipdata
123694     ADD CONSTRAINT shipdata_shipdata_total_freight_curr_id_fkey FOREIGN KEY (shipdata_total_freight_curr_id) REFERENCES curr_symbol(curr_id);
123695
123696
123697 --
123698 -- TOC entry 8089 (class 2606 OID 146574029)
123699 -- Dependencies: 6834 208 771 8894
123700 -- Name: shipdatasum_shipdatasum_base_freight_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123701 --
123702
123703 ALTER TABLE ONLY shipdatasum
123704     ADD CONSTRAINT shipdatasum_shipdatasum_base_freight_curr_id_fkey FOREIGN KEY (shipdatasum_base_freight_curr_id) REFERENCES curr_symbol(curr_id);
123705
123706
123707 --
123708 -- TOC entry 8090 (class 2606 OID 146574034)
123709 -- Dependencies: 7305 526 771 8894
123710 -- Name: shipdatasum_shipdatasum_shiphead_number_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123711 --
123712
123713 ALTER TABLE ONLY shipdatasum
123714     ADD CONSTRAINT shipdatasum_shipdatasum_shiphead_number_fkey FOREIGN KEY (shipdatasum_shiphead_number) REFERENCES shiphead(shiphead_number);
123715
123716
123717 --
123718 -- TOC entry 8091 (class 2606 OID 146574039)
123719 -- Dependencies: 6834 208 771 8894
123720 -- Name: shipdatasum_shipdatasum_total_freight_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123721 --
123722
123723 ALTER TABLE ONLY shipdatasum
123724     ADD CONSTRAINT shipdatasum_shipdatasum_total_freight_curr_id_fkey FOREIGN KEY (shipdatasum_total_freight_curr_id) REFERENCES curr_symbol(curr_id);
123725
123726
123727 --
123728 -- TOC entry 8038 (class 2606 OID 146574044)
123729 -- Dependencies: 6834 208 526 8894
123730 -- Name: shiphead_shiphead_freight_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123731 --
123732
123733 ALTER TABLE ONLY shiphead
123734     ADD CONSTRAINT shiphead_shiphead_freight_curr_id_fkey FOREIGN KEY (shiphead_freight_curr_id) REFERENCES curr_symbol(curr_id);
123735
123736
123737 --
123738 -- TOC entry 8039 (class 2606 OID 146574049)
123739 -- Dependencies: 6982 281 526 8894
123740 -- Name: shiphead_shiphead_shipchrg_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123741 --
123742
123743 ALTER TABLE ONLY shiphead
123744     ADD CONSTRAINT shiphead_shiphead_shipchrg_id_fkey FOREIGN KEY (shiphead_shipchrg_id) REFERENCES shipchrg(shipchrg_id);
123745
123746
123747 --
123748 -- TOC entry 8040 (class 2606 OID 146574054)
123749 -- Dependencies: 6984 282 526 8894
123750 -- Name: shiphead_shiphead_shipform_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123751 --
123752
123753 ALTER TABLE ONLY shiphead
123754     ADD CONSTRAINT shiphead_shiphead_shipform_id_fkey FOREIGN KEY (shiphead_shipform_id) REFERENCES shipform(shipform_id);
123755
123756
123757 --
123758 -- TOC entry 8041 (class 2606 OID 146574059)
123759 -- Dependencies: 6905 229 527 8894
123760 -- Name: shipitem_shipitem_invcitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123761 --
123762
123763 ALTER TABLE ONLY shipitem
123764     ADD CONSTRAINT shipitem_shipitem_invcitem_id_fkey FOREIGN KEY (shipitem_invcitem_id) REFERENCES invcitem(invcitem_id);
123765
123766
123767 --
123768 -- TOC entry 8042 (class 2606 OID 146574064)
123769 -- Dependencies: 7417 623 527 8894
123770 -- Name: shipitem_shipitem_invhist_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123771 --
123772
123773 ALTER TABLE ONLY shipitem
123774     ADD CONSTRAINT shipitem_shipitem_invhist_id_fkey FOREIGN KEY (shipitem_invhist_id) REFERENCES invhist(invhist_id);
123775
123776
123777 --
123778 -- TOC entry 8043 (class 2606 OID 146574069)
123779 -- Dependencies: 7303 526 527 8894
123780 -- Name: shipitem_shipitem_shiphead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123781 --
123782
123783 ALTER TABLE ONLY shipitem
123784     ADD CONSTRAINT shipitem_shipitem_shiphead_id_fkey FOREIGN KEY (shipitem_shiphead_id) REFERENCES shiphead(shiphead_id);
123785
123786
123787 --
123788 -- TOC entry 7821 (class 2606 OID 146574074)
123789 -- Dependencies: 6920 234 219 8894
123790 -- Name: shiptoinfo_shipto_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123791 --
123792
123793 ALTER TABLE ONLY shiptoinfo
123794     ADD CONSTRAINT shiptoinfo_shipto_addr_id_fkey FOREIGN KEY (shipto_addr_id) REFERENCES addr(addr_id);
123795
123796
123797 --
123798 -- TOC entry 7822 (class 2606 OID 146574079)
123799 -- Dependencies: 6816 204 219 8894
123800 -- Name: shiptoinfo_shipto_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123801 --
123802
123803 ALTER TABLE ONLY shiptoinfo
123804     ADD CONSTRAINT shiptoinfo_shipto_cntct_id_fkey FOREIGN KEY (shipto_cntct_id) REFERENCES cntct(cntct_id);
123805
123806
123807 --
123808 -- TOC entry 7823 (class 2606 OID 146574084)
123809 -- Dependencies: 6853 213 219 8894
123810 -- Name: shiptoinfo_shipto_cust_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123811 --
123812
123813 ALTER TABLE ONLY shiptoinfo
123814     ADD CONSTRAINT shiptoinfo_shipto_cust_id_fkey FOREIGN KEY (shipto_cust_id) REFERENCES custinfo(cust_id);
123815
123816
123817 --
123818 -- TOC entry 7824 (class 2606 OID 146574089)
123819 -- Dependencies: 6865 216 219 8894
123820 -- Name: shiptoinfo_shipto_salesrep_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123821 --
123822
123823 ALTER TABLE ONLY shiptoinfo
123824     ADD CONSTRAINT shiptoinfo_shipto_salesrep_fkey FOREIGN KEY (shipto_salesrep_id) REFERENCES salesrep(salesrep_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
123825
123826
123827 --
123828 -- TOC entry 7825 (class 2606 OID 146574094)
123829 -- Dependencies: 6865 216 219 8894
123830 -- Name: shiptoinfo_shipto_salesrep_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123831 --
123832
123833 ALTER TABLE ONLY shiptoinfo
123834     ADD CONSTRAINT shiptoinfo_shipto_salesrep_id_fkey FOREIGN KEY (shipto_salesrep_id) REFERENCES salesrep(salesrep_id);
123835
123836
123837 --
123838 -- TOC entry 7826 (class 2606 OID 146574099)
123839 -- Dependencies: 6984 282 219 8894
123840 -- Name: shiptoinfo_shipto_shipform_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123841 --
123842
123843 ALTER TABLE ONLY shiptoinfo
123844     ADD CONSTRAINT shiptoinfo_shipto_shipform_fkey FOREIGN KEY (shipto_shipform_id) REFERENCES shipform(shipform_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
123845
123846
123847 --
123848 -- TOC entry 7827 (class 2606 OID 146574104)
123849 -- Dependencies: 6984 282 219 8894
123850 -- Name: shiptoinfo_shipto_shipform_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123851 --
123852
123853 ALTER TABLE ONLY shiptoinfo
123854     ADD CONSTRAINT shiptoinfo_shipto_shipform_id_fkey FOREIGN KEY (shipto_shipform_id) REFERENCES shipform(shipform_id);
123855
123856
123857 --
123858 -- TOC entry 7828 (class 2606 OID 146574109)
123859 -- Dependencies: 6897 227 219 8894
123860 -- Name: shiptoinfo_shipto_shipzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123861 --
123862
123863 ALTER TABLE ONLY shiptoinfo
123864     ADD CONSTRAINT shiptoinfo_shipto_shipzone_id_fkey FOREIGN KEY (shipto_shipzone_id) REFERENCES shipzone(shipzone_id);
123865
123866
123867 --
123868 -- TOC entry 7829 (class 2606 OID 146574114)
123869 -- Dependencies: 6878 220 219 8894
123870 -- Name: shiptoinfo_shipto_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123871 --
123872
123873 ALTER TABLE ONLY shiptoinfo
123874     ADD CONSTRAINT shiptoinfo_shipto_taxzone_id_fkey FOREIGN KEY (shipto_taxzone_id) REFERENCES taxzone(taxzone_id);
123875
123876
123877 --
123878 -- TOC entry 8092 (class 2606 OID 146574119)
123879 -- Dependencies: 7321 538 787 8894
123880 -- Name: state_state_country_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123881 --
123882
123883 ALTER TABLE ONLY state
123884     ADD CONSTRAINT state_state_country_id_fkey FOREIGN KEY (state_country_id) REFERENCES country(country_id);
123885
123886
123887 --
123888 -- TOC entry 7929 (class 2606 OID 146574124)
123889 -- Dependencies: 7124 363 363 8894
123890 -- Name: tax_tax_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123891 --
123892
123893 ALTER TABLE ONLY tax
123894     ADD CONSTRAINT tax_tax_basis_tax_id_fkey FOREIGN KEY (tax_basis_tax_id) REFERENCES tax(tax_id) ON DELETE CASCADE;
123895
123896
123897 --
123898 -- TOC entry 7930 (class 2606 OID 146574129)
123899 -- Dependencies: 6954 262 363 8894
123900 -- Name: tax_tax_sales_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123901 --
123902
123903 ALTER TABLE ONLY tax
123904     ADD CONSTRAINT tax_tax_sales_accnt_id_fkey FOREIGN KEY (tax_sales_accnt_id) REFERENCES accnt(accnt_id);
123905
123906
123907 --
123908 -- TOC entry 7931 (class 2606 OID 146574134)
123909 -- Dependencies: 6988 284 363 8894
123910 -- Name: tax_tax_taxauth_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123911 --
123912
123913 ALTER TABLE ONLY tax
123914     ADD CONSTRAINT tax_tax_taxauth_id_fkey FOREIGN KEY (tax_taxauth_id) REFERENCES taxauth(taxauth_id);
123915
123916
123917 --
123918 -- TOC entry 7932 (class 2606 OID 146574139)
123919 -- Dependencies: 7618 807 363 8894
123920 -- Name: tax_tax_taxclass_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123921 --
123922
123923 ALTER TABLE ONLY tax
123924     ADD CONSTRAINT tax_tax_taxclass_id_fkey FOREIGN KEY (tax_taxclass_id) REFERENCES taxclass(taxclass_id);
123925
123926
123927 --
123928 -- TOC entry 8093 (class 2606 OID 146574144)
123929 -- Dependencies: 7124 363 804 8894
123930 -- Name: taxass_taxass_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123931 --
123932
123933 ALTER TABLE ONLY taxass
123934     ADD CONSTRAINT taxass_taxass_tax_id_fkey FOREIGN KEY (taxass_tax_id) REFERENCES tax(tax_id);
123935
123936
123937 --
123938 -- TOC entry 8094 (class 2606 OID 146574149)
123939 -- Dependencies: 6796 199 804 8894
123940 -- Name: taxass_taxass_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123941 --
123942
123943 ALTER TABLE ONLY taxass
123944     ADD CONSTRAINT taxass_taxass_taxtype_id_fkey FOREIGN KEY (taxass_taxtype_id) REFERENCES taxtype(taxtype_id);
123945
123946
123947 --
123948 -- TOC entry 8095 (class 2606 OID 146574154)
123949 -- Dependencies: 6878 220 804 8894
123950 -- Name: taxass_taxass_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123951 --
123952
123953 ALTER TABLE ONLY taxass
123954     ADD CONSTRAINT taxass_taxass_taxzone_id_fkey FOREIGN KEY (taxass_taxzone_id) REFERENCES taxzone(taxzone_id);
123955
123956
123957 --
123958 -- TOC entry 7876 (class 2606 OID 146574159)
123959 -- Dependencies: 6954 262 284 8894
123960 -- Name: taxauth_taxauth_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123961 --
123962
123963 ALTER TABLE ONLY taxauth
123964     ADD CONSTRAINT taxauth_taxauth_accnt_id_fkey FOREIGN KEY (taxauth_accnt_id) REFERENCES accnt(accnt_id);
123965
123966
123967 --
123968 -- TOC entry 7877 (class 2606 OID 146574164)
123969 -- Dependencies: 6920 234 284 8894
123970 -- Name: taxauth_taxauth_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123971 --
123972
123973 ALTER TABLE ONLY taxauth
123974     ADD CONSTRAINT taxauth_taxauth_addr_id_fkey FOREIGN KEY (taxauth_addr_id) REFERENCES addr(addr_id);
123975
123976
123977 --
123978 -- TOC entry 7878 (class 2606 OID 146574169)
123979 -- Dependencies: 6834 208 284 8894
123980 -- Name: taxauth_taxauth_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123981 --
123982
123983 ALTER TABLE ONLY taxauth
123984     ADD CONSTRAINT taxauth_taxauth_curr_id_fkey FOREIGN KEY (taxauth_curr_id) REFERENCES curr_symbol(curr_id);
123985
123986
123987 --
123988 -- TOC entry 7960 (class 2606 OID 146574174)
123989 -- Dependencies: 6834 208 377 8894
123990 -- Name: taxhist_taxhist_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
123991 --
123992
123993 ALTER TABLE ONLY taxhist
123994     ADD CONSTRAINT taxhist_taxhist_curr_id_fkey FOREIGN KEY (taxhist_curr_id) REFERENCES curr_symbol(curr_id);
123995
123996
123997 --
123998 -- TOC entry 7961 (class 2606 OID 146574179)
123999 -- Dependencies: 7124 363 377 8894
124000 -- Name: taxhist_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124001 --
124002
124003 ALTER TABLE ONLY taxhist
124004     ADD CONSTRAINT taxhist_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
124005
124006
124007 --
124008 -- TOC entry 7962 (class 2606 OID 146574184)
124009 -- Dependencies: 6796 199 377 8894
124010 -- Name: taxhist_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124011 --
124012
124013 ALTER TABLE ONLY taxhist
124014     ADD CONSTRAINT taxhist_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
124015
124016
124017 --
124018 -- TOC entry 8096 (class 2606 OID 146574189)
124019 -- Dependencies: 6834 208 809 8894
124020 -- Name: taxrate_taxrate_curr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124021 --
124022
124023 ALTER TABLE ONLY taxrate
124024     ADD CONSTRAINT taxrate_taxrate_curr_id_fkey FOREIGN KEY (taxrate_curr_id) REFERENCES curr_symbol(curr_id);
124025
124026
124027 --
124028 -- TOC entry 8097 (class 2606 OID 146574194)
124029 -- Dependencies: 7124 363 809 8894
124030 -- Name: taxrate_taxrate_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124031 --
124032
124033 ALTER TABLE ONLY taxrate
124034     ADD CONSTRAINT taxrate_taxrate_tax_id_fkey FOREIGN KEY (taxrate_tax_id) REFERENCES tax(tax_id);
124035
124036
124037 --
124038 -- TOC entry 7879 (class 2606 OID 146574199)
124039 -- Dependencies: 6988 284 285 8894
124040 -- Name: taxreg_taxreg_taxauth_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124041 --
124042
124043 ALTER TABLE ONLY taxreg
124044     ADD CONSTRAINT taxreg_taxreg_taxauth_id_fkey FOREIGN KEY (taxreg_taxauth_id) REFERENCES taxauth(taxauth_id);
124045
124046
124047 --
124048 -- TOC entry 7880 (class 2606 OID 146574204)
124049 -- Dependencies: 6878 220 285 8894
124050 -- Name: taxreg_taxreg_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124051 --
124052
124053 ALTER TABLE ONLY taxreg
124054     ADD CONSTRAINT taxreg_taxreg_taxzone_id_fkey FOREIGN KEY (taxreg_taxzone_id) REFERENCES taxzone(taxzone_id);
124055
124056
124057 --
124058 -- TOC entry 7854 (class 2606 OID 146574209)
124059 -- Dependencies: 6816 204 233 8894
124060 -- Name: todoitem_todoitem_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124061 --
124062
124063 ALTER TABLE ONLY todoitem
124064     ADD CONSTRAINT todoitem_todoitem_cntct_id_fkey FOREIGN KEY (todoitem_cntct_id) REFERENCES cntct(cntct_id);
124065
124066
124067 --
124068 -- TOC entry 7855 (class 2606 OID 146574214)
124069 -- Dependencies: 6820 205 233 8894
124070 -- Name: todoitem_todoitem_crmacct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124071 --
124072
124073 ALTER TABLE ONLY todoitem
124074     ADD CONSTRAINT todoitem_todoitem_crmacct_id_fkey FOREIGN KEY (todoitem_crmacct_id) REFERENCES crmacct(crmacct_id);
124075
124076
124077 --
124078 -- TOC entry 7856 (class 2606 OID 146574219)
124079 -- Dependencies: 6824 206 233 8894
124080 -- Name: todoitem_todoitem_incdt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124081 --
124082
124083 ALTER TABLE ONLY todoitem
124084     ADD CONSTRAINT todoitem_todoitem_incdt_id_fkey FOREIGN KEY (todoitem_incdt_id) REFERENCES incdt(incdt_id);
124085
124086
124087 --
124088 -- TOC entry 7857 (class 2606 OID 146574224)
124089 -- Dependencies: 6909 231 233 8894
124090 -- Name: todoitem_todoitem_ophead_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124091 --
124092
124093 ALTER TABLE ONLY todoitem
124094     ADD CONSTRAINT todoitem_todoitem_ophead_id_fkey FOREIGN KEY (todoitem_ophead_id) REFERENCES ophead(ophead_id) ON UPDATE RESTRICT ON DELETE RESTRICT;
124095
124096
124097 --
124098 -- TOC entry 7858 (class 2606 OID 146574229)
124099 -- Dependencies: 6915 233 233 8894
124100 -- Name: todoitem_todoitem_recurring_todoitem_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124101 --
124102
124103 ALTER TABLE ONLY todoitem
124104     ADD CONSTRAINT todoitem_todoitem_recurring_todoitem_id_fkey FOREIGN KEY (todoitem_recurring_todoitem_id) REFERENCES todoitem(todoitem_id);
124105
124106
124107 --
124108 -- TOC entry 8098 (class 2606 OID 146574234)
124109 -- Dependencies: 7282 510 816 8894
124110 -- Name: trgthist_trgthist_src_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124111 --
124112
124113 ALTER TABLE ONLY trgthist
124114     ADD CONSTRAINT trgthist_trgthist_src_cntct_id_fkey FOREIGN KEY (trgthist_src_cntct_id) REFERENCES cntctmrgd(cntctmrgd_cntct_id) ON DELETE CASCADE;
124115
124116
124117 --
124118 -- TOC entry 8099 (class 2606 OID 146574239)
124119 -- Dependencies: 6816 204 816 8894
124120 -- Name: trgthist_trgthist_trgt_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124121 --
124122
124123 ALTER TABLE ONLY trgthist
124124     ADD CONSTRAINT trgthist_trgthist_trgt_cntct_id_fkey FOREIGN KEY (trgthist_trgt_cntct_id) REFERENCES cntct(cntct_id) ON DELETE CASCADE;
124125
124126
124127 --
124128 -- TOC entry 8100 (class 2606 OID 146574244)
124129 -- Dependencies: 6800 200 820 8894
124130 -- Name: uomconv_uomconv_from_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124131 --
124132
124133 ALTER TABLE ONLY uomconv
124134     ADD CONSTRAINT uomconv_uomconv_from_uom_id_fkey FOREIGN KEY (uomconv_from_uom_id) REFERENCES uom(uom_id);
124135
124136
124137 --
124138 -- TOC entry 8101 (class 2606 OID 146574249)
124139 -- Dependencies: 6800 200 820 8894
124140 -- Name: uomconv_uomconv_to_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124141 --
124142
124143 ALTER TABLE ONLY uomconv
124144     ADD CONSTRAINT uomconv_uomconv_to_uom_id_fkey FOREIGN KEY (uomconv_to_uom_id) REFERENCES uom(uom_id);
124145
124146
124147 --
124148 -- TOC entry 8087 (class 2606 OID 146574254)
124149 -- Dependencies: 7395 601 732 8894
124150 -- Name: usrgrp_usrgrp_grp_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124151 --
124152
124153 ALTER TABLE ONLY usrgrp
124154     ADD CONSTRAINT usrgrp_usrgrp_grp_id_fkey FOREIGN KEY (usrgrp_grp_id) REFERENCES grp(grp_id);
124155
124156
124157 --
124158 -- TOC entry 7794 (class 2606 OID 146574259)
124159 -- Dependencies: 6834 208 210 8894
124160 -- Name: vend_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
124161 --
124162
124163 ALTER TABLE ONLY vendinfo
124164     ADD CONSTRAINT vend_to_curr_symbol FOREIGN KEY (vend_curr_id) REFERENCES curr_symbol(curr_id);
124165
124166
124167 --
124168 -- TOC entry 7795 (class 2606 OID 146574264)
124169 -- Dependencies: 6816 204 210 8894
124170 -- Name: vend_vend_cntct1_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124171 --
124172
124173 ALTER TABLE ONLY vendinfo
124174     ADD CONSTRAINT vend_vend_cntct1_id_fkey FOREIGN KEY (vend_cntct1_id) REFERENCES cntct(cntct_id);
124175
124176
124177 --
124178 -- TOC entry 7796 (class 2606 OID 146574269)
124179 -- Dependencies: 6816 204 210 8894
124180 -- Name: vend_vend_cntct2_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124181 --
124182
124183 ALTER TABLE ONLY vendinfo
124184     ADD CONSTRAINT vend_vend_cntct2_id_fkey FOREIGN KEY (vend_cntct2_id) REFERENCES cntct(cntct_id);
124185
124186
124187 --
124188 -- TOC entry 7933 (class 2606 OID 146574274)
124189 -- Dependencies: 6920 234 364 8894
124190 -- Name: vendaddrinfo_vendaddr_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124191 --
124192
124193 ALTER TABLE ONLY vendaddrinfo
124194     ADD CONSTRAINT vendaddrinfo_vendaddr_addr_id_fkey FOREIGN KEY (vendaddr_addr_id) REFERENCES addr(addr_id);
124195
124196
124197 --
124198 -- TOC entry 7934 (class 2606 OID 146574279)
124199 -- Dependencies: 6816 204 364 8894
124200 -- Name: vendaddrinfo_vendaddr_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124201 --
124202
124203 ALTER TABLE ONLY vendaddrinfo
124204     ADD CONSTRAINT vendaddrinfo_vendaddr_cntct_id_fkey FOREIGN KEY (vendaddr_cntct_id) REFERENCES cntct(cntct_id);
124205
124206
124207 --
124208 -- TOC entry 7935 (class 2606 OID 146574284)
124209 -- Dependencies: 6878 220 364 8894
124210 -- Name: vendaddrinfo_vendaddr_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124211 --
124212
124213 ALTER TABLE ONLY vendaddrinfo
124214     ADD CONSTRAINT vendaddrinfo_vendaddr_taxzone_id_fkey FOREIGN KEY (vendaddr_taxzone_id) REFERENCES taxzone(taxzone_id);
124215
124216
124217 --
124218 -- TOC entry 7797 (class 2606 OID 146574289)
124219 -- Dependencies: 6920 234 210 8894
124220 -- Name: vendinfo_vend_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124221 --
124222
124223 ALTER TABLE ONLY vendinfo
124224     ADD CONSTRAINT vendinfo_vend_addr_id_fkey FOREIGN KEY (vend_addr_id) REFERENCES addr(addr_id);
124225
124226
124227 --
124228 -- TOC entry 7798 (class 2606 OID 146574294)
124229 -- Dependencies: 6878 220 210 8894
124230 -- Name: vendinfo_vend_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124231 --
124232
124233 ALTER TABLE ONLY vendinfo
124234     ADD CONSTRAINT vendinfo_vend_taxzone_id_fkey FOREIGN KEY (vend_taxzone_id) REFERENCES taxzone(taxzone_id);
124235
124236
124237 --
124238 -- TOC entry 7799 (class 2606 OID 146574299)
124239 -- Dependencies: 7158 393 210 8894
124240 -- Name: vendinfo_vend_vendtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124241 --
124242
124243 ALTER TABLE ONLY vendinfo
124244     ADD CONSTRAINT vendinfo_vend_vendtype_id_fkey FOREIGN KEY (vend_vendtype_id) REFERENCES vendtype(vendtype_id);
124245
124246
124247 --
124248 -- TOC entry 8102 (class 2606 OID 146574304)
124249 -- Dependencies: 6834 208 839 8894
124250 -- Name: vohead_to_curr_symbol; Type: FK CONSTRAINT; Schema: public; Owner: admin
124251 --
124252
124253 ALTER TABLE ONLY vohead
124254     ADD CONSTRAINT vohead_to_curr_symbol FOREIGN KEY (vohead_curr_id) REFERENCES curr_symbol(curr_id);
124255
124256
124257 --
124258 -- TOC entry 8103 (class 2606 OID 146574309)
124259 -- Dependencies: 6796 199 839 8894
124260 -- Name: vohead_vohead_adjtaxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124261 --
124262
124263 ALTER TABLE ONLY vohead
124264     ADD CONSTRAINT vohead_vohead_adjtaxtype_id_fkey FOREIGN KEY (vohead_adjtaxtype_id) REFERENCES taxtype(taxtype_id);
124265
124266
124267 --
124268 -- TOC entry 8104 (class 2606 OID 146574314)
124269 -- Dependencies: 6796 199 839 8894
124270 -- Name: vohead_vohead_freighttaxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124271 --
124272
124273 ALTER TABLE ONLY vohead
124274     ADD CONSTRAINT vohead_vohead_freighttaxtype_id_fkey FOREIGN KEY (vohead_freighttaxtype_id) REFERENCES taxtype(taxtype_id);
124275
124276
124277 --
124278 -- TOC entry 8105 (class 2606 OID 146574319)
124279 -- Dependencies: 6796 199 839 8894
124280 -- Name: vohead_vohead_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124281 --
124282
124283 ALTER TABLE ONLY vohead
124284     ADD CONSTRAINT vohead_vohead_taxtype_id_fkey FOREIGN KEY (vohead_taxtype_id) REFERENCES taxtype(taxtype_id);
124285
124286
124287 --
124288 -- TOC entry 8106 (class 2606 OID 146574324)
124289 -- Dependencies: 6878 220 839 8894
124290 -- Name: vohead_vohead_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124291 --
124292
124293 ALTER TABLE ONLY vohead
124294     ADD CONSTRAINT vohead_vohead_taxzone_id_fkey FOREIGN KEY (vohead_taxzone_id) REFERENCES taxzone(taxzone_id);
124295
124296
124297 --
124298 -- TOC entry 8107 (class 2606 OID 146574329)
124299 -- Dependencies: 6841 210 839 8894
124300 -- Name: vohead_vohead_vend_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124301 --
124302
124303 ALTER TABLE ONLY vohead
124304     ADD CONSTRAINT vohead_vohead_vend_id_fkey FOREIGN KEY (vohead_vend_id) REFERENCES vendinfo(vend_id);
124305
124306
124307 --
124308 -- TOC entry 8108 (class 2606 OID 146574334)
124309 -- Dependencies: 7124 363 841 8894
124310 -- Name: voheadtax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124311 --
124312
124313 ALTER TABLE ONLY voheadtax
124314     ADD CONSTRAINT voheadtax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
124315
124316
124317 --
124318 -- TOC entry 8109 (class 2606 OID 146574339)
124319 -- Dependencies: 7642 839 841 8894
124320 -- Name: voheadtax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124321 --
124322
124323 ALTER TABLE ONLY voheadtax
124324     ADD CONSTRAINT voheadtax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES vohead(vohead_id) ON DELETE CASCADE;
124325
124326
124327 --
124328 -- TOC entry 8110 (class 2606 OID 146574344)
124329 -- Dependencies: 7124 363 841 8894
124330 -- Name: voheadtax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124331 --
124332
124333 ALTER TABLE ONLY voheadtax
124334     ADD CONSTRAINT voheadtax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
124335
124336
124337 --
124338 -- TOC entry 8111 (class 2606 OID 146574349)
124339 -- Dependencies: 6796 199 841 8894
124340 -- Name: voheadtax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124341 --
124342
124343 ALTER TABLE ONLY voheadtax
124344     ADD CONSTRAINT voheadtax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
124345
124346
124347 --
124348 -- TOC entry 8112 (class 2606 OID 146574354)
124349 -- Dependencies: 6796 199 842 8894
124350 -- Name: voitem_voitem_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124351 --
124352
124353 ALTER TABLE ONLY voitem
124354     ADD CONSTRAINT voitem_voitem_taxtype_id_fkey FOREIGN KEY (voitem_taxtype_id) REFERENCES taxtype(taxtype_id);
124355
124356
124357 --
124358 -- TOC entry 8113 (class 2606 OID 146574359)
124359 -- Dependencies: 7124 363 844 8894
124360 -- Name: voitemtax_taxhist_basis_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124361 --
124362
124363 ALTER TABLE ONLY voitemtax
124364     ADD CONSTRAINT voitemtax_taxhist_basis_tax_id_fkey FOREIGN KEY (taxhist_basis_tax_id) REFERENCES tax(tax_id);
124365
124366
124367 --
124368 -- TOC entry 8114 (class 2606 OID 146574364)
124369 -- Dependencies: 7648 842 844 8894
124370 -- Name: voitemtax_taxhist_parent_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124371 --
124372
124373 ALTER TABLE ONLY voitemtax
124374     ADD CONSTRAINT voitemtax_taxhist_parent_id_fkey FOREIGN KEY (taxhist_parent_id) REFERENCES voitem(voitem_id) ON DELETE CASCADE;
124375
124376
124377 --
124378 -- TOC entry 8115 (class 2606 OID 146574369)
124379 -- Dependencies: 7124 363 844 8894
124380 -- Name: voitemtax_taxhist_tax_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124381 --
124382
124383 ALTER TABLE ONLY voitemtax
124384     ADD CONSTRAINT voitemtax_taxhist_tax_id_fkey FOREIGN KEY (taxhist_tax_id) REFERENCES tax(tax_id);
124385
124386
124387 --
124388 -- TOC entry 8116 (class 2606 OID 146574374)
124389 -- Dependencies: 6796 199 844 8894
124390 -- Name: voitemtax_taxhist_taxtype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124391 --
124392
124393 ALTER TABLE ONLY voitemtax
124394     ADD CONSTRAINT voitemtax_taxhist_taxtype_id_fkey FOREIGN KEY (taxhist_taxtype_id) REFERENCES taxtype(taxtype_id);
124395
124396
124397 --
124398 -- TOC entry 7717 (class 2606 OID 146574379)
124399 -- Dependencies: 6954 262 193 8894
124400 -- Name: whsinfo_warehous_accnt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124401 --
124402
124403 ALTER TABLE ONLY whsinfo
124404     ADD CONSTRAINT whsinfo_warehous_accnt_id_fkey FOREIGN KEY (warehous_default_accnt_id) REFERENCES accnt(accnt_id);
124405
124406
124407 --
124408 -- TOC entry 7718 (class 2606 OID 146574384)
124409 -- Dependencies: 6920 234 193 8894
124410 -- Name: whsinfo_warehous_addr_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124411 --
124412
124413 ALTER TABLE ONLY whsinfo
124414     ADD CONSTRAINT whsinfo_warehous_addr_id_fkey FOREIGN KEY (warehous_addr_id) REFERENCES addr(addr_id);
124415
124416
124417 --
124418 -- TOC entry 7719 (class 2606 OID 146574389)
124419 -- Dependencies: 6816 204 193 8894
124420 -- Name: whsinfo_warehous_cntct_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124421 --
124422
124423 ALTER TABLE ONLY whsinfo
124424     ADD CONSTRAINT whsinfo_warehous_cntct_id_fkey FOREIGN KEY (warehous_cntct_id) REFERENCES cntct(cntct_id);
124425
124426
124427 --
124428 -- TOC entry 7720 (class 2606 OID 146574394)
124429 -- Dependencies: 7057 325 193 8894
124430 -- Name: whsinfo_warehous_costcat_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124431 --
124432
124433 ALTER TABLE ONLY whsinfo
124434     ADD CONSTRAINT whsinfo_warehous_costcat_id_fkey FOREIGN KEY (warehous_costcat_id) REFERENCES costcat(costcat_id);
124435
124436
124437 --
124438 -- TOC entry 7721 (class 2606 OID 146574399)
124439 -- Dependencies: 6984 282 193 8894
124440 -- Name: whsinfo_warehous_shipform_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124441 --
124442
124443 ALTER TABLE ONLY whsinfo
124444     ADD CONSTRAINT whsinfo_warehous_shipform_id_fkey FOREIGN KEY (warehous_shipform_id) REFERENCES shipform(shipform_id);
124445
124446
124447 --
124448 -- TOC entry 7722 (class 2606 OID 146574404)
124449 -- Dependencies: 7150 386 193 8894
124450 -- Name: whsinfo_warehous_shipvia_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124451 --
124452
124453 ALTER TABLE ONLY whsinfo
124454     ADD CONSTRAINT whsinfo_warehous_shipvia_id_fkey FOREIGN KEY (warehous_shipvia_id) REFERENCES shipvia(shipvia_id);
124455
124456
124457 --
124458 -- TOC entry 7723 (class 2606 OID 146574409)
124459 -- Dependencies: 7154 387 193 8894
124460 -- Name: whsinfo_warehous_sitetype_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124461 --
124462
124463 ALTER TABLE ONLY whsinfo
124464     ADD CONSTRAINT whsinfo_warehous_sitetype_id_fkey FOREIGN KEY (warehous_sitetype_id) REFERENCES sitetype(sitetype_id);
124465
124466
124467 --
124468 -- TOC entry 7724 (class 2606 OID 146574414)
124469 -- Dependencies: 6878 220 193 8894
124470 -- Name: whsinfo_warehous_taxzone_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124471 --
124472
124473 ALTER TABLE ONLY whsinfo
124474     ADD CONSTRAINT whsinfo_warehous_taxzone_id_fkey FOREIGN KEY (warehous_taxzone_id) REFERENCES taxzone(taxzone_id);
124475
124476
124477 --
124478 -- TOC entry 8049 (class 2606 OID 146574419)
124479 -- Dependencies: 7121 359 560 8894
124480 -- Name: wo_wo_womatl_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124481 --
124482
124483 ALTER TABLE ONLY wo
124484     ADD CONSTRAINT wo_wo_womatl_id_fkey FOREIGN KEY (wo_womatl_id) REFERENCES womatl(womatl_id) ON DELETE SET NULL;
124485
124486
124487 --
124488 -- TOC entry 7928 (class 2606 OID 146574424)
124489 -- Dependencies: 6800 200 359 8894
124490 -- Name: womatl_womatl_uom_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124491 --
124492
124493 ALTER TABLE ONLY womatl
124494     ADD CONSTRAINT womatl_womatl_uom_id_fkey FOREIGN KEY (womatl_uom_id) REFERENCES uom(uom_id);
124495
124496
124497 --
124498 -- TOC entry 8117 (class 2606 OID 146574429)
124499 -- Dependencies: 7417 623 850 8894
124500 -- Name: womatlpost_womatlpost_invhist_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124501 --
124502
124503 ALTER TABLE ONLY womatlpost
124504     ADD CONSTRAINT womatlpost_womatlpost_invhist_id_fkey FOREIGN KEY (womatlpost_invhist_id) REFERENCES invhist(invhist_id);
124505
124506
124507 --
124508 -- TOC entry 8118 (class 2606 OID 146574434)
124509 -- Dependencies: 7121 359 850 8894
124510 -- Name: womatlpost_womatlpost_womatl_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: admin
124511 --
124512
124513 ALTER TABLE ONLY womatlpost
124514     ADD CONSTRAINT womatlpost_womatlpost_womatl_id_fkey FOREIGN KEY (womatlpost_womatl_id) REFERENCES womatl(womatl_id) ON DELETE CASCADE;
124515
124516
124517 SET search_path = te, pg_catalog;
124518
124519 --
124520 -- TOC entry 8119 (class 2606 OID 146574439)
124521 -- Dependencies: 7662 859 860 8894
124522 -- Name: pkgcmdarg_cmdarg_cmd_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124523 --
124524
124525 ALTER TABLE ONLY pkgcmdarg
124526     ADD CONSTRAINT pkgcmdarg_cmdarg_cmd_id_fkey FOREIGN KEY (cmdarg_cmd_id) REFERENCES pkgcmd(cmd_id);
124527
124528
124529 --
124530 -- TOC entry 8120 (class 2606 OID 146574444)
124531 -- Dependencies: 6834 208 867 8894
124532 -- Name: tecustrate_tecustrate_curr_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124533 --
124534
124535 ALTER TABLE ONLY tecustrate
124536     ADD CONSTRAINT tecustrate_tecustrate_curr_id_fkey FOREIGN KEY (tecustrate_curr_id) REFERENCES public.curr_symbol(curr_id) ON DELETE SET DEFAULT;
124537
124538
124539 --
124540 -- TOC entry 8121 (class 2606 OID 146574449)
124541 -- Dependencies: 6853 213 867 8894
124542 -- Name: tecustrate_tecustrate_cust_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124543 --
124544
124545 ALTER TABLE ONLY tecustrate
124546     ADD CONSTRAINT tecustrate_tecustrate_cust_id_fkey FOREIGN KEY (tecustrate_cust_id) REFERENCES public.custinfo(cust_id) ON DELETE CASCADE;
124547
124548
124549 --
124550 -- TOC entry 8122 (class 2606 OID 146574454)
124551 -- Dependencies: 7002 292 869 8894
124552 -- Name: teemp_teemp_emp_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124553 --
124554
124555 ALTER TABLE ONLY teemp
124556     ADD CONSTRAINT teemp_teemp_emp_id_fkey FOREIGN KEY (teemp_emp_id) REFERENCES public.emp(emp_id) ON DELETE CASCADE;
124557
124558
124559 --
124560 -- TOC entry 8123 (class 2606 OID 146574459)
124561 -- Dependencies: 6834 208 875 8894
124562 -- Name: teitem_teitem_curr_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124563 --
124564
124565 ALTER TABLE ONLY teitem
124566     ADD CONSTRAINT teitem_teitem_curr_id_fkey FOREIGN KEY (teitem_curr_id) REFERENCES public.curr_symbol(curr_id) ON DELETE SET DEFAULT;
124567
124568
124569 --
124570 -- TOC entry 8124 (class 2606 OID 146574464)
124571 -- Dependencies: 6905 229 875 8894
124572 -- Name: teitem_teitem_invcitem_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124573 --
124574
124575 ALTER TABLE ONLY teitem
124576     ADD CONSTRAINT teitem_teitem_invcitem_id_fkey FOREIGN KEY (teitem_invcitem_id) REFERENCES public.invcitem(invcitem_id) ON DELETE SET NULL;
124577
124578
124579 --
124580 -- TOC entry 8125 (class 2606 OID 146574469)
124581 -- Dependencies: 7682 873 875 8894
124582 -- Name: teitem_teitem_tehead_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124583 --
124584
124585 ALTER TABLE ONLY teitem
124586     ADD CONSTRAINT teitem_teitem_tehead_id_fkey FOREIGN KEY (teitem_tehead_id) REFERENCES tehead(tehead_id) ON DELETE CASCADE;
124587
124588
124589 --
124590 -- TOC entry 8126 (class 2606 OID 146574474)
124591 -- Dependencies: 7640 837 875 8894
124592 -- Name: teitem_teitem_vodist_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124593 --
124594
124595 ALTER TABLE ONLY teitem
124596     ADD CONSTRAINT teitem_teitem_vodist_id_fkey FOREIGN KEY (teitem_vodist_id) REFERENCES public.vodist(vodist_id) ON DELETE SET NULL;
124597
124598
124599 --
124600 -- TOC entry 8127 (class 2606 OID 146574479)
124601 -- Dependencies: 6834 208 877 8894
124602 -- Name: teprj_teprj_curr_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124603 --
124604
124605 ALTER TABLE ONLY teprj
124606     ADD CONSTRAINT teprj_teprj_curr_id_fkey FOREIGN KEY (teprj_curr_id) REFERENCES public.curr_symbol(curr_id) ON DELETE SET NULL;
124607
124608
124609 --
124610 -- TOC entry 8128 (class 2606 OID 146574484)
124611 -- Dependencies: 6853 213 877 8894
124612 -- Name: teprj_teprj_cust_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124613 --
124614
124615 ALTER TABLE ONLY teprj
124616     ADD CONSTRAINT teprj_teprj_cust_id_fkey FOREIGN KEY (teprj_cust_id) REFERENCES public.custinfo(cust_id) ON DELETE SET NULL;
124617
124618
124619 --
124620 -- TOC entry 8129 (class 2606 OID 146574489)
124621 -- Dependencies: 6834 208 879 8894
124622 -- Name: teprjtask_teprjtask_curr_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124623 --
124624
124625 ALTER TABLE ONLY teprjtask
124626     ADD CONSTRAINT teprjtask_teprjtask_curr_id_fkey FOREIGN KEY (teprjtask_curr_id) REFERENCES public.curr_symbol(curr_id) ON DELETE SET DEFAULT;
124627
124628
124629 --
124630 -- TOC entry 8130 (class 2606 OID 146574494)
124631 -- Dependencies: 6751 191 879 8894
124632 -- Name: teprjtask_teprjtask_item_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124633 --
124634
124635 ALTER TABLE ONLY teprjtask
124636     ADD CONSTRAINT teprjtask_teprjtask_item_id_fkey FOREIGN KEY (teprjtask_item_id) REFERENCES public.item(item_id) ON DELETE SET NULL;
124637
124638
124639 --
124640 -- TOC entry 8131 (class 2606 OID 146574499)
124641 -- Dependencies: 6911 232 879 8894
124642 -- Name: teprjtask_teprjtask_prjtask_id_fkey; Type: FK CONSTRAINT; Schema: te; Owner: admin
124643 --
124644
124645 ALTER TABLE ONLY teprjtask
124646     ADD CONSTRAINT teprjtask_teprjtask_prjtask_id_fkey FOREIGN KEY (teprjtask_prjtask_id) REFERENCES public.prjtask(prjtask_id) ON DELETE CASCADE;
124647
124648
124649 SET search_path = xtdesktop, pg_catalog;
124650
124651 --
124652 -- TOC entry 8132 (class 2606 OID 146574504)
124653 -- Dependencies: 7693 881 882 8894
124654 -- Name: pkgcmdarg_cmdarg_cmd_id_fkey; Type: FK CONSTRAINT; Schema: xtdesktop; Owner: admin
124655 --
124656
124657 ALTER TABLE ONLY pkgcmdarg
124658     ADD CONSTRAINT pkgcmdarg_cmdarg_cmd_id_fkey FOREIGN KEY (cmdarg_cmd_id) REFERENCES pkgcmd(cmd_id);
124659
124660
124661 --
124662 -- TOC entry 8898 (class 0 OID 0)
124663 -- Dependencies: 6
124664 -- Name: api; Type: ACL; Schema: -; Owner: admin
124665 --
124666
124667 REVOKE ALL ON SCHEMA api FROM PUBLIC;
124668 REVOKE ALL ON SCHEMA api FROM admin;
124669 GRANT ALL ON SCHEMA api TO admin;
124670 GRANT ALL ON SCHEMA api TO xtrole;
124671
124672
124673 --
124674 -- TOC entry 8900 (class 0 OID 0)
124675 -- Dependencies: 7
124676 -- Name: fixcountry; Type: ACL; Schema: -; Owner: admin
124677 --
124678
124679 REVOKE ALL ON SCHEMA fixcountry FROM PUBLIC;
124680 REVOKE ALL ON SCHEMA fixcountry FROM admin;
124681 GRANT ALL ON SCHEMA fixcountry TO admin;
124682 GRANT ALL ON SCHEMA fixcountry TO xtrole;
124683
124684
124685 --
124686 -- TOC entry 8902 (class 0 OID 0)
124687 -- Dependencies: 8
124688 -- Name: public; Type: ACL; Schema: -; Owner: postgres
124689 --
124690
124691 REVOKE ALL ON SCHEMA public FROM PUBLIC;
124692 REVOKE ALL ON SCHEMA public FROM postgres;
124693 GRANT ALL ON SCHEMA public TO postgres;
124694 GRANT ALL ON SCHEMA public TO PUBLIC;
124695
124696
124697 --
124698 -- TOC entry 8904 (class 0 OID 0)
124699 -- Dependencies: 9
124700 -- Name: te; Type: ACL; Schema: -; Owner: admin
124701 --
124702
124703 REVOKE ALL ON SCHEMA te FROM PUBLIC;
124704 REVOKE ALL ON SCHEMA te FROM admin;
124705 GRANT ALL ON SCHEMA te TO admin;
124706 GRANT ALL ON SCHEMA te TO xtrole;
124707
124708
124709 --
124710 -- TOC entry 8906 (class 0 OID 0)
124711 -- Dependencies: 10
124712 -- Name: xtdesktop; Type: ACL; Schema: -; Owner: admin
124713 --
124714
124715 REVOKE ALL ON SCHEMA xtdesktop FROM PUBLIC;
124716 REVOKE ALL ON SCHEMA xtdesktop FROM admin;
124717 GRANT ALL ON SCHEMA xtdesktop TO admin;
124718 GRANT ALL ON SCHEMA xtdesktop TO xtrole;
124719
124720
124721 SET search_path = public, pg_catalog;
124722
124723 --
124724 -- TOC entry 8909 (class 0 OID 0)
124725 -- Dependencies: 189
124726 -- Name: cntslip; Type: ACL; Schema: public; Owner: admin
124727 --
124728
124729 REVOKE ALL ON TABLE cntslip FROM PUBLIC;
124730 REVOKE ALL ON TABLE cntslip FROM admin;
124731 GRANT ALL ON TABLE cntslip TO admin;
124732 GRANT ALL ON TABLE cntslip TO xtrole;
124733
124734
124735 --
124736 -- TOC entry 8911 (class 0 OID 0)
124737 -- Dependencies: 190
124738 -- Name: invcnt; Type: ACL; Schema: public; Owner: admin
124739 --
124740
124741 REVOKE ALL ON TABLE invcnt FROM PUBLIC;
124742 REVOKE ALL ON TABLE invcnt FROM admin;
124743 GRANT ALL ON TABLE invcnt TO admin;
124744 GRANT ALL ON TABLE invcnt TO xtrole;
124745
124746
124747 --
124748 -- TOC entry 8915 (class 0 OID 0)
124749 -- Dependencies: 191
124750 -- Name: item; Type: ACL; Schema: public; Owner: admin
124751 --
124752
124753 REVOKE ALL ON TABLE item FROM PUBLIC;
124754 REVOKE ALL ON TABLE item FROM admin;
124755 GRANT ALL ON TABLE item TO admin;
124756 GRANT ALL ON TABLE item TO xtrole;
124757
124758
124759 --
124760 -- TOC entry 8921 (class 0 OID 0)
124761 -- Dependencies: 192
124762 -- Name: itemsite; Type: ACL; Schema: public; Owner: admin
124763 --
124764
124765 REVOKE ALL ON TABLE itemsite FROM PUBLIC;
124766 REVOKE ALL ON TABLE itemsite FROM admin;
124767 GRANT ALL ON TABLE itemsite TO admin;
124768 GRANT ALL ON TABLE itemsite TO xtrole;
124769
124770
124771 --
124772 -- TOC entry 8923 (class 0 OID 0)
124773 -- Dependencies: 193
124774 -- Name: whsinfo; Type: ACL; Schema: public; Owner: admin
124775 --
124776
124777 REVOKE ALL ON TABLE whsinfo FROM PUBLIC;
124778 REVOKE ALL ON TABLE whsinfo FROM admin;
124779 GRANT ALL ON TABLE whsinfo TO admin;
124780 GRANT ALL ON TABLE whsinfo TO xtrole;
124781
124782
124783 SET search_path = api, pg_catalog;
124784
124785 --
124786 -- TOC entry 8925 (class 0 OID 0)
124787 -- Dependencies: 194
124788 -- Name: physinvcount; Type: ACL; Schema: api; Owner: admin
124789 --
124790
124791 REVOKE ALL ON TABLE physinvcount FROM PUBLIC;
124792 REVOKE ALL ON TABLE physinvcount FROM admin;
124793 GRANT ALL ON TABLE physinvcount TO admin;
124794 GRANT ALL ON TABLE physinvcount TO xtrole;
124795
124796
124797 SET search_path = public, pg_catalog;
124798
124799 --
124800 -- TOC entry 8929 (class 0 OID 0)
124801 -- Dependencies: 195
124802 -- Name: cohead; Type: ACL; Schema: public; Owner: admin
124803 --
124804
124805 REVOKE ALL ON TABLE cohead FROM PUBLIC;
124806 REVOKE ALL ON TABLE cohead FROM admin;
124807 GRANT ALL ON TABLE cohead TO admin;
124808 GRANT ALL ON TABLE cohead TO xtrole;
124809
124810
124811 --
124812 -- TOC entry 8932 (class 0 OID 0)
124813 -- Dependencies: 196
124814 -- Name: coitem; Type: ACL; Schema: public; Owner: admin
124815 --
124816
124817 REVOKE ALL ON TABLE coitem FROM PUBLIC;
124818 REVOKE ALL ON TABLE coitem FROM admin;
124819 GRANT ALL ON TABLE coitem TO admin;
124820 GRANT ALL ON TABLE coitem TO xtrole;
124821
124822
124823 --
124824 -- TOC entry 8934 (class 0 OID 0)
124825 -- Dependencies: 197
124826 -- Name: pohead; Type: ACL; Schema: public; Owner: admin
124827 --
124828
124829 REVOKE ALL ON TABLE pohead FROM PUBLIC;
124830 REVOKE ALL ON TABLE pohead FROM admin;
124831 GRANT ALL ON TABLE pohead TO admin;
124832 GRANT ALL ON TABLE pohead TO xtrole;
124833
124834
124835 --
124836 -- TOC entry 8936 (class 0 OID 0)
124837 -- Dependencies: 198
124838 -- Name: poitem; Type: ACL; Schema: public; Owner: admin
124839 --
124840
124841 REVOKE ALL ON TABLE poitem FROM PUBLIC;
124842 REVOKE ALL ON TABLE poitem FROM admin;
124843 GRANT ALL ON TABLE poitem TO admin;
124844 GRANT ALL ON TABLE poitem TO xtrole;
124845
124846
124847 --
124848 -- TOC entry 8938 (class 0 OID 0)
124849 -- Dependencies: 199
124850 -- Name: taxtype; Type: ACL; Schema: public; Owner: admin
124851 --
124852
124853 REVOKE ALL ON TABLE taxtype FROM PUBLIC;
124854 REVOKE ALL ON TABLE taxtype FROM admin;
124855 GRANT ALL ON TABLE taxtype TO admin;
124856 GRANT ALL ON TABLE taxtype TO xtrole;
124857
124858
124859 --
124860 -- TOC entry 8940 (class 0 OID 0)
124861 -- Dependencies: 200
124862 -- Name: uom; Type: ACL; Schema: public; Owner: admin
124863 --
124864
124865 REVOKE ALL ON TABLE uom FROM PUBLIC;
124866 REVOKE ALL ON TABLE uom FROM admin;
124867 GRANT ALL ON TABLE uom TO admin;
124868 GRANT ALL ON TABLE uom TO xtrole;
124869
124870
124871 SET search_path = api, pg_catalog;
124872
124873 --
124874 -- TOC entry 8942 (class 0 OID 0)
124875 -- Dependencies: 201
124876 -- Name: salesline; Type: ACL; Schema: api; Owner: admin
124877 --
124878
124879 REVOKE ALL ON TABLE salesline FROM PUBLIC;
124880 REVOKE ALL ON TABLE salesline FROM admin;
124881 GRANT ALL ON TABLE salesline TO admin;
124882 GRANT ALL ON TABLE salesline TO xtrole;
124883
124884
124885 SET search_path = public, pg_catalog;
124886
124887 --
124888 -- TOC entry 8943 (class 0 OID 0)
124889 -- Dependencies: 202
124890 -- Name: invbal; Type: ACL; Schema: public; Owner: admin
124891 --
124892
124893 REVOKE ALL ON TABLE invbal FROM PUBLIC;
124894 REVOKE ALL ON TABLE invbal FROM admin;
124895 GRANT ALL ON TABLE invbal TO admin;
124896 GRANT ALL ON TABLE invbal TO xtrole;
124897
124898
124899 --
124900 -- TOC entry 8946 (class 0 OID 0)
124901 -- Dependencies: 203
124902 -- Name: bomitem; Type: ACL; Schema: public; Owner: admin
124903 --
124904
124905 REVOKE ALL ON TABLE bomitem FROM PUBLIC;
124906 REVOKE ALL ON TABLE bomitem FROM admin;
124907 GRANT ALL ON TABLE bomitem TO admin;
124908 GRANT ALL ON TABLE bomitem TO xtrole;
124909
124910
124911 --
124912 -- TOC entry 8951 (class 0 OID 0)
124913 -- Dependencies: 204
124914 -- Name: cntct; Type: ACL; Schema: public; Owner: admin
124915 --
124916
124917 REVOKE ALL ON TABLE cntct FROM PUBLIC;
124918 REVOKE ALL ON TABLE cntct FROM admin;
124919 GRANT ALL ON TABLE cntct TO admin;
124920 GRANT ALL ON TABLE cntct TO xtrole;
124921
124922
124923 --
124924 -- TOC entry 8973 (class 0 OID 0)
124925 -- Dependencies: 205
124926 -- Name: crmacct; Type: ACL; Schema: public; Owner: admin
124927 --
124928
124929 REVOKE ALL ON TABLE crmacct FROM PUBLIC;
124930 REVOKE ALL ON TABLE crmacct FROM admin;
124931 GRANT ALL ON TABLE crmacct TO admin;
124932 GRANT ALL ON TABLE crmacct TO xtrole;
124933
124934
124935 --
124936 -- TOC entry 8979 (class 0 OID 0)
124937 -- Dependencies: 206
124938 -- Name: incdt; Type: ACL; Schema: public; Owner: admin
124939 --
124940
124941 REVOKE ALL ON TABLE incdt FROM PUBLIC;
124942 REVOKE ALL ON TABLE incdt FROM admin;
124943 GRANT ALL ON TABLE incdt TO admin;
124944 GRANT ALL ON TABLE incdt TO xtrole;
124945
124946
124947 --
124948 -- TOC entry 8982 (class 0 OID 0)
124949 -- Dependencies: 207
124950 -- Name: apopen; Type: ACL; Schema: public; Owner: admin
124951 --
124952
124953 REVOKE ALL ON TABLE apopen FROM PUBLIC;
124954 REVOKE ALL ON TABLE apopen FROM admin;
124955 GRANT ALL ON TABLE apopen TO admin;
124956 GRANT ALL ON TABLE apopen TO xtrole;
124957
124958
124959 --
124960 -- TOC entry 8984 (class 0 OID 0)
124961 -- Dependencies: 208
124962 -- Name: curr_symbol; Type: ACL; Schema: public; Owner: admin
124963 --
124964
124965 REVOKE ALL ON TABLE curr_symbol FROM PUBLIC;
124966 REVOKE ALL ON TABLE curr_symbol FROM admin;
124967 GRANT ALL ON TABLE curr_symbol TO admin;
124968 GRANT ALL ON TABLE curr_symbol TO xtrole;
124969
124970
124971 --
124972 -- TOC entry 8986 (class 0 OID 0)
124973 -- Dependencies: 209
124974 -- Name: terms; Type: ACL; Schema: public; Owner: admin
124975 --
124976
124977 REVOKE ALL ON TABLE terms FROM PUBLIC;
124978 REVOKE ALL ON TABLE terms FROM admin;
124979 GRANT ALL ON TABLE terms TO admin;
124980 GRANT ALL ON TABLE terms TO xtrole;
124981
124982
124983 --
124984 -- TOC entry 8989 (class 0 OID 0)
124985 -- Dependencies: 210
124986 -- Name: vendinfo; Type: ACL; Schema: public; Owner: admin
124987 --
124988
124989 REVOKE ALL ON TABLE vendinfo FROM PUBLIC;
124990 REVOKE ALL ON TABLE vendinfo FROM admin;
124991 GRANT ALL ON TABLE vendinfo TO admin;
124992 GRANT ALL ON TABLE vendinfo TO xtrole;
124993
124994
124995 SET search_path = api, pg_catalog;
124996
124997 --
124998 -- TOC entry 8991 (class 0 OID 0)
124999 -- Dependencies: 211
125000 -- Name: apmemo; Type: ACL; Schema: api; Owner: admin
125001 --
125002
125003 REVOKE ALL ON TABLE apmemo FROM PUBLIC;
125004 REVOKE ALL ON TABLE apmemo FROM admin;
125005 GRANT ALL ON TABLE apmemo TO admin;
125006 GRANT ALL ON TABLE apmemo TO xtrole;
125007
125008
125009 SET search_path = public, pg_catalog;
125010
125011 --
125012 -- TOC entry 8993 (class 0 OID 0)
125013 -- Dependencies: 212
125014 -- Name: aropen; Type: ACL; Schema: public; Owner: admin
125015 --
125016
125017 REVOKE ALL ON TABLE aropen FROM PUBLIC;
125018 REVOKE ALL ON TABLE aropen FROM admin;
125019 GRANT ALL ON TABLE aropen TO admin;
125020 GRANT ALL ON TABLE aropen TO xtrole;
125021
125022
125023 --
125024 -- TOC entry 9009 (class 0 OID 0)
125025 -- Dependencies: 213
125026 -- Name: custinfo; Type: ACL; Schema: public; Owner: admin
125027 --
125028
125029 REVOKE ALL ON TABLE custinfo FROM PUBLIC;
125030 REVOKE ALL ON TABLE custinfo FROM admin;
125031 GRANT ALL ON TABLE custinfo TO admin;
125032 GRANT ALL ON TABLE custinfo TO xtrole;
125033
125034
125035 --
125036 -- TOC entry 9011 (class 0 OID 0)
125037 -- Dependencies: 214
125038 -- Name: rsncode; Type: ACL; Schema: public; Owner: admin
125039 --
125040
125041 REVOKE ALL ON TABLE rsncode FROM PUBLIC;
125042 REVOKE ALL ON TABLE rsncode FROM admin;
125043 GRANT ALL ON TABLE rsncode TO admin;
125044 GRANT ALL ON TABLE rsncode TO xtrole;
125045
125046
125047 --
125048 -- TOC entry 9013 (class 0 OID 0)
125049 -- Dependencies: 215
125050 -- Name: salescat; Type: ACL; Schema: public; Owner: admin
125051 --
125052
125053 REVOKE ALL ON TABLE salescat FROM PUBLIC;
125054 REVOKE ALL ON TABLE salescat FROM admin;
125055 GRANT ALL ON TABLE salescat TO admin;
125056 GRANT ALL ON TABLE salescat TO xtrole;
125057
125058
125059 --
125060 -- TOC entry 9016 (class 0 OID 0)
125061 -- Dependencies: 216
125062 -- Name: salesrep; Type: ACL; Schema: public; Owner: admin
125063 --
125064
125065 REVOKE ALL ON TABLE salesrep FROM PUBLIC;
125066 REVOKE ALL ON TABLE salesrep FROM admin;
125067 GRANT ALL ON TABLE salesrep TO admin;
125068 GRANT ALL ON TABLE salesrep TO xtrole;
125069
125070
125071 SET search_path = api, pg_catalog;
125072
125073 --
125074 -- TOC entry 9018 (class 0 OID 0)
125075 -- Dependencies: 217
125076 -- Name: armemo; Type: ACL; Schema: api; Owner: admin
125077 --
125078
125079 REVOKE ALL ON TABLE armemo FROM PUBLIC;
125080 REVOKE ALL ON TABLE armemo FROM admin;
125081 GRANT ALL ON TABLE armemo TO admin;
125082 GRANT ALL ON TABLE armemo TO xtrole;
125083
125084
125085 SET search_path = public, pg_catalog;
125086
125087 --
125088 -- TOC entry 9024 (class 0 OID 0)
125089 -- Dependencies: 218
125090 -- Name: cmhead; Type: ACL; Schema: public; Owner: admin
125091 --
125092
125093 REVOKE ALL ON TABLE cmhead FROM PUBLIC;
125094 REVOKE ALL ON TABLE cmhead FROM admin;
125095 GRANT ALL ON TABLE cmhead TO admin;
125096 GRANT ALL ON TABLE cmhead TO xtrole;
125097
125098
125099 --
125100 -- TOC entry 9027 (class 0 OID 0)
125101 -- Dependencies: 219
125102 -- Name: shiptoinfo; Type: ACL; Schema: public; Owner: admin
125103 --
125104
125105 REVOKE ALL ON TABLE shiptoinfo FROM PUBLIC;
125106 REVOKE ALL ON TABLE shiptoinfo FROM admin;
125107 GRANT ALL ON TABLE shiptoinfo TO admin;
125108 GRANT ALL ON TABLE shiptoinfo TO xtrole;
125109
125110
125111 --
125112 -- TOC entry 9032 (class 0 OID 0)
125113 -- Dependencies: 220
125114 -- Name: taxzone; Type: ACL; Schema: public; Owner: admin
125115 --
125116
125117 REVOKE ALL ON TABLE taxzone FROM PUBLIC;
125118 REVOKE ALL ON TABLE taxzone FROM admin;
125119 GRANT ALL ON TABLE taxzone TO admin;
125120 GRANT ALL ON TABLE taxzone TO xtrole;
125121
125122
125123 SET search_path = api, pg_catalog;
125124
125125 --
125126 -- TOC entry 9034 (class 0 OID 0)
125127 -- Dependencies: 221
125128 -- Name: creditmemo; Type: ACL; Schema: api; Owner: admin
125129 --
125130
125131 REVOKE ALL ON TABLE creditmemo FROM PUBLIC;
125132 REVOKE ALL ON TABLE creditmemo FROM admin;
125133 GRANT ALL ON TABLE creditmemo TO admin;
125134 GRANT ALL ON TABLE creditmemo TO xtrole;
125135
125136
125137 SET search_path = public, pg_catalog;
125138
125139 --
125140 -- TOC entry 9036 (class 0 OID 0)
125141 -- Dependencies: 222
125142 -- Name: cmitem; Type: ACL; Schema: public; Owner: admin
125143 --
125144
125145 REVOKE ALL ON TABLE cmitem FROM PUBLIC;
125146 REVOKE ALL ON TABLE cmitem FROM admin;
125147 GRANT ALL ON TABLE cmitem TO admin;
125148 GRANT ALL ON TABLE cmitem TO xtrole;
125149
125150
125151 SET search_path = api, pg_catalog;
125152
125153 --
125154 -- TOC entry 9038 (class 0 OID 0)
125155 -- Dependencies: 223
125156 -- Name: creditmemoline; Type: ACL; Schema: api; Owner: admin
125157 --
125158
125159 REVOKE ALL ON TABLE creditmemoline FROM PUBLIC;
125160 REVOKE ALL ON TABLE creditmemoline FROM admin;
125161 GRANT ALL ON TABLE creditmemoline TO admin;
125162 GRANT ALL ON TABLE creditmemoline TO xtrole;
125163
125164
125165 SET search_path = public, pg_catalog;
125166
125167 --
125168 -- TOC entry 9046 (class 0 OID 0)
125169 -- Dependencies: 224
125170 -- Name: invchead; Type: ACL; Schema: public; Owner: admin
125171 --
125172
125173 REVOKE ALL ON TABLE invchead FROM PUBLIC;
125174 REVOKE ALL ON TABLE invchead FROM admin;
125175 GRANT ALL ON TABLE invchead TO admin;
125176 GRANT ALL ON TABLE invchead TO xtrole;
125177
125178
125179 --
125180 -- TOC entry 9049 (class 0 OID 0)
125181 -- Dependencies: 225
125182 -- Name: prj; Type: ACL; Schema: public; Owner: admin
125183 --
125184
125185 REVOKE ALL ON TABLE prj FROM PUBLIC;
125186 REVOKE ALL ON TABLE prj FROM admin;
125187 GRANT ALL ON TABLE prj TO admin;
125188 GRANT ALL ON TABLE prj TO xtrole;
125189
125190
125191 --
125192 -- TOC entry 9055 (class 0 OID 0)
125193 -- Dependencies: 226
125194 -- Name: saletype; Type: ACL; Schema: public; Owner: admin
125195 --
125196
125197 REVOKE ALL ON TABLE saletype FROM PUBLIC;
125198 REVOKE ALL ON TABLE saletype FROM admin;
125199 GRANT ALL ON TABLE saletype TO admin;
125200 GRANT ALL ON TABLE saletype TO xtrole;
125201
125202
125203 --
125204 -- TOC entry 9057 (class 0 OID 0)
125205 -- Dependencies: 227
125206 -- Name: shipzone; Type: ACL; Schema: public; Owner: admin
125207 --
125208
125209 REVOKE ALL ON TABLE shipzone FROM PUBLIC;
125210 REVOKE ALL ON TABLE shipzone FROM admin;
125211 GRANT ALL ON TABLE shipzone TO admin;
125212 GRANT ALL ON TABLE shipzone TO xtrole;
125213
125214
125215 SET search_path = api, pg_catalog;
125216
125217 --
125218 -- TOC entry 9059 (class 0 OID 0)
125219 -- Dependencies: 228
125220 -- Name: invoice; Type: ACL; Schema: api; Owner: admin
125221 --
125222
125223 REVOKE ALL ON TABLE invoice FROM PUBLIC;
125224 REVOKE ALL ON TABLE invoice FROM admin;
125225 GRANT ALL ON TABLE invoice TO admin;
125226 GRANT ALL ON TABLE invoice TO xtrole;
125227
125228
125229 SET search_path = public, pg_catalog;
125230
125231 --
125232 -- TOC entry 9061 (class 0 OID 0)
125233 -- Dependencies: 229
125234 -- Name: invcitem; Type: ACL; Schema: public; Owner: admin
125235 --
125236
125237 REVOKE ALL ON TABLE invcitem FROM PUBLIC;
125238 REVOKE ALL ON TABLE invcitem FROM admin;
125239 GRANT ALL ON TABLE invcitem TO admin;
125240 GRANT ALL ON TABLE invcitem TO xtrole;
125241
125242
125243 SET search_path = api, pg_catalog;
125244
125245 --
125246 -- TOC entry 9063 (class 0 OID 0)
125247 -- Dependencies: 230
125248 -- Name: invoiceline; Type: ACL; Schema: api; Owner: admin
125249 --
125250
125251 REVOKE ALL ON TABLE invoiceline FROM PUBLIC;
125252 REVOKE ALL ON TABLE invoiceline FROM admin;
125253 GRANT ALL ON TABLE invoiceline TO admin;
125254 GRANT ALL ON TABLE invoiceline TO xtrole;
125255
125256
125257 SET search_path = public, pg_catalog;
125258
125259 --
125260 -- TOC entry 9068 (class 0 OID 0)
125261 -- Dependencies: 231
125262 -- Name: ophead; Type: ACL; Schema: public; Owner: admin
125263 --
125264
125265 REVOKE ALL ON TABLE ophead FROM PUBLIC;
125266 REVOKE ALL ON TABLE ophead FROM admin;
125267 GRANT ALL ON TABLE ophead TO admin;
125268 GRANT ALL ON TABLE ophead TO xtrole;
125269
125270
125271 --
125272 -- TOC entry 9073 (class 0 OID 0)
125273 -- Dependencies: 232
125274 -- Name: prjtask; Type: ACL; Schema: public; Owner: admin
125275 --
125276
125277 REVOKE ALL ON TABLE prjtask FROM PUBLIC;
125278 REVOKE ALL ON TABLE prjtask FROM admin;
125279 GRANT ALL ON TABLE prjtask TO admin;
125280 GRANT ALL ON TABLE prjtask TO xtrole;
125281
125282
125283 --
125284 -- TOC entry 9078 (class 0 OID 0)
125285 -- Dependencies: 233
125286 -- Name: todoitem; Type: ACL; Schema: public; Owner: admin
125287 --
125288
125289 REVOKE ALL ON TABLE todoitem FROM PUBLIC;
125290 REVOKE ALL ON TABLE todoitem FROM admin;
125291 GRANT ALL ON TABLE todoitem TO admin;
125292 GRANT ALL ON TABLE todoitem TO xtrole;
125293
125294
125295 --
125296 -- TOC entry 9082 (class 0 OID 0)
125297 -- Dependencies: 234
125298 -- Name: addr; Type: ACL; Schema: public; Owner: admin
125299 --
125300
125301 REVOKE ALL ON TABLE addr FROM PUBLIC;
125302 REVOKE ALL ON TABLE addr FROM admin;
125303 GRANT ALL ON TABLE addr TO admin;
125304 GRANT ALL ON TABLE addr TO xtrole;
125305
125306
125307 SET search_path = api, pg_catalog;
125308
125309 --
125310 -- TOC entry 9084 (class 0 OID 0)
125311 -- Dependencies: 235
125312 -- Name: account; Type: ACL; Schema: api; Owner: admin
125313 --
125314
125315 REVOKE ALL ON TABLE account FROM PUBLIC;
125316 REVOKE ALL ON TABLE account FROM admin;
125317 GRANT ALL ON TABLE account TO admin;
125318 GRANT ALL ON TABLE account TO xtrole;
125319
125320
125321 SET search_path = public, pg_catalog;
125322
125323 --
125324 -- TOC entry 9086 (class 0 OID 0)
125325 -- Dependencies: 236
125326 -- Name: char; Type: ACL; Schema: public; Owner: admin
125327 --
125328
125329 REVOKE ALL ON TABLE "char" FROM PUBLIC;
125330 REVOKE ALL ON TABLE "char" FROM admin;
125331 GRANT ALL ON TABLE "char" TO admin;
125332 GRANT ALL ON TABLE "char" TO xtrole;
125333
125334
125335 --
125336 -- TOC entry 9088 (class 0 OID 0)
125337 -- Dependencies: 237
125338 -- Name: charass; Type: ACL; Schema: public; Owner: admin
125339 --
125340
125341 REVOKE ALL ON TABLE charass FROM PUBLIC;
125342 REVOKE ALL ON TABLE charass FROM admin;
125343 GRANT ALL ON TABLE charass TO admin;
125344 GRANT ALL ON TABLE charass TO xtrole;
125345
125346
125347 SET search_path = api, pg_catalog;
125348
125349 --
125350 -- TOC entry 9090 (class 0 OID 0)
125351 -- Dependencies: 238
125352 -- Name: accountchar; Type: ACL; Schema: api; Owner: admin
125353 --
125354
125355 REVOKE ALL ON TABLE accountchar FROM PUBLIC;
125356 REVOKE ALL ON TABLE accountchar FROM admin;
125357 GRANT ALL ON TABLE accountchar TO admin;
125358 GRANT ALL ON TABLE accountchar TO xtrole;
125359
125360
125361 SET search_path = public, pg_catalog;
125362
125363 --
125364 -- TOC entry 9092 (class 0 OID 0)
125365 -- Dependencies: 239
125366 -- Name: cmnttype; Type: ACL; Schema: public; Owner: admin
125367 --
125368
125369 REVOKE ALL ON TABLE cmnttype FROM PUBLIC;
125370 REVOKE ALL ON TABLE cmnttype FROM admin;
125371 GRANT ALL ON TABLE cmnttype TO admin;
125372 GRANT ALL ON TABLE cmnttype TO xtrole;
125373
125374
125375 --
125376 -- TOC entry 9094 (class 0 OID 0)
125377 -- Dependencies: 240
125378 -- Name: comment; Type: ACL; Schema: public; Owner: admin
125379 --
125380
125381 REVOKE ALL ON TABLE comment FROM PUBLIC;
125382 REVOKE ALL ON TABLE comment FROM admin;
125383 GRANT ALL ON TABLE comment TO admin;
125384 GRANT ALL ON TABLE comment TO xtrole;
125385
125386
125387 SET search_path = api, pg_catalog;
125388
125389 --
125390 -- TOC entry 9096 (class 0 OID 0)
125391 -- Dependencies: 241
125392 -- Name: accountcomment; Type: ACL; Schema: api; Owner: admin
125393 --
125394
125395 REVOKE ALL ON TABLE accountcomment FROM PUBLIC;
125396 REVOKE ALL ON TABLE accountcomment FROM admin;
125397 GRANT ALL ON TABLE accountcomment TO admin;
125398 GRANT ALL ON TABLE accountcomment TO xtrole;
125399
125400
125401 SET search_path = public, pg_catalog;
125402
125403 --
125404 -- TOC entry 9098 (class 0 OID 0)
125405 -- Dependencies: 242
125406 -- Name: docass; Type: ACL; Schema: public; Owner: admin
125407 --
125408
125409 REVOKE ALL ON TABLE docass FROM PUBLIC;
125410 REVOKE ALL ON TABLE docass FROM admin;
125411 GRANT ALL ON TABLE docass TO admin;
125412 GRANT ALL ON TABLE docass TO xtrole;
125413
125414
125415 --
125416 -- TOC entry 9099 (class 0 OID 0)
125417 -- Dependencies: 243
125418 -- Name: file; Type: ACL; Schema: public; Owner: admin
125419 --
125420
125421 REVOKE ALL ON TABLE file FROM PUBLIC;
125422 REVOKE ALL ON TABLE file FROM admin;
125423 GRANT ALL ON TABLE file TO admin;
125424 GRANT ALL ON TABLE file TO xtrole;
125425
125426
125427 --
125428 -- TOC entry 9100 (class 0 OID 0)
125429 -- Dependencies: 244
125430 -- Name: urlinfo; Type: ACL; Schema: public; Owner: admin
125431 --
125432
125433 REVOKE ALL ON TABLE urlinfo FROM PUBLIC;
125434 REVOKE ALL ON TABLE urlinfo FROM admin;
125435 GRANT ALL ON TABLE urlinfo TO admin;
125436 GRANT ALL ON TABLE urlinfo TO xtrole;
125437
125438
125439 --
125440 -- TOC entry 9101 (class 0 OID 0)
125441 -- Dependencies: 245
125442 -- Name: url; Type: ACL; Schema: public; Owner: admin
125443 --
125444
125445 REVOKE ALL ON TABLE url FROM PUBLIC;
125446 REVOKE ALL ON TABLE url FROM admin;
125447 GRANT ALL ON TABLE url TO admin;
125448 GRANT ALL ON TABLE url TO xtrole;
125449
125450
125451 SET search_path = api, pg_catalog;
125452
125453 --
125454 -- TOC entry 9103 (class 0 OID 0)
125455 -- Dependencies: 246
125456 -- Name: accountfile; Type: ACL; Schema: api; Owner: admin
125457 --
125458
125459 REVOKE ALL ON TABLE accountfile FROM PUBLIC;
125460 REVOKE ALL ON TABLE accountfile FROM admin;
125461 GRANT ALL ON TABLE accountfile TO admin;
125462 GRANT ALL ON TABLE accountfile TO xtrole;
125463
125464
125465 SET search_path = public, pg_catalog;
125466
125467 --
125468 -- TOC entry 9105 (class 0 OID 0)
125469 -- Dependencies: 247
125470 -- Name: docass_docass_id_seq; Type: ACL; Schema: public; Owner: admin
125471 --
125472
125473 REVOKE ALL ON SEQUENCE docass_docass_id_seq FROM PUBLIC;
125474 REVOKE ALL ON SEQUENCE docass_docass_id_seq FROM admin;
125475 GRANT ALL ON SEQUENCE docass_docass_id_seq TO admin;
125476 GRANT ALL ON SEQUENCE docass_docass_id_seq TO xtrole;
125477
125478
125479 --
125480 -- TOC entry 9107 (class 0 OID 0)
125481 -- Dependencies: 248
125482 -- Name: image; Type: ACL; Schema: public; Owner: admin
125483 --
125484
125485 REVOKE ALL ON TABLE image FROM PUBLIC;
125486 REVOKE ALL ON TABLE image FROM admin;
125487 GRANT ALL ON TABLE image TO admin;
125488 GRANT ALL ON TABLE image TO xtrole;
125489
125490
125491 --
125492 -- TOC entry 9109 (class 0 OID 0)
125493 -- Dependencies: 249
125494 -- Name: imageass; Type: ACL; Schema: public; Owner: admin
125495 --
125496
125497 REVOKE ALL ON TABLE imageass FROM PUBLIC;
125498 REVOKE ALL ON TABLE imageass FROM admin;
125499 GRANT ALL ON TABLE imageass TO admin;
125500 GRANT ALL ON TABLE imageass TO xtrole;
125501
125502
125503 SET search_path = api, pg_catalog;
125504
125505 --
125506 -- TOC entry 9111 (class 0 OID 0)
125507 -- Dependencies: 250
125508 -- Name: accountimage; Type: ACL; Schema: api; Owner: admin
125509 --
125510
125511 REVOKE ALL ON TABLE accountimage FROM PUBLIC;
125512 REVOKE ALL ON TABLE accountimage FROM admin;
125513 GRANT ALL ON TABLE accountimage TO admin;
125514 GRANT ALL ON TABLE accountimage TO xtrole;
125515
125516
125517 --
125518 -- TOC entry 9113 (class 0 OID 0)
125519 -- Dependencies: 251
125520 -- Name: address; Type: ACL; Schema: api; Owner: admin
125521 --
125522
125523 REVOKE ALL ON TABLE address FROM PUBLIC;
125524 REVOKE ALL ON TABLE address FROM admin;
125525 GRANT ALL ON TABLE address TO admin;
125526 GRANT ALL ON TABLE address TO xtrole;
125527
125528
125529 --
125530 -- TOC entry 9115 (class 0 OID 0)
125531 -- Dependencies: 252
125532 -- Name: addresschar; Type: ACL; Schema: api; Owner: admin
125533 --
125534
125535 REVOKE ALL ON TABLE addresschar FROM PUBLIC;
125536 REVOKE ALL ON TABLE addresschar FROM admin;
125537 GRANT ALL ON TABLE addresschar TO admin;
125538 GRANT ALL ON TABLE addresschar TO xtrole;
125539
125540
125541 --
125542 -- TOC entry 9117 (class 0 OID 0)
125543 -- Dependencies: 253
125544 -- Name: addresscomment; Type: ACL; Schema: api; Owner: admin
125545 --
125546
125547 REVOKE ALL ON TABLE addresscomment FROM PUBLIC;
125548 REVOKE ALL ON TABLE addresscomment FROM admin;
125549 GRANT ALL ON TABLE addresscomment TO admin;
125550 GRANT ALL ON TABLE addresscomment TO xtrole;
125551
125552
125553 SET search_path = public, pg_catalog;
125554
125555 --
125556 -- TOC entry 9119 (class 0 OID 0)
125557 -- Dependencies: 254
125558 -- Name: bomhead; Type: ACL; Schema: public; Owner: admin
125559 --
125560
125561 REVOKE ALL ON TABLE bomhead FROM PUBLIC;
125562 REVOKE ALL ON TABLE bomhead FROM admin;
125563 GRANT ALL ON TABLE bomhead TO admin;
125564 GRANT ALL ON TABLE bomhead TO xtrole;
125565
125566
125567 SET search_path = api, pg_catalog;
125568
125569 --
125570 -- TOC entry 9121 (class 0 OID 0)
125571 -- Dependencies: 255
125572 -- Name: bom; Type: ACL; Schema: api; Owner: admin
125573 --
125574
125575 REVOKE ALL ON TABLE bom FROM PUBLIC;
125576 REVOKE ALL ON TABLE bom FROM admin;
125577 GRANT ALL ON TABLE bom TO admin;
125578 GRANT ALL ON TABLE bom TO xtrole;
125579
125580
125581 --
125582 -- TOC entry 9123 (class 0 OID 0)
125583 -- Dependencies: 256
125584 -- Name: bomitem; Type: ACL; Schema: api; Owner: admin
125585 --
125586
125587 REVOKE ALL ON TABLE bomitem FROM PUBLIC;
125588 REVOKE ALL ON TABLE bomitem FROM admin;
125589 GRANT ALL ON TABLE bomitem TO admin;
125590 GRANT ALL ON TABLE bomitem TO xtrole;
125591
125592
125593 --
125594 -- TOC entry 9125 (class 0 OID 0)
125595 -- Dependencies: 257
125596 -- Name: bomitemcomment; Type: ACL; Schema: api; Owner: admin
125597 --
125598
125599 REVOKE ALL ON TABLE bomitemcomment FROM PUBLIC;
125600 REVOKE ALL ON TABLE bomitemcomment FROM admin;
125601 GRANT ALL ON TABLE bomitemcomment TO admin;
125602 GRANT ALL ON TABLE bomitemcomment TO xtrole;
125603
125604
125605 SET search_path = public, pg_catalog;
125606
125607 --
125608 -- TOC entry 9127 (class 0 OID 0)
125609 -- Dependencies: 258
125610 -- Name: bomitemsub; Type: ACL; Schema: public; Owner: admin
125611 --
125612
125613 REVOKE ALL ON TABLE bomitemsub FROM PUBLIC;
125614 REVOKE ALL ON TABLE bomitemsub FROM admin;
125615 GRANT ALL ON TABLE bomitemsub TO admin;
125616 GRANT ALL ON TABLE bomitemsub TO xtrole;
125617
125618
125619 SET search_path = api, pg_catalog;
125620
125621 --
125622 -- TOC entry 9129 (class 0 OID 0)
125623 -- Dependencies: 259
125624 -- Name: bomitemsubstitute; Type: ACL; Schema: api; Owner: admin
125625 --
125626
125627 REVOKE ALL ON TABLE bomitemsubstitute FROM PUBLIC;
125628 REVOKE ALL ON TABLE bomitemsubstitute FROM admin;
125629 GRANT ALL ON TABLE bomitemsubstitute TO admin;
125630 GRANT ALL ON TABLE bomitemsubstitute TO xtrole;
125631
125632
125633 SET search_path = public, pg_catalog;
125634
125635 --
125636 -- TOC entry 9130 (class 0 OID 0)
125637 -- Dependencies: 260
125638 -- Name: budghead; Type: ACL; Schema: public; Owner: admin
125639 --
125640
125641 REVOKE ALL ON TABLE budghead FROM PUBLIC;
125642 REVOKE ALL ON TABLE budghead FROM admin;
125643 GRANT ALL ON TABLE budghead TO admin;
125644 GRANT ALL ON TABLE budghead TO xtrole;
125645
125646
125647 SET search_path = api, pg_catalog;
125648
125649 --
125650 -- TOC entry 9132 (class 0 OID 0)
125651 -- Dependencies: 261
125652 -- Name: budget; Type: ACL; Schema: api; Owner: admin
125653 --
125654
125655 REVOKE ALL ON TABLE budget FROM PUBLIC;
125656 REVOKE ALL ON TABLE budget FROM admin;
125657 GRANT ALL ON TABLE budget TO admin;
125658 GRANT ALL ON TABLE budget TO xtrole;
125659
125660
125661 SET search_path = public, pg_catalog;
125662
125663 --
125664 -- TOC entry 9134 (class 0 OID 0)
125665 -- Dependencies: 262
125666 -- Name: accnt; Type: ACL; Schema: public; Owner: admin
125667 --
125668
125669 REVOKE ALL ON TABLE accnt FROM PUBLIC;
125670 REVOKE ALL ON TABLE accnt FROM admin;
125671 GRANT ALL ON TABLE accnt TO admin;
125672 GRANT ALL ON TABLE accnt TO xtrole;
125673
125674
125675 --
125676 -- TOC entry 9135 (class 0 OID 0)
125677 -- Dependencies: 263
125678 -- Name: budgitem; Type: ACL; Schema: public; Owner: admin
125679 --
125680
125681 REVOKE ALL ON TABLE budgitem FROM PUBLIC;
125682 REVOKE ALL ON TABLE budgitem FROM admin;
125683 GRANT ALL ON TABLE budgitem TO admin;
125684 GRANT ALL ON TABLE budgitem TO xtrole;
125685
125686
125687 --
125688 -- TOC entry 9137 (class 0 OID 0)
125689 -- Dependencies: 264
125690 -- Name: period; Type: ACL; Schema: public; Owner: admin
125691 --
125692
125693 REVOKE ALL ON TABLE period FROM PUBLIC;
125694 REVOKE ALL ON TABLE period FROM admin;
125695 GRANT ALL ON TABLE period TO admin;
125696 GRANT ALL ON TABLE period TO xtrole;
125697
125698
125699 SET search_path = api, pg_catalog;
125700
125701 --
125702 -- TOC entry 9139 (class 0 OID 0)
125703 -- Dependencies: 265
125704 -- Name: budgetentry; Type: ACL; Schema: api; Owner: admin
125705 --
125706
125707 REVOKE ALL ON TABLE budgetentry FROM PUBLIC;
125708 REVOKE ALL ON TABLE budgetentry FROM admin;
125709 GRANT ALL ON TABLE budgetentry TO admin;
125710 GRANT ALL ON TABLE budgetentry TO xtrole;
125711
125712
125713 SET search_path = public, pg_catalog;
125714
125715 --
125716 -- TOC entry 9141 (class 0 OID 0)
125717 -- Dependencies: 266
125718 -- Name: bankaccnt; Type: ACL; Schema: public; Owner: admin
125719 --
125720
125721 REVOKE ALL ON TABLE bankaccnt FROM PUBLIC;
125722 REVOKE ALL ON TABLE bankaccnt FROM admin;
125723 GRANT ALL ON TABLE bankaccnt TO admin;
125724 GRANT ALL ON TABLE bankaccnt TO xtrole;
125725
125726
125727 --
125728 -- TOC entry 9143 (class 0 OID 0)
125729 -- Dependencies: 267
125730 -- Name: cashrcpt; Type: ACL; Schema: public; Owner: admin
125731 --
125732
125733 REVOKE ALL ON TABLE cashrcpt FROM PUBLIC;
125734 REVOKE ALL ON TABLE cashrcpt FROM admin;
125735 GRANT ALL ON TABLE cashrcpt TO admin;
125736 GRANT ALL ON TABLE cashrcpt TO xtrole;
125737
125738
125739 SET search_path = api, pg_catalog;
125740
125741 --
125742 -- TOC entry 9145 (class 0 OID 0)
125743 -- Dependencies: 268
125744 -- Name: cashreceipt; Type: ACL; Schema: api; Owner: admin
125745 --
125746
125747 REVOKE ALL ON TABLE cashreceipt FROM PUBLIC;
125748 REVOKE ALL ON TABLE cashreceipt FROM admin;
125749 GRANT ALL ON TABLE cashreceipt TO admin;
125750 GRANT ALL ON TABLE cashreceipt TO xtrole;
125751
125752
125753 SET search_path = public, pg_catalog;
125754
125755 --
125756 -- TOC entry 9147 (class 0 OID 0)
125757 -- Dependencies: 269
125758 -- Name: cashrcptitem; Type: ACL; Schema: public; Owner: admin
125759 --
125760
125761 REVOKE ALL ON TABLE cashrcptitem FROM PUBLIC;
125762 REVOKE ALL ON TABLE cashrcptitem FROM admin;
125763 GRANT ALL ON TABLE cashrcptitem TO admin;
125764 GRANT ALL ON TABLE cashrcptitem TO xtrole;
125765
125766
125767 SET search_path = api, pg_catalog;
125768
125769 --
125770 -- TOC entry 9149 (class 0 OID 0)
125771 -- Dependencies: 270
125772 -- Name: cashreceiptapply; Type: ACL; Schema: api; Owner: admin
125773 --
125774
125775 REVOKE ALL ON TABLE cashreceiptapply FROM PUBLIC;
125776 REVOKE ALL ON TABLE cashreceiptapply FROM admin;
125777 GRANT ALL ON TABLE cashreceiptapply TO admin;
125778 GRANT ALL ON TABLE cashreceiptapply TO xtrole;
125779
125780
125781 SET search_path = public, pg_catalog;
125782
125783 --
125784 -- TOC entry 9151 (class 0 OID 0)
125785 -- Dependencies: 271
125786 -- Name: cashrcptmisc; Type: ACL; Schema: public; Owner: admin
125787 --
125788
125789 REVOKE ALL ON TABLE cashrcptmisc FROM PUBLIC;
125790 REVOKE ALL ON TABLE cashrcptmisc FROM admin;
125791 GRANT ALL ON TABLE cashrcptmisc TO admin;
125792 GRANT ALL ON TABLE cashrcptmisc TO xtrole;
125793
125794
125795 SET search_path = api, pg_catalog;
125796
125797 --
125798 -- TOC entry 9153 (class 0 OID 0)
125799 -- Dependencies: 272
125800 -- Name: cashreceiptapplymisc; Type: ACL; Schema: api; Owner: admin
125801 --
125802
125803 REVOKE ALL ON TABLE cashreceiptapplymisc FROM PUBLIC;
125804 REVOKE ALL ON TABLE cashreceiptapplymisc FROM admin;
125805 GRANT ALL ON TABLE cashreceiptapplymisc TO admin;
125806 GRANT ALL ON TABLE cashreceiptapplymisc TO xtrole;
125807
125808
125809 --
125810 -- TOC entry 9155 (class 0 OID 0)
125811 -- Dependencies: 273
125812 -- Name: contact; Type: ACL; Schema: api; Owner: admin
125813 --
125814
125815 REVOKE ALL ON TABLE contact FROM PUBLIC;
125816 REVOKE ALL ON TABLE contact FROM admin;
125817 GRANT ALL ON TABLE contact TO admin;
125818 GRANT ALL ON TABLE contact TO xtrole;
125819
125820
125821 --
125822 -- TOC entry 9157 (class 0 OID 0)
125823 -- Dependencies: 274
125824 -- Name: contactchar; Type: ACL; Schema: api; Owner: admin
125825 --
125826
125827 REVOKE ALL ON TABLE contactchar FROM PUBLIC;
125828 REVOKE ALL ON TABLE contactchar FROM admin;
125829 GRANT ALL ON TABLE contactchar TO admin;
125830 GRANT ALL ON TABLE contactchar TO xtrole;
125831
125832
125833 --
125834 -- TOC entry 9159 (class 0 OID 0)
125835 -- Dependencies: 275
125836 -- Name: contactcomment; Type: ACL; Schema: api; Owner: admin
125837 --
125838
125839 REVOKE ALL ON TABLE contactcomment FROM PUBLIC;
125840 REVOKE ALL ON TABLE contactcomment FROM admin;
125841 GRANT ALL ON TABLE contactcomment TO admin;
125842 GRANT ALL ON TABLE contactcomment TO xtrole;
125843
125844
125845 --
125846 -- TOC entry 9161 (class 0 OID 0)
125847 -- Dependencies: 276
125848 -- Name: custchar; Type: ACL; Schema: api; Owner: admin
125849 --
125850
125851 REVOKE ALL ON TABLE custchar FROM PUBLIC;
125852 REVOKE ALL ON TABLE custchar FROM admin;
125853 GRANT ALL ON TABLE custchar TO admin;
125854 GRANT ALL ON TABLE custchar TO xtrole;
125855
125856
125857 --
125858 -- TOC entry 9163 (class 0 OID 0)
125859 -- Dependencies: 277
125860 -- Name: custcomment; Type: ACL; Schema: api; Owner: admin
125861 --
125862
125863 REVOKE ALL ON TABLE custcomment FROM PUBLIC;
125864 REVOKE ALL ON TABLE custcomment FROM admin;
125865 GRANT ALL ON TABLE custcomment TO admin;
125866 GRANT ALL ON TABLE custcomment TO xtrole;
125867
125868
125869 SET search_path = public, pg_catalog;
125870
125871 --
125872 -- TOC entry 9165 (class 0 OID 0)
125873 -- Dependencies: 278
125874 -- Name: ccard; Type: ACL; Schema: public; Owner: admin
125875 --
125876
125877 REVOKE ALL ON TABLE ccard FROM PUBLIC;
125878 REVOKE ALL ON TABLE ccard FROM admin;
125879 GRANT ALL ON TABLE ccard TO admin;
125880 GRANT ALL ON TABLE ccard TO xtrole;
125881
125882
125883 SET search_path = api, pg_catalog;
125884
125885 --
125886 -- TOC entry 9167 (class 0 OID 0)
125887 -- Dependencies: 279
125888 -- Name: custcreditcard; Type: ACL; Schema: api; Owner: admin
125889 --
125890
125891 REVOKE ALL ON TABLE custcreditcard FROM PUBLIC;
125892 REVOKE ALL ON TABLE custcreditcard FROM admin;
125893 GRANT ALL ON TABLE custcreditcard TO admin;
125894 GRANT ALL ON TABLE custcreditcard TO xtrole;
125895
125896
125897 SET search_path = public, pg_catalog;
125898
125899 --
125900 -- TOC entry 9169 (class 0 OID 0)
125901 -- Dependencies: 280
125902 -- Name: custtype; Type: ACL; Schema: public; Owner: admin
125903 --
125904
125905 REVOKE ALL ON TABLE custtype FROM PUBLIC;
125906 REVOKE ALL ON TABLE custtype FROM admin;
125907 GRANT ALL ON TABLE custtype TO admin;
125908 GRANT ALL ON TABLE custtype TO xtrole;
125909
125910
125911 --
125912 -- TOC entry 9171 (class 0 OID 0)
125913 -- Dependencies: 281
125914 -- Name: shipchrg; Type: ACL; Schema: public; Owner: admin
125915 --
125916
125917 REVOKE ALL ON TABLE shipchrg FROM PUBLIC;
125918 REVOKE ALL ON TABLE shipchrg FROM admin;
125919 GRANT ALL ON TABLE shipchrg TO admin;
125920 GRANT ALL ON TABLE shipchrg TO xtrole;
125921
125922
125923 --
125924 -- TOC entry 9174 (class 0 OID 0)
125925 -- Dependencies: 282
125926 -- Name: shipform; Type: ACL; Schema: public; Owner: admin
125927 --
125928
125929 REVOKE ALL ON TABLE shipform FROM PUBLIC;
125930 REVOKE ALL ON TABLE shipform FROM admin;
125931 GRANT ALL ON TABLE shipform TO admin;
125932 GRANT ALL ON TABLE shipform TO xtrole;
125933
125934
125935 SET search_path = api, pg_catalog;
125936
125937 --
125938 -- TOC entry 9176 (class 0 OID 0)
125939 -- Dependencies: 283
125940 -- Name: customer; Type: ACL; Schema: api; Owner: admin
125941 --
125942
125943 REVOKE ALL ON TABLE customer FROM PUBLIC;
125944 REVOKE ALL ON TABLE customer FROM admin;
125945 GRANT ALL ON TABLE customer TO admin;
125946 GRANT ALL ON TABLE customer TO xtrole;
125947
125948
125949 SET search_path = public, pg_catalog;
125950
125951 --
125952 -- TOC entry 9179 (class 0 OID 0)
125953 -- Dependencies: 284
125954 -- Name: taxauth; Type: ACL; Schema: public; Owner: admin
125955 --
125956
125957 REVOKE ALL ON TABLE taxauth FROM PUBLIC;
125958 REVOKE ALL ON TABLE taxauth FROM admin;
125959 GRANT ALL ON TABLE taxauth TO admin;
125960 GRANT ALL ON TABLE taxauth TO xtrole;
125961
125962
125963 --
125964 -- TOC entry 9182 (class 0 OID 0)
125965 -- Dependencies: 285
125966 -- Name: taxreg; Type: ACL; Schema: public; Owner: admin
125967 --
125968
125969 REVOKE ALL ON TABLE taxreg FROM PUBLIC;
125970 REVOKE ALL ON TABLE taxreg FROM admin;
125971 GRANT ALL ON TABLE taxreg TO admin;
125972 GRANT ALL ON TABLE taxreg TO xtrole;
125973
125974
125975 SET search_path = api, pg_catalog;
125976
125977 --
125978 -- TOC entry 9184 (class 0 OID 0)
125979 -- Dependencies: 286
125980 -- Name: customertaxreg; Type: ACL; Schema: api; Owner: admin
125981 --
125982
125983 REVOKE ALL ON TABLE customertaxreg FROM PUBLIC;
125984 REVOKE ALL ON TABLE customertaxreg FROM admin;
125985 GRANT ALL ON TABLE customertaxreg TO admin;
125986 GRANT ALL ON TABLE customertaxreg TO xtrole;
125987
125988
125989 --
125990 -- TOC entry 9186 (class 0 OID 0)
125991 -- Dependencies: 287
125992 -- Name: customertype; Type: ACL; Schema: api; Owner: admin
125993 --
125994
125995 REVOKE ALL ON TABLE customertype FROM PUBLIC;
125996 REVOKE ALL ON TABLE customertype FROM admin;
125997 GRANT ALL ON TABLE customertype TO admin;
125998 GRANT ALL ON TABLE customertype TO xtrole;
125999
126000
126001 --
126002 -- TOC entry 9188 (class 0 OID 0)
126003 -- Dependencies: 288
126004 -- Name: customertypechar; Type: ACL; Schema: api; Owner: admin
126005 --
126006
126007 REVOKE ALL ON TABLE customertypechar FROM PUBLIC;
126008 REVOKE ALL ON TABLE customertypechar FROM admin;
126009 GRANT ALL ON TABLE customertypechar TO admin;
126010 GRANT ALL ON TABLE customertypechar TO xtrole;
126011
126012
126013 --
126014 -- TOC entry 9190 (class 0 OID 0)
126015 -- Dependencies: 289
126016 -- Name: custshipto; Type: ACL; Schema: api; Owner: admin
126017 --
126018
126019 REVOKE ALL ON TABLE custshipto FROM PUBLIC;
126020 REVOKE ALL ON TABLE custshipto FROM admin;
126021 GRANT ALL ON TABLE custshipto TO admin;
126022 GRANT ALL ON TABLE custshipto TO xtrole;
126023
126024
126025 --
126026 -- TOC entry 9192 (class 0 OID 0)
126027 -- Dependencies: 290
126028 -- Name: custtax; Type: ACL; Schema: api; Owner: admin
126029 --
126030
126031 REVOKE ALL ON TABLE custtax FROM PUBLIC;
126032 REVOKE ALL ON TABLE custtax FROM admin;
126033 GRANT ALL ON TABLE custtax TO admin;
126034 GRANT ALL ON TABLE custtax TO xtrole;
126035
126036
126037 SET search_path = public, pg_catalog;
126038
126039 --
126040 -- TOC entry 9194 (class 0 OID 0)
126041 -- Dependencies: 291
126042 -- Name: dept; Type: ACL; Schema: public; Owner: admin
126043 --
126044
126045 REVOKE ALL ON TABLE dept FROM PUBLIC;
126046 REVOKE ALL ON TABLE dept FROM admin;
126047 GRANT ALL ON TABLE dept TO admin;
126048 GRANT ALL ON TABLE dept TO xtrole;
126049
126050
126051 --
126052 -- TOC entry 9203 (class 0 OID 0)
126053 -- Dependencies: 292
126054 -- Name: emp; Type: ACL; Schema: public; Owner: admin
126055 --
126056
126057 REVOKE ALL ON TABLE emp FROM PUBLIC;
126058 REVOKE ALL ON TABLE emp FROM admin;
126059 GRANT ALL ON TABLE emp TO admin;
126060 GRANT ALL ON TABLE emp TO xtrole;
126061
126062
126063 --
126064 -- TOC entry 9205 (class 0 OID 0)
126065 -- Dependencies: 293
126066 -- Name: shift; Type: ACL; Schema: public; Owner: admin
126067 --
126068
126069 REVOKE ALL ON TABLE shift FROM PUBLIC;
126070 REVOKE ALL ON TABLE shift FROM admin;
126071 GRANT ALL ON TABLE shift TO admin;
126072 GRANT ALL ON TABLE shift TO xtrole;
126073
126074
126075 SET search_path = api, pg_catalog;
126076
126077 --
126078 -- TOC entry 9207 (class 0 OID 0)
126079 -- Dependencies: 294
126080 -- Name: employee; Type: ACL; Schema: api; Owner: admin
126081 --
126082
126083 REVOKE ALL ON TABLE employee FROM PUBLIC;
126084 REVOKE ALL ON TABLE employee FROM admin;
126085 GRANT ALL ON TABLE employee TO admin;
126086 GRANT ALL ON TABLE employee TO xtrole;
126087
126088
126089 --
126090 -- TOC entry 9209 (class 0 OID 0)
126091 -- Dependencies: 295
126092 -- Name: employeechar; Type: ACL; Schema: api; Owner: admin
126093 --
126094
126095 REVOKE ALL ON TABLE employeechar FROM PUBLIC;
126096 REVOKE ALL ON TABLE employeechar FROM admin;
126097 GRANT ALL ON TABLE employeechar TO admin;
126098 GRANT ALL ON TABLE employeechar TO xtrole;
126099
126100
126101 --
126102 -- TOC entry 9211 (class 0 OID 0)
126103 -- Dependencies: 296
126104 -- Name: employeecomment; Type: ACL; Schema: api; Owner: admin
126105 --
126106
126107 REVOKE ALL ON TABLE employeecomment FROM PUBLIC;
126108 REVOKE ALL ON TABLE employeecomment FROM admin;
126109 GRANT ALL ON TABLE employeecomment TO admin;
126110 GRANT ALL ON TABLE employeecomment TO xtrole;
126111
126112
126113 SET search_path = public, pg_catalog;
126114
126115 --
126116 -- TOC entry 9213 (class 0 OID 0)
126117 -- Dependencies: 297
126118 -- Name: shipdata; Type: ACL; Schema: public; Owner: admin
126119 --
126120
126121 REVOKE ALL ON TABLE shipdata FROM PUBLIC;
126122 REVOKE ALL ON TABLE shipdata FROM admin;
126123 GRANT ALL ON TABLE shipdata TO admin;
126124 GRANT ALL ON TABLE shipdata TO xtrole;
126125
126126
126127 SET search_path = api, pg_catalog;
126128
126129 --
126130 -- TOC entry 9215 (class 0 OID 0)
126131 -- Dependencies: 298
126132 -- Name: extshipmaint; Type: ACL; Schema: api; Owner: admin
126133 --
126134
126135 REVOKE ALL ON TABLE extshipmaint FROM PUBLIC;
126136 REVOKE ALL ON TABLE extshipmaint FROM admin;
126137 GRANT ALL ON TABLE extshipmaint TO admin;
126138 GRANT ALL ON TABLE extshipmaint TO xtrole;
126139
126140
126141 SET search_path = public, pg_catalog;
126142
126143 --
126144 -- TOC entry 9217 (class 0 OID 0)
126145 -- Dependencies: 299
126146 -- Name: freightclass; Type: ACL; Schema: public; Owner: admin
126147 --
126148
126149 REVOKE ALL ON TABLE freightclass FROM PUBLIC;
126150 REVOKE ALL ON TABLE freightclass FROM admin;
126151 GRANT ALL ON TABLE freightclass TO admin;
126152 GRANT ALL ON TABLE freightclass TO xtrole;
126153
126154
126155 --
126156 -- TOC entry 9218 (class 0 OID 0)
126157 -- Dependencies: 300
126158 -- Name: ipsfreight; Type: ACL; Schema: public; Owner: admin
126159 --
126160
126161 REVOKE ALL ON TABLE ipsfreight FROM PUBLIC;
126162 REVOKE ALL ON TABLE ipsfreight FROM admin;
126163 GRANT ALL ON TABLE ipsfreight TO admin;
126164 GRANT ALL ON TABLE ipsfreight TO xtrole;
126165
126166
126167 --
126168 -- TOC entry 9220 (class 0 OID 0)
126169 -- Dependencies: 301
126170 -- Name: ipshead; Type: ACL; Schema: public; Owner: admin
126171 --
126172
126173 REVOKE ALL ON TABLE ipshead FROM PUBLIC;
126174 REVOKE ALL ON TABLE ipshead FROM admin;
126175 GRANT ALL ON TABLE ipshead TO admin;
126176 GRANT ALL ON TABLE ipshead TO xtrole;
126177
126178
126179 SET search_path = api, pg_catalog;
126180
126181 --
126182 -- TOC entry 9222 (class 0 OID 0)
126183 -- Dependencies: 302
126184 -- Name: freightpricingscheduleitem; Type: ACL; Schema: api; Owner: admin
126185 --
126186
126187 REVOKE ALL ON TABLE freightpricingscheduleitem FROM PUBLIC;
126188 REVOKE ALL ON TABLE freightpricingscheduleitem FROM admin;
126189 GRANT ALL ON TABLE freightpricingscheduleitem TO admin;
126190 GRANT ALL ON TABLE freightpricingscheduleitem TO xtrole;
126191
126192
126193 --
126194 -- TOC entry 9224 (class 0 OID 0)
126195 -- Dependencies: 303
126196 -- Name: glaccount; Type: ACL; Schema: api; Owner: admin
126197 --
126198
126199 REVOKE ALL ON TABLE glaccount FROM PUBLIC;
126200 REVOKE ALL ON TABLE glaccount FROM admin;
126201 GRANT ALL ON TABLE glaccount TO admin;
126202 GRANT ALL ON TABLE glaccount TO xtrole;
126203
126204
126205 SET search_path = public, pg_catalog;
126206
126207 --
126208 -- TOC entry 9226 (class 0 OID 0)
126209 -- Dependencies: 304
126210 -- Name: incdtcat; Type: ACL; Schema: public; Owner: admin
126211 --
126212
126213 REVOKE ALL ON TABLE incdtcat FROM PUBLIC;
126214 REVOKE ALL ON TABLE incdtcat FROM admin;
126215 GRANT ALL ON TABLE incdtcat TO admin;
126216 GRANT ALL ON TABLE incdtcat TO xtrole;
126217
126218
126219 --
126220 -- TOC entry 9228 (class 0 OID 0)
126221 -- Dependencies: 305
126222 -- Name: incdtpriority; Type: ACL; Schema: public; Owner: admin
126223 --
126224
126225 REVOKE ALL ON TABLE incdtpriority FROM PUBLIC;
126226 REVOKE ALL ON TABLE incdtpriority FROM admin;
126227 GRANT ALL ON TABLE incdtpriority TO admin;
126228 GRANT ALL ON TABLE incdtpriority TO xtrole;
126229
126230
126231 --
126232 -- TOC entry 9230 (class 0 OID 0)
126233 -- Dependencies: 306
126234 -- Name: incdtresolution; Type: ACL; Schema: public; Owner: admin
126235 --
126236
126237 REVOKE ALL ON TABLE incdtresolution FROM PUBLIC;
126238 REVOKE ALL ON TABLE incdtresolution FROM admin;
126239 GRANT ALL ON TABLE incdtresolution TO admin;
126240 GRANT ALL ON TABLE incdtresolution TO xtrole;
126241
126242
126243 --
126244 -- TOC entry 9232 (class 0 OID 0)
126245 -- Dependencies: 307
126246 -- Name: incdtseverity; Type: ACL; Schema: public; Owner: admin
126247 --
126248
126249 REVOKE ALL ON TABLE incdtseverity FROM PUBLIC;
126250 REVOKE ALL ON TABLE incdtseverity FROM admin;
126251 GRANT ALL ON TABLE incdtseverity TO admin;
126252 GRANT ALL ON TABLE incdtseverity TO xtrole;
126253
126254
126255 SET search_path = api, pg_catalog;
126256
126257 --
126258 -- TOC entry 9234 (class 0 OID 0)
126259 -- Dependencies: 308
126260 -- Name: incident; Type: ACL; Schema: api; Owner: admin
126261 --
126262
126263 REVOKE ALL ON TABLE incident FROM PUBLIC;
126264 REVOKE ALL ON TABLE incident FROM admin;
126265 GRANT ALL ON TABLE incident TO admin;
126266 GRANT ALL ON TABLE incident TO xtrole;
126267
126268
126269 --
126270 -- TOC entry 9236 (class 0 OID 0)
126271 -- Dependencies: 309
126272 -- Name: incidentchar; Type: ACL; Schema: api; Owner: admin
126273 --
126274
126275 REVOKE ALL ON TABLE incidentchar FROM PUBLIC;
126276 REVOKE ALL ON TABLE incidentchar FROM admin;
126277 GRANT ALL ON TABLE incidentchar TO admin;
126278 GRANT ALL ON TABLE incidentchar TO xtrole;
126279
126280
126281 --
126282 -- TOC entry 9238 (class 0 OID 0)
126283 -- Dependencies: 310
126284 -- Name: incidentcomment; Type: ACL; Schema: api; Owner: admin
126285 --
126286
126287 REVOKE ALL ON TABLE incidentcomment FROM PUBLIC;
126288 REVOKE ALL ON TABLE incidentcomment FROM admin;
126289 GRANT ALL ON TABLE incidentcomment TO admin;
126290 GRANT ALL ON TABLE incidentcomment TO xtrole;
126291
126292
126293 --
126294 -- TOC entry 9240 (class 0 OID 0)
126295 -- Dependencies: 311
126296 -- Name: incidentfile; Type: ACL; Schema: api; Owner: admin
126297 --
126298
126299 REVOKE ALL ON TABLE incidentfile FROM PUBLIC;
126300 REVOKE ALL ON TABLE incidentfile FROM admin;
126301 GRANT ALL ON TABLE incidentfile TO admin;
126302 GRANT ALL ON TABLE incidentfile TO xtrole;
126303
126304
126305 --
126306 -- TOC entry 9242 (class 0 OID 0)
126307 -- Dependencies: 312
126308 -- Name: incidentimage; Type: ACL; Schema: api; Owner: admin
126309 --
126310
126311 REVOKE ALL ON TABLE incidentimage FROM PUBLIC;
126312 REVOKE ALL ON TABLE incidentimage FROM admin;
126313 GRANT ALL ON TABLE incidentimage TO admin;
126314 GRANT ALL ON TABLE incidentimage TO xtrole;
126315
126316
126317 SET search_path = public, pg_catalog;
126318
126319 --
126320 -- TOC entry 9244 (class 0 OID 0)
126321 -- Dependencies: 313
126322 -- Name: classcode; Type: ACL; Schema: public; Owner: admin
126323 --
126324
126325 REVOKE ALL ON TABLE classcode FROM PUBLIC;
126326 REVOKE ALL ON TABLE classcode FROM admin;
126327 GRANT ALL ON TABLE classcode TO admin;
126328 GRANT ALL ON TABLE classcode TO xtrole;
126329
126330
126331 --
126332 -- TOC entry 9246 (class 0 OID 0)
126333 -- Dependencies: 314
126334 -- Name: prodcat; Type: ACL; Schema: public; Owner: admin
126335 --
126336
126337 REVOKE ALL ON TABLE prodcat FROM PUBLIC;
126338 REVOKE ALL ON TABLE prodcat FROM admin;
126339 GRANT ALL ON TABLE prodcat TO admin;
126340 GRANT ALL ON TABLE prodcat TO xtrole;
126341
126342
126343 SET search_path = api, pg_catalog;
126344
126345 --
126346 -- TOC entry 9248 (class 0 OID 0)
126347 -- Dependencies: 315
126348 -- Name: item; Type: ACL; Schema: api; Owner: admin
126349 --
126350
126351 REVOKE ALL ON TABLE item FROM PUBLIC;
126352 REVOKE ALL ON TABLE item FROM admin;
126353 GRANT ALL ON TABLE item TO admin;
126354 GRANT ALL ON TABLE item TO xtrole;
126355
126356
126357 SET search_path = public, pg_catalog;
126358
126359 --
126360 -- TOC entry 9251 (class 0 OID 0)
126361 -- Dependencies: 316
126362 -- Name: itemalias; Type: ACL; Schema: public; Owner: admin
126363 --
126364
126365 REVOKE ALL ON TABLE itemalias FROM PUBLIC;
126366 REVOKE ALL ON TABLE itemalias FROM admin;
126367 GRANT ALL ON TABLE itemalias TO admin;
126368 GRANT ALL ON TABLE itemalias TO xtrole;
126369
126370
126371 SET search_path = api, pg_catalog;
126372
126373 --
126374 -- TOC entry 9253 (class 0 OID 0)
126375 -- Dependencies: 317
126376 -- Name: itemalias; Type: ACL; Schema: api; Owner: admin
126377 --
126378
126379 REVOKE ALL ON TABLE itemalias FROM PUBLIC;
126380 REVOKE ALL ON TABLE itemalias FROM admin;
126381 GRANT ALL ON TABLE itemalias TO admin;
126382 GRANT ALL ON TABLE itemalias TO xtrole;
126383
126384
126385 --
126386 -- TOC entry 9255 (class 0 OID 0)
126387 -- Dependencies: 318
126388 -- Name: itemchar; Type: ACL; Schema: api; Owner: admin
126389 --
126390
126391 REVOKE ALL ON TABLE itemchar FROM PUBLIC;
126392 REVOKE ALL ON TABLE itemchar FROM admin;
126393 GRANT ALL ON TABLE itemchar TO admin;
126394 GRANT ALL ON TABLE itemchar TO xtrole;
126395
126396
126397 --
126398 -- TOC entry 9257 (class 0 OID 0)
126399 -- Dependencies: 319
126400 -- Name: itemcomment; Type: ACL; Schema: api; Owner: admin
126401 --
126402
126403 REVOKE ALL ON TABLE itemcomment FROM PUBLIC;
126404 REVOKE ALL ON TABLE itemcomment FROM admin;
126405 GRANT ALL ON TABLE itemcomment TO admin;
126406 GRANT ALL ON TABLE itemcomment TO xtrole;
126407
126408
126409 SET search_path = public, pg_catalog;
126410
126411 --
126412 -- TOC entry 9259 (class 0 OID 0)
126413 -- Dependencies: 320
126414 -- Name: costelem; Type: ACL; Schema: public; Owner: admin
126415 --
126416
126417 REVOKE ALL ON TABLE costelem FROM PUBLIC;
126418 REVOKE ALL ON TABLE costelem FROM admin;
126419 GRANT ALL ON TABLE costelem TO admin;
126420 GRANT ALL ON TABLE costelem TO xtrole;
126421
126422
126423 --
126424 -- TOC entry 9261 (class 0 OID 0)
126425 -- Dependencies: 321
126426 -- Name: itemcost; Type: ACL; Schema: public; Owner: admin
126427 --
126428
126429 REVOKE ALL ON TABLE itemcost FROM PUBLIC;
126430 REVOKE ALL ON TABLE itemcost FROM admin;
126431 GRANT ALL ON TABLE itemcost TO admin;
126432 GRANT ALL ON TABLE itemcost TO xtrole;
126433
126434
126435 SET search_path = api, pg_catalog;
126436
126437 --
126438 -- TOC entry 9263 (class 0 OID 0)
126439 -- Dependencies: 322
126440 -- Name: itemcost; Type: ACL; Schema: api; Owner: admin
126441 --
126442
126443 REVOKE ALL ON TABLE itemcost FROM PUBLIC;
126444 REVOKE ALL ON TABLE itemcost FROM admin;
126445 GRANT ALL ON TABLE itemcost TO admin;
126446 GRANT ALL ON TABLE itemcost TO xtrole;
126447
126448
126449 --
126450 -- TOC entry 9265 (class 0 OID 0)
126451 -- Dependencies: 323
126452 -- Name: itemfile; Type: ACL; Schema: api; Owner: admin
126453 --
126454
126455 REVOKE ALL ON TABLE itemfile FROM PUBLIC;
126456 REVOKE ALL ON TABLE itemfile FROM admin;
126457 GRANT ALL ON TABLE itemfile TO admin;
126458 GRANT ALL ON TABLE itemfile TO xtrole;
126459
126460
126461 --
126462 -- TOC entry 9267 (class 0 OID 0)
126463 -- Dependencies: 324
126464 -- Name: itemimage; Type: ACL; Schema: api; Owner: admin
126465 --
126466
126467 REVOKE ALL ON TABLE itemimage FROM PUBLIC;
126468 REVOKE ALL ON TABLE itemimage FROM admin;
126469 GRANT ALL ON TABLE itemimage TO admin;
126470 GRANT ALL ON TABLE itemimage TO xtrole;
126471
126472
126473 SET search_path = public, pg_catalog;
126474
126475 --
126476 -- TOC entry 9269 (class 0 OID 0)
126477 -- Dependencies: 325
126478 -- Name: costcat; Type: ACL; Schema: public; Owner: admin
126479 --
126480
126481 REVOKE ALL ON TABLE costcat FROM PUBLIC;
126482 REVOKE ALL ON TABLE costcat FROM admin;
126483 GRANT ALL ON TABLE costcat TO admin;
126484 GRANT ALL ON TABLE costcat TO xtrole;
126485
126486
126487 --
126488 -- TOC entry 9271 (class 0 OID 0)
126489 -- Dependencies: 326
126490 -- Name: plancode; Type: ACL; Schema: public; Owner: admin
126491 --
126492
126493 REVOKE ALL ON TABLE plancode FROM PUBLIC;
126494 REVOKE ALL ON TABLE plancode FROM admin;
126495 GRANT ALL ON TABLE plancode TO admin;
126496 GRANT ALL ON TABLE plancode TO xtrole;
126497
126498
126499 SET search_path = api, pg_catalog;
126500
126501 --
126502 -- TOC entry 9273 (class 0 OID 0)
126503 -- Dependencies: 327
126504 -- Name: itemsite; Type: ACL; Schema: api; Owner: admin
126505 --
126506
126507 REVOKE ALL ON TABLE itemsite FROM PUBLIC;
126508 REVOKE ALL ON TABLE itemsite FROM admin;
126509 GRANT ALL ON TABLE itemsite TO admin;
126510 GRANT ALL ON TABLE itemsite TO xtrole;
126511
126512
126513 --
126514 -- TOC entry 9275 (class 0 OID 0)
126515 -- Dependencies: 328
126516 -- Name: itemsitecomment; Type: ACL; Schema: api; Owner: admin
126517 --
126518
126519 REVOKE ALL ON TABLE itemsitecomment FROM PUBLIC;
126520 REVOKE ALL ON TABLE itemsitecomment FROM admin;
126521 GRANT ALL ON TABLE itemsitecomment TO admin;
126522 GRANT ALL ON TABLE itemsitecomment TO xtrole;
126523
126524
126525 SET search_path = public, pg_catalog;
126526
126527 --
126528 -- TOC entry 9284 (class 0 OID 0)
126529 -- Dependencies: 329
126530 -- Name: contrct; Type: ACL; Schema: public; Owner: admin
126531 --
126532
126533 REVOKE ALL ON TABLE contrct FROM PUBLIC;
126534 REVOKE ALL ON TABLE contrct FROM admin;
126535 GRANT ALL ON TABLE contrct TO admin;
126536 GRANT ALL ON TABLE contrct TO xtrole;
126537
126538
126539 --
126540 -- TOC entry 9289 (class 0 OID 0)
126541 -- Dependencies: 330
126542 -- Name: itemsrc; Type: ACL; Schema: public; Owner: admin
126543 --
126544
126545 REVOKE ALL ON TABLE itemsrc FROM PUBLIC;
126546 REVOKE ALL ON TABLE itemsrc FROM admin;
126547 GRANT ALL ON TABLE itemsrc TO admin;
126548 GRANT ALL ON TABLE itemsrc TO xtrole;
126549
126550
126551 SET search_path = api, pg_catalog;
126552
126553 --
126554 -- TOC entry 9291 (class 0 OID 0)
126555 -- Dependencies: 331
126556 -- Name: itemsource; Type: ACL; Schema: api; Owner: admin
126557 --
126558
126559 REVOKE ALL ON TABLE itemsource FROM PUBLIC;
126560 REVOKE ALL ON TABLE itemsource FROM admin;
126561 GRANT ALL ON TABLE itemsource TO admin;
126562 GRANT ALL ON TABLE itemsource TO xtrole;
126563
126564
126565 SET search_path = public, pg_catalog;
126566
126567 --
126568 -- TOC entry 9298 (class 0 OID 0)
126569 -- Dependencies: 332
126570 -- Name: itemsrcp; Type: ACL; Schema: public; Owner: admin
126571 --
126572
126573 REVOKE ALL ON TABLE itemsrcp FROM PUBLIC;
126574 REVOKE ALL ON TABLE itemsrcp FROM admin;
126575 GRANT ALL ON TABLE itemsrcp TO admin;
126576 GRANT ALL ON TABLE itemsrcp TO xtrole;
126577
126578
126579 SET search_path = api, pg_catalog;
126580
126581 --
126582 -- TOC entry 9300 (class 0 OID 0)
126583 -- Dependencies: 333
126584 -- Name: itemsourceprice; Type: ACL; Schema: api; Owner: admin
126585 --
126586
126587 REVOKE ALL ON TABLE itemsourceprice FROM PUBLIC;
126588 REVOKE ALL ON TABLE itemsourceprice FROM admin;
126589 GRANT ALL ON TABLE itemsourceprice TO admin;
126590 GRANT ALL ON TABLE itemsourceprice TO xtrole;
126591
126592
126593 SET search_path = public, pg_catalog;
126594
126595 --
126596 -- TOC entry 9302 (class 0 OID 0)
126597 -- Dependencies: 334
126598 -- Name: itemsub; Type: ACL; Schema: public; Owner: admin
126599 --
126600
126601 REVOKE ALL ON TABLE itemsub FROM PUBLIC;
126602 REVOKE ALL ON TABLE itemsub FROM admin;
126603 GRANT ALL ON TABLE itemsub TO admin;
126604 GRANT ALL ON TABLE itemsub TO xtrole;
126605
126606
126607 SET search_path = api, pg_catalog;
126608
126609 --
126610 -- TOC entry 9304 (class 0 OID 0)
126611 -- Dependencies: 335
126612 -- Name: itemsubstitute; Type: ACL; Schema: api; Owner: admin
126613 --
126614
126615 REVOKE ALL ON TABLE itemsubstitute FROM PUBLIC;
126616 REVOKE ALL ON TABLE itemsubstitute FROM admin;
126617 GRANT ALL ON TABLE itemsubstitute TO admin;
126618 GRANT ALL ON TABLE itemsubstitute TO xtrole;
126619
126620
126621 SET search_path = public, pg_catalog;
126622
126623 --
126624 -- TOC entry 9306 (class 0 OID 0)
126625 -- Dependencies: 336
126626 -- Name: itemtax; Type: ACL; Schema: public; Owner: admin
126627 --
126628
126629 REVOKE ALL ON TABLE itemtax FROM PUBLIC;
126630 REVOKE ALL ON TABLE itemtax FROM admin;
126631 GRANT ALL ON TABLE itemtax TO admin;
126632 GRANT ALL ON TABLE itemtax TO xtrole;
126633
126634
126635 SET search_path = api, pg_catalog;
126636
126637 --
126638 -- TOC entry 9308 (class 0 OID 0)
126639 -- Dependencies: 337
126640 -- Name: itemtaxtype; Type: ACL; Schema: api; Owner: admin
126641 --
126642
126643 REVOKE ALL ON TABLE itemtaxtype FROM PUBLIC;
126644 REVOKE ALL ON TABLE itemtaxtype FROM admin;
126645 GRANT ALL ON TABLE itemtaxtype TO admin;
126646 GRANT ALL ON TABLE itemtaxtype TO xtrole;
126647
126648
126649 SET search_path = public, pg_catalog;
126650
126651 --
126652 -- TOC entry 9310 (class 0 OID 0)
126653 -- Dependencies: 338
126654 -- Name: itemuomconv; Type: ACL; Schema: public; Owner: admin
126655 --
126656
126657 REVOKE ALL ON TABLE itemuomconv FROM PUBLIC;
126658 REVOKE ALL ON TABLE itemuomconv FROM admin;
126659 GRANT ALL ON TABLE itemuomconv TO admin;
126660 GRANT ALL ON TABLE itemuomconv TO xtrole;
126661
126662
126663 SET search_path = api, pg_catalog;
126664
126665 --
126666 -- TOC entry 9312 (class 0 OID 0)
126667 -- Dependencies: 339
126668 -- Name: itemuomconversion; Type: ACL; Schema: api; Owner: admin
126669 --
126670
126671 REVOKE ALL ON TABLE itemuomconversion FROM PUBLIC;
126672 REVOKE ALL ON TABLE itemuomconversion FROM admin;
126673 GRANT ALL ON TABLE itemuomconversion TO admin;
126674 GRANT ALL ON TABLE itemuomconversion TO xtrole;
126675
126676
126677 SET search_path = public, pg_catalog;
126678
126679 --
126680 -- TOC entry 9314 (class 0 OID 0)
126681 -- Dependencies: 340
126682 -- Name: gltrans; Type: ACL; Schema: public; Owner: admin
126683 --
126684
126685 REVOKE ALL ON TABLE gltrans FROM PUBLIC;
126686 REVOKE ALL ON TABLE gltrans FROM admin;
126687 GRANT ALL ON TABLE gltrans TO admin;
126688 GRANT ALL ON TABLE gltrans TO xtrole;
126689
126690
126691 SET search_path = api, pg_catalog;
126692
126693 --
126694 -- TOC entry 9316 (class 0 OID 0)
126695 -- Dependencies: 341
126696 -- Name: journalentry; Type: ACL; Schema: api; Owner: admin
126697 --
126698
126699 REVOKE ALL ON TABLE journalentry FROM PUBLIC;
126700 REVOKE ALL ON TABLE journalentry FROM admin;
126701 GRANT ALL ON TABLE journalentry TO admin;
126702 GRANT ALL ON TABLE journalentry TO xtrole;
126703
126704
126705 SET search_path = public, pg_catalog;
126706
126707 --
126708 -- TOC entry 9318 (class 0 OID 0)
126709 -- Dependencies: 342
126710 -- Name: location; Type: ACL; Schema: public; Owner: admin
126711 --
126712
126713 REVOKE ALL ON TABLE location FROM PUBLIC;
126714 REVOKE ALL ON TABLE location FROM admin;
126715 GRANT ALL ON TABLE location TO admin;
126716 GRANT ALL ON TABLE location TO xtrole;
126717
126718
126719 --
126720 -- TOC entry 9320 (class 0 OID 0)
126721 -- Dependencies: 343
126722 -- Name: whsezone; Type: ACL; Schema: public; Owner: admin
126723 --
126724
126725 REVOKE ALL ON TABLE whsezone FROM PUBLIC;
126726 REVOKE ALL ON TABLE whsezone FROM admin;
126727 GRANT ALL ON TABLE whsezone TO admin;
126728 GRANT ALL ON TABLE whsezone TO xtrole;
126729
126730
126731 SET search_path = api, pg_catalog;
126732
126733 --
126734 -- TOC entry 9322 (class 0 OID 0)
126735 -- Dependencies: 344
126736 -- Name: location; Type: ACL; Schema: api; Owner: admin
126737 --
126738
126739 REVOKE ALL ON TABLE location FROM PUBLIC;
126740 REVOKE ALL ON TABLE location FROM admin;
126741 GRANT ALL ON TABLE location TO admin;
126742 GRANT ALL ON TABLE location TO xtrole;
126743
126744
126745 --
126746 -- TOC entry 9324 (class 0 OID 0)
126747 -- Dependencies: 345
126748 -- Name: misccounttag; Type: ACL; Schema: api; Owner: admin
126749 --
126750
126751 REVOKE ALL ON TABLE misccounttag FROM PUBLIC;
126752 REVOKE ALL ON TABLE misccounttag FROM admin;
126753 GRANT ALL ON TABLE misccounttag TO admin;
126754 GRANT ALL ON TABLE misccounttag TO xtrole;
126755
126756
126757 --
126758 -- TOC entry 9326 (class 0 OID 0)
126759 -- Dependencies: 346
126760 -- Name: pricingschedule; Type: ACL; Schema: api; Owner: admin
126761 --
126762
126763 REVOKE ALL ON TABLE pricingschedule FROM PUBLIC;
126764 REVOKE ALL ON TABLE pricingschedule FROM admin;
126765 GRANT ALL ON TABLE pricingschedule TO admin;
126766 GRANT ALL ON TABLE pricingschedule TO xtrole;
126767
126768
126769 SET search_path = public, pg_catalog;
126770
126771 --
126772 -- TOC entry 9328 (class 0 OID 0)
126773 -- Dependencies: 347
126774 -- Name: ipsass; Type: ACL; Schema: public; Owner: admin
126775 --
126776
126777 REVOKE ALL ON TABLE ipsass FROM PUBLIC;
126778 REVOKE ALL ON TABLE ipsass FROM admin;
126779 GRANT ALL ON TABLE ipsass TO admin;
126780 GRANT ALL ON TABLE ipsass TO xtrole;
126781
126782
126783 SET search_path = api, pg_catalog;
126784
126785 --
126786 -- TOC entry 9330 (class 0 OID 0)
126787 -- Dependencies: 348
126788 -- Name: pricingscheduleassign; Type: ACL; Schema: api; Owner: admin
126789 --
126790
126791 REVOKE ALL ON TABLE pricingscheduleassign FROM PUBLIC;
126792 REVOKE ALL ON TABLE pricingscheduleassign FROM admin;
126793 GRANT ALL ON TABLE pricingscheduleassign TO admin;
126794 GRANT ALL ON TABLE pricingscheduleassign TO xtrole;
126795
126796
126797 SET search_path = public, pg_catalog;
126798
126799 --
126800 -- TOC entry 9335 (class 0 OID 0)
126801 -- Dependencies: 349
126802 -- Name: ipsiteminfo; Type: ACL; Schema: public; Owner: admin
126803 --
126804
126805 REVOKE ALL ON TABLE ipsiteminfo FROM PUBLIC;
126806 REVOKE ALL ON TABLE ipsiteminfo FROM admin;
126807 GRANT ALL ON TABLE ipsiteminfo TO admin;
126808 GRANT ALL ON TABLE ipsiteminfo TO xtrole;
126809
126810
126811 SET search_path = api, pg_catalog;
126812
126813 --
126814 -- TOC entry 9337 (class 0 OID 0)
126815 -- Dependencies: 350
126816 -- Name: pricingscheduleitem; Type: ACL; Schema: api; Owner: admin
126817 --
126818
126819 REVOKE ALL ON TABLE pricingscheduleitem FROM PUBLIC;
126820 REVOKE ALL ON TABLE pricingscheduleitem FROM admin;
126821 GRANT ALL ON TABLE pricingscheduleitem TO admin;
126822 GRANT ALL ON TABLE pricingscheduleitem TO xtrole;
126823
126824
126825 SET search_path = public, pg_catalog;
126826
126827 --
126828 -- TOC entry 9339 (class 0 OID 0)
126829 -- Dependencies: 351
126830 -- Name: ipsitemchar; Type: ACL; Schema: public; Owner: admin
126831 --
126832
126833 REVOKE ALL ON TABLE ipsitemchar FROM PUBLIC;
126834 REVOKE ALL ON TABLE ipsitemchar FROM admin;
126835 GRANT ALL ON TABLE ipsitemchar TO admin;
126836 GRANT ALL ON TABLE ipsitemchar TO xtrole;
126837
126838
126839 SET search_path = api, pg_catalog;
126840
126841 --
126842 -- TOC entry 9341 (class 0 OID 0)
126843 -- Dependencies: 352
126844 -- Name: pricingscheduleitemchar; Type: ACL; Schema: api; Owner: admin
126845 --
126846
126847 REVOKE ALL ON TABLE pricingscheduleitemchar FROM PUBLIC;
126848 REVOKE ALL ON TABLE pricingscheduleitemchar FROM admin;
126849 GRANT ALL ON TABLE pricingscheduleitemchar TO admin;
126850 GRANT ALL ON TABLE pricingscheduleitemchar TO xtrole;
126851
126852
126853 --
126854 -- TOC entry 9343 (class 0 OID 0)
126855 -- Dependencies: 353
126856 -- Name: project; Type: ACL; Schema: api; Owner: admin
126857 --
126858
126859 REVOKE ALL ON TABLE project FROM PUBLIC;
126860 REVOKE ALL ON TABLE project FROM admin;
126861 GRANT ALL ON TABLE project TO admin;
126862 GRANT ALL ON TABLE project TO xtrole;
126863
126864
126865 --
126866 -- TOC entry 9345 (class 0 OID 0)
126867 -- Dependencies: 354
126868 -- Name: projectcomment; Type: ACL; Schema: api; Owner: admin
126869 --
126870
126871 REVOKE ALL ON TABLE projectcomment FROM PUBLIC;
126872 REVOKE ALL ON TABLE projectcomment FROM admin;
126873 GRANT ALL ON TABLE projectcomment TO admin;
126874 GRANT ALL ON TABLE projectcomment TO xtrole;
126875
126876
126877 SET search_path = public, pg_catalog;
126878
126879 --
126880 -- TOC entry 9346 (class 0 OID 0)
126881 -- Dependencies: 355
126882 -- Name: cust_cust_id_seq; Type: ACL; Schema: public; Owner: admin
126883 --
126884
126885 REVOKE ALL ON SEQUENCE cust_cust_id_seq FROM PUBLIC;
126886 REVOKE ALL ON SEQUENCE cust_cust_id_seq FROM admin;
126887 GRANT ALL ON SEQUENCE cust_cust_id_seq TO admin;
126888 GRANT ALL ON SEQUENCE cust_cust_id_seq TO xtrole;
126889
126890
126891 --
126892 -- TOC entry 9348 (class 0 OID 0)
126893 -- Dependencies: 356
126894 -- Name: prospect; Type: ACL; Schema: public; Owner: admin
126895 --
126896
126897 REVOKE ALL ON TABLE prospect FROM PUBLIC;
126898 REVOKE ALL ON TABLE prospect FROM admin;
126899 GRANT ALL ON TABLE prospect TO admin;
126900 GRANT ALL ON TABLE prospect TO xtrole;
126901
126902
126903 SET search_path = api, pg_catalog;
126904
126905 --
126906 -- TOC entry 9350 (class 0 OID 0)
126907 -- Dependencies: 357
126908 -- Name: prospect; Type: ACL; Schema: api; Owner: admin
126909 --
126910
126911 REVOKE ALL ON TABLE prospect FROM PUBLIC;
126912 REVOKE ALL ON TABLE prospect FROM admin;
126913 GRANT ALL ON TABLE prospect TO admin;
126914 GRANT ALL ON TABLE prospect TO xtrole;
126915
126916
126917 SET search_path = public, pg_catalog;
126918
126919 --
126920 -- TOC entry 9352 (class 0 OID 0)
126921 -- Dependencies: 358
126922 -- Name: expcat; Type: ACL; Schema: public; Owner: admin
126923 --
126924
126925 REVOKE ALL ON TABLE expcat FROM PUBLIC;
126926 REVOKE ALL ON TABLE expcat FROM admin;
126927 GRANT ALL ON TABLE expcat TO admin;
126928 GRANT ALL ON TABLE expcat TO xtrole;
126929
126930
126931 --
126932 -- TOC entry 9355 (class 0 OID 0)
126933 -- Dependencies: 359
126934 -- Name: womatl; Type: ACL; Schema: public; Owner: admin
126935 --
126936
126937 REVOKE ALL ON TABLE womatl FROM PUBLIC;
126938 REVOKE ALL ON TABLE womatl FROM admin;
126939 GRANT ALL ON TABLE womatl TO admin;
126940 GRANT ALL ON TABLE womatl TO xtrole;
126941
126942
126943 SET search_path = api, pg_catalog;
126944
126945 --
126946 -- TOC entry 9357 (class 0 OID 0)
126947 -- Dependencies: 360
126948 -- Name: purchaseline; Type: ACL; Schema: api; Owner: admin
126949 --
126950
126951 REVOKE ALL ON TABLE purchaseline FROM PUBLIC;
126952 REVOKE ALL ON TABLE purchaseline FROM admin;
126953 GRANT ALL ON TABLE purchaseline TO admin;
126954 GRANT ALL ON TABLE purchaseline TO xtrole;
126955
126956
126957 --
126958 -- TOC entry 9359 (class 0 OID 0)
126959 -- Dependencies: 361
126960 -- Name: purchaselinechar; Type: ACL; Schema: api; Owner: admin
126961 --
126962
126963 REVOKE ALL ON TABLE purchaselinechar FROM PUBLIC;
126964 REVOKE ALL ON TABLE purchaselinechar FROM admin;
126965 GRANT ALL ON TABLE purchaselinechar TO admin;
126966 GRANT ALL ON TABLE purchaselinechar TO xtrole;
126967
126968
126969 --
126970 -- TOC entry 9361 (class 0 OID 0)
126971 -- Dependencies: 362
126972 -- Name: purchaselinecomment; Type: ACL; Schema: api; Owner: admin
126973 --
126974
126975 REVOKE ALL ON TABLE purchaselinecomment FROM PUBLIC;
126976 REVOKE ALL ON TABLE purchaselinecomment FROM admin;
126977 GRANT ALL ON TABLE purchaselinecomment TO admin;
126978 GRANT ALL ON TABLE purchaselinecomment TO xtrole;
126979
126980
126981 SET search_path = public, pg_catalog;
126982
126983 --
126984 -- TOC entry 9364 (class 0 OID 0)
126985 -- Dependencies: 363
126986 -- Name: tax; Type: ACL; Schema: public; Owner: admin
126987 --
126988
126989 REVOKE ALL ON TABLE tax FROM PUBLIC;
126990 REVOKE ALL ON TABLE tax FROM admin;
126991 GRANT ALL ON TABLE tax TO admin;
126992 GRANT ALL ON TABLE tax TO xtrole;
126993
126994
126995 --
126996 -- TOC entry 9366 (class 0 OID 0)
126997 -- Dependencies: 364
126998 -- Name: vendaddrinfo; Type: ACL; Schema: public; Owner: admin
126999 --
127000
127001 REVOKE ALL ON TABLE vendaddrinfo FROM PUBLIC;
127002 REVOKE ALL ON TABLE vendaddrinfo FROM admin;
127003 GRANT ALL ON TABLE vendaddrinfo TO admin;
127004 GRANT ALL ON TABLE vendaddrinfo TO xtrole;
127005
127006
127007 SET search_path = api, pg_catalog;
127008
127009 --
127010 -- TOC entry 9368 (class 0 OID 0)
127011 -- Dependencies: 365
127012 -- Name: purchaseorder; Type: ACL; Schema: api; Owner: admin
127013 --
127014
127015 REVOKE ALL ON TABLE purchaseorder FROM PUBLIC;
127016 REVOKE ALL ON TABLE purchaseorder FROM admin;
127017 GRANT ALL ON TABLE purchaseorder TO admin;
127018 GRANT ALL ON TABLE purchaseorder TO xtrole;
127019
127020
127021 --
127022 -- TOC entry 9370 (class 0 OID 0)
127023 -- Dependencies: 366
127024 -- Name: purchaseordercomment; Type: ACL; Schema: api; Owner: admin
127025 --
127026
127027 REVOKE ALL ON TABLE purchaseordercomment FROM PUBLIC;
127028 REVOKE ALL ON TABLE purchaseordercomment FROM admin;
127029 GRANT ALL ON TABLE purchaseordercomment TO admin;
127030 GRANT ALL ON TABLE purchaseordercomment TO xtrole;
127031
127032
127033 SET search_path = public, pg_catalog;
127034
127035 --
127036 -- TOC entry 9374 (class 0 OID 0)
127037 -- Dependencies: 367
127038 -- Name: quhead; Type: ACL; Schema: public; Owner: admin
127039 --
127040
127041 REVOKE ALL ON TABLE quhead FROM PUBLIC;
127042 REVOKE ALL ON TABLE quhead FROM admin;
127043 GRANT ALL ON TABLE quhead TO admin;
127044 GRANT ALL ON TABLE quhead TO xtrole;
127045
127046
127047 SET search_path = api, pg_catalog;
127048
127049 --
127050 -- TOC entry 9376 (class 0 OID 0)
127051 -- Dependencies: 368
127052 -- Name: quote; Type: ACL; Schema: api; Owner: admin
127053 --
127054
127055 REVOKE ALL ON TABLE quote FROM PUBLIC;
127056 REVOKE ALL ON TABLE quote FROM admin;
127057 GRANT ALL ON TABLE quote TO admin;
127058 GRANT ALL ON TABLE quote TO xtrole;
127059
127060
127061 --
127062 -- TOC entry 9378 (class 0 OID 0)
127063 -- Dependencies: 369
127064 -- Name: quotecomment; Type: ACL; Schema: api; Owner: admin
127065 --
127066
127067 REVOKE ALL ON TABLE quotecomment FROM PUBLIC;
127068 REVOKE ALL ON TABLE quotecomment FROM admin;
127069 GRANT ALL ON TABLE quotecomment TO admin;
127070 GRANT ALL ON TABLE quotecomment TO xtrole;
127071
127072
127073 SET search_path = public, pg_catalog;
127074
127075 --
127076 -- TOC entry 9381 (class 0 OID 0)
127077 -- Dependencies: 370
127078 -- Name: quitem; Type: ACL; Schema: public; Owner: admin
127079 --
127080
127081 REVOKE ALL ON TABLE quitem FROM PUBLIC;
127082 REVOKE ALL ON TABLE quitem FROM admin;
127083 GRANT ALL ON TABLE quitem TO admin;
127084 GRANT ALL ON TABLE quitem TO xtrole;
127085
127086
127087 SET search_path = api, pg_catalog;
127088
127089 --
127090 -- TOC entry 9383 (class 0 OID 0)
127091 -- Dependencies: 371
127092 -- Name: quoteline; Type: ACL; Schema: api; Owner: admin
127093 --
127094
127095 REVOKE ALL ON TABLE quoteline FROM PUBLIC;
127096 REVOKE ALL ON TABLE quoteline FROM admin;
127097 GRANT ALL ON TABLE quoteline TO admin;
127098 GRANT ALL ON TABLE quoteline TO xtrole;
127099
127100
127101 --
127102 -- TOC entry 9385 (class 0 OID 0)
127103 -- Dependencies: 372
127104 -- Name: quotelinechar; Type: ACL; Schema: api; Owner: admin
127105 --
127106
127107 REVOKE ALL ON TABLE quotelinechar FROM PUBLIC;
127108 REVOKE ALL ON TABLE quotelinechar FROM admin;
127109 GRANT ALL ON TABLE quotelinechar TO admin;
127110 GRANT ALL ON TABLE quotelinechar TO xtrole;
127111
127112
127113 --
127114 -- TOC entry 9387 (class 0 OID 0)
127115 -- Dependencies: 373
127116 -- Name: quotelinecomment; Type: ACL; Schema: api; Owner: admin
127117 --
127118
127119 REVOKE ALL ON TABLE quotelinecomment FROM PUBLIC;
127120 REVOKE ALL ON TABLE quotelinecomment FROM admin;
127121 GRANT ALL ON TABLE quotelinecomment TO admin;
127122 GRANT ALL ON TABLE quotelinecomment TO xtrole;
127123
127124
127125 SET search_path = public, pg_catalog;
127126
127127 --
127128 -- TOC entry 9388 (class 0 OID 0)
127129 -- Dependencies: 374
127130 -- Name: aropenalloc; Type: ACL; Schema: public; Owner: admin
127131 --
127132
127133 REVOKE ALL ON TABLE aropenalloc FROM PUBLIC;
127134 REVOKE ALL ON TABLE aropenalloc FROM admin;
127135 GRANT ALL ON TABLE aropenalloc TO admin;
127136 GRANT ALL ON TABLE aropenalloc TO xtrole;
127137
127138
127139 SET search_path = api, pg_catalog;
127140
127141 --
127142 -- TOC entry 9390 (class 0 OID 0)
127143 -- Dependencies: 375
127144 -- Name: salescredit; Type: ACL; Schema: api; Owner: admin
127145 --
127146
127147 REVOKE ALL ON TABLE salescredit FROM PUBLIC;
127148 REVOKE ALL ON TABLE salescredit FROM admin;
127149 GRANT ALL ON TABLE salescredit TO admin;
127150 GRANT ALL ON TABLE salescredit TO xtrole;
127151
127152
127153 SET search_path = public, pg_catalog;
127154
127155 --
127156 -- TOC entry 9395 (class 0 OID 0)
127157 -- Dependencies: 376
127158 -- Name: cohist; Type: ACL; Schema: public; Owner: admin
127159 --
127160
127161 REVOKE ALL ON TABLE cohist FROM PUBLIC;
127162 REVOKE ALL ON TABLE cohist FROM admin;
127163 GRANT ALL ON TABLE cohist TO admin;
127164 GRANT ALL ON TABLE cohist TO xtrole;
127165
127166
127167 --
127168 -- TOC entry 9407 (class 0 OID 0)
127169 -- Dependencies: 377
127170 -- Name: taxhist; Type: ACL; Schema: public; Owner: admin
127171 --
127172
127173 REVOKE ALL ON TABLE taxhist FROM PUBLIC;
127174 REVOKE ALL ON TABLE taxhist FROM admin;
127175 GRANT ALL ON TABLE taxhist TO admin;
127176 GRANT ALL ON TABLE taxhist TO xtrole;
127177
127178
127179 --
127180 -- TOC entry 9408 (class 0 OID 0)
127181 -- Dependencies: 379
127182 -- Name: cohisttax; Type: ACL; Schema: public; Owner: admin
127183 --
127184
127185 REVOKE ALL ON TABLE cohisttax FROM PUBLIC;
127186 REVOKE ALL ON TABLE cohisttax FROM admin;
127187 GRANT ALL ON TABLE cohisttax TO admin;
127188 GRANT ALL ON TABLE cohisttax TO xtrole;
127189
127190
127191 SET search_path = api, pg_catalog;
127192
127193 --
127194 -- TOC entry 9410 (class 0 OID 0)
127195 -- Dependencies: 380
127196 -- Name: saleshistory; Type: ACL; Schema: api; Owner: admin
127197 --
127198
127199 REVOKE ALL ON TABLE saleshistory FROM PUBLIC;
127200 REVOKE ALL ON TABLE saleshistory FROM admin;
127201 GRANT ALL ON TABLE saleshistory TO admin;
127202 GRANT ALL ON TABLE saleshistory TO xtrole;
127203
127204
127205 --
127206 -- TOC entry 9412 (class 0 OID 0)
127207 -- Dependencies: 381
127208 -- Name: saleslinechar; Type: ACL; Schema: api; Owner: admin
127209 --
127210
127211 REVOKE ALL ON TABLE saleslinechar FROM PUBLIC;
127212 REVOKE ALL ON TABLE saleslinechar FROM admin;
127213 GRANT ALL ON TABLE saleslinechar TO admin;
127214 GRANT ALL ON TABLE saleslinechar TO xtrole;
127215
127216
127217 --
127218 -- TOC entry 9414 (class 0 OID 0)
127219 -- Dependencies: 382
127220 -- Name: saleslinecomment; Type: ACL; Schema: api; Owner: admin
127221 --
127222
127223 REVOKE ALL ON TABLE saleslinecomment FROM PUBLIC;
127224 REVOKE ALL ON TABLE saleslinecomment FROM admin;
127225 GRANT ALL ON TABLE saleslinecomment TO admin;
127226 GRANT ALL ON TABLE saleslinecomment TO xtrole;
127227
127228
127229 --
127230 -- TOC entry 9416 (class 0 OID 0)
127231 -- Dependencies: 383
127232 -- Name: salesorder; Type: ACL; Schema: api; Owner: admin
127233 --
127234
127235 REVOKE ALL ON TABLE salesorder FROM PUBLIC;
127236 REVOKE ALL ON TABLE salesorder FROM admin;
127237 GRANT ALL ON TABLE salesorder TO admin;
127238 GRANT ALL ON TABLE salesorder TO xtrole;
127239
127240
127241 --
127242 -- TOC entry 9418 (class 0 OID 0)
127243 -- Dependencies: 384
127244 -- Name: salesordercomment; Type: ACL; Schema: api; Owner: admin
127245 --
127246
127247 REVOKE ALL ON TABLE salesordercomment FROM PUBLIC;
127248 REVOKE ALL ON TABLE salesordercomment FROM admin;
127249 GRANT ALL ON TABLE salesordercomment TO admin;
127250 GRANT ALL ON TABLE salesordercomment TO xtrole;
127251
127252
127253 --
127254 -- TOC entry 9420 (class 0 OID 0)
127255 -- Dependencies: 385
127256 -- Name: salesrep; Type: ACL; Schema: api; Owner: admin
127257 --
127258
127259 REVOKE ALL ON TABLE salesrep FROM PUBLIC;
127260 REVOKE ALL ON TABLE salesrep FROM admin;
127261 GRANT ALL ON TABLE salesrep TO admin;
127262 GRANT ALL ON TABLE salesrep TO xtrole;
127263
127264
127265 SET search_path = public, pg_catalog;
127266
127267 --
127268 -- TOC entry 9422 (class 0 OID 0)
127269 -- Dependencies: 386
127270 -- Name: shipvia; Type: ACL; Schema: public; Owner: admin
127271 --
127272
127273 REVOKE ALL ON TABLE shipvia FROM PUBLIC;
127274 REVOKE ALL ON TABLE shipvia FROM admin;
127275 GRANT ALL ON TABLE shipvia TO admin;
127276 GRANT ALL ON TABLE shipvia TO xtrole;
127277
127278
127279 --
127280 -- TOC entry 9424 (class 0 OID 0)
127281 -- Dependencies: 387
127282 -- Name: sitetype; Type: ACL; Schema: public; Owner: admin
127283 --
127284
127285 REVOKE ALL ON TABLE sitetype FROM PUBLIC;
127286 REVOKE ALL ON TABLE sitetype FROM admin;
127287 GRANT ALL ON TABLE sitetype TO admin;
127288 GRANT ALL ON TABLE sitetype TO xtrole;
127289
127290
127291 SET search_path = api, pg_catalog;
127292
127293 --
127294 -- TOC entry 9426 (class 0 OID 0)
127295 -- Dependencies: 388
127296 -- Name: site; Type: ACL; Schema: api; Owner: admin
127297 --
127298
127299 REVOKE ALL ON TABLE site FROM PUBLIC;
127300 REVOKE ALL ON TABLE site FROM admin;
127301 GRANT ALL ON TABLE site TO admin;
127302 GRANT ALL ON TABLE site TO xtrole;
127303
127304
127305 --
127306 -- TOC entry 9428 (class 0 OID 0)
127307 -- Dependencies: 389
127308 -- Name: sitezone; Type: ACL; Schema: api; Owner: admin
127309 --
127310
127311 REVOKE ALL ON TABLE sitezone FROM PUBLIC;
127312 REVOKE ALL ON TABLE sitezone FROM admin;
127313 GRANT ALL ON TABLE sitezone TO admin;
127314 GRANT ALL ON TABLE sitezone TO xtrole;
127315
127316
127317 --
127318 -- TOC entry 9430 (class 0 OID 0)
127319 -- Dependencies: 390
127320 -- Name: task; Type: ACL; Schema: api; Owner: admin
127321 --
127322
127323 REVOKE ALL ON TABLE task FROM PUBLIC;
127324 REVOKE ALL ON TABLE task FROM admin;
127325 GRANT ALL ON TABLE task TO admin;
127326 GRANT ALL ON TABLE task TO xtrole;
127327
127328
127329 --
127330 -- TOC entry 9432 (class 0 OID 0)
127331 -- Dependencies: 391
127332 -- Name: taskcomment; Type: ACL; Schema: api; Owner: admin
127333 --
127334
127335 REVOKE ALL ON TABLE taskcomment FROM PUBLIC;
127336 REVOKE ALL ON TABLE taskcomment FROM admin;
127337 GRANT ALL ON TABLE taskcomment TO admin;
127338 GRANT ALL ON TABLE taskcomment TO xtrole;
127339
127340
127341 --
127342 -- TOC entry 9434 (class 0 OID 0)
127343 -- Dependencies: 392
127344 -- Name: todo; Type: ACL; Schema: api; Owner: admin
127345 --
127346
127347 REVOKE ALL ON TABLE todo FROM PUBLIC;
127348 REVOKE ALL ON TABLE todo FROM admin;
127349 GRANT ALL ON TABLE todo TO admin;
127350 GRANT ALL ON TABLE todo TO xtrole;
127351
127352
127353 SET search_path = public, pg_catalog;
127354
127355 --
127356 -- TOC entry 9436 (class 0 OID 0)
127357 -- Dependencies: 393
127358 -- Name: vendtype; Type: ACL; Schema: public; Owner: admin
127359 --
127360
127361 REVOKE ALL ON TABLE vendtype FROM PUBLIC;
127362 REVOKE ALL ON TABLE vendtype FROM admin;
127363 GRANT ALL ON TABLE vendtype TO admin;
127364 GRANT ALL ON TABLE vendtype TO xtrole;
127365
127366
127367 SET search_path = api, pg_catalog;
127368
127369 --
127370 -- TOC entry 9438 (class 0 OID 0)
127371 -- Dependencies: 394
127372 -- Name: vendor; Type: ACL; Schema: api; Owner: admin
127373 --
127374
127375 REVOKE ALL ON TABLE vendor FROM PUBLIC;
127376 REVOKE ALL ON TABLE vendor FROM admin;
127377 GRANT ALL ON TABLE vendor TO admin;
127378 GRANT ALL ON TABLE vendor TO xtrole;
127379
127380
127381 --
127382 -- TOC entry 9440 (class 0 OID 0)
127383 -- Dependencies: 395
127384 -- Name: vendoraddress; Type: ACL; Schema: api; Owner: admin
127385 --
127386
127387 REVOKE ALL ON TABLE vendoraddress FROM PUBLIC;
127388 REVOKE ALL ON TABLE vendoraddress FROM admin;
127389 GRANT ALL ON TABLE vendoraddress TO admin;
127390 GRANT ALL ON TABLE vendoraddress TO xtrole;
127391
127392
127393 --
127394 -- TOC entry 9442 (class 0 OID 0)
127395 -- Dependencies: 396
127396 -- Name: vendortype; Type: ACL; Schema: api; Owner: admin
127397 --
127398
127399 REVOKE ALL ON TABLE vendortype FROM PUBLIC;
127400 REVOKE ALL ON TABLE vendortype FROM admin;
127401 GRANT ALL ON TABLE vendortype TO admin;
127402 GRANT ALL ON TABLE vendortype TO xtrole;
127403
127404
127405 SET search_path = public, pg_catalog;
127406
127407 --
127408 -- TOC entry 9444 (class 0 OID 0)
127409 -- Dependencies: 397
127410 -- Name: cmd; Type: ACL; Schema: public; Owner: admin
127411 --
127412
127413 REVOKE ALL ON TABLE cmd FROM PUBLIC;
127414 REVOKE ALL ON TABLE cmd FROM admin;
127415 GRANT ALL ON TABLE cmd TO admin;
127416 GRANT ALL ON TABLE cmd TO xtrole;
127417
127418
127419 --
127420 -- TOC entry 9446 (class 0 OID 0)
127421 -- Dependencies: 398
127422 -- Name: cmd_cmd_id_seq; Type: ACL; Schema: public; Owner: admin
127423 --
127424
127425 REVOKE ALL ON SEQUENCE cmd_cmd_id_seq FROM PUBLIC;
127426 REVOKE ALL ON SEQUENCE cmd_cmd_id_seq FROM admin;
127427 GRANT ALL ON SEQUENCE cmd_cmd_id_seq TO admin;
127428 GRANT ALL ON SEQUENCE cmd_cmd_id_seq TO xtrole;
127429
127430
127431 SET search_path = fixcountry, pg_catalog;
127432
127433 --
127434 -- TOC entry 9447 (class 0 OID 0)
127435 -- Dependencies: 399
127436 -- Name: pkgcmd; Type: ACL; Schema: fixcountry; Owner: admin
127437 --
127438
127439 REVOKE ALL ON TABLE pkgcmd FROM PUBLIC;
127440 REVOKE ALL ON TABLE pkgcmd FROM admin;
127441 GRANT ALL ON TABLE pkgcmd TO admin;
127442 GRANT ALL ON TABLE pkgcmd TO xtrole;
127443
127444
127445 SET search_path = public, pg_catalog;
127446
127447 --
127448 -- TOC entry 9449 (class 0 OID 0)
127449 -- Dependencies: 400
127450 -- Name: cmdarg; Type: ACL; Schema: public; Owner: admin
127451 --
127452
127453 REVOKE ALL ON TABLE cmdarg FROM PUBLIC;
127454 REVOKE ALL ON TABLE cmdarg FROM admin;
127455 GRANT ALL ON TABLE cmdarg TO admin;
127456 GRANT ALL ON TABLE cmdarg TO xtrole;
127457
127458
127459 --
127460 -- TOC entry 9451 (class 0 OID 0)
127461 -- Dependencies: 401
127462 -- Name: cmdarg_cmdarg_id_seq; Type: ACL; Schema: public; Owner: admin
127463 --
127464
127465 REVOKE ALL ON SEQUENCE cmdarg_cmdarg_id_seq FROM PUBLIC;
127466 REVOKE ALL ON SEQUENCE cmdarg_cmdarg_id_seq FROM admin;
127467 GRANT ALL ON SEQUENCE cmdarg_cmdarg_id_seq TO admin;
127468 GRANT ALL ON SEQUENCE cmdarg_cmdarg_id_seq TO xtrole;
127469
127470
127471 SET search_path = fixcountry, pg_catalog;
127472
127473 --
127474 -- TOC entry 9452 (class 0 OID 0)
127475 -- Dependencies: 402
127476 -- Name: pkgcmdarg; Type: ACL; Schema: fixcountry; Owner: admin
127477 --
127478
127479 REVOKE ALL ON TABLE pkgcmdarg FROM PUBLIC;
127480 REVOKE ALL ON TABLE pkgcmdarg FROM admin;
127481 GRANT ALL ON TABLE pkgcmdarg TO admin;
127482 GRANT ALL ON TABLE pkgcmdarg TO xtrole;
127483
127484
127485 SET search_path = public, pg_catalog;
127486
127487 --
127488 -- TOC entry 9453 (class 0 OID 0)
127489 -- Dependencies: 403
127490 -- Name: image_image_id_seq; Type: ACL; Schema: public; Owner: admin
127491 --
127492
127493 REVOKE ALL ON SEQUENCE image_image_id_seq FROM PUBLIC;
127494 REVOKE ALL ON SEQUENCE image_image_id_seq FROM admin;
127495 GRANT ALL ON SEQUENCE image_image_id_seq TO admin;
127496 GRANT ALL ON SEQUENCE image_image_id_seq TO xtrole;
127497
127498
127499 SET search_path = fixcountry, pg_catalog;
127500
127501 --
127502 -- TOC entry 9454 (class 0 OID 0)
127503 -- Dependencies: 404
127504 -- Name: pkgimage; Type: ACL; Schema: fixcountry; Owner: admin
127505 --
127506
127507 REVOKE ALL ON TABLE pkgimage FROM PUBLIC;
127508 REVOKE ALL ON TABLE pkgimage FROM admin;
127509 GRANT ALL ON TABLE pkgimage TO admin;
127510 GRANT ALL ON TABLE pkgimage TO xtrole;
127511
127512
127513 SET search_path = public, pg_catalog;
127514
127515 --
127516 -- TOC entry 9456 (class 0 OID 0)
127517 -- Dependencies: 405
127518 -- Name: metasql; Type: ACL; Schema: public; Owner: admin
127519 --
127520
127521 REVOKE ALL ON TABLE metasql FROM PUBLIC;
127522 REVOKE ALL ON TABLE metasql FROM admin;
127523 GRANT ALL ON TABLE metasql TO admin;
127524 GRANT ALL ON TABLE metasql TO xtrole;
127525
127526
127527 --
127528 -- TOC entry 9458 (class 0 OID 0)
127529 -- Dependencies: 406
127530 -- Name: metasql_metasql_id_seq; Type: ACL; Schema: public; Owner: admin
127531 --
127532
127533 REVOKE ALL ON SEQUENCE metasql_metasql_id_seq FROM PUBLIC;
127534 REVOKE ALL ON SEQUENCE metasql_metasql_id_seq FROM admin;
127535 GRANT ALL ON SEQUENCE metasql_metasql_id_seq TO admin;
127536 GRANT ALL ON SEQUENCE metasql_metasql_id_seq TO xtrole;
127537
127538
127539 SET search_path = fixcountry, pg_catalog;
127540
127541 --
127542 -- TOC entry 9459 (class 0 OID 0)
127543 -- Dependencies: 407
127544 -- Name: pkgmetasql; Type: ACL; Schema: fixcountry; Owner: admin
127545 --
127546
127547 REVOKE ALL ON TABLE pkgmetasql FROM PUBLIC;
127548 REVOKE ALL ON TABLE pkgmetasql FROM admin;
127549 GRANT ALL ON TABLE pkgmetasql TO admin;
127550 GRANT ALL ON TABLE pkgmetasql TO xtrole;
127551
127552
127553 SET search_path = public, pg_catalog;
127554
127555 --
127556 -- TOC entry 9461 (class 0 OID 0)
127557 -- Dependencies: 408
127558 -- Name: priv; Type: ACL; Schema: public; Owner: admin
127559 --
127560
127561 REVOKE ALL ON TABLE priv FROM PUBLIC;
127562 REVOKE ALL ON TABLE priv FROM admin;
127563 GRANT ALL ON TABLE priv TO admin;
127564 GRANT ALL ON TABLE priv TO xtrole;
127565
127566
127567 --
127568 -- TOC entry 9462 (class 0 OID 0)
127569 -- Dependencies: 409
127570 -- Name: priv_priv_id_seq; Type: ACL; Schema: public; Owner: admin
127571 --
127572
127573 REVOKE ALL ON SEQUENCE priv_priv_id_seq FROM PUBLIC;
127574 REVOKE ALL ON SEQUENCE priv_priv_id_seq FROM admin;
127575 GRANT ALL ON SEQUENCE priv_priv_id_seq TO admin;
127576 GRANT ALL ON SEQUENCE priv_priv_id_seq TO xtrole;
127577
127578
127579 SET search_path = fixcountry, pg_catalog;
127580
127581 --
127582 -- TOC entry 9463 (class 0 OID 0)
127583 -- Dependencies: 410
127584 -- Name: pkgpriv; Type: ACL; Schema: fixcountry; Owner: admin
127585 --
127586
127587 REVOKE ALL ON TABLE pkgpriv FROM PUBLIC;
127588 REVOKE ALL ON TABLE pkgpriv FROM admin;
127589 GRANT ALL ON TABLE pkgpriv TO admin;
127590 GRANT ALL ON TABLE pkgpriv TO xtrole;
127591
127592
127593 SET search_path = public, pg_catalog;
127594
127595 --
127596 -- TOC entry 9465 (class 0 OID 0)
127597 -- Dependencies: 411
127598 -- Name: report; Type: ACL; Schema: public; Owner: admin
127599 --
127600
127601 REVOKE ALL ON TABLE report FROM PUBLIC;
127602 REVOKE ALL ON TABLE report FROM admin;
127603 GRANT ALL ON TABLE report TO admin;
127604 GRANT ALL ON TABLE report TO xtrole;
127605
127606
127607 --
127608 -- TOC entry 9466 (class 0 OID 0)
127609 -- Dependencies: 412
127610 -- Name: report_report_id_seq; Type: ACL; Schema: public; Owner: admin
127611 --
127612
127613 REVOKE ALL ON SEQUENCE report_report_id_seq FROM PUBLIC;
127614 REVOKE ALL ON SEQUENCE report_report_id_seq FROM admin;
127615 GRANT ALL ON SEQUENCE report_report_id_seq TO admin;
127616 GRANT ALL ON SEQUENCE report_report_id_seq TO xtrole;
127617
127618
127619 SET search_path = fixcountry, pg_catalog;
127620
127621 --
127622 -- TOC entry 9467 (class 0 OID 0)
127623 -- Dependencies: 413
127624 -- Name: pkgreport; Type: ACL; Schema: fixcountry; Owner: admin
127625 --
127626
127627 REVOKE ALL ON TABLE pkgreport FROM PUBLIC;
127628 REVOKE ALL ON TABLE pkgreport FROM admin;
127629 GRANT ALL ON TABLE pkgreport TO admin;
127630 GRANT ALL ON TABLE pkgreport TO xtrole;
127631
127632
127633 SET search_path = public, pg_catalog;
127634
127635 --
127636 -- TOC entry 9468 (class 0 OID 0)
127637 -- Dependencies: 414
127638 -- Name: script; Type: ACL; Schema: public; Owner: admin
127639 --
127640
127641 REVOKE ALL ON TABLE script FROM PUBLIC;
127642 REVOKE ALL ON TABLE script FROM admin;
127643 GRANT ALL ON TABLE script TO admin;
127644 GRANT ALL ON TABLE script TO xtrole;
127645
127646
127647 --
127648 -- TOC entry 9470 (class 0 OID 0)
127649 -- Dependencies: 415
127650 -- Name: script_script_id_seq; Type: ACL; Schema: public; Owner: admin
127651 --
127652
127653 REVOKE ALL ON SEQUENCE script_script_id_seq FROM PUBLIC;
127654 REVOKE ALL ON SEQUENCE script_script_id_seq FROM admin;
127655 GRANT ALL ON SEQUENCE script_script_id_seq TO admin;
127656 GRANT ALL ON SEQUENCE script_script_id_seq TO xtrole;
127657
127658
127659 SET search_path = fixcountry, pg_catalog;
127660
127661 --
127662 -- TOC entry 9471 (class 0 OID 0)
127663 -- Dependencies: 416
127664 -- Name: pkgscript; Type: ACL; Schema: fixcountry; Owner: admin
127665 --
127666
127667 REVOKE ALL ON TABLE pkgscript FROM PUBLIC;
127668 REVOKE ALL ON TABLE pkgscript FROM admin;
127669 GRANT ALL ON TABLE pkgscript TO admin;
127670 GRANT ALL ON TABLE pkgscript TO xtrole;
127671
127672
127673 SET search_path = public, pg_catalog;
127674
127675 --
127676 -- TOC entry 9472 (class 0 OID 0)
127677 -- Dependencies: 417
127678 -- Name: uiform; Type: ACL; Schema: public; Owner: admin
127679 --
127680
127681 REVOKE ALL ON TABLE uiform FROM PUBLIC;
127682 REVOKE ALL ON TABLE uiform FROM admin;
127683 GRANT ALL ON TABLE uiform TO admin;
127684 GRANT ALL ON TABLE uiform TO xtrole;
127685
127686
127687 --
127688 -- TOC entry 9474 (class 0 OID 0)
127689 -- Dependencies: 418
127690 -- Name: uiform_uiform_id_seq; Type: ACL; Schema: public; Owner: admin
127691 --
127692
127693 REVOKE ALL ON SEQUENCE uiform_uiform_id_seq FROM PUBLIC;
127694 REVOKE ALL ON SEQUENCE uiform_uiform_id_seq FROM admin;
127695 GRANT ALL ON SEQUENCE uiform_uiform_id_seq TO admin;
127696 GRANT ALL ON SEQUENCE uiform_uiform_id_seq TO xtrole;
127697
127698
127699 SET search_path = fixcountry, pg_catalog;
127700
127701 --
127702 -- TOC entry 9475 (class 0 OID 0)
127703 -- Dependencies: 419
127704 -- Name: pkguiform; Type: ACL; Schema: fixcountry; Owner: admin
127705 --
127706
127707 REVOKE ALL ON TABLE pkguiform FROM PUBLIC;
127708 REVOKE ALL ON TABLE pkguiform FROM admin;
127709 GRANT ALL ON TABLE pkguiform TO admin;
127710 GRANT ALL ON TABLE pkguiform TO xtrole;
127711
127712
127713 SET search_path = public, pg_catalog;
127714
127715 --
127716 -- TOC entry 9477 (class 0 OID 0)
127717 -- Dependencies: 420
127718 -- Name: acalitem; Type: ACL; Schema: public; Owner: admin
127719 --
127720
127721 REVOKE ALL ON TABLE acalitem FROM PUBLIC;
127722 REVOKE ALL ON TABLE acalitem FROM admin;
127723 GRANT ALL ON TABLE acalitem TO admin;
127724 GRANT ALL ON TABLE acalitem TO xtrole;
127725
127726
127727 --
127728 -- TOC entry 9478 (class 0 OID 0)
127729 -- Dependencies: 421
127730 -- Name: accnt_accnt_id_seq; Type: ACL; Schema: public; Owner: admin
127731 --
127732
127733 REVOKE ALL ON SEQUENCE accnt_accnt_id_seq FROM PUBLIC;
127734 REVOKE ALL ON SEQUENCE accnt_accnt_id_seq FROM admin;
127735 GRANT ALL ON SEQUENCE accnt_accnt_id_seq TO admin;
127736 GRANT ALL ON SEQUENCE accnt_accnt_id_seq TO xtrole;
127737
127738
127739 --
127740 -- TOC entry 9480 (class 0 OID 0)
127741 -- Dependencies: 422
127742 -- Name: addr_addr_id_seq; Type: ACL; Schema: public; Owner: admin
127743 --
127744
127745 REVOKE ALL ON SEQUENCE addr_addr_id_seq FROM PUBLIC;
127746 REVOKE ALL ON SEQUENCE addr_addr_id_seq FROM admin;
127747 GRANT ALL ON SEQUENCE addr_addr_id_seq TO admin;
127748 GRANT ALL ON SEQUENCE addr_addr_id_seq TO xtrole;
127749
127750
127751 --
127752 -- TOC entry 9481 (class 0 OID 0)
127753 -- Dependencies: 423
127754 -- Name: address; Type: ACL; Schema: public; Owner: admin
127755 --
127756
127757 REVOKE ALL ON TABLE address FROM PUBLIC;
127758 REVOKE ALL ON TABLE address FROM admin;
127759 GRANT ALL ON TABLE address TO admin;
127760 GRANT ALL ON TABLE address TO xtrole;
127761
127762
127763 --
127764 -- TOC entry 9483 (class 0 OID 0)
127765 -- Dependencies: 424
127766 -- Name: alarm; Type: ACL; Schema: public; Owner: admin
127767 --
127768
127769 REVOKE ALL ON TABLE alarm FROM PUBLIC;
127770 REVOKE ALL ON TABLE alarm FROM admin;
127771 GRANT ALL ON TABLE alarm TO admin;
127772 GRANT ALL ON TABLE alarm TO xtrole;
127773
127774
127775 --
127776 -- TOC entry 9485 (class 0 OID 0)
127777 -- Dependencies: 425
127778 -- Name: alarm_alarm_id_seq; Type: ACL; Schema: public; Owner: admin
127779 --
127780
127781 REVOKE ALL ON SEQUENCE alarm_alarm_id_seq FROM PUBLIC;
127782 REVOKE ALL ON SEQUENCE alarm_alarm_id_seq FROM admin;
127783 GRANT ALL ON SEQUENCE alarm_alarm_id_seq TO admin;
127784 GRANT ALL ON SEQUENCE alarm_alarm_id_seq TO xtrole;
127785
127786
127787 --
127788 -- TOC entry 9487 (class 0 OID 0)
127789 -- Dependencies: 426
127790 -- Name: apaccnt; Type: ACL; Schema: public; Owner: admin
127791 --
127792
127793 REVOKE ALL ON TABLE apaccnt FROM PUBLIC;
127794 REVOKE ALL ON TABLE apaccnt FROM admin;
127795 GRANT ALL ON TABLE apaccnt TO admin;
127796 GRANT ALL ON TABLE apaccnt TO xtrole;
127797
127798
127799 --
127800 -- TOC entry 9489 (class 0 OID 0)
127801 -- Dependencies: 427
127802 -- Name: apaccnt_apaccnt_id_seq; Type: ACL; Schema: public; Owner: admin
127803 --
127804
127805 REVOKE ALL ON SEQUENCE apaccnt_apaccnt_id_seq FROM PUBLIC;
127806 REVOKE ALL ON SEQUENCE apaccnt_apaccnt_id_seq FROM admin;
127807 GRANT ALL ON SEQUENCE apaccnt_apaccnt_id_seq TO admin;
127808 GRANT ALL ON SEQUENCE apaccnt_apaccnt_id_seq TO xtrole;
127809
127810
127811 --
127812 -- TOC entry 9492 (class 0 OID 0)
127813 -- Dependencies: 428
127814 -- Name: apapply; Type: ACL; Schema: public; Owner: admin
127815 --
127816
127817 REVOKE ALL ON TABLE apapply FROM PUBLIC;
127818 REVOKE ALL ON TABLE apapply FROM admin;
127819 GRANT ALL ON TABLE apapply TO admin;
127820 GRANT ALL ON TABLE apapply TO xtrole;
127821
127822
127823 --
127824 -- TOC entry 9494 (class 0 OID 0)
127825 -- Dependencies: 429
127826 -- Name: apapply_apapply_id_seq; Type: ACL; Schema: public; Owner: admin
127827 --
127828
127829 REVOKE ALL ON SEQUENCE apapply_apapply_id_seq FROM PUBLIC;
127830 REVOKE ALL ON SEQUENCE apapply_apapply_id_seq FROM admin;
127831 GRANT ALL ON SEQUENCE apapply_apapply_id_seq TO admin;
127832 GRANT ALL ON SEQUENCE apapply_apapply_id_seq TO xtrole;
127833
127834
127835 --
127836 -- TOC entry 9496 (class 0 OID 0)
127837 -- Dependencies: 430
127838 -- Name: checkhead; Type: ACL; Schema: public; Owner: admin
127839 --
127840
127841 REVOKE ALL ON TABLE checkhead FROM PUBLIC;
127842 REVOKE ALL ON TABLE checkhead FROM admin;
127843 GRANT ALL ON TABLE checkhead TO admin;
127844 GRANT ALL ON TABLE checkhead TO xtrole;
127845
127846
127847 --
127848 -- TOC entry 9497 (class 0 OID 0)
127849 -- Dependencies: 431
127850 -- Name: apchk; Type: ACL; Schema: public; Owner: admin
127851 --
127852
127853 REVOKE ALL ON TABLE apchk FROM PUBLIC;
127854 REVOKE ALL ON TABLE apchk FROM admin;
127855 GRANT ALL ON TABLE apchk TO admin;
127856 GRANT ALL ON TABLE apchk TO xtrole;
127857
127858
127859 --
127860 -- TOC entry 9499 (class 0 OID 0)
127861 -- Dependencies: 432
127862 -- Name: checkitem; Type: ACL; Schema: public; Owner: admin
127863 --
127864
127865 REVOKE ALL ON TABLE checkitem FROM PUBLIC;
127866 REVOKE ALL ON TABLE checkitem FROM admin;
127867 GRANT ALL ON TABLE checkitem TO admin;
127868 GRANT ALL ON TABLE checkitem TO xtrole;
127869
127870
127871 --
127872 -- TOC entry 9500 (class 0 OID 0)
127873 -- Dependencies: 433
127874 -- Name: apchkitem; Type: ACL; Schema: public; Owner: admin
127875 --
127876
127877 REVOKE ALL ON TABLE apchkitem FROM PUBLIC;
127878 REVOKE ALL ON TABLE apchkitem FROM admin;
127879 GRANT ALL ON TABLE apchkitem TO admin;
127880 GRANT ALL ON TABLE apchkitem TO xtrole;
127881
127882
127883 --
127884 -- TOC entry 9502 (class 0 OID 0)
127885 -- Dependencies: 434
127886 -- Name: apcreditapply; Type: ACL; Schema: public; Owner: admin
127887 --
127888
127889 REVOKE ALL ON TABLE apcreditapply FROM PUBLIC;
127890 REVOKE ALL ON TABLE apcreditapply FROM admin;
127891 GRANT ALL ON TABLE apcreditapply TO admin;
127892 GRANT ALL ON TABLE apcreditapply TO xtrole;
127893
127894
127895 --
127896 -- TOC entry 9504 (class 0 OID 0)
127897 -- Dependencies: 435
127898 -- Name: apcreditapply_apcreditapply_id_seq; Type: ACL; Schema: public; Owner: admin
127899 --
127900
127901 REVOKE ALL ON SEQUENCE apcreditapply_apcreditapply_id_seq FROM PUBLIC;
127902 REVOKE ALL ON SEQUENCE apcreditapply_apcreditapply_id_seq FROM admin;
127903 GRANT ALL ON SEQUENCE apcreditapply_apcreditapply_id_seq TO admin;
127904 GRANT ALL ON SEQUENCE apcreditapply_apcreditapply_id_seq TO xtrole;
127905
127906
127907 --
127908 -- TOC entry 9505 (class 0 OID 0)
127909 -- Dependencies: 436
127910 -- Name: apmemo; Type: ACL; Schema: public; Owner: admin
127911 --
127912
127913 REVOKE ALL ON TABLE apmemo FROM PUBLIC;
127914 REVOKE ALL ON TABLE apmemo FROM admin;
127915 GRANT ALL ON TABLE apmemo TO admin;
127916 GRANT ALL ON TABLE apmemo TO xtrole;
127917
127918
127919 --
127920 -- TOC entry 9506 (class 0 OID 0)
127921 -- Dependencies: 437
127922 -- Name: apopen_apopen_id_seq; Type: ACL; Schema: public; Owner: admin
127923 --
127924
127925 REVOKE ALL ON SEQUENCE apopen_apopen_id_seq FROM PUBLIC;
127926 REVOKE ALL ON SEQUENCE apopen_apopen_id_seq FROM admin;
127927 GRANT ALL ON SEQUENCE apopen_apopen_id_seq TO admin;
127928 GRANT ALL ON SEQUENCE apopen_apopen_id_seq TO xtrole;
127929
127930
127931 --
127932 -- TOC entry 9507 (class 0 OID 0)
127933 -- Dependencies: 438
127934 -- Name: apopentax; Type: ACL; Schema: public; Owner: admin
127935 --
127936
127937 REVOKE ALL ON TABLE apopentax FROM PUBLIC;
127938 REVOKE ALL ON TABLE apopentax FROM admin;
127939 GRANT ALL ON TABLE apopentax TO admin;
127940 GRANT ALL ON TABLE apopentax TO xtrole;
127941
127942
127943 --
127944 -- TOC entry 9509 (class 0 OID 0)
127945 -- Dependencies: 439
127946 -- Name: apselect; Type: ACL; Schema: public; Owner: admin
127947 --
127948
127949 REVOKE ALL ON TABLE apselect FROM PUBLIC;
127950 REVOKE ALL ON TABLE apselect FROM admin;
127951 GRANT ALL ON TABLE apselect TO admin;
127952 GRANT ALL ON TABLE apselect TO xtrole;
127953
127954
127955 --
127956 -- TOC entry 9511 (class 0 OID 0)
127957 -- Dependencies: 440
127958 -- Name: apselect_apselect_id_seq; Type: ACL; Schema: public; Owner: admin
127959 --
127960
127961 REVOKE ALL ON SEQUENCE apselect_apselect_id_seq FROM PUBLIC;
127962 REVOKE ALL ON SEQUENCE apselect_apselect_id_seq FROM admin;
127963 GRANT ALL ON SEQUENCE apselect_apselect_id_seq TO admin;
127964 GRANT ALL ON SEQUENCE apselect_apselect_id_seq TO xtrole;
127965
127966
127967 --
127968 -- TOC entry 9513 (class 0 OID 0)
127969 -- Dependencies: 441
127970 -- Name: araccnt; Type: ACL; Schema: public; Owner: admin
127971 --
127972
127973 REVOKE ALL ON TABLE araccnt FROM PUBLIC;
127974 REVOKE ALL ON TABLE araccnt FROM admin;
127975 GRANT ALL ON TABLE araccnt TO admin;
127976 GRANT ALL ON TABLE araccnt TO xtrole;
127977
127978
127979 --
127980 -- TOC entry 9514 (class 0 OID 0)
127981 -- Dependencies: 442
127982 -- Name: araccnt_araccnt_id_seq; Type: ACL; Schema: public; Owner: admin
127983 --
127984
127985 REVOKE ALL ON SEQUENCE araccnt_araccnt_id_seq FROM PUBLIC;
127986 REVOKE ALL ON SEQUENCE araccnt_araccnt_id_seq FROM admin;
127987 GRANT ALL ON SEQUENCE araccnt_araccnt_id_seq TO admin;
127988 GRANT ALL ON SEQUENCE araccnt_araccnt_id_seq TO xtrole;
127989
127990
127991 --
127992 -- TOC entry 9516 (class 0 OID 0)
127993 -- Dependencies: 443
127994 -- Name: arapply; Type: ACL; Schema: public; Owner: admin
127995 --
127996
127997 REVOKE ALL ON TABLE arapply FROM PUBLIC;
127998 REVOKE ALL ON TABLE arapply FROM admin;
127999 GRANT ALL ON TABLE arapply TO admin;
128000 GRANT ALL ON TABLE arapply TO xtrole;
128001
128002
128003 --
128004 -- TOC entry 9518 (class 0 OID 0)
128005 -- Dependencies: 444
128006 -- Name: arapply_arapply_id_seq; Type: ACL; Schema: public; Owner: admin
128007 --
128008
128009 REVOKE ALL ON SEQUENCE arapply_arapply_id_seq FROM PUBLIC;
128010 REVOKE ALL ON SEQUENCE arapply_arapply_id_seq FROM admin;
128011 GRANT ALL ON SEQUENCE arapply_arapply_id_seq TO admin;
128012 GRANT ALL ON SEQUENCE arapply_arapply_id_seq TO xtrole;
128013
128014
128015 --
128016 -- TOC entry 9520 (class 0 OID 0)
128017 -- Dependencies: 445
128018 -- Name: cashrcptitem_cashrcptitem_id_seq; Type: ACL; Schema: public; Owner: admin
128019 --
128020
128021 REVOKE ALL ON SEQUENCE cashrcptitem_cashrcptitem_id_seq FROM PUBLIC;
128022 REVOKE ALL ON SEQUENCE cashrcptitem_cashrcptitem_id_seq FROM admin;
128023 GRANT ALL ON SEQUENCE cashrcptitem_cashrcptitem_id_seq TO admin;
128024 GRANT ALL ON SEQUENCE cashrcptitem_cashrcptitem_id_seq TO xtrole;
128025
128026
128027 --
128028 -- TOC entry 9522 (class 0 OID 0)
128029 -- Dependencies: 446
128030 -- Name: arcreditapply; Type: ACL; Schema: public; Owner: admin
128031 --
128032
128033 REVOKE ALL ON TABLE arcreditapply FROM PUBLIC;
128034 REVOKE ALL ON TABLE arcreditapply FROM admin;
128035 GRANT ALL ON TABLE arcreditapply TO admin;
128036 GRANT ALL ON TABLE arcreditapply TO xtrole;
128037
128038
128039 --
128040 -- TOC entry 9524 (class 0 OID 0)
128041 -- Dependencies: 447
128042 -- Name: arcreditapply_arcreditapply_id_seq; Type: ACL; Schema: public; Owner: admin
128043 --
128044
128045 REVOKE ALL ON SEQUENCE arcreditapply_arcreditapply_id_seq FROM PUBLIC;
128046 REVOKE ALL ON SEQUENCE arcreditapply_arcreditapply_id_seq FROM admin;
128047 GRANT ALL ON SEQUENCE arcreditapply_arcreditapply_id_seq TO admin;
128048 GRANT ALL ON SEQUENCE arcreditapply_arcreditapply_id_seq TO xtrole;
128049
128050
128051 --
128052 -- TOC entry 9525 (class 0 OID 0)
128053 -- Dependencies: 448
128054 -- Name: armemo; Type: ACL; Schema: public; Owner: admin
128055 --
128056
128057 REVOKE ALL ON TABLE armemo FROM PUBLIC;
128058 REVOKE ALL ON TABLE armemo FROM admin;
128059 GRANT ALL ON TABLE armemo TO admin;
128060 GRANT ALL ON TABLE armemo TO xtrole;
128061
128062
128063 --
128064 -- TOC entry 9526 (class 0 OID 0)
128065 -- Dependencies: 449
128066 -- Name: aropen_aropen_id_seq; Type: ACL; Schema: public; Owner: admin
128067 --
128068
128069 REVOKE ALL ON SEQUENCE aropen_aropen_id_seq FROM PUBLIC;
128070 REVOKE ALL ON SEQUENCE aropen_aropen_id_seq FROM admin;
128071 GRANT ALL ON SEQUENCE aropen_aropen_id_seq TO admin;
128072 GRANT ALL ON SEQUENCE aropen_aropen_id_seq TO xtrole;
128073
128074
128075 --
128076 -- TOC entry 9527 (class 0 OID 0)
128077 -- Dependencies: 450
128078 -- Name: aropentax; Type: ACL; Schema: public; Owner: admin
128079 --
128080
128081 REVOKE ALL ON TABLE aropentax FROM PUBLIC;
128082 REVOKE ALL ON TABLE aropentax FROM admin;
128083 GRANT ALL ON TABLE aropentax TO admin;
128084 GRANT ALL ON TABLE aropentax TO xtrole;
128085
128086
128087 --
128088 -- TOC entry 9529 (class 0 OID 0)
128089 -- Dependencies: 451
128090 -- Name: asohist; Type: ACL; Schema: public; Owner: admin
128091 --
128092
128093 REVOKE ALL ON TABLE asohist FROM PUBLIC;
128094 REVOKE ALL ON TABLE asohist FROM admin;
128095 GRANT ALL ON TABLE asohist TO admin;
128096 GRANT ALL ON TABLE asohist TO xtrole;
128097
128098
128099 --
128100 -- TOC entry 9531 (class 0 OID 0)
128101 -- Dependencies: 452
128102 -- Name: asohist_asohist_id_seq; Type: ACL; Schema: public; Owner: admin
128103 --
128104
128105 REVOKE ALL ON SEQUENCE asohist_asohist_id_seq FROM PUBLIC;
128106 REVOKE ALL ON SEQUENCE asohist_asohist_id_seq FROM admin;
128107 GRANT ALL ON SEQUENCE asohist_asohist_id_seq TO admin;
128108 GRANT ALL ON SEQUENCE asohist_asohist_id_seq TO xtrole;
128109
128110
128111 --
128112 -- TOC entry 9532 (class 0 OID 0)
128113 -- Dependencies: 453
128114 -- Name: asohisttax; Type: ACL; Schema: public; Owner: admin
128115 --
128116
128117 REVOKE ALL ON TABLE asohisttax FROM PUBLIC;
128118 REVOKE ALL ON TABLE asohisttax FROM admin;
128119 GRANT ALL ON TABLE asohisttax TO admin;
128120 GRANT ALL ON TABLE asohisttax TO xtrole;
128121
128122
128123 --
128124 -- TOC entry 9541 (class 0 OID 0)
128125 -- Dependencies: 454
128126 -- Name: atlasmap; Type: ACL; Schema: public; Owner: admin
128127 --
128128
128129 REVOKE ALL ON TABLE atlasmap FROM PUBLIC;
128130 REVOKE ALL ON TABLE atlasmap FROM admin;
128131 GRANT ALL ON TABLE atlasmap TO admin;
128132 GRANT ALL ON TABLE atlasmap TO xtrole;
128133
128134
128135 --
128136 -- TOC entry 9543 (class 0 OID 0)
128137 -- Dependencies: 455
128138 -- Name: atlasmap_atlasmap_id_seq; Type: ACL; Schema: public; Owner: admin
128139 --
128140
128141 REVOKE ALL ON SEQUENCE atlasmap_atlasmap_id_seq FROM PUBLIC;
128142 REVOKE ALL ON SEQUENCE atlasmap_atlasmap_id_seq FROM admin;
128143 GRANT ALL ON SEQUENCE atlasmap_atlasmap_id_seq TO admin;
128144 GRANT ALL ON SEQUENCE atlasmap_atlasmap_id_seq TO xtrole;
128145
128146
128147 --
128148 -- TOC entry 9544 (class 0 OID 0)
128149 -- Dependencies: 456
128150 -- Name: backup_usr; Type: ACL; Schema: public; Owner: admin
128151 --
128152
128153 REVOKE ALL ON TABLE backup_usr FROM PUBLIC;
128154 REVOKE ALL ON TABLE backup_usr FROM admin;
128155 GRANT ALL ON TABLE backup_usr TO admin;
128156 GRANT ALL ON TABLE backup_usr TO xtrole;
128157
128158
128159 --
128160 -- TOC entry 9546 (class 0 OID 0)
128161 -- Dependencies: 457
128162 -- Name: bankaccnt_bankaccnt_id_seq; Type: ACL; Schema: public; Owner: admin
128163 --
128164
128165 REVOKE ALL ON SEQUENCE bankaccnt_bankaccnt_id_seq FROM PUBLIC;
128166 REVOKE ALL ON SEQUENCE bankaccnt_bankaccnt_id_seq FROM admin;
128167 GRANT ALL ON SEQUENCE bankaccnt_bankaccnt_id_seq TO admin;
128168 GRANT ALL ON SEQUENCE bankaccnt_bankaccnt_id_seq TO xtrole;
128169
128170
128171 --
128172 -- TOC entry 9548 (class 0 OID 0)
128173 -- Dependencies: 458
128174 -- Name: bankadj; Type: ACL; Schema: public; Owner: admin
128175 --
128176
128177 REVOKE ALL ON TABLE bankadj FROM PUBLIC;
128178 REVOKE ALL ON TABLE bankadj FROM admin;
128179 GRANT ALL ON TABLE bankadj TO admin;
128180 GRANT ALL ON TABLE bankadj TO xtrole;
128181
128182
128183 --
128184 -- TOC entry 9550 (class 0 OID 0)
128185 -- Dependencies: 459
128186 -- Name: bankadj_bankadj_id_seq; Type: ACL; Schema: public; Owner: admin
128187 --
128188
128189 REVOKE ALL ON SEQUENCE bankadj_bankadj_id_seq FROM PUBLIC;
128190 REVOKE ALL ON SEQUENCE bankadj_bankadj_id_seq FROM admin;
128191 GRANT ALL ON SEQUENCE bankadj_bankadj_id_seq TO admin;
128192 GRANT ALL ON SEQUENCE bankadj_bankadj_id_seq TO xtrole;
128193
128194
128195 --
128196 -- TOC entry 9552 (class 0 OID 0)
128197 -- Dependencies: 460
128198 -- Name: bankadjtype; Type: ACL; Schema: public; Owner: admin
128199 --
128200
128201 REVOKE ALL ON TABLE bankadjtype FROM PUBLIC;
128202 REVOKE ALL ON TABLE bankadjtype FROM admin;
128203 GRANT ALL ON TABLE bankadjtype TO admin;
128204 GRANT ALL ON TABLE bankadjtype TO xtrole;
128205
128206
128207 --
128208 -- TOC entry 9554 (class 0 OID 0)
128209 -- Dependencies: 461
128210 -- Name: bankadjtype_bankadjtype_id_seq; Type: ACL; Schema: public; Owner: admin
128211 --
128212
128213 REVOKE ALL ON SEQUENCE bankadjtype_bankadjtype_id_seq FROM PUBLIC;
128214 REVOKE ALL ON SEQUENCE bankadjtype_bankadjtype_id_seq FROM admin;
128215 GRANT ALL ON SEQUENCE bankadjtype_bankadjtype_id_seq TO admin;
128216 GRANT ALL ON SEQUENCE bankadjtype_bankadjtype_id_seq TO xtrole;
128217
128218
128219 --
128220 -- TOC entry 9556 (class 0 OID 0)
128221 -- Dependencies: 462
128222 -- Name: bankrec; Type: ACL; Schema: public; Owner: admin
128223 --
128224
128225 REVOKE ALL ON TABLE bankrec FROM PUBLIC;
128226 REVOKE ALL ON TABLE bankrec FROM admin;
128227 GRANT ALL ON TABLE bankrec TO admin;
128228 GRANT ALL ON TABLE bankrec TO xtrole;
128229
128230
128231 --
128232 -- TOC entry 9558 (class 0 OID 0)
128233 -- Dependencies: 463
128234 -- Name: bankrec_bankrec_id_seq; Type: ACL; Schema: public; Owner: admin
128235 --
128236
128237 REVOKE ALL ON SEQUENCE bankrec_bankrec_id_seq FROM PUBLIC;
128238 REVOKE ALL ON SEQUENCE bankrec_bankrec_id_seq FROM admin;
128239 GRANT ALL ON SEQUENCE bankrec_bankrec_id_seq TO admin;
128240 GRANT ALL ON SEQUENCE bankrec_bankrec_id_seq TO xtrole;
128241
128242
128243 --
128244 -- TOC entry 9560 (class 0 OID 0)
128245 -- Dependencies: 464
128246 -- Name: bankrecitem; Type: ACL; Schema: public; Owner: admin
128247 --
128248
128249 REVOKE ALL ON TABLE bankrecitem FROM PUBLIC;
128250 REVOKE ALL ON TABLE bankrecitem FROM admin;
128251 GRANT ALL ON TABLE bankrecitem TO admin;
128252 GRANT ALL ON TABLE bankrecitem TO xtrole;
128253
128254
128255 --
128256 -- TOC entry 9562 (class 0 OID 0)
128257 -- Dependencies: 465
128258 -- Name: bankrecitem_bankrecitem_id_seq; Type: ACL; Schema: public; Owner: admin
128259 --
128260
128261 REVOKE ALL ON SEQUENCE bankrecitem_bankrecitem_id_seq FROM PUBLIC;
128262 REVOKE ALL ON SEQUENCE bankrecitem_bankrecitem_id_seq FROM admin;
128263 GRANT ALL ON SEQUENCE bankrecitem_bankrecitem_id_seq TO admin;
128264 GRANT ALL ON SEQUENCE bankrecitem_bankrecitem_id_seq TO xtrole;
128265
128266
128267 --
128268 -- TOC entry 9563 (class 0 OID 0)
128269 -- Dependencies: 466
128270 -- Name: bomhead_bomhead_id_seq; Type: ACL; Schema: public; Owner: admin
128271 --
128272
128273 REVOKE ALL ON SEQUENCE bomhead_bomhead_id_seq FROM PUBLIC;
128274 REVOKE ALL ON SEQUENCE bomhead_bomhead_id_seq FROM admin;
128275 GRANT ALL ON SEQUENCE bomhead_bomhead_id_seq TO admin;
128276 GRANT ALL ON SEQUENCE bomhead_bomhead_id_seq TO xtrole;
128277
128278
128279 --
128280 -- TOC entry 9564 (class 0 OID 0)
128281 -- Dependencies: 467
128282 -- Name: bomitem_bomitem_id_seq; Type: ACL; Schema: public; Owner: admin
128283 --
128284
128285 REVOKE ALL ON SEQUENCE bomitem_bomitem_id_seq FROM PUBLIC;
128286 REVOKE ALL ON SEQUENCE bomitem_bomitem_id_seq FROM admin;
128287 GRANT ALL ON SEQUENCE bomitem_bomitem_id_seq TO admin;
128288 GRANT ALL ON SEQUENCE bomitem_bomitem_id_seq TO xtrole;
128289
128290
128291 --
128292 -- TOC entry 9566 (class 0 OID 0)
128293 -- Dependencies: 468
128294 -- Name: bomitemcost; Type: ACL; Schema: public; Owner: admin
128295 --
128296
128297 REVOKE ALL ON TABLE bomitemcost FROM PUBLIC;
128298 REVOKE ALL ON TABLE bomitemcost FROM admin;
128299 GRANT ALL ON TABLE bomitemcost TO admin;
128300 GRANT ALL ON TABLE bomitemcost TO xtrole;
128301
128302
128303 --
128304 -- TOC entry 9568 (class 0 OID 0)
128305 -- Dependencies: 469
128306 -- Name: bomitemcost_bomitemcost_id_seq; Type: ACL; Schema: public; Owner: admin
128307 --
128308
128309 REVOKE ALL ON SEQUENCE bomitemcost_bomitemcost_id_seq FROM PUBLIC;
128310 REVOKE ALL ON SEQUENCE bomitemcost_bomitemcost_id_seq FROM admin;
128311 GRANT ALL ON SEQUENCE bomitemcost_bomitemcost_id_seq TO admin;
128312 GRANT ALL ON SEQUENCE bomitemcost_bomitemcost_id_seq TO xtrole;
128313
128314
128315 --
128316 -- TOC entry 9570 (class 0 OID 0)
128317 -- Dependencies: 470
128318 -- Name: bomitemsub_bomitemsub_id_seq; Type: ACL; Schema: public; Owner: admin
128319 --
128320
128321 REVOKE ALL ON SEQUENCE bomitemsub_bomitemsub_id_seq FROM PUBLIC;
128322 REVOKE ALL ON SEQUENCE bomitemsub_bomitemsub_id_seq FROM admin;
128323 GRANT ALL ON SEQUENCE bomitemsub_bomitemsub_id_seq TO admin;
128324 GRANT ALL ON SEQUENCE bomitemsub_bomitemsub_id_seq TO xtrole;
128325
128326
128327 --
128328 -- TOC entry 9574 (class 0 OID 0)
128329 -- Dependencies: 471
128330 -- Name: bomwork; Type: ACL; Schema: public; Owner: admin
128331 --
128332
128333 REVOKE ALL ON TABLE bomwork FROM PUBLIC;
128334 REVOKE ALL ON TABLE bomwork FROM admin;
128335 GRANT ALL ON TABLE bomwork TO admin;
128336 GRANT ALL ON TABLE bomwork TO xtrole;
128337
128338
128339 --
128340 -- TOC entry 9576 (class 0 OID 0)
128341 -- Dependencies: 472
128342 -- Name: bomwork_bomwork_id_seq; Type: ACL; Schema: public; Owner: admin
128343 --
128344
128345 REVOKE ALL ON SEQUENCE bomwork_bomwork_id_seq FROM PUBLIC;
128346 REVOKE ALL ON SEQUENCE bomwork_bomwork_id_seq FROM admin;
128347 GRANT ALL ON SEQUENCE bomwork_bomwork_id_seq TO admin;
128348 GRANT ALL ON SEQUENCE bomwork_bomwork_id_seq TO xtrole;
128349
128350
128351 --
128352 -- TOC entry 9577 (class 0 OID 0)
128353 -- Dependencies: 473
128354 -- Name: budget; Type: ACL; Schema: public; Owner: admin
128355 --
128356
128357 REVOKE ALL ON TABLE budget FROM PUBLIC;
128358 REVOKE ALL ON TABLE budget FROM admin;
128359 GRANT ALL ON TABLE budget TO admin;
128360 GRANT ALL ON TABLE budget TO xtrole;
128361
128362
128363 --
128364 -- TOC entry 9579 (class 0 OID 0)
128365 -- Dependencies: 474
128366 -- Name: budghead_budghead_id_seq; Type: ACL; Schema: public; Owner: admin
128367 --
128368
128369 REVOKE ALL ON SEQUENCE budghead_budghead_id_seq FROM PUBLIC;
128370 REVOKE ALL ON SEQUENCE budghead_budghead_id_seq FROM admin;
128371 GRANT ALL ON SEQUENCE budghead_budghead_id_seq TO admin;
128372 GRANT ALL ON SEQUENCE budghead_budghead_id_seq TO xtrole;
128373
128374
128375 --
128376 -- TOC entry 9581 (class 0 OID 0)
128377 -- Dependencies: 475
128378 -- Name: budgitem_budgitem_id_seq; Type: ACL; Schema: public; Owner: admin
128379 --
128380
128381 REVOKE ALL ON SEQUENCE budgitem_budgitem_id_seq FROM PUBLIC;
128382 REVOKE ALL ON SEQUENCE budgitem_budgitem_id_seq FROM admin;
128383 GRANT ALL ON SEQUENCE budgitem_budgitem_id_seq TO admin;
128384 GRANT ALL ON SEQUENCE budgitem_budgitem_id_seq TO xtrole;
128385
128386
128387 --
128388 -- TOC entry 9583 (class 0 OID 0)
128389 -- Dependencies: 476
128390 -- Name: calhead; Type: ACL; Schema: public; Owner: admin
128391 --
128392
128393 REVOKE ALL ON TABLE calhead FROM PUBLIC;
128394 REVOKE ALL ON TABLE calhead FROM admin;
128395 GRANT ALL ON TABLE calhead TO admin;
128396 GRANT ALL ON TABLE calhead TO xtrole;
128397
128398
128399 --
128400 -- TOC entry 9584 (class 0 OID 0)
128401 -- Dependencies: 477
128402 -- Name: calhead_calhead_id_seq; Type: ACL; Schema: public; Owner: admin
128403 --
128404
128405 REVOKE ALL ON SEQUENCE calhead_calhead_id_seq FROM PUBLIC;
128406 REVOKE ALL ON SEQUENCE calhead_calhead_id_seq FROM admin;
128407 GRANT ALL ON SEQUENCE calhead_calhead_id_seq TO admin;
128408 GRANT ALL ON SEQUENCE calhead_calhead_id_seq TO xtrole;
128409
128410
128411 --
128412 -- TOC entry 9585 (class 0 OID 0)
128413 -- Dependencies: 478
128414 -- Name: carrier_carrier_id_seq; Type: ACL; Schema: public; Owner: admin
128415 --
128416
128417 REVOKE ALL ON SEQUENCE carrier_carrier_id_seq FROM PUBLIC;
128418 REVOKE ALL ON SEQUENCE carrier_carrier_id_seq FROM admin;
128419 GRANT ALL ON SEQUENCE carrier_carrier_id_seq TO admin;
128420 GRANT ALL ON SEQUENCE carrier_carrier_id_seq TO xtrole;
128421
128422
128423 --
128424 -- TOC entry 9587 (class 0 OID 0)
128425 -- Dependencies: 479
128426 -- Name: cashrcpt_cashrcpt_id_seq; Type: ACL; Schema: public; Owner: admin
128427 --
128428
128429 REVOKE ALL ON SEQUENCE cashrcpt_cashrcpt_id_seq FROM PUBLIC;
128430 REVOKE ALL ON SEQUENCE cashrcpt_cashrcpt_id_seq FROM admin;
128431 GRANT ALL ON SEQUENCE cashrcpt_cashrcpt_id_seq TO admin;
128432 GRANT ALL ON SEQUENCE cashrcpt_cashrcpt_id_seq TO xtrole;
128433
128434
128435 --
128436 -- TOC entry 9589 (class 0 OID 0)
128437 -- Dependencies: 480
128438 -- Name: cashrcptmisc_cashrcptmisc_id_seq; Type: ACL; Schema: public; Owner: admin
128439 --
128440
128441 REVOKE ALL ON SEQUENCE cashrcptmisc_cashrcptmisc_id_seq FROM PUBLIC;
128442 REVOKE ALL ON SEQUENCE cashrcptmisc_cashrcptmisc_id_seq FROM admin;
128443 GRANT ALL ON SEQUENCE cashrcptmisc_cashrcptmisc_id_seq TO admin;
128444 GRANT ALL ON SEQUENCE cashrcptmisc_cashrcptmisc_id_seq TO xtrole;
128445
128446
128447 --
128448 -- TOC entry 9591 (class 0 OID 0)
128449 -- Dependencies: 481
128450 -- Name: ccard_ccard_id_seq; Type: ACL; Schema: public; Owner: admin
128451 --
128452
128453 REVOKE ALL ON SEQUENCE ccard_ccard_id_seq FROM PUBLIC;
128454 REVOKE ALL ON SEQUENCE ccard_ccard_id_seq FROM admin;
128455 GRANT ALL ON SEQUENCE ccard_ccard_id_seq TO admin;
128456 GRANT ALL ON SEQUENCE ccard_ccard_id_seq TO xtrole;
128457
128458
128459 --
128460 -- TOC entry 9593 (class 0 OID 0)
128461 -- Dependencies: 482
128462 -- Name: ccardaud; Type: ACL; Schema: public; Owner: admin
128463 --
128464
128465 REVOKE ALL ON TABLE ccardaud FROM PUBLIC;
128466 REVOKE ALL ON TABLE ccardaud FROM admin;
128467 GRANT ALL ON TABLE ccardaud TO admin;
128468 GRANT ALL ON TABLE ccardaud TO xtrole;
128469
128470
128471 --
128472 -- TOC entry 9595 (class 0 OID 0)
128473 -- Dependencies: 483
128474 -- Name: ccardaud_ccardaud_id_seq; Type: ACL; Schema: public; Owner: admin
128475 --
128476
128477 REVOKE ALL ON SEQUENCE ccardaud_ccardaud_id_seq FROM PUBLIC;
128478 REVOKE ALL ON SEQUENCE ccardaud_ccardaud_id_seq FROM admin;
128479 GRANT ALL ON SEQUENCE ccardaud_ccardaud_id_seq TO admin;
128480 GRANT ALL ON SEQUENCE ccardaud_ccardaud_id_seq TO xtrole;
128481
128482
128483 --
128484 -- TOC entry 9596 (class 0 OID 0)
128485 -- Dependencies: 484
128486 -- Name: ccbank; Type: ACL; Schema: public; Owner: admin
128487 --
128488
128489 REVOKE ALL ON TABLE ccbank FROM PUBLIC;
128490 REVOKE ALL ON TABLE ccbank FROM admin;
128491 GRANT ALL ON TABLE ccbank TO admin;
128492 GRANT ALL ON TABLE ccbank TO xtrole;
128493
128494
128495 --
128496 -- TOC entry 9598 (class 0 OID 0)
128497 -- Dependencies: 485
128498 -- Name: ccbank_ccbank_id_seq; Type: ACL; Schema: public; Owner: admin
128499 --
128500
128501 REVOKE ALL ON SEQUENCE ccbank_ccbank_id_seq FROM PUBLIC;
128502 REVOKE ALL ON SEQUENCE ccbank_ccbank_id_seq FROM admin;
128503 GRANT ALL ON SEQUENCE ccbank_ccbank_id_seq TO admin;
128504 GRANT ALL ON SEQUENCE ccbank_ccbank_id_seq TO xtrole;
128505
128506
128507 --
128508 -- TOC entry 9626 (class 0 OID 0)
128509 -- Dependencies: 486
128510 -- Name: ccpay; Type: ACL; Schema: public; Owner: admin
128511 --
128512
128513 REVOKE ALL ON TABLE ccpay FROM PUBLIC;
128514 REVOKE ALL ON TABLE ccpay FROM admin;
128515 GRANT ALL ON TABLE ccpay TO admin;
128516 GRANT ALL ON TABLE ccpay TO xtrole;
128517
128518
128519 --
128520 -- TOC entry 9628 (class 0 OID 0)
128521 -- Dependencies: 487
128522 -- Name: ccpay_ccpay_id_seq; Type: ACL; Schema: public; Owner: admin
128523 --
128524
128525 REVOKE ALL ON SEQUENCE ccpay_ccpay_id_seq FROM PUBLIC;
128526 REVOKE ALL ON SEQUENCE ccpay_ccpay_id_seq FROM admin;
128527 GRANT ALL ON SEQUENCE ccpay_ccpay_id_seq TO admin;
128528 GRANT ALL ON SEQUENCE ccpay_ccpay_id_seq TO xtrole;
128529
128530
128531 --
128532 -- TOC entry 9630 (class 0 OID 0)
128533 -- Dependencies: 488
128534 -- Name: char_char_id_seq; Type: ACL; Schema: public; Owner: admin
128535 --
128536
128537 REVOKE ALL ON SEQUENCE char_char_id_seq FROM PUBLIC;
128538 REVOKE ALL ON SEQUENCE char_char_id_seq FROM admin;
128539 GRANT ALL ON SEQUENCE char_char_id_seq TO admin;
128540 GRANT ALL ON SEQUENCE char_char_id_seq TO xtrole;
128541
128542
128543 --
128544 -- TOC entry 9632 (class 0 OID 0)
128545 -- Dependencies: 489
128546 -- Name: charass_charass_id_seq; Type: ACL; Schema: public; Owner: admin
128547 --
128548
128549 REVOKE ALL ON SEQUENCE charass_charass_id_seq FROM PUBLIC;
128550 REVOKE ALL ON SEQUENCE charass_charass_id_seq FROM admin;
128551 GRANT ALL ON SEQUENCE charass_charass_id_seq TO admin;
128552 GRANT ALL ON SEQUENCE charass_charass_id_seq TO xtrole;
128553
128554
128555 --
128556 -- TOC entry 9638 (class 0 OID 0)
128557 -- Dependencies: 490
128558 -- Name: charopt; Type: ACL; Schema: public; Owner: admin
128559 --
128560
128561 REVOKE ALL ON TABLE charopt FROM PUBLIC;
128562 REVOKE ALL ON TABLE charopt FROM admin;
128563 GRANT ALL ON TABLE charopt TO admin;
128564 GRANT ALL ON TABLE charopt TO xtrole;
128565
128566
128567 --
128568 -- TOC entry 9640 (class 0 OID 0)
128569 -- Dependencies: 491
128570 -- Name: charopt_charopt_id_seq; Type: ACL; Schema: public; Owner: admin
128571 --
128572
128573 REVOKE ALL ON SEQUENCE charopt_charopt_id_seq FROM PUBLIC;
128574 REVOKE ALL ON SEQUENCE charopt_charopt_id_seq FROM admin;
128575 GRANT ALL ON SEQUENCE charopt_charopt_id_seq TO admin;
128576 GRANT ALL ON SEQUENCE charopt_charopt_id_seq TO xtrole;
128577
128578
128579 --
128580 -- TOC entry 9642 (class 0 OID 0)
128581 -- Dependencies: 492
128582 -- Name: checkhead_checkhead_id_seq; Type: ACL; Schema: public; Owner: admin
128583 --
128584
128585 REVOKE ALL ON SEQUENCE checkhead_checkhead_id_seq FROM PUBLIC;
128586 REVOKE ALL ON SEQUENCE checkhead_checkhead_id_seq FROM admin;
128587 GRANT ALL ON SEQUENCE checkhead_checkhead_id_seq TO admin;
128588 GRANT ALL ON SEQUENCE checkhead_checkhead_id_seq TO xtrole;
128589
128590
128591 --
128592 -- TOC entry 9644 (class 0 OID 0)
128593 -- Dependencies: 493
128594 -- Name: checkitem_checkitem_id_seq; Type: ACL; Schema: public; Owner: admin
128595 --
128596
128597 REVOKE ALL ON SEQUENCE checkitem_checkitem_id_seq FROM PUBLIC;
128598 REVOKE ALL ON SEQUENCE checkitem_checkitem_id_seq FROM admin;
128599 GRANT ALL ON SEQUENCE checkitem_checkitem_id_seq TO admin;
128600 GRANT ALL ON SEQUENCE checkitem_checkitem_id_seq TO xtrole;
128601
128602
128603 --
128604 -- TOC entry 9645 (class 0 OID 0)
128605 -- Dependencies: 494
128606 -- Name: checkrecip; Type: ACL; Schema: public; Owner: admin
128607 --
128608
128609 REVOKE ALL ON TABLE checkrecip FROM PUBLIC;
128610 REVOKE ALL ON TABLE checkrecip FROM admin;
128611 GRANT ALL ON TABLE checkrecip TO admin;
128612 GRANT ALL ON TABLE checkrecip TO xtrole;
128613
128614
128615 --
128616 -- TOC entry 9646 (class 0 OID 0)
128617 -- Dependencies: 495
128618 -- Name: classcode_classcode_id_seq; Type: ACL; Schema: public; Owner: admin
128619 --
128620
128621 REVOKE ALL ON SEQUENCE classcode_classcode_id_seq FROM PUBLIC;
128622 REVOKE ALL ON SEQUENCE classcode_classcode_id_seq FROM admin;
128623 GRANT ALL ON SEQUENCE classcode_classcode_id_seq TO admin;
128624 GRANT ALL ON SEQUENCE classcode_classcode_id_seq TO xtrole;
128625
128626
128627 --
128628 -- TOC entry 9647 (class 0 OID 0)
128629 -- Dependencies: 496
128630 -- Name: cmhead_cmhead_id_seq; Type: ACL; Schema: public; Owner: admin
128631 --
128632
128633 REVOKE ALL ON SEQUENCE cmhead_cmhead_id_seq FROM PUBLIC;
128634 REVOKE ALL ON SEQUENCE cmhead_cmhead_id_seq FROM admin;
128635 GRANT ALL ON SEQUENCE cmhead_cmhead_id_seq TO admin;
128636 GRANT ALL ON SEQUENCE cmhead_cmhead_id_seq TO xtrole;
128637
128638
128639 --
128640 -- TOC entry 9648 (class 0 OID 0)
128641 -- Dependencies: 497
128642 -- Name: cmheadtax; Type: ACL; Schema: public; Owner: admin
128643 --
128644
128645 REVOKE ALL ON TABLE cmheadtax FROM PUBLIC;
128646 REVOKE ALL ON TABLE cmheadtax FROM admin;
128647 GRANT ALL ON TABLE cmheadtax TO admin;
128648 GRANT ALL ON TABLE cmheadtax TO xtrole;
128649
128650
128651 --
128652 -- TOC entry 9649 (class 0 OID 0)
128653 -- Dependencies: 498
128654 -- Name: cmitem_cmitem_id_seq; Type: ACL; Schema: public; Owner: admin
128655 --
128656
128657 REVOKE ALL ON SEQUENCE cmitem_cmitem_id_seq FROM PUBLIC;
128658 REVOKE ALL ON SEQUENCE cmitem_cmitem_id_seq FROM admin;
128659 GRANT ALL ON SEQUENCE cmitem_cmitem_id_seq TO admin;
128660 GRANT ALL ON SEQUENCE cmitem_cmitem_id_seq TO xtrole;
128661
128662
128663 --
128664 -- TOC entry 9650 (class 0 OID 0)
128665 -- Dependencies: 499
128666 -- Name: cmitemtax; Type: ACL; Schema: public; Owner: admin
128667 --
128668
128669 REVOKE ALL ON TABLE cmitemtax FROM PUBLIC;
128670 REVOKE ALL ON TABLE cmitemtax FROM admin;
128671 GRANT ALL ON TABLE cmitemtax TO admin;
128672 GRANT ALL ON TABLE cmitemtax TO xtrole;
128673
128674
128675 --
128676 -- TOC entry 9652 (class 0 OID 0)
128677 -- Dependencies: 500
128678 -- Name: cmnttype_cmnttype_id_seq; Type: ACL; Schema: public; Owner: admin
128679 --
128680
128681 REVOKE ALL ON SEQUENCE cmnttype_cmnttype_id_seq FROM PUBLIC;
128682 REVOKE ALL ON SEQUENCE cmnttype_cmnttype_id_seq FROM admin;
128683 GRANT ALL ON SEQUENCE cmnttype_cmnttype_id_seq TO admin;
128684 GRANT ALL ON SEQUENCE cmnttype_cmnttype_id_seq TO xtrole;
128685
128686
128687 --
128688 -- TOC entry 9654 (class 0 OID 0)
128689 -- Dependencies: 501
128690 -- Name: cmnttypesource; Type: ACL; Schema: public; Owner: admin
128691 --
128692
128693 REVOKE ALL ON TABLE cmnttypesource FROM PUBLIC;
128694 REVOKE ALL ON TABLE cmnttypesource FROM admin;
128695 GRANT ALL ON TABLE cmnttypesource TO admin;
128696 GRANT ALL ON TABLE cmnttypesource TO xtrole;
128697
128698
128699 --
128700 -- TOC entry 9656 (class 0 OID 0)
128701 -- Dependencies: 502
128702 -- Name: cmnttypesource_cmnttypesource_id_seq; Type: ACL; Schema: public; Owner: admin
128703 --
128704
128705 REVOKE ALL ON SEQUENCE cmnttypesource_cmnttypesource_id_seq FROM PUBLIC;
128706 REVOKE ALL ON SEQUENCE cmnttypesource_cmnttypesource_id_seq FROM admin;
128707 GRANT ALL ON SEQUENCE cmnttypesource_cmnttypesource_id_seq TO admin;
128708 GRANT ALL ON SEQUENCE cmnttypesource_cmnttypesource_id_seq TO xtrole;
128709
128710
128711 --
128712 -- TOC entry 9658 (class 0 OID 0)
128713 -- Dependencies: 503
128714 -- Name: cntct_cntct_id_seq; Type: ACL; Schema: public; Owner: admin
128715 --
128716
128717 REVOKE ALL ON SEQUENCE cntct_cntct_id_seq FROM PUBLIC;
128718 REVOKE ALL ON SEQUENCE cntct_cntct_id_seq FROM admin;
128719 GRANT ALL ON SEQUENCE cntct_cntct_id_seq TO admin;
128720 GRANT ALL ON SEQUENCE cntct_cntct_id_seq TO xtrole;
128721
128722
128723 --
128724 -- TOC entry 9659 (class 0 OID 0)
128725 -- Dependencies: 504
128726 -- Name: cntctaddr; Type: ACL; Schema: public; Owner: admin
128727 --
128728
128729 REVOKE ALL ON TABLE cntctaddr FROM PUBLIC;
128730 REVOKE ALL ON TABLE cntctaddr FROM admin;
128731 GRANT ALL ON TABLE cntctaddr TO admin;
128732 GRANT ALL ON TABLE cntctaddr TO xtrole;
128733
128734
128735 --
128736 -- TOC entry 9661 (class 0 OID 0)
128737 -- Dependencies: 505
128738 -- Name: cntctaddr_cntctaddr_id_seq; Type: ACL; Schema: public; Owner: admin
128739 --
128740
128741 REVOKE ALL ON SEQUENCE cntctaddr_cntctaddr_id_seq FROM PUBLIC;
128742 REVOKE ALL ON SEQUENCE cntctaddr_cntctaddr_id_seq FROM admin;
128743 GRANT ALL ON SEQUENCE cntctaddr_cntctaddr_id_seq TO admin;
128744 GRANT ALL ON SEQUENCE cntctaddr_cntctaddr_id_seq TO xtrole;
128745
128746
128747 --
128748 -- TOC entry 9662 (class 0 OID 0)
128749 -- Dependencies: 506
128750 -- Name: cntctdata; Type: ACL; Schema: public; Owner: admin
128751 --
128752
128753 REVOKE ALL ON TABLE cntctdata FROM PUBLIC;
128754 REVOKE ALL ON TABLE cntctdata FROM admin;
128755 GRANT ALL ON TABLE cntctdata TO admin;
128756 GRANT ALL ON TABLE cntctdata TO xtrole;
128757
128758
128759 --
128760 -- TOC entry 9664 (class 0 OID 0)
128761 -- Dependencies: 507
128762 -- Name: cntctdata_cntctdata_id_seq; Type: ACL; Schema: public; Owner: admin
128763 --
128764
128765 REVOKE ALL ON SEQUENCE cntctdata_cntctdata_id_seq FROM PUBLIC;
128766 REVOKE ALL ON SEQUENCE cntctdata_cntctdata_id_seq FROM admin;
128767 GRANT ALL ON SEQUENCE cntctdata_cntctdata_id_seq TO admin;
128768 GRANT ALL ON SEQUENCE cntctdata_cntctdata_id_seq TO xtrole;
128769
128770
128771 --
128772 -- TOC entry 9670 (class 0 OID 0)
128773 -- Dependencies: 508
128774 -- Name: cntcteml; Type: ACL; Schema: public; Owner: admin
128775 --
128776
128777 REVOKE ALL ON TABLE cntcteml FROM PUBLIC;
128778 REVOKE ALL ON TABLE cntcteml FROM admin;
128779 GRANT ALL ON TABLE cntcteml TO admin;
128780 GRANT ALL ON TABLE cntcteml TO xtrole;
128781
128782
128783 --
128784 -- TOC entry 9672 (class 0 OID 0)
128785 -- Dependencies: 509
128786 -- Name: cntcteml_cntcteml_id_seq; Type: ACL; Schema: public; Owner: admin
128787 --
128788
128789 REVOKE ALL ON SEQUENCE cntcteml_cntcteml_id_seq FROM PUBLIC;
128790 REVOKE ALL ON SEQUENCE cntcteml_cntcteml_id_seq FROM admin;
128791 GRANT ALL ON SEQUENCE cntcteml_cntcteml_id_seq TO admin;
128792 GRANT ALL ON SEQUENCE cntcteml_cntcteml_id_seq TO xtrole;
128793
128794
128795 --
128796 -- TOC entry 9673 (class 0 OID 0)
128797 -- Dependencies: 510
128798 -- Name: cntctmrgd; Type: ACL; Schema: public; Owner: admin
128799 --
128800
128801 REVOKE ALL ON TABLE cntctmrgd FROM PUBLIC;
128802 REVOKE ALL ON TABLE cntctmrgd FROM admin;
128803 GRANT ALL ON TABLE cntctmrgd TO admin;
128804 GRANT ALL ON TABLE cntctmrgd TO xtrole;
128805
128806
128807 --
128808 -- TOC entry 9674 (class 0 OID 0)
128809 -- Dependencies: 511
128810 -- Name: cntctsel; Type: ACL; Schema: public; Owner: admin
128811 --
128812
128813 REVOKE ALL ON TABLE cntctsel FROM PUBLIC;
128814 REVOKE ALL ON TABLE cntctsel FROM admin;
128815 GRANT ALL ON TABLE cntctsel TO admin;
128816 GRANT ALL ON TABLE cntctsel TO xtrole;
128817
128818
128819 --
128820 -- TOC entry 9675 (class 0 OID 0)
128821 -- Dependencies: 512
128822 -- Name: cntslip_cntslip_id_seq; Type: ACL; Schema: public; Owner: admin
128823 --
128824
128825 REVOKE ALL ON SEQUENCE cntslip_cntslip_id_seq FROM PUBLIC;
128826 REVOKE ALL ON SEQUENCE cntslip_cntslip_id_seq FROM admin;
128827 GRANT ALL ON SEQUENCE cntslip_cntslip_id_seq TO admin;
128828 GRANT ALL ON SEQUENCE cntslip_cntslip_id_seq TO xtrole;
128829
128830
128831 --
128832 -- TOC entry 9677 (class 0 OID 0)
128833 -- Dependencies: 513
128834 -- Name: cobill; Type: ACL; Schema: public; Owner: admin
128835 --
128836
128837 REVOKE ALL ON TABLE cobill FROM PUBLIC;
128838 REVOKE ALL ON TABLE cobill FROM admin;
128839 GRANT ALL ON TABLE cobill TO admin;
128840 GRANT ALL ON TABLE cobill TO xtrole;
128841
128842
128843 --
128844 -- TOC entry 9678 (class 0 OID 0)
128845 -- Dependencies: 514
128846 -- Name: cobill_cobill_id_seq; Type: ACL; Schema: public; Owner: admin
128847 --
128848
128849 REVOKE ALL ON SEQUENCE cobill_cobill_id_seq FROM PUBLIC;
128850 REVOKE ALL ON SEQUENCE cobill_cobill_id_seq FROM admin;
128851 GRANT ALL ON SEQUENCE cobill_cobill_id_seq TO admin;
128852 GRANT ALL ON SEQUENCE cobill_cobill_id_seq TO xtrole;
128853
128854
128855 --
128856 -- TOC entry 9679 (class 0 OID 0)
128857 -- Dependencies: 515
128858 -- Name: cobilltax; Type: ACL; Schema: public; Owner: admin
128859 --
128860
128861 REVOKE ALL ON TABLE cobilltax FROM PUBLIC;
128862 REVOKE ALL ON TABLE cobilltax FROM admin;
128863 GRANT ALL ON TABLE cobilltax TO admin;
128864 GRANT ALL ON TABLE cobilltax TO xtrole;
128865
128866
128867 --
128868 -- TOC entry 9681 (class 0 OID 0)
128869 -- Dependencies: 516
128870 -- Name: cobmisc; Type: ACL; Schema: public; Owner: admin
128871 --
128872
128873 REVOKE ALL ON TABLE cobmisc FROM PUBLIC;
128874 REVOKE ALL ON TABLE cobmisc FROM admin;
128875 GRANT ALL ON TABLE cobmisc TO admin;
128876 GRANT ALL ON TABLE cobmisc TO xtrole;
128877
128878
128879 --
128880 -- TOC entry 9682 (class 0 OID 0)
128881 -- Dependencies: 517
128882 -- Name: cobmisc_cobmisc_id_seq; Type: ACL; Schema: public; Owner: admin
128883 --
128884
128885 REVOKE ALL ON SEQUENCE cobmisc_cobmisc_id_seq FROM PUBLIC;
128886 REVOKE ALL ON SEQUENCE cobmisc_cobmisc_id_seq FROM admin;
128887 GRANT ALL ON SEQUENCE cobmisc_cobmisc_id_seq TO admin;
128888 GRANT ALL ON SEQUENCE cobmisc_cobmisc_id_seq TO xtrole;
128889
128890
128891 --
128892 -- TOC entry 9683 (class 0 OID 0)
128893 -- Dependencies: 518
128894 -- Name: cobmisctax; Type: ACL; Schema: public; Owner: admin
128895 --
128896
128897 REVOKE ALL ON TABLE cobmisctax FROM PUBLIC;
128898 REVOKE ALL ON TABLE cobmisctax FROM admin;
128899 GRANT ALL ON TABLE cobmisctax TO admin;
128900 GRANT ALL ON TABLE cobmisctax TO xtrole;
128901
128902
128903 --
128904 -- TOC entry 9684 (class 0 OID 0)
128905 -- Dependencies: 519
128906 -- Name: cohead_cohead_id_seq; Type: ACL; Schema: public; Owner: admin
128907 --
128908
128909 REVOKE ALL ON SEQUENCE cohead_cohead_id_seq FROM PUBLIC;
128910 REVOKE ALL ON SEQUENCE cohead_cohead_id_seq FROM admin;
128911 GRANT ALL ON SEQUENCE cohead_cohead_id_seq TO admin;
128912 GRANT ALL ON SEQUENCE cohead_cohead_id_seq TO xtrole;
128913
128914
128915 --
128916 -- TOC entry 9685 (class 0 OID 0)
128917 -- Dependencies: 520
128918 -- Name: cohist_cohist_id_seq; Type: ACL; Schema: public; Owner: admin
128919 --
128920
128921 REVOKE ALL ON SEQUENCE cohist_cohist_id_seq FROM PUBLIC;
128922 REVOKE ALL ON SEQUENCE cohist_cohist_id_seq FROM admin;
128923 GRANT ALL ON SEQUENCE cohist_cohist_id_seq TO admin;
128924 GRANT ALL ON SEQUENCE cohist_cohist_id_seq TO xtrole;
128925
128926
128927 --
128928 -- TOC entry 9686 (class 0 OID 0)
128929 -- Dependencies: 521
128930 -- Name: coitem_coitem_id_seq; Type: ACL; Schema: public; Owner: admin
128931 --
128932
128933 REVOKE ALL ON SEQUENCE coitem_coitem_id_seq FROM PUBLIC;
128934 REVOKE ALL ON SEQUENCE coitem_coitem_id_seq FROM admin;
128935 GRANT ALL ON SEQUENCE coitem_coitem_id_seq TO admin;
128936 GRANT ALL ON SEQUENCE coitem_coitem_id_seq TO xtrole;
128937
128938
128939 --
128940 -- TOC entry 9687 (class 0 OID 0)
128941 -- Dependencies: 522
128942 -- Name: comment_comment_id_seq; Type: ACL; Schema: public; Owner: admin
128943 --
128944
128945 REVOKE ALL ON SEQUENCE comment_comment_id_seq FROM PUBLIC;
128946 REVOKE ALL ON SEQUENCE comment_comment_id_seq FROM admin;
128947 GRANT ALL ON SEQUENCE comment_comment_id_seq TO admin;
128948 GRANT ALL ON SEQUENCE comment_comment_id_seq TO xtrole;
128949
128950
128951 --
128952 -- TOC entry 9689 (class 0 OID 0)
128953 -- Dependencies: 523
128954 -- Name: company; Type: ACL; Schema: public; Owner: admin
128955 --
128956
128957 REVOKE ALL ON TABLE company FROM PUBLIC;
128958 REVOKE ALL ON TABLE company FROM admin;
128959 GRANT ALL ON TABLE company TO admin;
128960 GRANT ALL ON TABLE company TO xtrole;
128961
128962
128963 --
128964 -- TOC entry 9691 (class 0 OID 0)
128965 -- Dependencies: 524
128966 -- Name: company_company_id_seq; Type: ACL; Schema: public; Owner: admin
128967 --
128968
128969 REVOKE ALL ON SEQUENCE company_company_id_seq FROM PUBLIC;
128970 REVOKE ALL ON SEQUENCE company_company_id_seq FROM admin;
128971 GRANT ALL ON SEQUENCE company_company_id_seq TO admin;
128972 GRANT ALL ON SEQUENCE company_company_id_seq TO xtrole;
128973
128974
128975 --
128976 -- TOC entry 9693 (class 0 OID 0)
128977 -- Dependencies: 525
128978 -- Name: contrct_contrct_id_seq; Type: ACL; Schema: public; Owner: admin
128979 --
128980
128981 REVOKE ALL ON SEQUENCE contrct_contrct_id_seq FROM PUBLIC;
128982 REVOKE ALL ON SEQUENCE contrct_contrct_id_seq FROM admin;
128983 GRANT ALL ON SEQUENCE contrct_contrct_id_seq TO admin;
128984 GRANT ALL ON SEQUENCE contrct_contrct_id_seq TO xtrole;
128985
128986
128987 --
128988 -- TOC entry 9695 (class 0 OID 0)
128989 -- Dependencies: 526
128990 -- Name: shiphead; Type: ACL; Schema: public; Owner: admin
128991 --
128992
128993 REVOKE ALL ON TABLE shiphead FROM PUBLIC;
128994 REVOKE ALL ON TABLE shiphead FROM admin;
128995 GRANT ALL ON TABLE shiphead TO admin;
128996 GRANT ALL ON TABLE shiphead TO xtrole;
128997
128998
128999 --
129000 -- TOC entry 9697 (class 0 OID 0)
129001 -- Dependencies: 527
129002 -- Name: shipitem; Type: ACL; Schema: public; Owner: admin
129003 --
129004
129005 REVOKE ALL ON TABLE shipitem FROM PUBLIC;
129006 REVOKE ALL ON TABLE shipitem FROM admin;
129007 GRANT ALL ON TABLE shipitem TO admin;
129008 GRANT ALL ON TABLE shipitem TO xtrole;
129009
129010
129011 --
129012 -- TOC entry 9698 (class 0 OID 0)
129013 -- Dependencies: 528
129014 -- Name: coship; Type: ACL; Schema: public; Owner: admin
129015 --
129016
129017 REVOKE ALL ON TABLE coship FROM PUBLIC;
129018 REVOKE ALL ON TABLE coship FROM admin;
129019 GRANT ALL ON TABLE coship TO admin;
129020 GRANT ALL ON TABLE coship TO xtrole;
129021
129022
129023 --
129024 -- TOC entry 9699 (class 0 OID 0)
129025 -- Dependencies: 529
129026 -- Name: coship_coship_id_seq; Type: ACL; Schema: public; Owner: admin
129027 --
129028
129029 REVOKE ALL ON SEQUENCE coship_coship_id_seq FROM PUBLIC;
129030 REVOKE ALL ON SEQUENCE coship_coship_id_seq FROM admin;
129031 GRANT ALL ON SEQUENCE coship_coship_id_seq TO admin;
129032 GRANT ALL ON SEQUENCE coship_coship_id_seq TO xtrole;
129033
129034
129035 --
129036 -- TOC entry 9700 (class 0 OID 0)
129037 -- Dependencies: 530
129038 -- Name: cosmisc; Type: ACL; Schema: public; Owner: admin
129039 --
129040
129041 REVOKE ALL ON TABLE cosmisc FROM PUBLIC;
129042 REVOKE ALL ON TABLE cosmisc FROM admin;
129043 GRANT ALL ON TABLE cosmisc TO admin;
129044 GRANT ALL ON TABLE cosmisc TO xtrole;
129045
129046
129047 --
129048 -- TOC entry 9701 (class 0 OID 0)
129049 -- Dependencies: 531
129050 -- Name: cosmisc_cosmisc_id_seq; Type: ACL; Schema: public; Owner: admin
129051 --
129052
129053 REVOKE ALL ON SEQUENCE cosmisc_cosmisc_id_seq FROM PUBLIC;
129054 REVOKE ALL ON SEQUENCE cosmisc_cosmisc_id_seq FROM admin;
129055 GRANT ALL ON SEQUENCE cosmisc_cosmisc_id_seq TO admin;
129056 GRANT ALL ON SEQUENCE cosmisc_cosmisc_id_seq TO xtrole;
129057
129058
129059 --
129060 -- TOC entry 9702 (class 0 OID 0)
129061 -- Dependencies: 532
129062 -- Name: cosrc_cosrc_id_seq; Type: ACL; Schema: public; Owner: admin
129063 --
129064
129065 REVOKE ALL ON SEQUENCE cosrc_cosrc_id_seq FROM PUBLIC;
129066 REVOKE ALL ON SEQUENCE cosrc_cosrc_id_seq FROM admin;
129067 GRANT ALL ON SEQUENCE cosrc_cosrc_id_seq TO admin;
129068 GRANT ALL ON SEQUENCE cosrc_cosrc_id_seq TO xtrole;
129069
129070
129071 --
129072 -- TOC entry 9703 (class 0 OID 0)
129073 -- Dependencies: 533
129074 -- Name: costcat_costcat_id_seq; Type: ACL; Schema: public; Owner: admin
129075 --
129076
129077 REVOKE ALL ON SEQUENCE costcat_costcat_id_seq FROM PUBLIC;
129078 REVOKE ALL ON SEQUENCE costcat_costcat_id_seq FROM admin;
129079 GRANT ALL ON SEQUENCE costcat_costcat_id_seq TO admin;
129080 GRANT ALL ON SEQUENCE costcat_costcat_id_seq TO xtrole;
129081
129082
129083 --
129084 -- TOC entry 9704 (class 0 OID 0)
129085 -- Dependencies: 534
129086 -- Name: costelem_costelem_id_seq; Type: ACL; Schema: public; Owner: admin
129087 --
129088
129089 REVOKE ALL ON SEQUENCE costelem_costelem_id_seq FROM PUBLIC;
129090 REVOKE ALL ON SEQUENCE costelem_costelem_id_seq FROM admin;
129091 GRANT ALL ON SEQUENCE costelem_costelem_id_seq TO admin;
129092 GRANT ALL ON SEQUENCE costelem_costelem_id_seq TO xtrole;
129093
129094
129095 --
129096 -- TOC entry 9706 (class 0 OID 0)
129097 -- Dependencies: 535
129098 -- Name: costhist; Type: ACL; Schema: public; Owner: admin
129099 --
129100
129101 REVOKE ALL ON TABLE costhist FROM PUBLIC;
129102 REVOKE ALL ON TABLE costhist FROM admin;
129103 GRANT ALL ON TABLE costhist TO admin;
129104 GRANT ALL ON TABLE costhist TO xtrole;
129105
129106
129107 --
129108 -- TOC entry 9707 (class 0 OID 0)
129109 -- Dependencies: 536
129110 -- Name: costhist_costhist_id_seq; Type: ACL; Schema: public; Owner: admin
129111 --
129112
129113 REVOKE ALL ON SEQUENCE costhist_costhist_id_seq FROM PUBLIC;
129114 REVOKE ALL ON SEQUENCE costhist_costhist_id_seq FROM admin;
129115 GRANT ALL ON SEQUENCE costhist_costhist_id_seq TO admin;
129116 GRANT ALL ON SEQUENCE costhist_costhist_id_seq TO xtrole;
129117
129118
129119 --
129120 -- TOC entry 9709 (class 0 OID 0)
129121 -- Dependencies: 537
129122 -- Name: costupdate; Type: ACL; Schema: public; Owner: admin
129123 --
129124
129125 REVOKE ALL ON TABLE costupdate FROM PUBLIC;
129126 REVOKE ALL ON TABLE costupdate FROM admin;
129127 GRANT ALL ON TABLE costupdate TO admin;
129128 GRANT ALL ON TABLE costupdate TO xtrole;
129129
129130
129131 --
129132 -- TOC entry 9711 (class 0 OID 0)
129133 -- Dependencies: 538
129134 -- Name: country; Type: ACL; Schema: public; Owner: admin
129135 --
129136
129137 REVOKE ALL ON TABLE country FROM PUBLIC;
129138 REVOKE ALL ON TABLE country FROM admin;
129139 GRANT ALL ON TABLE country TO admin;
129140 GRANT ALL ON TABLE country TO xtrole;
129141
129142
129143 --
129144 -- TOC entry 9713 (class 0 OID 0)
129145 -- Dependencies: 539
129146 -- Name: country_country_id_seq; Type: ACL; Schema: public; Owner: admin
129147 --
129148
129149 REVOKE ALL ON SEQUENCE country_country_id_seq FROM PUBLIC;
129150 REVOKE ALL ON SEQUENCE country_country_id_seq FROM admin;
129151 GRANT ALL ON SEQUENCE country_country_id_seq TO admin;
129152 GRANT ALL ON SEQUENCE country_country_id_seq TO xtrole;
129153
129154
129155 --
129156 -- TOC entry 9717 (class 0 OID 0)
129157 -- Dependencies: 540
129158 -- Name: salesaccnt; Type: ACL; Schema: public; Owner: admin
129159 --
129160
129161 REVOKE ALL ON TABLE salesaccnt FROM PUBLIC;
129162 REVOKE ALL ON TABLE salesaccnt FROM admin;
129163 GRANT ALL ON TABLE salesaccnt TO admin;
129164 GRANT ALL ON TABLE salesaccnt TO xtrole;
129165
129166
129167 --
129168 -- TOC entry 9718 (class 0 OID 0)
129169 -- Dependencies: 541
129170 -- Name: creditmemoeditlist; Type: ACL; Schema: public; Owner: admin
129171 --
129172
129173 REVOKE ALL ON TABLE creditmemoeditlist FROM PUBLIC;
129174 REVOKE ALL ON TABLE creditmemoeditlist FROM admin;
129175 GRANT ALL ON TABLE creditmemoeditlist TO admin;
129176 GRANT ALL ON TABLE creditmemoeditlist TO xtrole;
129177
129178
129179 --
129180 -- TOC entry 9720 (class 0 OID 0)
129181 -- Dependencies: 542
129182 -- Name: creditmemoitem; Type: ACL; Schema: public; Owner: admin
129183 --
129184
129185 REVOKE ALL ON TABLE creditmemoitem FROM PUBLIC;
129186 REVOKE ALL ON TABLE creditmemoitem FROM admin;
129187 GRANT ALL ON TABLE creditmemoitem TO admin;
129188 GRANT ALL ON TABLE creditmemoitem TO xtrole;
129189
129190
129191 --
129192 -- TOC entry 9722 (class 0 OID 0)
129193 -- Dependencies: 543
129194 -- Name: crmacct_crmacct_id_seq; Type: ACL; Schema: public; Owner: admin
129195 --
129196
129197 REVOKE ALL ON SEQUENCE crmacct_crmacct_id_seq FROM PUBLIC;
129198 REVOKE ALL ON SEQUENCE crmacct_crmacct_id_seq FROM admin;
129199 GRANT ALL ON SEQUENCE crmacct_crmacct_id_seq TO admin;
129200 GRANT ALL ON SEQUENCE crmacct_crmacct_id_seq TO xtrole;
129201
129202
129203 --
129204 -- TOC entry 9726 (class 0 OID 0)
129205 -- Dependencies: 544
129206 -- Name: crmacctsel; Type: ACL; Schema: public; Owner: admin
129207 --
129208
129209 REVOKE ALL ON TABLE crmacctsel FROM PUBLIC;
129210 REVOKE ALL ON TABLE crmacctsel FROM admin;
129211 GRANT ALL ON TABLE crmacctsel TO admin;
129212 GRANT ALL ON TABLE crmacctsel TO xtrole;
129213
129214
129215 --
129216 -- TOC entry 9728 (class 0 OID 0)
129217 -- Dependencies: 545
129218 -- Name: curr_rate; Type: ACL; Schema: public; Owner: admin
129219 --
129220
129221 REVOKE ALL ON TABLE curr_rate FROM PUBLIC;
129222 REVOKE ALL ON TABLE curr_rate FROM admin;
129223 GRANT ALL ON TABLE curr_rate TO admin;
129224 GRANT ALL ON TABLE curr_rate TO xtrole;
129225
129226
129227 --
129228 -- TOC entry 9730 (class 0 OID 0)
129229 -- Dependencies: 546
129230 -- Name: curr_rate_curr_rate_id_seq; Type: ACL; Schema: public; Owner: admin
129231 --
129232
129233 REVOKE ALL ON SEQUENCE curr_rate_curr_rate_id_seq FROM PUBLIC;
129234 REVOKE ALL ON SEQUENCE curr_rate_curr_rate_id_seq FROM admin;
129235 GRANT ALL ON SEQUENCE curr_rate_curr_rate_id_seq TO admin;
129236 GRANT ALL ON SEQUENCE curr_rate_curr_rate_id_seq TO xtrole;
129237
129238
129239 --
129240 -- TOC entry 9732 (class 0 OID 0)
129241 -- Dependencies: 547
129242 -- Name: curr_symbol_curr_id_seq; Type: ACL; Schema: public; Owner: admin
129243 --
129244
129245 REVOKE ALL ON SEQUENCE curr_symbol_curr_id_seq FROM PUBLIC;
129246 REVOKE ALL ON SEQUENCE curr_symbol_curr_id_seq FROM admin;
129247 GRANT ALL ON SEQUENCE curr_symbol_curr_id_seq TO admin;
129248 GRANT ALL ON SEQUENCE curr_symbol_curr_id_seq TO xtrole;
129249
129250
129251 --
129252 -- TOC entry 9733 (class 0 OID 0)
129253 -- Dependencies: 548
129254 -- Name: cust; Type: ACL; Schema: public; Owner: admin
129255 --
129256
129257 REVOKE ALL ON TABLE cust FROM PUBLIC;
129258 REVOKE ALL ON TABLE cust FROM admin;
129259 GRANT ALL ON TABLE cust TO admin;
129260 GRANT ALL ON TABLE cust TO xtrole;
129261
129262
129263 --
129264 -- TOC entry 9734 (class 0 OID 0)
129265 -- Dependencies: 549
129266 -- Name: cust_serial_seq; Type: ACL; Schema: public; Owner: admin
129267 --
129268
129269 REVOKE ALL ON SEQUENCE cust_serial_seq FROM PUBLIC;
129270 REVOKE ALL ON SEQUENCE cust_serial_seq FROM admin;
129271 GRANT ALL ON SEQUENCE cust_serial_seq TO admin;
129272 GRANT ALL ON SEQUENCE cust_serial_seq TO xtrole;
129273
129274
129275 --
129276 -- TOC entry 9742 (class 0 OID 0)
129277 -- Dependencies: 550
129278 -- Name: custform; Type: ACL; Schema: public; Owner: admin
129279 --
129280
129281 REVOKE ALL ON TABLE custform FROM PUBLIC;
129282 REVOKE ALL ON TABLE custform FROM admin;
129283 GRANT ALL ON TABLE custform TO admin;
129284 GRANT ALL ON TABLE custform TO xtrole;
129285
129286
129287 --
129288 -- TOC entry 9743 (class 0 OID 0)
129289 -- Dependencies: 551
129290 -- Name: custform_custform_id_seq; Type: ACL; Schema: public; Owner: admin
129291 --
129292
129293 REVOKE ALL ON SEQUENCE custform_custform_id_seq FROM PUBLIC;
129294 REVOKE ALL ON SEQUENCE custform_custform_id_seq FROM admin;
129295 GRANT ALL ON SEQUENCE custform_custform_id_seq TO admin;
129296 GRANT ALL ON SEQUENCE custform_custform_id_seq TO xtrole;
129297
129298
129299 --
129300 -- TOC entry 9745 (class 0 OID 0)
129301 -- Dependencies: 552
129302 -- Name: custgrp; Type: ACL; Schema: public; Owner: admin
129303 --
129304
129305 REVOKE ALL ON TABLE custgrp FROM PUBLIC;
129306 REVOKE ALL ON TABLE custgrp FROM admin;
129307 GRANT ALL ON TABLE custgrp TO admin;
129308 GRANT ALL ON TABLE custgrp TO xtrole;
129309
129310
129311 --
129312 -- TOC entry 9746 (class 0 OID 0)
129313 -- Dependencies: 553
129314 -- Name: custgrp_custgrp_id_seq; Type: ACL; Schema: public; Owner: admin
129315 --
129316
129317 REVOKE ALL ON SEQUENCE custgrp_custgrp_id_seq FROM PUBLIC;
129318 REVOKE ALL ON SEQUENCE custgrp_custgrp_id_seq FROM admin;
129319 GRANT ALL ON SEQUENCE custgrp_custgrp_id_seq TO admin;
129320 GRANT ALL ON SEQUENCE custgrp_custgrp_id_seq TO xtrole;
129321
129322
129323 --
129324 -- TOC entry 9748 (class 0 OID 0)
129325 -- Dependencies: 554
129326 -- Name: custgrpitem; Type: ACL; Schema: public; Owner: admin
129327 --
129328
129329 REVOKE ALL ON TABLE custgrpitem FROM PUBLIC;
129330 REVOKE ALL ON TABLE custgrpitem FROM admin;
129331 GRANT ALL ON TABLE custgrpitem TO admin;
129332 GRANT ALL ON TABLE custgrpitem TO xtrole;
129333
129334
129335 --
129336 -- TOC entry 9749 (class 0 OID 0)
129337 -- Dependencies: 555
129338 -- Name: custgrpitem_custgrpitem_id_seq; Type: ACL; Schema: public; Owner: admin
129339 --
129340
129341 REVOKE ALL ON SEQUENCE custgrpitem_custgrpitem_id_seq FROM PUBLIC;
129342 REVOKE ALL ON SEQUENCE custgrpitem_custgrpitem_id_seq FROM admin;
129343 GRANT ALL ON SEQUENCE custgrpitem_custgrpitem_id_seq TO admin;
129344 GRANT ALL ON SEQUENCE custgrpitem_custgrpitem_id_seq TO xtrole;
129345
129346
129347 --
129348 -- TOC entry 9750 (class 0 OID 0)
129349 -- Dependencies: 556
129350 -- Name: custtype_custtype_id_seq; Type: ACL; Schema: public; Owner: admin
129351 --
129352
129353 REVOKE ALL ON SEQUENCE custtype_custtype_id_seq FROM PUBLIC;
129354 REVOKE ALL ON SEQUENCE custtype_custtype_id_seq FROM admin;
129355 GRANT ALL ON SEQUENCE custtype_custtype_id_seq TO admin;
129356 GRANT ALL ON SEQUENCE custtype_custtype_id_seq TO xtrole;
129357
129358
129359 --
129360 -- TOC entry 9752 (class 0 OID 0)
129361 -- Dependencies: 557
129362 -- Name: dept_dept_id_seq; Type: ACL; Schema: public; Owner: admin
129363 --
129364
129365 REVOKE ALL ON SEQUENCE dept_dept_id_seq FROM PUBLIC;
129366 REVOKE ALL ON SEQUENCE dept_dept_id_seq FROM admin;
129367 GRANT ALL ON SEQUENCE dept_dept_id_seq TO admin;
129368 GRANT ALL ON SEQUENCE dept_dept_id_seq TO xtrole;
129369
129370
129371 --
129372 -- TOC entry 9754 (class 0 OID 0)
129373 -- Dependencies: 558
129374 -- Name: destination; Type: ACL; Schema: public; Owner: admin
129375 --
129376
129377 REVOKE ALL ON TABLE destination FROM PUBLIC;
129378 REVOKE ALL ON TABLE destination FROM admin;
129379 GRANT ALL ON TABLE destination TO admin;
129380 GRANT ALL ON TABLE destination TO xtrole;
129381
129382
129383 --
129384 -- TOC entry 9755 (class 0 OID 0)
129385 -- Dependencies: 559
129386 -- Name: destination_destination_id_seq; Type: ACL; Schema: public; Owner: admin
129387 --
129388
129389 REVOKE ALL ON SEQUENCE destination_destination_id_seq FROM PUBLIC;
129390 REVOKE ALL ON SEQUENCE destination_destination_id_seq FROM admin;
129391 GRANT ALL ON SEQUENCE destination_destination_id_seq TO admin;
129392 GRANT ALL ON SEQUENCE destination_destination_id_seq TO xtrole;
129393
129394
129395 --
129396 -- TOC entry 9757 (class 0 OID 0)
129397 -- Dependencies: 560
129398 -- Name: wo; Type: ACL; Schema: public; Owner: admin
129399 --
129400
129401 REVOKE ALL ON TABLE wo FROM PUBLIC;
129402 REVOKE ALL ON TABLE wo FROM admin;
129403 GRANT ALL ON TABLE wo TO admin;
129404 GRANT ALL ON TABLE wo TO xtrole;
129405
129406
129407 --
129408 -- TOC entry 9758 (class 0 OID 0)
129409 -- Dependencies: 561
129410 -- Name: docinfo; Type: ACL; Schema: public; Owner: admin
129411 --
129412
129413 REVOKE ALL ON TABLE docinfo FROM PUBLIC;
129414 REVOKE ALL ON TABLE docinfo FROM admin;
129415 GRANT ALL ON TABLE docinfo TO admin;
129416 GRANT ALL ON TABLE docinfo TO xtrole;
129417
129418
129419 --
129420 -- TOC entry 9760 (class 0 OID 0)
129421 -- Dependencies: 562
129422 -- Name: emp_emp_id_seq; Type: ACL; Schema: public; Owner: admin
129423 --
129424
129425 REVOKE ALL ON SEQUENCE emp_emp_id_seq FROM PUBLIC;
129426 REVOKE ALL ON SEQUENCE emp_emp_id_seq FROM admin;
129427 GRANT ALL ON SEQUENCE emp_emp_id_seq TO admin;
129428 GRANT ALL ON SEQUENCE emp_emp_id_seq TO xtrole;
129429
129430
129431 --
129432 -- TOC entry 9761 (class 0 OID 0)
129433 -- Dependencies: 563
129434 -- Name: empgrp; Type: ACL; Schema: public; Owner: admin
129435 --
129436
129437 REVOKE ALL ON TABLE empgrp FROM PUBLIC;
129438 REVOKE ALL ON TABLE empgrp FROM admin;
129439 GRANT ALL ON TABLE empgrp TO admin;
129440 GRANT ALL ON TABLE empgrp TO xtrole;
129441
129442
129443 --
129444 -- TOC entry 9763 (class 0 OID 0)
129445 -- Dependencies: 564
129446 -- Name: empgrp_empgrp_id_seq; Type: ACL; Schema: public; Owner: admin
129447 --
129448
129449 REVOKE ALL ON SEQUENCE empgrp_empgrp_id_seq FROM PUBLIC;
129450 REVOKE ALL ON SEQUENCE empgrp_empgrp_id_seq FROM admin;
129451 GRANT ALL ON SEQUENCE empgrp_empgrp_id_seq TO admin;
129452 GRANT ALL ON SEQUENCE empgrp_empgrp_id_seq TO xtrole;
129453
129454
129455 --
129456 -- TOC entry 9764 (class 0 OID 0)
129457 -- Dependencies: 565
129458 -- Name: empgrpitem; Type: ACL; Schema: public; Owner: admin
129459 --
129460
129461 REVOKE ALL ON TABLE empgrpitem FROM PUBLIC;
129462 REVOKE ALL ON TABLE empgrpitem FROM admin;
129463 GRANT ALL ON TABLE empgrpitem TO admin;
129464 GRANT ALL ON TABLE empgrpitem TO xtrole;
129465
129466
129467 --
129468 -- TOC entry 9766 (class 0 OID 0)
129469 -- Dependencies: 566
129470 -- Name: empgrpitem_empgrpitem_id_seq; Type: ACL; Schema: public; Owner: admin
129471 --
129472
129473 REVOKE ALL ON SEQUENCE empgrpitem_empgrpitem_id_seq FROM PUBLIC;
129474 REVOKE ALL ON SEQUENCE empgrpitem_empgrpitem_id_seq FROM admin;
129475 GRANT ALL ON SEQUENCE empgrpitem_empgrpitem_id_seq TO admin;
129476 GRANT ALL ON SEQUENCE empgrpitem_empgrpitem_id_seq TO xtrole;
129477
129478
129479 --
129480 -- TOC entry 9768 (class 0 OID 0)
129481 -- Dependencies: 567
129482 -- Name: evntlog; Type: ACL; Schema: public; Owner: admin
129483 --
129484
129485 REVOKE ALL ON TABLE evntlog FROM PUBLIC;
129486 REVOKE ALL ON TABLE evntlog FROM admin;
129487 GRANT ALL ON TABLE evntlog TO admin;
129488 GRANT ALL ON TABLE evntlog TO xtrole;
129489
129490
129491 --
129492 -- TOC entry 9769 (class 0 OID 0)
129493 -- Dependencies: 568
129494 -- Name: evntlog_evntlog_id_seq; Type: ACL; Schema: public; Owner: admin
129495 --
129496
129497 REVOKE ALL ON SEQUENCE evntlog_evntlog_id_seq FROM PUBLIC;
129498 REVOKE ALL ON SEQUENCE evntlog_evntlog_id_seq FROM admin;
129499 GRANT ALL ON SEQUENCE evntlog_evntlog_id_seq TO admin;
129500 GRANT ALL ON SEQUENCE evntlog_evntlog_id_seq TO xtrole;
129501
129502
129503 --
129504 -- TOC entry 9771 (class 0 OID 0)
129505 -- Dependencies: 569
129506 -- Name: evntnot; Type: ACL; Schema: public; Owner: admin
129507 --
129508
129509 REVOKE ALL ON TABLE evntnot FROM PUBLIC;
129510 REVOKE ALL ON TABLE evntnot FROM admin;
129511 GRANT ALL ON TABLE evntnot TO admin;
129512 GRANT ALL ON TABLE evntnot TO xtrole;
129513
129514
129515 --
129516 -- TOC entry 9772 (class 0 OID 0)
129517 -- Dependencies: 570
129518 -- Name: evntnot_evntnot_id_seq; Type: ACL; Schema: public; Owner: admin
129519 --
129520
129521 REVOKE ALL ON SEQUENCE evntnot_evntnot_id_seq FROM PUBLIC;
129522 REVOKE ALL ON SEQUENCE evntnot_evntnot_id_seq FROM admin;
129523 GRANT ALL ON SEQUENCE evntnot_evntnot_id_seq TO admin;
129524 GRANT ALL ON SEQUENCE evntnot_evntnot_id_seq TO xtrole;
129525
129526
129527 --
129528 -- TOC entry 9774 (class 0 OID 0)
129529 -- Dependencies: 571
129530 -- Name: evnttype; Type: ACL; Schema: public; Owner: admin
129531 --
129532
129533 REVOKE ALL ON TABLE evnttype FROM PUBLIC;
129534 REVOKE ALL ON TABLE evnttype FROM admin;
129535 GRANT ALL ON TABLE evnttype TO admin;
129536 GRANT ALL ON TABLE evnttype TO xtrole;
129537
129538
129539 --
129540 -- TOC entry 9775 (class 0 OID 0)
129541 -- Dependencies: 572
129542 -- Name: evnttype_evnttype_id_seq; Type: ACL; Schema: public; Owner: admin
129543 --
129544
129545 REVOKE ALL ON SEQUENCE evnttype_evnttype_id_seq FROM PUBLIC;
129546 REVOKE ALL ON SEQUENCE evnttype_evnttype_id_seq FROM admin;
129547 GRANT ALL ON SEQUENCE evnttype_evnttype_id_seq TO admin;
129548 GRANT ALL ON SEQUENCE evnttype_evnttype_id_seq TO xtrole;
129549
129550
129551 --
129552 -- TOC entry 9777 (class 0 OID 0)
129553 -- Dependencies: 573
129554 -- Name: expcat_expcat_id_seq; Type: ACL; Schema: public; Owner: admin
129555 --
129556
129557 REVOKE ALL ON SEQUENCE expcat_expcat_id_seq FROM PUBLIC;
129558 REVOKE ALL ON SEQUENCE expcat_expcat_id_seq FROM admin;
129559 GRANT ALL ON SEQUENCE expcat_expcat_id_seq TO admin;
129560 GRANT ALL ON SEQUENCE expcat_expcat_id_seq TO xtrole;
129561
129562
129563 --
129564 -- TOC entry 9779 (class 0 OID 0)
129565 -- Dependencies: 574
129566 -- Name: file_file_id_seq; Type: ACL; Schema: public; Owner: admin
129567 --
129568
129569 REVOKE ALL ON SEQUENCE file_file_id_seq FROM PUBLIC;
129570 REVOKE ALL ON SEQUENCE file_file_id_seq FROM admin;
129571 GRANT ALL ON SEQUENCE file_file_id_seq TO admin;
129572 GRANT ALL ON SEQUENCE file_file_id_seq TO xtrole;
129573
129574
129575 --
129576 -- TOC entry 9780 (class 0 OID 0)
129577 -- Dependencies: 575
129578 -- Name: filter; Type: ACL; Schema: public; Owner: admin
129579 --
129580
129581 REVOKE ALL ON TABLE filter FROM PUBLIC;
129582 REVOKE ALL ON TABLE filter FROM admin;
129583 GRANT ALL ON TABLE filter TO admin;
129584 GRANT ALL ON TABLE filter TO xtrole;
129585
129586
129587 --
129588 -- TOC entry 9782 (class 0 OID 0)
129589 -- Dependencies: 576
129590 -- Name: filter_filter_id_seq; Type: ACL; Schema: public; Owner: admin
129591 --
129592
129593 REVOKE ALL ON SEQUENCE filter_filter_id_seq FROM PUBLIC;
129594 REVOKE ALL ON SEQUENCE filter_filter_id_seq FROM admin;
129595 GRANT ALL ON SEQUENCE filter_filter_id_seq TO admin;
129596 GRANT ALL ON SEQUENCE filter_filter_id_seq TO xtrole;
129597
129598
129599 --
129600 -- TOC entry 9784 (class 0 OID 0)
129601 -- Dependencies: 577
129602 -- Name: fincharg; Type: ACL; Schema: public; Owner: admin
129603 --
129604
129605 REVOKE ALL ON TABLE fincharg FROM PUBLIC;
129606 REVOKE ALL ON TABLE fincharg FROM admin;
129607 GRANT ALL ON TABLE fincharg TO admin;
129608 GRANT ALL ON TABLE fincharg TO xtrole;
129609
129610
129611 --
129612 -- TOC entry 9786 (class 0 OID 0)
129613 -- Dependencies: 578
129614 -- Name: fincharg_fincharg_id_seq; Type: ACL; Schema: public; Owner: admin
129615 --
129616
129617 REVOKE ALL ON SEQUENCE fincharg_fincharg_id_seq FROM PUBLIC;
129618 REVOKE ALL ON SEQUENCE fincharg_fincharg_id_seq FROM admin;
129619 GRANT ALL ON SEQUENCE fincharg_fincharg_id_seq TO admin;
129620 GRANT ALL ON SEQUENCE fincharg_fincharg_id_seq TO xtrole;
129621
129622
129623 --
129624 -- TOC entry 9788 (class 0 OID 0)
129625 -- Dependencies: 579
129626 -- Name: flhead; Type: ACL; Schema: public; Owner: admin
129627 --
129628
129629 REVOKE ALL ON TABLE flhead FROM PUBLIC;
129630 REVOKE ALL ON TABLE flhead FROM admin;
129631 GRANT ALL ON TABLE flhead TO admin;
129632 GRANT ALL ON TABLE flhead TO xtrole;
129633
129634
129635 --
129636 -- TOC entry 9790 (class 0 OID 0)
129637 -- Dependencies: 580
129638 -- Name: flitem; Type: ACL; Schema: public; Owner: admin
129639 --
129640
129641 REVOKE ALL ON TABLE flitem FROM PUBLIC;
129642 REVOKE ALL ON TABLE flitem FROM admin;
129643 GRANT ALL ON TABLE flitem TO admin;
129644 GRANT ALL ON TABLE flitem TO xtrole;
129645
129646
129647 --
129648 -- TOC entry 9791 (class 0 OID 0)
129649 -- Dependencies: 581
129650 -- Name: flaccnt; Type: ACL; Schema: public; Owner: admin
129651 --
129652
129653 REVOKE ALL ON TABLE flaccnt FROM PUBLIC;
129654 REVOKE ALL ON TABLE flaccnt FROM admin;
129655 GRANT ALL ON TABLE flaccnt TO admin;
129656 GRANT ALL ON TABLE flaccnt TO xtrole;
129657
129658
129659 --
129660 -- TOC entry 9792 (class 0 OID 0)
129661 -- Dependencies: 582
129662 -- Name: flcol; Type: ACL; Schema: public; Owner: admin
129663 --
129664
129665 REVOKE ALL ON TABLE flcol FROM PUBLIC;
129666 REVOKE ALL ON TABLE flcol FROM admin;
129667 GRANT ALL ON TABLE flcol TO admin;
129668 GRANT ALL ON TABLE flcol TO xtrole;
129669
129670
129671 --
129672 -- TOC entry 9794 (class 0 OID 0)
129673 -- Dependencies: 583
129674 -- Name: flcol_flcol_id_seq; Type: ACL; Schema: public; Owner: admin
129675 --
129676
129677 REVOKE ALL ON SEQUENCE flcol_flcol_id_seq FROM PUBLIC;
129678 REVOKE ALL ON SEQUENCE flcol_flcol_id_seq FROM admin;
129679 GRANT ALL ON SEQUENCE flcol_flcol_id_seq TO admin;
129680 GRANT ALL ON SEQUENCE flcol_flcol_id_seq TO xtrole;
129681
129682
129683 --
129684 -- TOC entry 9796 (class 0 OID 0)
129685 -- Dependencies: 584
129686 -- Name: flgrp; Type: ACL; Schema: public; Owner: admin
129687 --
129688
129689 REVOKE ALL ON TABLE flgrp FROM PUBLIC;
129690 REVOKE ALL ON TABLE flgrp FROM admin;
129691 GRANT ALL ON TABLE flgrp TO admin;
129692 GRANT ALL ON TABLE flgrp TO xtrole;
129693
129694
129695 --
129696 -- TOC entry 9798 (class 0 OID 0)
129697 -- Dependencies: 585
129698 -- Name: flgrp_flgrp_id_seq; Type: ACL; Schema: public; Owner: admin
129699 --
129700
129701 REVOKE ALL ON SEQUENCE flgrp_flgrp_id_seq FROM PUBLIC;
129702 REVOKE ALL ON SEQUENCE flgrp_flgrp_id_seq FROM admin;
129703 GRANT ALL ON SEQUENCE flgrp_flgrp_id_seq TO admin;
129704 GRANT ALL ON SEQUENCE flgrp_flgrp_id_seq TO xtrole;
129705
129706
129707 --
129708 -- TOC entry 9800 (class 0 OID 0)
129709 -- Dependencies: 586
129710 -- Name: flhead_flhead_id_seq; Type: ACL; Schema: public; Owner: admin
129711 --
129712
129713 REVOKE ALL ON SEQUENCE flhead_flhead_id_seq FROM PUBLIC;
129714 REVOKE ALL ON SEQUENCE flhead_flhead_id_seq FROM admin;
129715 GRANT ALL ON SEQUENCE flhead_flhead_id_seq TO admin;
129716 GRANT ALL ON SEQUENCE flhead_flhead_id_seq TO xtrole;
129717
129718
129719 --
129720 -- TOC entry 9802 (class 0 OID 0)
129721 -- Dependencies: 587
129722 -- Name: flitem_flitem_id_seq; Type: ACL; Schema: public; Owner: admin
129723 --
129724
129725 REVOKE ALL ON SEQUENCE flitem_flitem_id_seq FROM PUBLIC;
129726 REVOKE ALL ON SEQUENCE flitem_flitem_id_seq FROM admin;
129727 GRANT ALL ON SEQUENCE flitem_flitem_id_seq TO admin;
129728 GRANT ALL ON SEQUENCE flitem_flitem_id_seq TO xtrole;
129729
129730
129731 --
129732 -- TOC entry 9803 (class 0 OID 0)
129733 -- Dependencies: 588
129734 -- Name: flnotes; Type: ACL; Schema: public; Owner: admin
129735 --
129736
129737 REVOKE ALL ON TABLE flnotes FROM PUBLIC;
129738 REVOKE ALL ON TABLE flnotes FROM admin;
129739 GRANT ALL ON TABLE flnotes TO admin;
129740 GRANT ALL ON TABLE flnotes TO xtrole;
129741
129742
129743 --
129744 -- TOC entry 9805 (class 0 OID 0)
129745 -- Dependencies: 589
129746 -- Name: flnotes_flnotes_id_seq; Type: ACL; Schema: public; Owner: admin
129747 --
129748
129749 REVOKE ALL ON SEQUENCE flnotes_flnotes_id_seq FROM PUBLIC;
129750 REVOKE ALL ON SEQUENCE flnotes_flnotes_id_seq FROM admin;
129751 GRANT ALL ON SEQUENCE flnotes_flnotes_id_seq TO admin;
129752 GRANT ALL ON SEQUENCE flnotes_flnotes_id_seq TO xtrole;
129753
129754
129755 --
129756 -- TOC entry 9807 (class 0 OID 0)
129757 -- Dependencies: 590
129758 -- Name: flrpt; Type: ACL; Schema: public; Owner: admin
129759 --
129760
129761 REVOKE ALL ON TABLE flrpt FROM PUBLIC;
129762 REVOKE ALL ON TABLE flrpt FROM admin;
129763 GRANT ALL ON TABLE flrpt TO admin;
129764 GRANT ALL ON TABLE flrpt TO xtrole;
129765
129766
129767 --
129768 -- TOC entry 9809 (class 0 OID 0)
129769 -- Dependencies: 591
129770 -- Name: flrpt_flrpt_id_seq; Type: ACL; Schema: public; Owner: admin
129771 --
129772
129773 REVOKE ALL ON SEQUENCE flrpt_flrpt_id_seq FROM PUBLIC;
129774 REVOKE ALL ON SEQUENCE flrpt_flrpt_id_seq FROM admin;
129775 GRANT ALL ON SEQUENCE flrpt_flrpt_id_seq TO admin;
129776 GRANT ALL ON SEQUENCE flrpt_flrpt_id_seq TO xtrole;
129777
129778
129779 --
129780 -- TOC entry 9811 (class 0 OID 0)
129781 -- Dependencies: 592
129782 -- Name: flspec; Type: ACL; Schema: public; Owner: admin
129783 --
129784
129785 REVOKE ALL ON TABLE flspec FROM PUBLIC;
129786 REVOKE ALL ON TABLE flspec FROM admin;
129787 GRANT ALL ON TABLE flspec TO admin;
129788 GRANT ALL ON TABLE flspec TO xtrole;
129789
129790
129791 --
129792 -- TOC entry 9813 (class 0 OID 0)
129793 -- Dependencies: 593
129794 -- Name: flspec_flspec_id_seq; Type: ACL; Schema: public; Owner: admin
129795 --
129796
129797 REVOKE ALL ON SEQUENCE flspec_flspec_id_seq FROM PUBLIC;
129798 REVOKE ALL ON SEQUENCE flspec_flspec_id_seq FROM admin;
129799 GRANT ALL ON SEQUENCE flspec_flspec_id_seq TO admin;
129800 GRANT ALL ON SEQUENCE flspec_flspec_id_seq TO xtrole;
129801
129802
129803 --
129804 -- TOC entry 9816 (class 0 OID 0)
129805 -- Dependencies: 594
129806 -- Name: form; Type: ACL; Schema: public; Owner: admin
129807 --
129808
129809 REVOKE ALL ON TABLE form FROM PUBLIC;
129810 REVOKE ALL ON TABLE form FROM admin;
129811 GRANT ALL ON TABLE form TO admin;
129812 GRANT ALL ON TABLE form TO xtrole;
129813
129814
129815 --
129816 -- TOC entry 9817 (class 0 OID 0)
129817 -- Dependencies: 595
129818 -- Name: form_form_id_seq; Type: ACL; Schema: public; Owner: admin
129819 --
129820
129821 REVOKE ALL ON SEQUENCE form_form_id_seq FROM PUBLIC;
129822 REVOKE ALL ON SEQUENCE form_form_id_seq FROM admin;
129823 GRANT ALL ON SEQUENCE form_form_id_seq TO admin;
129824 GRANT ALL ON SEQUENCE form_form_id_seq TO xtrole;
129825
129826
129827 --
129828 -- TOC entry 9819 (class 0 OID 0)
129829 -- Dependencies: 596
129830 -- Name: freightclass_freightclass_id_seq; Type: ACL; Schema: public; Owner: admin
129831 --
129832
129833 REVOKE ALL ON SEQUENCE freightclass_freightclass_id_seq FROM PUBLIC;
129834 REVOKE ALL ON SEQUENCE freightclass_freightclass_id_seq FROM admin;
129835 GRANT ALL ON SEQUENCE freightclass_freightclass_id_seq TO admin;
129836 GRANT ALL ON SEQUENCE freightclass_freightclass_id_seq TO xtrole;
129837
129838
129839 --
129840 -- TOC entry 9821 (class 0 OID 0)
129841 -- Dependencies: 597
129842 -- Name: glseries; Type: ACL; Schema: public; Owner: admin
129843 --
129844
129845 REVOKE ALL ON TABLE glseries FROM PUBLIC;
129846 REVOKE ALL ON TABLE glseries FROM admin;
129847 GRANT ALL ON TABLE glseries TO admin;
129848 GRANT ALL ON TABLE glseries TO xtrole;
129849
129850
129851 --
129852 -- TOC entry 9822 (class 0 OID 0)
129853 -- Dependencies: 598
129854 -- Name: glseries_glseries_id_seq; Type: ACL; Schema: public; Owner: admin
129855 --
129856
129857 REVOKE ALL ON SEQUENCE glseries_glseries_id_seq FROM PUBLIC;
129858 REVOKE ALL ON SEQUENCE glseries_glseries_id_seq FROM admin;
129859 GRANT ALL ON SEQUENCE glseries_glseries_id_seq TO admin;
129860 GRANT ALL ON SEQUENCE glseries_glseries_id_seq TO xtrole;
129861
129862
129863 --
129864 -- TOC entry 9823 (class 0 OID 0)
129865 -- Dependencies: 599
129866 -- Name: gltrans_gltrans_id_seq; Type: ACL; Schema: public; Owner: admin
129867 --
129868
129869 REVOKE ALL ON SEQUENCE gltrans_gltrans_id_seq FROM PUBLIC;
129870 REVOKE ALL ON SEQUENCE gltrans_gltrans_id_seq FROM admin;
129871 GRANT ALL ON SEQUENCE gltrans_gltrans_id_seq TO admin;
129872 GRANT ALL ON SEQUENCE gltrans_gltrans_id_seq TO xtrole;
129873
129874
129875 --
129876 -- TOC entry 9824 (class 0 OID 0)
129877 -- Dependencies: 600
129878 -- Name: gltrans_sequence_seq; Type: ACL; Schema: public; Owner: admin
129879 --
129880
129881 REVOKE ALL ON SEQUENCE gltrans_sequence_seq FROM PUBLIC;
129882 REVOKE ALL ON SEQUENCE gltrans_sequence_seq FROM admin;
129883 GRANT ALL ON SEQUENCE gltrans_sequence_seq TO admin;
129884 GRANT ALL ON SEQUENCE gltrans_sequence_seq TO xtrole;
129885
129886
129887 --
129888 -- TOC entry 9826 (class 0 OID 0)
129889 -- Dependencies: 601
129890 -- Name: grp; Type: ACL; Schema: public; Owner: admin
129891 --
129892
129893 REVOKE ALL ON TABLE grp FROM PUBLIC;
129894 REVOKE ALL ON TABLE grp FROM admin;
129895 GRANT ALL ON TABLE grp TO admin;
129896 GRANT ALL ON TABLE grp TO xtrole;
129897
129898
129899 --
129900 -- TOC entry 9828 (class 0 OID 0)
129901 -- Dependencies: 602
129902 -- Name: grp_grp_id_seq; Type: ACL; Schema: public; Owner: admin
129903 --
129904
129905 REVOKE ALL ON SEQUENCE grp_grp_id_seq FROM PUBLIC;
129906 REVOKE ALL ON SEQUENCE grp_grp_id_seq FROM admin;
129907 GRANT ALL ON SEQUENCE grp_grp_id_seq TO admin;
129908 GRANT ALL ON SEQUENCE grp_grp_id_seq TO xtrole;
129909
129910
129911 --
129912 -- TOC entry 9830 (class 0 OID 0)
129913 -- Dependencies: 603
129914 -- Name: grppriv; Type: ACL; Schema: public; Owner: admin
129915 --
129916
129917 REVOKE ALL ON TABLE grppriv FROM PUBLIC;
129918 REVOKE ALL ON TABLE grppriv FROM admin;
129919 GRANT ALL ON TABLE grppriv TO admin;
129920 GRANT ALL ON TABLE grppriv TO xtrole;
129921
129922
129923 --
129924 -- TOC entry 9832 (class 0 OID 0)
129925 -- Dependencies: 604
129926 -- Name: grppriv_grppriv_id_seq; Type: ACL; Schema: public; Owner: admin
129927 --
129928
129929 REVOKE ALL ON SEQUENCE grppriv_grppriv_id_seq FROM PUBLIC;
129930 REVOKE ALL ON SEQUENCE grppriv_grppriv_id_seq FROM admin;
129931 GRANT ALL ON SEQUENCE grppriv_grppriv_id_seq TO admin;
129932 GRANT ALL ON SEQUENCE grppriv_grppriv_id_seq TO xtrole;
129933
129934
129935 --
129936 -- TOC entry 9834 (class 0 OID 0)
129937 -- Dependencies: 605
129938 -- Name: hnfc; Type: ACL; Schema: public; Owner: admin
129939 --
129940
129941 REVOKE ALL ON TABLE hnfc FROM PUBLIC;
129942 REVOKE ALL ON TABLE hnfc FROM admin;
129943 GRANT ALL ON TABLE hnfc TO admin;
129944 GRANT ALL ON TABLE hnfc TO xtrole;
129945
129946
129947 --
129948 -- TOC entry 9836 (class 0 OID 0)
129949 -- Dependencies: 606
129950 -- Name: hnfc_hnfc_id_seq; Type: ACL; Schema: public; Owner: admin
129951 --
129952
129953 REVOKE ALL ON SEQUENCE hnfc_hnfc_id_seq FROM PUBLIC;
129954 REVOKE ALL ON SEQUENCE hnfc_hnfc_id_seq FROM admin;
129955 GRANT ALL ON SEQUENCE hnfc_hnfc_id_seq TO admin;
129956 GRANT ALL ON SEQUENCE hnfc_hnfc_id_seq TO xtrole;
129957
129958
129959 --
129960 -- TOC entry 9838 (class 0 OID 0)
129961 -- Dependencies: 607
129962 -- Name: incdt_incdt_id_seq; Type: ACL; Schema: public; Owner: admin
129963 --
129964
129965 REVOKE ALL ON SEQUENCE incdt_incdt_id_seq FROM PUBLIC;
129966 REVOKE ALL ON SEQUENCE incdt_incdt_id_seq FROM admin;
129967 GRANT ALL ON SEQUENCE incdt_incdt_id_seq TO admin;
129968 GRANT ALL ON SEQUENCE incdt_incdt_id_seq TO xtrole;
129969
129970
129971 --
129972 -- TOC entry 9840 (class 0 OID 0)
129973 -- Dependencies: 608
129974 -- Name: incdtcat_incdtcat_id_seq; Type: ACL; Schema: public; Owner: admin
129975 --
129976
129977 REVOKE ALL ON SEQUENCE incdtcat_incdtcat_id_seq FROM PUBLIC;
129978 REVOKE ALL ON SEQUENCE incdtcat_incdtcat_id_seq FROM admin;
129979 GRANT ALL ON SEQUENCE incdtcat_incdtcat_id_seq TO admin;
129980 GRANT ALL ON SEQUENCE incdtcat_incdtcat_id_seq TO xtrole;
129981
129982
129983 --
129984 -- TOC entry 9842 (class 0 OID 0)
129985 -- Dependencies: 609
129986 -- Name: incdthist; Type: ACL; Schema: public; Owner: admin
129987 --
129988
129989 REVOKE ALL ON TABLE incdthist FROM PUBLIC;
129990 REVOKE ALL ON TABLE incdthist FROM admin;
129991 GRANT ALL ON TABLE incdthist TO admin;
129992 GRANT ALL ON TABLE incdthist TO xtrole;
129993
129994
129995 --
129996 -- TOC entry 9844 (class 0 OID 0)
129997 -- Dependencies: 610
129998 -- Name: incdthist_incdthist_id_seq; Type: ACL; Schema: public; Owner: admin
129999 --
130000
130001 REVOKE ALL ON SEQUENCE incdthist_incdthist_id_seq FROM PUBLIC;
130002 REVOKE ALL ON SEQUENCE incdthist_incdthist_id_seq FROM admin;
130003 GRANT ALL ON SEQUENCE incdthist_incdthist_id_seq TO admin;
130004 GRANT ALL ON SEQUENCE incdthist_incdthist_id_seq TO xtrole;
130005
130006
130007 --
130008 -- TOC entry 9846 (class 0 OID 0)
130009 -- Dependencies: 611
130010 -- Name: incdtpriority_incdtpriority_id_seq; Type: ACL; Schema: public; Owner: admin
130011 --
130012
130013 REVOKE ALL ON SEQUENCE incdtpriority_incdtpriority_id_seq FROM PUBLIC;
130014 REVOKE ALL ON SEQUENCE incdtpriority_incdtpriority_id_seq FROM admin;
130015 GRANT ALL ON SEQUENCE incdtpriority_incdtpriority_id_seq TO admin;
130016 GRANT ALL ON SEQUENCE incdtpriority_incdtpriority_id_seq TO xtrole;
130017
130018
130019 --
130020 -- TOC entry 9848 (class 0 OID 0)
130021 -- Dependencies: 612
130022 -- Name: incdtresolution_incdtresolution_id_seq; Type: ACL; Schema: public; Owner: admin
130023 --
130024
130025 REVOKE ALL ON SEQUENCE incdtresolution_incdtresolution_id_seq FROM PUBLIC;
130026 REVOKE ALL ON SEQUENCE incdtresolution_incdtresolution_id_seq FROM admin;
130027 GRANT ALL ON SEQUENCE incdtresolution_incdtresolution_id_seq TO admin;
130028 GRANT ALL ON SEQUENCE incdtresolution_incdtresolution_id_seq TO xtrole;
130029
130030
130031 --
130032 -- TOC entry 9850 (class 0 OID 0)
130033 -- Dependencies: 613
130034 -- Name: incdtseverity_incdtseverity_id_seq; Type: ACL; Schema: public; Owner: admin
130035 --
130036
130037 REVOKE ALL ON SEQUENCE incdtseverity_incdtseverity_id_seq FROM PUBLIC;
130038 REVOKE ALL ON SEQUENCE incdtseverity_incdtseverity_id_seq FROM admin;
130039 GRANT ALL ON SEQUENCE incdtseverity_incdtseverity_id_seq TO admin;
130040 GRANT ALL ON SEQUENCE incdtseverity_incdtseverity_id_seq TO xtrole;
130041
130042
130043 --
130044 -- TOC entry 9852 (class 0 OID 0)
130045 -- Dependencies: 614
130046 -- Name: invbal_invbal_id_seq; Type: ACL; Schema: public; Owner: admin
130047 --
130048
130049 REVOKE ALL ON SEQUENCE invbal_invbal_id_seq FROM PUBLIC;
130050 REVOKE ALL ON SEQUENCE invbal_invbal_id_seq FROM admin;
130051 GRANT ALL ON SEQUENCE invbal_invbal_id_seq TO admin;
130052 GRANT ALL ON SEQUENCE invbal_invbal_id_seq TO xtrole;
130053
130054
130055 --
130056 -- TOC entry 9853 (class 0 OID 0)
130057 -- Dependencies: 615
130058 -- Name: invc_invc_id_seq; Type: ACL; Schema: public; Owner: admin
130059 --
130060
130061 REVOKE ALL ON SEQUENCE invc_invc_id_seq FROM PUBLIC;
130062 REVOKE ALL ON SEQUENCE invc_invc_id_seq FROM admin;
130063 GRANT ALL ON SEQUENCE invc_invc_id_seq TO admin;
130064 GRANT ALL ON SEQUENCE invc_invc_id_seq TO xtrole;
130065
130066
130067 --
130068 -- TOC entry 9855 (class 0 OID 0)
130069 -- Dependencies: 616
130070 -- Name: invchead_invchead_id_seq; Type: ACL; Schema: public; Owner: admin
130071 --
130072
130073 REVOKE ALL ON SEQUENCE invchead_invchead_id_seq FROM PUBLIC;
130074 REVOKE ALL ON SEQUENCE invchead_invchead_id_seq FROM admin;
130075 GRANT ALL ON SEQUENCE invchead_invchead_id_seq TO admin;
130076 GRANT ALL ON SEQUENCE invchead_invchead_id_seq TO xtrole;
130077
130078
130079 --
130080 -- TOC entry 9856 (class 0 OID 0)
130081 -- Dependencies: 617
130082 -- Name: invcheadtax; Type: ACL; Schema: public; Owner: admin
130083 --
130084
130085 REVOKE ALL ON TABLE invcheadtax FROM PUBLIC;
130086 REVOKE ALL ON TABLE invcheadtax FROM admin;
130087 GRANT ALL ON TABLE invcheadtax TO admin;
130088 GRANT ALL ON TABLE invcheadtax TO xtrole;
130089
130090
130091 --
130092 -- TOC entry 9858 (class 0 OID 0)
130093 -- Dependencies: 618
130094 -- Name: invcitem_invcitem_id_seq; Type: ACL; Schema: public; Owner: admin
130095 --
130096
130097 REVOKE ALL ON SEQUENCE invcitem_invcitem_id_seq FROM PUBLIC;
130098 REVOKE ALL ON SEQUENCE invcitem_invcitem_id_seq FROM admin;
130099 GRANT ALL ON SEQUENCE invcitem_invcitem_id_seq TO admin;
130100 GRANT ALL ON SEQUENCE invcitem_invcitem_id_seq TO xtrole;
130101
130102
130103 --
130104 -- TOC entry 9859 (class 0 OID 0)
130105 -- Dependencies: 619
130106 -- Name: invcitemtax; Type: ACL; Schema: public; Owner: admin
130107 --
130108
130109 REVOKE ALL ON TABLE invcitemtax FROM PUBLIC;
130110 REVOKE ALL ON TABLE invcitemtax FROM admin;
130111 GRANT ALL ON TABLE invcitemtax TO admin;
130112 GRANT ALL ON TABLE invcitemtax TO xtrole;
130113
130114
130115 --
130116 -- TOC entry 9860 (class 0 OID 0)
130117 -- Dependencies: 620
130118 -- Name: invcnt_invcnt_id_seq; Type: ACL; Schema: public; Owner: admin
130119 --
130120
130121 REVOKE ALL ON SEQUENCE invcnt_invcnt_id_seq FROM PUBLIC;
130122 REVOKE ALL ON SEQUENCE invcnt_invcnt_id_seq FROM admin;
130123 GRANT ALL ON SEQUENCE invcnt_invcnt_id_seq TO admin;
130124 GRANT ALL ON SEQUENCE invcnt_invcnt_id_seq TO xtrole;
130125
130126
130127 --
130128 -- TOC entry 9862 (class 0 OID 0)
130129 -- Dependencies: 621
130130 -- Name: invdetail; Type: ACL; Schema: public; Owner: admin
130131 --
130132
130133 REVOKE ALL ON TABLE invdetail FROM PUBLIC;
130134 REVOKE ALL ON TABLE invdetail FROM admin;
130135 GRANT ALL ON TABLE invdetail TO admin;
130136 GRANT ALL ON TABLE invdetail TO xtrole;
130137
130138
130139 --
130140 -- TOC entry 9863 (class 0 OID 0)
130141 -- Dependencies: 622
130142 -- Name: invdetail_invdetail_id_seq; Type: ACL; Schema: public; Owner: admin
130143 --
130144
130145 REVOKE ALL ON SEQUENCE invdetail_invdetail_id_seq FROM PUBLIC;
130146 REVOKE ALL ON SEQUENCE invdetail_invdetail_id_seq FROM admin;
130147 GRANT ALL ON SEQUENCE invdetail_invdetail_id_seq TO admin;
130148 GRANT ALL ON SEQUENCE invdetail_invdetail_id_seq TO xtrole;
130149
130150
130151 --
130152 -- TOC entry 9865 (class 0 OID 0)
130153 -- Dependencies: 623
130154 -- Name: invhist; Type: ACL; Schema: public; Owner: admin
130155 --
130156
130157 REVOKE ALL ON TABLE invhist FROM PUBLIC;
130158 REVOKE ALL ON TABLE invhist FROM admin;
130159 GRANT ALL ON TABLE invhist TO admin;
130160 GRANT ALL ON TABLE invhist TO xtrole;
130161
130162
130163 --
130164 -- TOC entry 9866 (class 0 OID 0)
130165 -- Dependencies: 624
130166 -- Name: invhist_invhist_id_seq; Type: ACL; Schema: public; Owner: admin
130167 --
130168
130169 REVOKE ALL ON SEQUENCE invhist_invhist_id_seq FROM PUBLIC;
130170 REVOKE ALL ON SEQUENCE invhist_invhist_id_seq FROM admin;
130171 GRANT ALL ON SEQUENCE invhist_invhist_id_seq TO admin;
130172 GRANT ALL ON SEQUENCE invhist_invhist_id_seq TO xtrole;
130173
130174
130175 --
130176 -- TOC entry 9868 (class 0 OID 0)
130177 -- Dependencies: 625
130178 -- Name: invhistexpcat; Type: ACL; Schema: public; Owner: admin
130179 --
130180
130181 REVOKE ALL ON TABLE invhistexpcat FROM PUBLIC;
130182 REVOKE ALL ON TABLE invhistexpcat FROM admin;
130183 GRANT ALL ON TABLE invhistexpcat TO admin;
130184 GRANT ALL ON TABLE invhistexpcat TO xtrole;
130185
130186
130187 --
130188 -- TOC entry 9870 (class 0 OID 0)
130189 -- Dependencies: 626
130190 -- Name: invhistexpcat_invhistexpcat_id_seq; Type: ACL; Schema: public; Owner: admin
130191 --
130192
130193 REVOKE ALL ON SEQUENCE invhistexpcat_invhistexpcat_id_seq FROM PUBLIC;
130194 REVOKE ALL ON SEQUENCE invhistexpcat_invhistexpcat_id_seq FROM admin;
130195 GRANT ALL ON SEQUENCE invhistexpcat_invhistexpcat_id_seq TO admin;
130196 GRANT ALL ON SEQUENCE invhistexpcat_invhistexpcat_id_seq TO xtrole;
130197
130198
130199 --
130200 -- TOC entry 9872 (class 0 OID 0)
130201 -- Dependencies: 627
130202 -- Name: invoiceitem; Type: ACL; Schema: public; Owner: admin
130203 --
130204
130205 REVOKE ALL ON TABLE invoiceitem FROM PUBLIC;
130206 REVOKE ALL ON TABLE invoiceitem FROM admin;
130207 GRANT ALL ON TABLE invoiceitem TO admin;
130208 GRANT ALL ON TABLE invoiceitem TO xtrole;
130209
130210
130211 --
130212 -- TOC entry 9874 (class 0 OID 0)
130213 -- Dependencies: 628
130214 -- Name: ipsass_ipsass_id_seq; Type: ACL; Schema: public; Owner: admin
130215 --
130216
130217 REVOKE ALL ON SEQUENCE ipsass_ipsass_id_seq FROM PUBLIC;
130218 REVOKE ALL ON SEQUENCE ipsass_ipsass_id_seq FROM admin;
130219 GRANT ALL ON SEQUENCE ipsass_ipsass_id_seq TO admin;
130220 GRANT ALL ON SEQUENCE ipsass_ipsass_id_seq TO xtrole;
130221
130222
130223 --
130224 -- TOC entry 9875 (class 0 OID 0)
130225 -- Dependencies: 629
130226 -- Name: ipsctyp_ipsctyp_id_seq; Type: ACL; Schema: public; Owner: admin
130227 --
130228
130229 REVOKE ALL ON SEQUENCE ipsctyp_ipsctyp_id_seq FROM PUBLIC;
130230 REVOKE ALL ON SEQUENCE ipsctyp_ipsctyp_id_seq FROM admin;
130231 GRANT ALL ON SEQUENCE ipsctyp_ipsctyp_id_seq TO admin;
130232 GRANT ALL ON SEQUENCE ipsctyp_ipsctyp_id_seq TO xtrole;
130233
130234
130235 --
130236 -- TOC entry 9876 (class 0 OID 0)
130237 -- Dependencies: 630
130238 -- Name: ipscust_ipscust_id_seq; Type: ACL; Schema: public; Owner: admin
130239 --
130240
130241 REVOKE ALL ON SEQUENCE ipscust_ipscust_id_seq FROM PUBLIC;
130242 REVOKE ALL ON SEQUENCE ipscust_ipscust_id_seq FROM admin;
130243 GRANT ALL ON SEQUENCE ipscust_ipscust_id_seq TO admin;
130244 GRANT ALL ON SEQUENCE ipscust_ipscust_id_seq TO xtrole;
130245
130246
130247 --
130248 -- TOC entry 9878 (class 0 OID 0)
130249 -- Dependencies: 631
130250 -- Name: ipsfreight_ipsfreight_id_seq; Type: ACL; Schema: public; Owner: admin
130251 --
130252
130253 REVOKE ALL ON SEQUENCE ipsfreight_ipsfreight_id_seq FROM PUBLIC;
130254 REVOKE ALL ON SEQUENCE ipsfreight_ipsfreight_id_seq FROM admin;
130255 GRANT ALL ON SEQUENCE ipsfreight_ipsfreight_id_seq TO admin;
130256 GRANT ALL ON SEQUENCE ipsfreight_ipsfreight_id_seq TO xtrole;
130257
130258
130259 --
130260 -- TOC entry 9879 (class 0 OID 0)
130261 -- Dependencies: 632
130262 -- Name: ipshead_ipshead_id_seq; Type: ACL; Schema: public; Owner: admin
130263 --
130264
130265 REVOKE ALL ON SEQUENCE ipshead_ipshead_id_seq FROM PUBLIC;
130266 REVOKE ALL ON SEQUENCE ipshead_ipshead_id_seq FROM admin;
130267 GRANT ALL ON SEQUENCE ipshead_ipshead_id_seq TO admin;
130268 GRANT ALL ON SEQUENCE ipshead_ipshead_id_seq TO xtrole;
130269
130270
130271 --
130272 -- TOC entry 9880 (class 0 OID 0)
130273 -- Dependencies: 633
130274 -- Name: ipsitem_ipsitem_id_seq; Type: ACL; Schema: public; Owner: admin
130275 --
130276
130277 REVOKE ALL ON SEQUENCE ipsitem_ipsitem_id_seq FROM PUBLIC;
130278 REVOKE ALL ON SEQUENCE ipsitem_ipsitem_id_seq FROM admin;
130279 GRANT ALL ON SEQUENCE ipsitem_ipsitem_id_seq TO admin;
130280 GRANT ALL ON SEQUENCE ipsitem_ipsitem_id_seq TO xtrole;
130281
130282
130283 --
130284 -- TOC entry 9882 (class 0 OID 0)
130285 -- Dependencies: 634
130286 -- Name: ipsitemchar_ipsitemchar_id_seq; Type: ACL; Schema: public; Owner: admin
130287 --
130288
130289 REVOKE ALL ON SEQUENCE ipsitemchar_ipsitemchar_id_seq FROM PUBLIC;
130290 REVOKE ALL ON SEQUENCE ipsitemchar_ipsitemchar_id_seq FROM admin;
130291 GRANT ALL ON SEQUENCE ipsitemchar_ipsitemchar_id_seq TO admin;
130292 GRANT ALL ON SEQUENCE ipsitemchar_ipsitemchar_id_seq TO xtrole;
130293
130294
130295 --
130296 -- TOC entry 9883 (class 0 OID 0)
130297 -- Dependencies: 635
130298 -- Name: ipsprice; Type: ACL; Schema: public; Owner: admin
130299 --
130300
130301 REVOKE ALL ON TABLE ipsprice FROM PUBLIC;
130302 REVOKE ALL ON TABLE ipsprice FROM admin;
130303 GRANT ALL ON TABLE ipsprice TO admin;
130304 GRANT ALL ON TABLE ipsprice TO xtrole;
130305
130306
130307 --
130308 -- TOC entry 9885 (class 0 OID 0)
130309 -- Dependencies: 636
130310 -- Name: ipsprodcat_bak; Type: ACL; Schema: public; Owner: admin
130311 --
130312
130313 REVOKE ALL ON TABLE ipsprodcat_bak FROM PUBLIC;
130314 REVOKE ALL ON TABLE ipsprodcat_bak FROM admin;
130315 GRANT ALL ON TABLE ipsprodcat_bak TO admin;
130316 GRANT ALL ON TABLE ipsprodcat_bak TO xtrole;
130317
130318
130319 --
130320 -- TOC entry 9887 (class 0 OID 0)
130321 -- Dependencies: 637
130322 -- Name: ipsprodcat_ipsprodcat_id_seq; Type: ACL; Schema: public; Owner: admin
130323 --
130324
130325 REVOKE ALL ON SEQUENCE ipsprodcat_ipsprodcat_id_seq FROM PUBLIC;
130326 REVOKE ALL ON SEQUENCE ipsprodcat_ipsprodcat_id_seq FROM admin;
130327 GRANT ALL ON SEQUENCE ipsprodcat_ipsprodcat_id_seq TO admin;
130328 GRANT ALL ON SEQUENCE ipsprodcat_ipsprodcat_id_seq TO xtrole;
130329
130330
130331 --
130332 -- TOC entry 9888 (class 0 OID 0)
130333 -- Dependencies: 638
130334 -- Name: item_item_id_seq; Type: ACL; Schema: public; Owner: admin
130335 --
130336
130337 REVOKE ALL ON SEQUENCE item_item_id_seq FROM PUBLIC;
130338 REVOKE ALL ON SEQUENCE item_item_id_seq FROM admin;
130339 GRANT ALL ON SEQUENCE item_item_id_seq TO admin;
130340 GRANT ALL ON SEQUENCE item_item_id_seq TO xtrole;
130341
130342
130343 --
130344 -- TOC entry 9889 (class 0 OID 0)
130345 -- Dependencies: 639
130346 -- Name: itemalias_itemalias_id_seq; Type: ACL; Schema: public; Owner: admin
130347 --
130348
130349 REVOKE ALL ON SEQUENCE itemalias_itemalias_id_seq FROM PUBLIC;
130350 REVOKE ALL ON SEQUENCE itemalias_itemalias_id_seq FROM admin;
130351 GRANT ALL ON SEQUENCE itemalias_itemalias_id_seq TO admin;
130352 GRANT ALL ON SEQUENCE itemalias_itemalias_id_seq TO xtrole;
130353
130354
130355 --
130356 -- TOC entry 9890 (class 0 OID 0)
130357 -- Dependencies: 640
130358 -- Name: itematr_itematr_id_seq; Type: ACL; Schema: public; Owner: admin
130359 --
130360
130361 REVOKE ALL ON SEQUENCE itematr_itematr_id_seq FROM PUBLIC;
130362 REVOKE ALL ON SEQUENCE itematr_itematr_id_seq FROM admin;
130363 GRANT ALL ON SEQUENCE itematr_itematr_id_seq TO admin;
130364 GRANT ALL ON SEQUENCE itematr_itematr_id_seq TO xtrole;
130365
130366
130367 --
130368 -- TOC entry 9891 (class 0 OID 0)
130369 -- Dependencies: 641
130370 -- Name: itemcost_itemcost_id_seq; Type: ACL; Schema: public; Owner: admin
130371 --
130372
130373 REVOKE ALL ON SEQUENCE itemcost_itemcost_id_seq FROM PUBLIC;
130374 REVOKE ALL ON SEQUENCE itemcost_itemcost_id_seq FROM admin;
130375 GRANT ALL ON SEQUENCE itemcost_itemcost_id_seq TO admin;
130376 GRANT ALL ON SEQUENCE itemcost_itemcost_id_seq TO xtrole;
130377
130378
130379 --
130380 -- TOC entry 9892 (class 0 OID 0)
130381 -- Dependencies: 642
130382 -- Name: itemfrez_itemfrez_seq; Type: ACL; Schema: public; Owner: admin
130383 --
130384
130385 REVOKE ALL ON SEQUENCE itemfrez_itemfrez_seq FROM PUBLIC;
130386 REVOKE ALL ON SEQUENCE itemfrez_itemfrez_seq FROM admin;
130387 GRANT ALL ON SEQUENCE itemfrez_itemfrez_seq TO admin;
130388 GRANT ALL ON SEQUENCE itemfrez_itemfrez_seq TO xtrole;
130389
130390
130391 --
130392 -- TOC entry 9894 (class 0 OID 0)
130393 -- Dependencies: 643
130394 -- Name: itemgrp; Type: ACL; Schema: public; Owner: admin
130395 --
130396
130397 REVOKE ALL ON TABLE itemgrp FROM PUBLIC;
130398 REVOKE ALL ON TABLE itemgrp FROM admin;
130399 GRANT ALL ON TABLE itemgrp TO admin;
130400 GRANT ALL ON TABLE itemgrp TO xtrole;
130401
130402
130403 --
130404 -- TOC entry 9895 (class 0 OID 0)
130405 -- Dependencies: 644
130406 -- Name: itemgrp_itemgrp_id_seq; Type: ACL; Schema: public; Owner: admin
130407 --
130408
130409 REVOKE ALL ON SEQUENCE itemgrp_itemgrp_id_seq FROM PUBLIC;
130410 REVOKE ALL ON SEQUENCE itemgrp_itemgrp_id_seq FROM admin;
130411 GRANT ALL ON SEQUENCE itemgrp_itemgrp_id_seq TO admin;
130412 GRANT ALL ON SEQUENCE itemgrp_itemgrp_id_seq TO xtrole;
130413
130414
130415 --
130416 -- TOC entry 9897 (class 0 OID 0)
130417 -- Dependencies: 645
130418 -- Name: itemgrpitem; Type: ACL; Schema: public; Owner: admin
130419 --
130420
130421 REVOKE ALL ON TABLE itemgrpitem FROM PUBLIC;
130422 REVOKE ALL ON TABLE itemgrpitem FROM admin;
130423 GRANT ALL ON TABLE itemgrpitem TO admin;
130424 GRANT ALL ON TABLE itemgrpitem TO xtrole;
130425
130426
130427 --
130428 -- TOC entry 9898 (class 0 OID 0)
130429 -- Dependencies: 646
130430 -- Name: itemgrpitem_itemgrpitem_id_seq; Type: ACL; Schema: public; Owner: admin
130431 --
130432
130433 REVOKE ALL ON SEQUENCE itemgrpitem_itemgrpitem_id_seq FROM PUBLIC;
130434 REVOKE ALL ON SEQUENCE itemgrpitem_itemgrpitem_id_seq FROM admin;
130435 GRANT ALL ON SEQUENCE itemgrpitem_itemgrpitem_id_seq TO admin;
130436 GRANT ALL ON SEQUENCE itemgrpitem_itemgrpitem_id_seq TO xtrole;
130437
130438
130439 --
130440 -- TOC entry 9900 (class 0 OID 0)
130441 -- Dependencies: 647
130442 -- Name: itemimage; Type: ACL; Schema: public; Owner: admin
130443 --
130444
130445 REVOKE ALL ON TABLE itemimage FROM PUBLIC;
130446 REVOKE ALL ON TABLE itemimage FROM admin;
130447 GRANT ALL ON TABLE itemimage TO admin;
130448 GRANT ALL ON TABLE itemimage TO xtrole;
130449
130450
130451 --
130452 -- TOC entry 9901 (class 0 OID 0)
130453 -- Dependencies: 648
130454 -- Name: itemimage_itemimage_id_seq; Type: ACL; Schema: public; Owner: admin
130455 --
130456
130457 REVOKE ALL ON SEQUENCE itemimage_itemimage_id_seq FROM PUBLIC;
130458 REVOKE ALL ON SEQUENCE itemimage_itemimage_id_seq FROM admin;
130459 GRANT ALL ON SEQUENCE itemimage_itemimage_id_seq TO admin;
130460 GRANT ALL ON SEQUENCE itemimage_itemimage_id_seq TO xtrole;
130461
130462
130463 --
130464 -- TOC entry 9903 (class 0 OID 0)
130465 -- Dependencies: 649
130466 -- Name: itemloc; Type: ACL; Schema: public; Owner: admin
130467 --
130468
130469 REVOKE ALL ON TABLE itemloc FROM PUBLIC;
130470 REVOKE ALL ON TABLE itemloc FROM admin;
130471 GRANT ALL ON TABLE itemloc TO admin;
130472 GRANT ALL ON TABLE itemloc TO xtrole;
130473
130474
130475 --
130476 -- TOC entry 9904 (class 0 OID 0)
130477 -- Dependencies: 650
130478 -- Name: itemloc_itemloc_id_seq; Type: ACL; Schema: public; Owner: admin
130479 --
130480
130481 REVOKE ALL ON SEQUENCE itemloc_itemloc_id_seq FROM PUBLIC;
130482 REVOKE ALL ON SEQUENCE itemloc_itemloc_id_seq FROM admin;
130483 GRANT ALL ON SEQUENCE itemloc_itemloc_id_seq TO admin;
130484 GRANT ALL ON SEQUENCE itemloc_itemloc_id_seq TO xtrole;
130485
130486
130487 --
130488 -- TOC entry 9905 (class 0 OID 0)
130489 -- Dependencies: 651
130490 -- Name: itemloc_series_seq; Type: ACL; Schema: public; Owner: admin
130491 --
130492
130493 REVOKE ALL ON SEQUENCE itemloc_series_seq FROM PUBLIC;
130494 REVOKE ALL ON SEQUENCE itemloc_series_seq FROM admin;
130495 GRANT ALL ON SEQUENCE itemloc_series_seq TO admin;
130496 GRANT ALL ON SEQUENCE itemloc_series_seq TO xtrole;
130497
130498
130499 --
130500 -- TOC entry 9907 (class 0 OID 0)
130501 -- Dependencies: 652
130502 -- Name: itemlocdist; Type: ACL; Schema: public; Owner: admin
130503 --
130504
130505 REVOKE ALL ON TABLE itemlocdist FROM PUBLIC;
130506 REVOKE ALL ON TABLE itemlocdist FROM admin;
130507 GRANT ALL ON TABLE itemlocdist TO admin;
130508 GRANT ALL ON TABLE itemlocdist TO xtrole;
130509
130510
130511 --
130512 -- TOC entry 9908 (class 0 OID 0)
130513 -- Dependencies: 653
130514 -- Name: itemlocdist_itemlocdist_id_seq; Type: ACL; Schema: public; Owner: admin
130515 --
130516
130517 REVOKE ALL ON SEQUENCE itemlocdist_itemlocdist_id_seq FROM PUBLIC;
130518 REVOKE ALL ON SEQUENCE itemlocdist_itemlocdist_id_seq FROM admin;
130519 GRANT ALL ON SEQUENCE itemlocdist_itemlocdist_id_seq TO admin;
130520 GRANT ALL ON SEQUENCE itemlocdist_itemlocdist_id_seq TO xtrole;
130521
130522
130523 --
130524 -- TOC entry 9910 (class 0 OID 0)
130525 -- Dependencies: 654
130526 -- Name: itemlocpost; Type: ACL; Schema: public; Owner: admin
130527 --
130528
130529 REVOKE ALL ON TABLE itemlocpost FROM PUBLIC;
130530 REVOKE ALL ON TABLE itemlocpost FROM admin;
130531 GRANT ALL ON TABLE itemlocpost TO admin;
130532 GRANT ALL ON TABLE itemlocpost TO xtrole;
130533
130534
130535 --
130536 -- TOC entry 9912 (class 0 OID 0)
130537 -- Dependencies: 655
130538 -- Name: itemlocpost_itemlocpost_id_seq; Type: ACL; Schema: public; Owner: admin
130539 --
130540
130541 REVOKE ALL ON SEQUENCE itemlocpost_itemlocpost_id_seq FROM PUBLIC;
130542 REVOKE ALL ON SEQUENCE itemlocpost_itemlocpost_id_seq FROM admin;
130543 GRANT ALL ON SEQUENCE itemlocpost_itemlocpost_id_seq TO admin;
130544 GRANT ALL ON SEQUENCE itemlocpost_itemlocpost_id_seq TO xtrole;
130545
130546
130547 --
130548 -- TOC entry 9913 (class 0 OID 0)
130549 -- Dependencies: 656
130550 -- Name: itemopn_itemopn_id_seq; Type: ACL; Schema: public; Owner: admin
130551 --
130552
130553 REVOKE ALL ON SEQUENCE itemopn_itemopn_id_seq FROM PUBLIC;
130554 REVOKE ALL ON SEQUENCE itemopn_itemopn_id_seq FROM admin;
130555 GRANT ALL ON SEQUENCE itemopn_itemopn_id_seq TO admin;
130556 GRANT ALL ON SEQUENCE itemopn_itemopn_id_seq TO xtrole;
130557
130558
130559 --
130560 -- TOC entry 9914 (class 0 OID 0)
130561 -- Dependencies: 657
130562 -- Name: itemsite_itemsite_id_seq; Type: ACL; Schema: public; Owner: admin
130563 --
130564
130565 REVOKE ALL ON SEQUENCE itemsite_itemsite_id_seq FROM PUBLIC;
130566 REVOKE ALL ON SEQUENCE itemsite_itemsite_id_seq FROM admin;
130567 GRANT ALL ON SEQUENCE itemsite_itemsite_id_seq TO admin;
130568 GRANT ALL ON SEQUENCE itemsite_itemsite_id_seq TO xtrole;
130569
130570
130571 --
130572 -- TOC entry 9915 (class 0 OID 0)
130573 -- Dependencies: 658
130574 -- Name: itemsrc_itemsrc_id_seq; Type: ACL; Schema: public; Owner: admin
130575 --
130576
130577 REVOKE ALL ON SEQUENCE itemsrc_itemsrc_id_seq FROM PUBLIC;
130578 REVOKE ALL ON SEQUENCE itemsrc_itemsrc_id_seq FROM admin;
130579 GRANT ALL ON SEQUENCE itemsrc_itemsrc_id_seq TO admin;
130580 GRANT ALL ON SEQUENCE itemsrc_itemsrc_id_seq TO xtrole;
130581
130582
130583 --
130584 -- TOC entry 9916 (class 0 OID 0)
130585 -- Dependencies: 659
130586 -- Name: itemsrcp_itemsrcp_id_seq; Type: ACL; Schema: public; Owner: admin
130587 --
130588
130589 REVOKE ALL ON SEQUENCE itemsrcp_itemsrcp_id_seq FROM PUBLIC;
130590 REVOKE ALL ON SEQUENCE itemsrcp_itemsrcp_id_seq FROM admin;
130591 GRANT ALL ON SEQUENCE itemsrcp_itemsrcp_id_seq TO admin;
130592 GRANT ALL ON SEQUENCE itemsrcp_itemsrcp_id_seq TO xtrole;
130593
130594
130595 --
130596 -- TOC entry 9917 (class 0 OID 0)
130597 -- Dependencies: 660
130598 -- Name: itemsub_itemsub_id_seq; Type: ACL; Schema: public; Owner: admin
130599 --
130600
130601 REVOKE ALL ON SEQUENCE itemsub_itemsub_id_seq FROM PUBLIC;
130602 REVOKE ALL ON SEQUENCE itemsub_itemsub_id_seq FROM admin;
130603 GRANT ALL ON SEQUENCE itemsub_itemsub_id_seq TO admin;
130604 GRANT ALL ON SEQUENCE itemsub_itemsub_id_seq TO xtrole;
130605
130606
130607 --
130608 -- TOC entry 9919 (class 0 OID 0)
130609 -- Dependencies: 661
130610 -- Name: itemtax_itemtax_id_seq; Type: ACL; Schema: public; Owner: admin
130611 --
130612
130613 REVOKE ALL ON SEQUENCE itemtax_itemtax_id_seq FROM PUBLIC;
130614 REVOKE ALL ON SEQUENCE itemtax_itemtax_id_seq FROM admin;
130615 GRANT ALL ON SEQUENCE itemtax_itemtax_id_seq TO admin;
130616 GRANT ALL ON SEQUENCE itemtax_itemtax_id_seq TO xtrole;
130617
130618
130619 --
130620 -- TOC entry 9921 (class 0 OID 0)
130621 -- Dependencies: 662
130622 -- Name: itemtrans; Type: ACL; Schema: public; Owner: admin
130623 --
130624
130625 REVOKE ALL ON TABLE itemtrans FROM PUBLIC;
130626 REVOKE ALL ON TABLE itemtrans FROM admin;
130627 GRANT ALL ON TABLE itemtrans TO admin;
130628 GRANT ALL ON TABLE itemtrans TO xtrole;
130629
130630
130631 --
130632 -- TOC entry 9923 (class 0 OID 0)
130633 -- Dependencies: 663
130634 -- Name: itemtrans_itemtrans_id_seq; Type: ACL; Schema: public; Owner: admin
130635 --
130636
130637 REVOKE ALL ON SEQUENCE itemtrans_itemtrans_id_seq FROM PUBLIC;
130638 REVOKE ALL ON SEQUENCE itemtrans_itemtrans_id_seq FROM admin;
130639 GRANT ALL ON SEQUENCE itemtrans_itemtrans_id_seq TO admin;
130640 GRANT ALL ON SEQUENCE itemtrans_itemtrans_id_seq TO xtrole;
130641
130642
130643 --
130644 -- TOC entry 9925 (class 0 OID 0)
130645 -- Dependencies: 664
130646 -- Name: itemuom; Type: ACL; Schema: public; Owner: admin
130647 --
130648
130649 REVOKE ALL ON TABLE itemuom FROM PUBLIC;
130650 REVOKE ALL ON TABLE itemuom FROM admin;
130651 GRANT ALL ON TABLE itemuom TO admin;
130652 GRANT ALL ON TABLE itemuom TO xtrole;
130653
130654
130655 --
130656 -- TOC entry 9927 (class 0 OID 0)
130657 -- Dependencies: 665
130658 -- Name: itemuom_itemuom_id_seq; Type: ACL; Schema: public; Owner: admin
130659 --
130660
130661 REVOKE ALL ON SEQUENCE itemuom_itemuom_id_seq FROM PUBLIC;
130662 REVOKE ALL ON SEQUENCE itemuom_itemuom_id_seq FROM admin;
130663 GRANT ALL ON SEQUENCE itemuom_itemuom_id_seq TO admin;
130664 GRANT ALL ON SEQUENCE itemuom_itemuom_id_seq TO xtrole;
130665
130666
130667 --
130668 -- TOC entry 9929 (class 0 OID 0)
130669 -- Dependencies: 666
130670 -- Name: itemuomconv_itemuomconv_id_seq; Type: ACL; Schema: public; Owner: admin
130671 --
130672
130673 REVOKE ALL ON SEQUENCE itemuomconv_itemuomconv_id_seq FROM PUBLIC;
130674 REVOKE ALL ON SEQUENCE itemuomconv_itemuomconv_id_seq FROM admin;
130675 GRANT ALL ON SEQUENCE itemuomconv_itemuomconv_id_seq TO admin;
130676 GRANT ALL ON SEQUENCE itemuomconv_itemuomconv_id_seq TO xtrole;
130677
130678
130679 --
130680 -- TOC entry 9930 (class 0 OID 0)
130681 -- Dependencies: 667
130682 -- Name: journal_number_seq; Type: ACL; Schema: public; Owner: admin
130683 --
130684
130685 REVOKE ALL ON SEQUENCE journal_number_seq FROM PUBLIC;
130686 REVOKE ALL ON SEQUENCE journal_number_seq FROM admin;
130687 GRANT ALL ON SEQUENCE journal_number_seq TO admin;
130688 GRANT ALL ON SEQUENCE journal_number_seq TO xtrole;
130689
130690
130691 --
130692 -- TOC entry 9932 (class 0 OID 0)
130693 -- Dependencies: 668
130694 -- Name: jrnluse; Type: ACL; Schema: public; Owner: admin
130695 --
130696
130697 REVOKE ALL ON TABLE jrnluse FROM PUBLIC;
130698 REVOKE ALL ON TABLE jrnluse FROM admin;
130699 GRANT ALL ON TABLE jrnluse TO admin;
130700 GRANT ALL ON TABLE jrnluse TO xtrole;
130701
130702
130703 --
130704 -- TOC entry 9933 (class 0 OID 0)
130705 -- Dependencies: 669
130706 -- Name: jrnluse_jrnluse_id_seq; Type: ACL; Schema: public; Owner: admin
130707 --
130708
130709 REVOKE ALL ON SEQUENCE jrnluse_jrnluse_id_seq FROM PUBLIC;
130710 REVOKE ALL ON SEQUENCE jrnluse_jrnluse_id_seq FROM admin;
130711 GRANT ALL ON SEQUENCE jrnluse_jrnluse_id_seq TO admin;
130712 GRANT ALL ON SEQUENCE jrnluse_jrnluse_id_seq TO xtrole;
130713
130714
130715 --
130716 -- TOC entry 9934 (class 0 OID 0)
130717 -- Dependencies: 670
130718 -- Name: labeldef; Type: ACL; Schema: public; Owner: admin
130719 --
130720
130721 REVOKE ALL ON TABLE labeldef FROM PUBLIC;
130722 REVOKE ALL ON TABLE labeldef FROM admin;
130723 GRANT ALL ON TABLE labeldef TO admin;
130724 GRANT ALL ON TABLE labeldef TO xtrole;
130725
130726
130727 --
130728 -- TOC entry 9936 (class 0 OID 0)
130729 -- Dependencies: 671
130730 -- Name: labeldef_labeldef_id_seq; Type: ACL; Schema: public; Owner: admin
130731 --
130732
130733 REVOKE ALL ON SEQUENCE labeldef_labeldef_id_seq FROM PUBLIC;
130734 REVOKE ALL ON SEQUENCE labeldef_labeldef_id_seq FROM admin;
130735 GRANT ALL ON SEQUENCE labeldef_labeldef_id_seq TO admin;
130736 GRANT ALL ON SEQUENCE labeldef_labeldef_id_seq TO xtrole;
130737
130738
130739 --
130740 -- TOC entry 9939 (class 0 OID 0)
130741 -- Dependencies: 672
130742 -- Name: labelform; Type: ACL; Schema: public; Owner: admin
130743 --
130744
130745 REVOKE ALL ON TABLE labelform FROM PUBLIC;
130746 REVOKE ALL ON TABLE labelform FROM admin;
130747 GRANT ALL ON TABLE labelform TO admin;
130748 GRANT ALL ON TABLE labelform TO xtrole;
130749
130750
130751 --
130752 -- TOC entry 9940 (class 0 OID 0)
130753 -- Dependencies: 673
130754 -- Name: labelform_labelform_id_seq; Type: ACL; Schema: public; Owner: admin
130755 --
130756
130757 REVOKE ALL ON SEQUENCE labelform_labelform_id_seq FROM PUBLIC;
130758 REVOKE ALL ON SEQUENCE labelform_labelform_id_seq FROM admin;
130759 GRANT ALL ON SEQUENCE labelform_labelform_id_seq TO admin;
130760 GRANT ALL ON SEQUENCE labelform_labelform_id_seq TO xtrole;
130761
130762
130763 --
130764 -- TOC entry 9945 (class 0 OID 0)
130765 -- Dependencies: 674
130766 -- Name: lang; Type: ACL; Schema: public; Owner: admin
130767 --
130768
130769 REVOKE ALL ON TABLE lang FROM PUBLIC;
130770 REVOKE ALL ON TABLE lang FROM admin;
130771 GRANT ALL ON TABLE lang TO admin;
130772 GRANT ALL ON TABLE lang TO xtrole;
130773
130774
130775 --
130776 -- TOC entry 9947 (class 0 OID 0)
130777 -- Dependencies: 675
130778 -- Name: lang_lang_id_seq; Type: ACL; Schema: public; Owner: admin
130779 --
130780
130781 REVOKE ALL ON SEQUENCE lang_lang_id_seq FROM PUBLIC;
130782 REVOKE ALL ON SEQUENCE lang_lang_id_seq FROM admin;
130783 GRANT ALL ON SEQUENCE lang_lang_id_seq TO admin;
130784 GRANT ALL ON SEQUENCE lang_lang_id_seq TO xtrole;
130785
130786
130787 --
130788 -- TOC entry 9977 (class 0 OID 0)
130789 -- Dependencies: 676
130790 -- Name: locale; Type: ACL; Schema: public; Owner: admin
130791 --
130792
130793 REVOKE ALL ON TABLE locale FROM PUBLIC;
130794 REVOKE ALL ON TABLE locale FROM admin;
130795 GRANT ALL ON TABLE locale TO admin;
130796 GRANT ALL ON TABLE locale TO xtrole;
130797
130798
130799 --
130800 -- TOC entry 9978 (class 0 OID 0)
130801 -- Dependencies: 677
130802 -- Name: locale_locale_id_seq; Type: ACL; Schema: public; Owner: admin
130803 --
130804
130805 REVOKE ALL ON SEQUENCE locale_locale_id_seq FROM PUBLIC;
130806 REVOKE ALL ON SEQUENCE locale_locale_id_seq FROM admin;
130807 GRANT ALL ON SEQUENCE locale_locale_id_seq TO admin;
130808 GRANT ALL ON SEQUENCE locale_locale_id_seq TO xtrole;
130809
130810
130811 --
130812 -- TOC entry 9979 (class 0 OID 0)
130813 -- Dependencies: 678
130814 -- Name: location_location_id_seq; Type: ACL; Schema: public; Owner: admin
130815 --
130816
130817 REVOKE ALL ON SEQUENCE location_location_id_seq FROM PUBLIC;
130818 REVOKE ALL ON SEQUENCE location_location_id_seq FROM admin;
130819 GRANT ALL ON SEQUENCE location_location_id_seq TO admin;
130820 GRANT ALL ON SEQUENCE location_location_id_seq TO xtrole;
130821
130822
130823 --
130824 -- TOC entry 9981 (class 0 OID 0)
130825 -- Dependencies: 679
130826 -- Name: locitem; Type: ACL; Schema: public; Owner: admin
130827 --
130828
130829 REVOKE ALL ON TABLE locitem FROM PUBLIC;
130830 REVOKE ALL ON TABLE locitem FROM admin;
130831 GRANT ALL ON TABLE locitem TO admin;
130832 GRANT ALL ON TABLE locitem TO xtrole;
130833
130834
130835 --
130836 -- TOC entry 9982 (class 0 OID 0)
130837 -- Dependencies: 680
130838 -- Name: locitem_locitem_id_seq; Type: ACL; Schema: public; Owner: admin
130839 --
130840
130841 REVOKE ALL ON SEQUENCE locitem_locitem_id_seq FROM PUBLIC;
130842 REVOKE ALL ON SEQUENCE locitem_locitem_id_seq FROM admin;
130843 GRANT ALL ON SEQUENCE locitem_locitem_id_seq TO admin;
130844 GRANT ALL ON SEQUENCE locitem_locitem_id_seq TO xtrole;
130845
130846
130847 --
130848 -- TOC entry 9983 (class 0 OID 0)
130849 -- Dependencies: 681
130850 -- Name: log_log_id_seq; Type: ACL; Schema: public; Owner: admin
130851 --
130852
130853 REVOKE ALL ON SEQUENCE log_log_id_seq FROM PUBLIC;
130854 REVOKE ALL ON SEQUENCE log_log_id_seq FROM admin;
130855 GRANT ALL ON SEQUENCE log_log_id_seq TO admin;
130856 GRANT ALL ON SEQUENCE log_log_id_seq TO xtrole;
130857
130858
130859 --
130860 -- TOC entry 9985 (class 0 OID 0)
130861 -- Dependencies: 682
130862 -- Name: metric; Type: ACL; Schema: public; Owner: admin
130863 --
130864
130865 REVOKE ALL ON TABLE metric FROM PUBLIC;
130866 REVOKE ALL ON TABLE metric FROM admin;
130867 GRANT ALL ON TABLE metric TO admin;
130868 GRANT ALL ON TABLE metric TO xtrole;
130869
130870
130871 --
130872 -- TOC entry 9986 (class 0 OID 0)
130873 -- Dependencies: 683
130874 -- Name: metric_metric_id_seq; Type: ACL; Schema: public; Owner: admin
130875 --
130876
130877 REVOKE ALL ON SEQUENCE metric_metric_id_seq FROM PUBLIC;
130878 REVOKE ALL ON SEQUENCE metric_metric_id_seq FROM admin;
130879 GRANT ALL ON SEQUENCE metric_metric_id_seq TO admin;
130880 GRANT ALL ON SEQUENCE metric_metric_id_seq TO xtrole;
130881
130882
130883 --
130884 -- TOC entry 9988 (class 0 OID 0)
130885 -- Dependencies: 684
130886 -- Name: metricenc; Type: ACL; Schema: public; Owner: admin
130887 --
130888
130889 REVOKE ALL ON TABLE metricenc FROM PUBLIC;
130890 REVOKE ALL ON TABLE metricenc FROM admin;
130891 GRANT ALL ON TABLE metricenc TO admin;
130892 GRANT ALL ON TABLE metricenc TO xtrole;
130893
130894
130895 --
130896 -- TOC entry 9990 (class 0 OID 0)
130897 -- Dependencies: 685
130898 -- Name: metricenc_metricenc_id_seq; Type: ACL; Schema: public; Owner: admin
130899 --
130900
130901 REVOKE ALL ON SEQUENCE metricenc_metricenc_id_seq FROM PUBLIC;
130902 REVOKE ALL ON SEQUENCE metricenc_metricenc_id_seq FROM admin;
130903 GRANT ALL ON SEQUENCE metricenc_metricenc_id_seq TO admin;
130904 GRANT ALL ON SEQUENCE metricenc_metricenc_id_seq TO xtrole;
130905
130906
130907 --
130908 -- TOC entry 9991 (class 0 OID 0)
130909 -- Dependencies: 686
130910 -- Name: misc_index_seq; Type: ACL; Schema: public; Owner: admin
130911 --
130912
130913 REVOKE ALL ON SEQUENCE misc_index_seq FROM PUBLIC;
130914 REVOKE ALL ON SEQUENCE misc_index_seq FROM admin;
130915 GRANT ALL ON SEQUENCE misc_index_seq TO admin;
130916 GRANT ALL ON SEQUENCE misc_index_seq TO xtrole;
130917
130918
130919 --
130920 -- TOC entry 9992 (class 0 OID 0)
130921 -- Dependencies: 687
130922 -- Name: mrghist; Type: ACL; Schema: public; Owner: admin
130923 --
130924
130925 REVOKE ALL ON TABLE mrghist FROM PUBLIC;
130926 REVOKE ALL ON TABLE mrghist FROM admin;
130927 GRANT ALL ON TABLE mrghist TO admin;
130928 GRANT ALL ON TABLE mrghist TO xtrole;
130929
130930
130931 --
130932 -- TOC entry 10004 (class 0 OID 0)
130933 -- Dependencies: 688
130934 -- Name: mrgundo; Type: ACL; Schema: public; Owner: admin
130935 --
130936
130937 REVOKE ALL ON TABLE mrgundo FROM PUBLIC;
130938 REVOKE ALL ON TABLE mrgundo FROM admin;
130939 GRANT ALL ON TABLE mrgundo TO admin;
130940 GRANT ALL ON TABLE mrgundo TO xtrole;
130941
130942
130943 --
130944 -- TOC entry 10006 (class 0 OID 0)
130945 -- Dependencies: 689
130946 -- Name: msg; Type: ACL; Schema: public; Owner: admin
130947 --
130948
130949 REVOKE ALL ON TABLE msg FROM PUBLIC;
130950 REVOKE ALL ON TABLE msg FROM admin;
130951 GRANT ALL ON TABLE msg TO admin;
130952 GRANT ALL ON TABLE msg TO xtrole;
130953
130954
130955 --
130956 -- TOC entry 10007 (class 0 OID 0)
130957 -- Dependencies: 690
130958 -- Name: msg_msg_id_seq; Type: ACL; Schema: public; Owner: admin
130959 --
130960
130961 REVOKE ALL ON SEQUENCE msg_msg_id_seq FROM PUBLIC;
130962 REVOKE ALL ON SEQUENCE msg_msg_id_seq FROM admin;
130963 GRANT ALL ON SEQUENCE msg_msg_id_seq TO admin;
130964 GRANT ALL ON SEQUENCE msg_msg_id_seq TO xtrole;
130965
130966
130967 --
130968 -- TOC entry 10009 (class 0 OID 0)
130969 -- Dependencies: 691
130970 -- Name: msguser; Type: ACL; Schema: public; Owner: admin
130971 --
130972
130973 REVOKE ALL ON TABLE msguser FROM PUBLIC;
130974 REVOKE ALL ON TABLE msguser FROM admin;
130975 GRANT ALL ON TABLE msguser TO admin;
130976 GRANT ALL ON TABLE msguser TO xtrole;
130977
130978
130979 --
130980 -- TOC entry 10010 (class 0 OID 0)
130981 -- Dependencies: 692
130982 -- Name: msguser_msguser_id_seq; Type: ACL; Schema: public; Owner: admin
130983 --
130984
130985 REVOKE ALL ON SEQUENCE msguser_msguser_id_seq FROM PUBLIC;
130986 REVOKE ALL ON SEQUENCE msguser_msguser_id_seq FROM admin;
130987 GRANT ALL ON SEQUENCE msguser_msguser_id_seq TO admin;
130988 GRANT ALL ON SEQUENCE msguser_msguser_id_seq TO xtrole;
130989
130990
130991 --
130992 -- TOC entry 10011 (class 0 OID 0)
130993 -- Dependencies: 693
130994 -- Name: nvend_nvend_id_seq; Type: ACL; Schema: public; Owner: admin
130995 --
130996
130997 REVOKE ALL ON SEQUENCE nvend_nvend_id_seq FROM PUBLIC;
130998 REVOKE ALL ON SEQUENCE nvend_nvend_id_seq FROM admin;
130999 GRANT ALL ON SEQUENCE nvend_nvend_id_seq TO admin;
131000 GRANT ALL ON SEQUENCE nvend_nvend_id_seq TO xtrole;
131001
131002
131003 --
131004 -- TOC entry 10014 (class 0 OID 0)
131005 -- Dependencies: 694
131006 -- Name: obsolete_tax; Type: ACL; Schema: public; Owner: admin
131007 --
131008
131009 REVOKE ALL ON TABLE obsolete_tax FROM PUBLIC;
131010 REVOKE ALL ON TABLE obsolete_tax FROM admin;
131011 GRANT ALL ON TABLE obsolete_tax TO admin;
131012 GRANT ALL ON TABLE obsolete_tax TO xtrole;
131013
131014
131015 --
131016 -- TOC entry 10016 (class 0 OID 0)
131017 -- Dependencies: 695
131018 -- Name: ophead_ophead_id_seq; Type: ACL; Schema: public; Owner: admin
131019 --
131020
131021 REVOKE ALL ON SEQUENCE ophead_ophead_id_seq FROM PUBLIC;
131022 REVOKE ALL ON SEQUENCE ophead_ophead_id_seq FROM admin;
131023 GRANT ALL ON SEQUENCE ophead_ophead_id_seq TO admin;
131024 GRANT ALL ON SEQUENCE ophead_ophead_id_seq TO xtrole;
131025
131026
131027 --
131028 -- TOC entry 10018 (class 0 OID 0)
131029 -- Dependencies: 696
131030 -- Name: opsource; Type: ACL; Schema: public; Owner: admin
131031 --
131032
131033 REVOKE ALL ON TABLE opsource FROM PUBLIC;
131034 REVOKE ALL ON TABLE opsource FROM admin;
131035 GRANT ALL ON TABLE opsource TO admin;
131036 GRANT ALL ON TABLE opsource TO xtrole;
131037
131038
131039 --
131040 -- TOC entry 10020 (class 0 OID 0)
131041 -- Dependencies: 697
131042 -- Name: opsource_opsource_id_seq; Type: ACL; Schema: public; Owner: admin
131043 --
131044
131045 REVOKE ALL ON SEQUENCE opsource_opsource_id_seq FROM PUBLIC;
131046 REVOKE ALL ON SEQUENCE opsource_opsource_id_seq FROM admin;
131047 GRANT ALL ON SEQUENCE opsource_opsource_id_seq TO admin;
131048 GRANT ALL ON SEQUENCE opsource_opsource_id_seq TO xtrole;
131049
131050
131051 --
131052 -- TOC entry 10022 (class 0 OID 0)
131053 -- Dependencies: 698
131054 -- Name: opstage; Type: ACL; Schema: public; Owner: admin
131055 --
131056
131057 REVOKE ALL ON TABLE opstage FROM PUBLIC;
131058 REVOKE ALL ON TABLE opstage FROM admin;
131059 GRANT ALL ON TABLE opstage TO admin;
131060 GRANT ALL ON TABLE opstage TO xtrole;
131061
131062
131063 --
131064 -- TOC entry 10024 (class 0 OID 0)
131065 -- Dependencies: 699
131066 -- Name: opstage_opstage_id_seq; Type: ACL; Schema: public; Owner: admin
131067 --
131068
131069 REVOKE ALL ON SEQUENCE opstage_opstage_id_seq FROM PUBLIC;
131070 REVOKE ALL ON SEQUENCE opstage_opstage_id_seq FROM admin;
131071 GRANT ALL ON SEQUENCE opstage_opstage_id_seq TO admin;
131072 GRANT ALL ON SEQUENCE opstage_opstage_id_seq TO xtrole;
131073
131074
131075 --
131076 -- TOC entry 10026 (class 0 OID 0)
131077 -- Dependencies: 700
131078 -- Name: optype; Type: ACL; Schema: public; Owner: admin
131079 --
131080
131081 REVOKE ALL ON TABLE optype FROM PUBLIC;
131082 REVOKE ALL ON TABLE optype FROM admin;
131083 GRANT ALL ON TABLE optype TO admin;
131084 GRANT ALL ON TABLE optype TO xtrole;
131085
131086
131087 --
131088 -- TOC entry 10028 (class 0 OID 0)
131089 -- Dependencies: 701
131090 -- Name: optype_optype_id_seq; Type: ACL; Schema: public; Owner: admin
131091 --
131092
131093 REVOKE ALL ON SEQUENCE optype_optype_id_seq FROM PUBLIC;
131094 REVOKE ALL ON SEQUENCE optype_optype_id_seq FROM admin;
131095 GRANT ALL ON SEQUENCE optype_optype_id_seq TO admin;
131096 GRANT ALL ON SEQUENCE optype_optype_id_seq TO xtrole;
131097
131098
131099 --
131100 -- TOC entry 10030 (class 0 OID 0)
131101 -- Dependencies: 702
131102 -- Name: orderhead; Type: ACL; Schema: public; Owner: admin
131103 --
131104
131105 REVOKE ALL ON TABLE orderhead FROM PUBLIC;
131106 REVOKE ALL ON TABLE orderhead FROM admin;
131107 GRANT ALL ON TABLE orderhead TO admin;
131108 GRANT ALL ON TABLE orderhead TO xtrole;
131109
131110
131111 --
131112 -- TOC entry 10032 (class 0 OID 0)
131113 -- Dependencies: 703
131114 -- Name: orderitem; Type: ACL; Schema: public; Owner: admin
131115 --
131116
131117 REVOKE ALL ON TABLE orderitem FROM PUBLIC;
131118 REVOKE ALL ON TABLE orderitem FROM admin;
131119 GRANT ALL ON TABLE orderitem TO admin;
131120 GRANT ALL ON TABLE orderitem TO xtrole;
131121
131122
131123 --
131124 -- TOC entry 10034 (class 0 OID 0)
131125 -- Dependencies: 704
131126 -- Name: orderseq; Type: ACL; Schema: public; Owner: admin
131127 --
131128
131129 REVOKE ALL ON TABLE orderseq FROM PUBLIC;
131130 REVOKE ALL ON TABLE orderseq FROM admin;
131131 GRANT ALL ON TABLE orderseq TO admin;
131132 GRANT ALL ON TABLE orderseq TO xtrole;
131133
131134
131135 --
131136 -- TOC entry 10035 (class 0 OID 0)
131137 -- Dependencies: 705
131138 -- Name: orderseq_orderseq_id_seq; Type: ACL; Schema: public; Owner: admin
131139 --
131140
131141 REVOKE ALL ON SEQUENCE orderseq_orderseq_id_seq FROM PUBLIC;
131142 REVOKE ALL ON SEQUENCE orderseq_orderseq_id_seq FROM admin;
131143 GRANT ALL ON SEQUENCE orderseq_orderseq_id_seq TO admin;
131144 GRANT ALL ON SEQUENCE orderseq_orderseq_id_seq TO xtrole;
131145
131146
131147 --
131148 -- TOC entry 10037 (class 0 OID 0)
131149 -- Dependencies: 706
131150 -- Name: pack; Type: ACL; Schema: public; Owner: admin
131151 --
131152
131153 REVOKE ALL ON TABLE pack FROM PUBLIC;
131154 REVOKE ALL ON TABLE pack FROM admin;
131155 GRANT ALL ON TABLE pack TO admin;
131156 GRANT ALL ON TABLE pack TO xtrole;
131157
131158
131159 --
131160 -- TOC entry 10039 (class 0 OID 0)
131161 -- Dependencies: 707
131162 -- Name: pack_pack_id_seq; Type: ACL; Schema: public; Owner: admin
131163 --
131164
131165 REVOKE ALL ON SEQUENCE pack_pack_id_seq FROM PUBLIC;
131166 REVOKE ALL ON SEQUENCE pack_pack_id_seq FROM admin;
131167 GRANT ALL ON SEQUENCE pack_pack_id_seq TO admin;
131168 GRANT ALL ON SEQUENCE pack_pack_id_seq TO xtrole;
131169
131170
131171 --
131172 -- TOC entry 10041 (class 0 OID 0)
131173 -- Dependencies: 708
131174 -- Name: payaropen; Type: ACL; Schema: public; Owner: admin
131175 --
131176
131177 REVOKE ALL ON TABLE payaropen FROM PUBLIC;
131178 REVOKE ALL ON TABLE payaropen FROM admin;
131179 GRANT ALL ON TABLE payaropen TO admin;
131180 GRANT ALL ON TABLE payaropen TO xtrole;
131181
131182
131183 --
131184 -- TOC entry 10043 (class 0 OID 0)
131185 -- Dependencies: 709
131186 -- Name: payco; Type: ACL; Schema: public; Owner: admin
131187 --
131188
131189 REVOKE ALL ON TABLE payco FROM PUBLIC;
131190 REVOKE ALL ON TABLE payco FROM admin;
131191 GRANT ALL ON TABLE payco TO admin;
131192 GRANT ALL ON TABLE payco TO xtrole;
131193
131194
131195 --
131196 -- TOC entry 10045 (class 0 OID 0)
131197 -- Dependencies: 710
131198 -- Name: period_period_id_seq; Type: ACL; Schema: public; Owner: admin
131199 --
131200
131201 REVOKE ALL ON SEQUENCE period_period_id_seq FROM PUBLIC;
131202 REVOKE ALL ON SEQUENCE period_period_id_seq FROM admin;
131203 GRANT ALL ON SEQUENCE period_period_id_seq TO admin;
131204 GRANT ALL ON SEQUENCE period_period_id_seq TO xtrole;
131205
131206
131207 --
131208 -- TOC entry 10049 (class 0 OID 0)
131209 -- Dependencies: 711
131210 -- Name: pkgdep; Type: ACL; Schema: public; Owner: admin
131211 --
131212
131213 REVOKE ALL ON TABLE pkgdep FROM PUBLIC;
131214 REVOKE ALL ON TABLE pkgdep FROM admin;
131215 GRANT ALL ON TABLE pkgdep TO admin;
131216 GRANT ALL ON TABLE pkgdep TO xtrole;
131217
131218
131219 --
131220 -- TOC entry 10051 (class 0 OID 0)
131221 -- Dependencies: 712
131222 -- Name: pkgdep_pkgdep_id_seq; Type: ACL; Schema: public; Owner: admin
131223 --
131224
131225 REVOKE ALL ON SEQUENCE pkgdep_pkgdep_id_seq FROM PUBLIC;
131226 REVOKE ALL ON SEQUENCE pkgdep_pkgdep_id_seq FROM admin;
131227 GRANT ALL ON SEQUENCE pkgdep_pkgdep_id_seq TO admin;
131228 GRANT ALL ON SEQUENCE pkgdep_pkgdep_id_seq TO xtrole;
131229
131230
131231 --
131232 -- TOC entry 10054 (class 0 OID 0)
131233 -- Dependencies: 713
131234 -- Name: pkghead; Type: ACL; Schema: public; Owner: admin
131235 --
131236
131237 REVOKE ALL ON TABLE pkghead FROM PUBLIC;
131238 REVOKE ALL ON TABLE pkghead FROM admin;
131239 GRANT ALL ON TABLE pkghead TO admin;
131240 GRANT ALL ON TABLE pkghead TO xtrole;
131241
131242
131243 --
131244 -- TOC entry 10056 (class 0 OID 0)
131245 -- Dependencies: 714
131246 -- Name: pkghead_pkghead_id_seq; Type: ACL; Schema: public; Owner: admin
131247 --
131248
131249 REVOKE ALL ON SEQUENCE pkghead_pkghead_id_seq FROM PUBLIC;
131250 REVOKE ALL ON SEQUENCE pkghead_pkghead_id_seq FROM admin;
131251 GRANT ALL ON SEQUENCE pkghead_pkghead_id_seq TO admin;
131252 GRANT ALL ON SEQUENCE pkghead_pkghead_id_seq TO xtrole;
131253
131254
131255 --
131256 -- TOC entry 10058 (class 0 OID 0)
131257 -- Dependencies: 715
131258 -- Name: pkgitem; Type: ACL; Schema: public; Owner: admin
131259 --
131260
131261 REVOKE ALL ON TABLE pkgitem FROM PUBLIC;
131262 REVOKE ALL ON TABLE pkgitem FROM admin;
131263 GRANT ALL ON TABLE pkgitem TO admin;
131264 GRANT ALL ON TABLE pkgitem TO xtrole;
131265
131266
131267 --
131268 -- TOC entry 10060 (class 0 OID 0)
131269 -- Dependencies: 716
131270 -- Name: pkgitem_pkgitem_id_seq; Type: ACL; Schema: public; Owner: admin
131271 --
131272
131273 REVOKE ALL ON SEQUENCE pkgitem_pkgitem_id_seq FROM PUBLIC;
131274 REVOKE ALL ON SEQUENCE pkgitem_pkgitem_id_seq FROM admin;
131275 GRANT ALL ON SEQUENCE pkgitem_pkgitem_id_seq TO admin;
131276 GRANT ALL ON SEQUENCE pkgitem_pkgitem_id_seq TO xtrole;
131277
131278
131279 --
131280 -- TOC entry 10061 (class 0 OID 0)
131281 -- Dependencies: 717
131282 -- Name: plancode_plancode_id_seq; Type: ACL; Schema: public; Owner: admin
131283 --
131284
131285 REVOKE ALL ON SEQUENCE plancode_plancode_id_seq FROM PUBLIC;
131286 REVOKE ALL ON SEQUENCE plancode_plancode_id_seq FROM admin;
131287 GRANT ALL ON SEQUENCE plancode_plancode_id_seq TO admin;
131288 GRANT ALL ON SEQUENCE plancode_plancode_id_seq TO xtrole;
131289
131290
131291 --
131292 -- TOC entry 10062 (class 0 OID 0)
131293 -- Dependencies: 718
131294 -- Name: planord_planord_id_seq; Type: ACL; Schema: public; Owner: admin
131295 --
131296
131297 REVOKE ALL ON SEQUENCE planord_planord_id_seq FROM PUBLIC;
131298 REVOKE ALL ON SEQUENCE planord_planord_id_seq FROM admin;
131299 GRANT ALL ON SEQUENCE planord_planord_id_seq TO admin;
131300 GRANT ALL ON SEQUENCE planord_planord_id_seq TO xtrole;
131301
131302
131303 --
131304 -- TOC entry 10063 (class 0 OID 0)
131305 -- Dependencies: 719
131306 -- Name: pohead_pohead_id_seq; Type: ACL; Schema: public; Owner: admin
131307 --
131308
131309 REVOKE ALL ON SEQUENCE pohead_pohead_id_seq FROM PUBLIC;
131310 REVOKE ALL ON SEQUENCE pohead_pohead_id_seq FROM admin;
131311 GRANT ALL ON SEQUENCE pohead_pohead_id_seq TO admin;
131312 GRANT ALL ON SEQUENCE pohead_pohead_id_seq TO xtrole;
131313
131314
131315 --
131316 -- TOC entry 10064 (class 0 OID 0)
131317 -- Dependencies: 720
131318 -- Name: poitem_poitem_id_seq; Type: ACL; Schema: public; Owner: admin
131319 --
131320
131321 REVOKE ALL ON SEQUENCE poitem_poitem_id_seq FROM PUBLIC;
131322 REVOKE ALL ON SEQUENCE poitem_poitem_id_seq FROM admin;
131323 GRANT ALL ON SEQUENCE poitem_poitem_id_seq TO admin;
131324 GRANT ALL ON SEQUENCE poitem_poitem_id_seq TO xtrole;
131325
131326
131327 --
131328 -- TOC entry 10066 (class 0 OID 0)
131329 -- Dependencies: 721
131330 -- Name: recv; Type: ACL; Schema: public; Owner: admin
131331 --
131332
131333 REVOKE ALL ON TABLE recv FROM PUBLIC;
131334 REVOKE ALL ON TABLE recv FROM admin;
131335 GRANT ALL ON TABLE recv TO admin;
131336 GRANT ALL ON TABLE recv TO xtrole;
131337
131338
131339 --
131340 -- TOC entry 10067 (class 0 OID 0)
131341 -- Dependencies: 722
131342 -- Name: porecv; Type: ACL; Schema: public; Owner: admin
131343 --
131344
131345 REVOKE ALL ON TABLE porecv FROM PUBLIC;
131346 REVOKE ALL ON TABLE porecv FROM admin;
131347 GRANT ALL ON TABLE porecv TO admin;
131348 GRANT ALL ON TABLE porecv TO xtrole;
131349
131350
131351 --
131352 -- TOC entry 10068 (class 0 OID 0)
131353 -- Dependencies: 723
131354 -- Name: porecv_porecv_id_seq; Type: ACL; Schema: public; Owner: admin
131355 --
131356
131357 REVOKE ALL ON SEQUENCE porecv_porecv_id_seq FROM PUBLIC;
131358 REVOKE ALL ON SEQUENCE porecv_porecv_id_seq FROM admin;
131359 GRANT ALL ON SEQUENCE porecv_porecv_id_seq TO admin;
131360 GRANT ALL ON SEQUENCE porecv_porecv_id_seq TO xtrole;
131361
131362
131363 --
131364 -- TOC entry 10088 (class 0 OID 0)
131365 -- Dependencies: 724
131366 -- Name: poreject; Type: ACL; Schema: public; Owner: admin
131367 --
131368
131369 REVOKE ALL ON TABLE poreject FROM PUBLIC;
131370 REVOKE ALL ON TABLE poreject FROM admin;
131371 GRANT ALL ON TABLE poreject TO admin;
131372 GRANT ALL ON TABLE poreject TO xtrole;
131373
131374
131375 --
131376 -- TOC entry 10089 (class 0 OID 0)
131377 -- Dependencies: 725
131378 -- Name: poreject_poreject_id_seq; Type: ACL; Schema: public; Owner: admin
131379 --
131380
131381 REVOKE ALL ON SEQUENCE poreject_poreject_id_seq FROM PUBLIC;
131382 REVOKE ALL ON SEQUENCE poreject_poreject_id_seq FROM admin;
131383 GRANT ALL ON SEQUENCE poreject_poreject_id_seq TO admin;
131384 GRANT ALL ON SEQUENCE poreject_poreject_id_seq TO xtrole;
131385
131386
131387 --
131388 -- TOC entry 10091 (class 0 OID 0)
131389 -- Dependencies: 726
131390 -- Name: potype; Type: ACL; Schema: public; Owner: admin
131391 --
131392
131393 REVOKE ALL ON TABLE potype FROM PUBLIC;
131394 REVOKE ALL ON TABLE potype FROM admin;
131395 GRANT ALL ON TABLE potype TO admin;
131396 GRANT ALL ON TABLE potype TO xtrole;
131397
131398
131399 --
131400 -- TOC entry 10093 (class 0 OID 0)
131401 -- Dependencies: 727
131402 -- Name: potype_potype_id_seq; Type: ACL; Schema: public; Owner: admin
131403 --
131404
131405 REVOKE ALL ON SEQUENCE potype_potype_id_seq FROM PUBLIC;
131406 REVOKE ALL ON SEQUENCE potype_potype_id_seq FROM admin;
131407 GRANT ALL ON SEQUENCE potype_potype_id_seq TO admin;
131408 GRANT ALL ON SEQUENCE potype_potype_id_seq TO xtrole;
131409
131410
131411 --
131412 -- TOC entry 10095 (class 0 OID 0)
131413 -- Dependencies: 728
131414 -- Name: pr; Type: ACL; Schema: public; Owner: admin
131415 --
131416
131417 REVOKE ALL ON TABLE pr FROM PUBLIC;
131418 REVOKE ALL ON TABLE pr FROM admin;
131419 GRANT ALL ON TABLE pr TO admin;
131420 GRANT ALL ON TABLE pr TO xtrole;
131421
131422
131423 --
131424 -- TOC entry 10096 (class 0 OID 0)
131425 -- Dependencies: 729
131426 -- Name: pr_pr_id_seq; Type: ACL; Schema: public; Owner: admin
131427 --
131428
131429 REVOKE ALL ON SEQUENCE pr_pr_id_seq FROM PUBLIC;
131430 REVOKE ALL ON SEQUENCE pr_pr_id_seq FROM admin;
131431 GRANT ALL ON SEQUENCE pr_pr_id_seq TO admin;
131432 GRANT ALL ON SEQUENCE pr_pr_id_seq TO xtrole;
131433
131434
131435 --
131436 -- TOC entry 10098 (class 0 OID 0)
131437 -- Dependencies: 730
131438 -- Name: prftcntr; Type: ACL; Schema: public; Owner: admin
131439 --
131440
131441 REVOKE ALL ON TABLE prftcntr FROM PUBLIC;
131442 REVOKE ALL ON TABLE prftcntr FROM admin;
131443 GRANT ALL ON TABLE prftcntr TO admin;
131444 GRANT ALL ON TABLE prftcntr TO xtrole;
131445
131446
131447 --
131448 -- TOC entry 10100 (class 0 OID 0)
131449 -- Dependencies: 731
131450 -- Name: prftcntr_prftcntr_id_seq; Type: ACL; Schema: public; Owner: admin
131451 --
131452
131453 REVOKE ALL ON SEQUENCE prftcntr_prftcntr_id_seq FROM PUBLIC;
131454 REVOKE ALL ON SEQUENCE prftcntr_prftcntr_id_seq FROM admin;
131455 GRANT ALL ON SEQUENCE prftcntr_prftcntr_id_seq TO admin;
131456 GRANT ALL ON SEQUENCE prftcntr_prftcntr_id_seq TO xtrole;
131457
131458
131459 --
131460 -- TOC entry 10102 (class 0 OID 0)
131461 -- Dependencies: 732
131462 -- Name: usrgrp; Type: ACL; Schema: public; Owner: admin
131463 --
131464
131465 REVOKE ALL ON TABLE usrgrp FROM PUBLIC;
131466 REVOKE ALL ON TABLE usrgrp FROM admin;
131467 GRANT ALL ON TABLE usrgrp TO admin;
131468 GRANT ALL ON TABLE usrgrp TO xtrole;
131469
131470
131471 --
131472 -- TOC entry 10104 (class 0 OID 0)
131473 -- Dependencies: 733
131474 -- Name: usrpriv; Type: ACL; Schema: public; Owner: admin
131475 --
131476
131477 REVOKE ALL ON TABLE usrpriv FROM PUBLIC;
131478 REVOKE ALL ON TABLE usrpriv FROM admin;
131479 GRANT ALL ON TABLE usrpriv TO admin;
131480 GRANT ALL ON TABLE usrpriv TO xtrole;
131481
131482
131483 --
131484 -- TOC entry 10105 (class 0 OID 0)
131485 -- Dependencies: 734
131486 -- Name: privgranted; Type: ACL; Schema: public; Owner: admin
131487 --
131488
131489 REVOKE ALL ON TABLE privgranted FROM PUBLIC;
131490 REVOKE ALL ON TABLE privgranted FROM admin;
131491 GRANT ALL ON TABLE privgranted TO admin;
131492 GRANT ALL ON TABLE privgranted TO xtrole;
131493
131494
131495 --
131496 -- TOC entry 10107 (class 0 OID 0)
131497 -- Dependencies: 735
131498 -- Name: prj_prj_id_seq; Type: ACL; Schema: public; Owner: admin
131499 --
131500
131501 REVOKE ALL ON SEQUENCE prj_prj_id_seq FROM PUBLIC;
131502 REVOKE ALL ON SEQUENCE prj_prj_id_seq FROM admin;
131503 GRANT ALL ON SEQUENCE prj_prj_id_seq TO admin;
131504 GRANT ALL ON SEQUENCE prj_prj_id_seq TO xtrole;
131505
131506
131507 --
131508 -- TOC entry 10109 (class 0 OID 0)
131509 -- Dependencies: 736
131510 -- Name: prjtask_prjtask_id_seq; Type: ACL; Schema: public; Owner: admin
131511 --
131512
131513 REVOKE ALL ON SEQUENCE prjtask_prjtask_id_seq FROM PUBLIC;
131514 REVOKE ALL ON SEQUENCE prjtask_prjtask_id_seq FROM admin;
131515 GRANT ALL ON SEQUENCE prjtask_prjtask_id_seq TO admin;
131516 GRANT ALL ON SEQUENCE prjtask_prjtask_id_seq TO xtrole;
131517
131518
131519 --
131520 -- TOC entry 10111 (class 0 OID 0)
131521 -- Dependencies: 737
131522 -- Name: prjtaskuser; Type: ACL; Schema: public; Owner: admin
131523 --
131524
131525 REVOKE ALL ON TABLE prjtaskuser FROM PUBLIC;
131526 REVOKE ALL ON TABLE prjtaskuser FROM admin;
131527 GRANT ALL ON TABLE prjtaskuser TO admin;
131528 GRANT ALL ON TABLE prjtaskuser TO xtrole;
131529
131530
131531 --
131532 -- TOC entry 10113 (class 0 OID 0)
131533 -- Dependencies: 738
131534 -- Name: prjtaskuser_prjtaskuser_id_seq; Type: ACL; Schema: public; Owner: admin
131535 --
131536
131537 REVOKE ALL ON SEQUENCE prjtaskuser_prjtaskuser_id_seq FROM PUBLIC;
131538 REVOKE ALL ON SEQUENCE prjtaskuser_prjtaskuser_id_seq FROM admin;
131539 GRANT ALL ON SEQUENCE prjtaskuser_prjtaskuser_id_seq TO admin;
131540 GRANT ALL ON SEQUENCE prjtaskuser_prjtaskuser_id_seq TO xtrole;
131541
131542
131543 --
131544 -- TOC entry 10114 (class 0 OID 0)
131545 -- Dependencies: 739
131546 -- Name: prjtype; Type: ACL; Schema: public; Owner: admin
131547 --
131548
131549 REVOKE ALL ON TABLE prjtype FROM PUBLIC;
131550 REVOKE ALL ON TABLE prjtype FROM admin;
131551 GRANT ALL ON TABLE prjtype TO admin;
131552 GRANT ALL ON TABLE prjtype TO xtrole;
131553
131554
131555 --
131556 -- TOC entry 10116 (class 0 OID 0)
131557 -- Dependencies: 741
131558 -- Name: prodcat_prodcat_id_seq; Type: ACL; Schema: public; Owner: admin
131559 --
131560
131561 REVOKE ALL ON SEQUENCE prodcat_prodcat_id_seq FROM PUBLIC;
131562 REVOKE ALL ON SEQUENCE prodcat_prodcat_id_seq FROM admin;
131563 GRANT ALL ON SEQUENCE prodcat_prodcat_id_seq TO admin;
131564 GRANT ALL ON SEQUENCE prodcat_prodcat_id_seq TO xtrole;
131565
131566
131567 --
131568 -- TOC entry 10124 (class 0 OID 0)
131569 -- Dependencies: 742
131570 -- Name: qryhead; Type: ACL; Schema: public; Owner: admin
131571 --
131572
131573 REVOKE ALL ON TABLE qryhead FROM PUBLIC;
131574 REVOKE ALL ON TABLE qryhead FROM admin;
131575 GRANT ALL ON TABLE qryhead TO admin;
131576 GRANT ALL ON TABLE qryhead TO xtrole;
131577
131578
131579 --
131580 -- TOC entry 10126 (class 0 OID 0)
131581 -- Dependencies: 743
131582 -- Name: qryhead_qryhead_id_seq; Type: ACL; Schema: public; Owner: admin
131583 --
131584
131585 REVOKE ALL ON SEQUENCE qryhead_qryhead_id_seq FROM PUBLIC;
131586 REVOKE ALL ON SEQUENCE qryhead_qryhead_id_seq FROM admin;
131587 GRANT ALL ON SEQUENCE qryhead_qryhead_id_seq TO admin;
131588 GRANT ALL ON SEQUENCE qryhead_qryhead_id_seq TO xtrole;
131589
131590
131591 --
131592 -- TOC entry 10137 (class 0 OID 0)
131593 -- Dependencies: 744
131594 -- Name: qryitem; Type: ACL; Schema: public; Owner: admin
131595 --
131596
131597 REVOKE ALL ON TABLE qryitem FROM PUBLIC;
131598 REVOKE ALL ON TABLE qryitem FROM admin;
131599 GRANT ALL ON TABLE qryitem TO admin;
131600 GRANT ALL ON TABLE qryitem TO xtrole;
131601
131602
131603 --
131604 -- TOC entry 10139 (class 0 OID 0)
131605 -- Dependencies: 745
131606 -- Name: qryitem_qryitem_id_seq; Type: ACL; Schema: public; Owner: admin
131607 --
131608
131609 REVOKE ALL ON SEQUENCE qryitem_qryitem_id_seq FROM PUBLIC;
131610 REVOKE ALL ON SEQUENCE qryitem_qryitem_id_seq FROM admin;
131611 GRANT ALL ON SEQUENCE qryitem_qryitem_id_seq TO admin;
131612 GRANT ALL ON SEQUENCE qryitem_qryitem_id_seq TO xtrole;
131613
131614
131615 --
131616 -- TOC entry 10140 (class 0 OID 0)
131617 -- Dependencies: 746
131618 -- Name: quhead_quhead_id_seq; Type: ACL; Schema: public; Owner: admin
131619 --
131620
131621 REVOKE ALL ON SEQUENCE quhead_quhead_id_seq FROM PUBLIC;
131622 REVOKE ALL ON SEQUENCE quhead_quhead_id_seq FROM admin;
131623 GRANT ALL ON SEQUENCE quhead_quhead_id_seq TO admin;
131624 GRANT ALL ON SEQUENCE quhead_quhead_id_seq TO xtrole;
131625
131626
131627 --
131628 -- TOC entry 10141 (class 0 OID 0)
131629 -- Dependencies: 747
131630 -- Name: quitem_quitem_id_seq; Type: ACL; Schema: public; Owner: admin
131631 --
131632
131633 REVOKE ALL ON SEQUENCE quitem_quitem_id_seq FROM PUBLIC;
131634 REVOKE ALL ON SEQUENCE quitem_quitem_id_seq FROM admin;
131635 GRANT ALL ON SEQUENCE quitem_quitem_id_seq TO admin;
131636 GRANT ALL ON SEQUENCE quitem_quitem_id_seq TO xtrole;
131637
131638
131639 --
131640 -- TOC entry 10143 (class 0 OID 0)
131641 -- Dependencies: 748
131642 -- Name: rcalitem; Type: ACL; Schema: public; Owner: admin
131643 --
131644
131645 REVOKE ALL ON TABLE rcalitem FROM PUBLIC;
131646 REVOKE ALL ON TABLE rcalitem FROM admin;
131647 GRANT ALL ON TABLE rcalitem TO admin;
131648 GRANT ALL ON TABLE rcalitem TO xtrole;
131649
131650
131651 --
131652 -- TOC entry 10154 (class 0 OID 0)
131653 -- Dependencies: 749
131654 -- Name: recur; Type: ACL; Schema: public; Owner: admin
131655 --
131656
131657 REVOKE ALL ON TABLE recur FROM PUBLIC;
131658 REVOKE ALL ON TABLE recur FROM admin;
131659 GRANT ALL ON TABLE recur TO admin;
131660 GRANT ALL ON TABLE recur TO xtrole;
131661
131662
131663 --
131664 -- TOC entry 10156 (class 0 OID 0)
131665 -- Dependencies: 750
131666 -- Name: recur_recur_id_seq; Type: ACL; Schema: public; Owner: admin
131667 --
131668
131669 REVOKE ALL ON SEQUENCE recur_recur_id_seq FROM PUBLIC;
131670 REVOKE ALL ON SEQUENCE recur_recur_id_seq FROM admin;
131671 GRANT ALL ON SEQUENCE recur_recur_id_seq TO admin;
131672 GRANT ALL ON SEQUENCE recur_recur_id_seq TO xtrole;
131673
131674
131675 --
131676 -- TOC entry 10167 (class 0 OID 0)
131677 -- Dependencies: 751
131678 -- Name: recurtype; Type: ACL; Schema: public; Owner: admin
131679 --
131680
131681 REVOKE ALL ON TABLE recurtype FROM PUBLIC;
131682 REVOKE ALL ON TABLE recurtype FROM admin;
131683 GRANT ALL ON TABLE recurtype TO admin;
131684 GRANT ALL ON TABLE recurtype TO xtrole;
131685
131686
131687 --
131688 -- TOC entry 10169 (class 0 OID 0)
131689 -- Dependencies: 752
131690 -- Name: recurtype_recurtype_id_seq; Type: ACL; Schema: public; Owner: admin
131691 --
131692
131693 REVOKE ALL ON SEQUENCE recurtype_recurtype_id_seq FROM PUBLIC;
131694 REVOKE ALL ON SEQUENCE recurtype_recurtype_id_seq FROM admin;
131695 GRANT ALL ON SEQUENCE recurtype_recurtype_id_seq TO admin;
131696 GRANT ALL ON SEQUENCE recurtype_recurtype_id_seq TO xtrole;
131697
131698
131699 --
131700 -- TOC entry 10171 (class 0 OID 0)
131701 -- Dependencies: 753
131702 -- Name: recv_recv_id_seq; Type: ACL; Schema: public; Owner: admin
131703 --
131704
131705 REVOKE ALL ON SEQUENCE recv_recv_id_seq FROM PUBLIC;
131706 REVOKE ALL ON SEQUENCE recv_recv_id_seq FROM admin;
131707 GRANT ALL ON SEQUENCE recv_recv_id_seq TO admin;
131708 GRANT ALL ON SEQUENCE recv_recv_id_seq TO xtrole;
131709
131710
131711 --
131712 -- TOC entry 10172 (class 0 OID 0)
131713 -- Dependencies: 754
131714 -- Name: remitto; Type: ACL; Schema: public; Owner: admin
131715 --
131716
131717 REVOKE ALL ON TABLE remitto FROM PUBLIC;
131718 REVOKE ALL ON TABLE remitto FROM admin;
131719 GRANT ALL ON TABLE remitto TO admin;
131720 GRANT ALL ON TABLE remitto TO xtrole;
131721
131722
131723 --
131724 -- TOC entry 10174 (class 0 OID 0)
131725 -- Dependencies: 755
131726 -- Name: rjctcode; Type: ACL; Schema: public; Owner: admin
131727 --
131728
131729 REVOKE ALL ON TABLE rjctcode FROM PUBLIC;
131730 REVOKE ALL ON TABLE rjctcode FROM admin;
131731 GRANT ALL ON TABLE rjctcode TO admin;
131732 GRANT ALL ON TABLE rjctcode TO xtrole;
131733
131734
131735 --
131736 -- TOC entry 10175 (class 0 OID 0)
131737 -- Dependencies: 756
131738 -- Name: rjctcode_rjctcode_id_seq; Type: ACL; Schema: public; Owner: admin
131739 --
131740
131741 REVOKE ALL ON SEQUENCE rjctcode_rjctcode_id_seq FROM PUBLIC;
131742 REVOKE ALL ON SEQUENCE rjctcode_rjctcode_id_seq FROM admin;
131743 GRANT ALL ON SEQUENCE rjctcode_rjctcode_id_seq TO admin;
131744 GRANT ALL ON SEQUENCE rjctcode_rjctcode_id_seq TO xtrole;
131745
131746
131747 --
131748 -- TOC entry 10177 (class 0 OID 0)
131749 -- Dependencies: 757
131750 -- Name: rsncode_rsncode_id_seq; Type: ACL; Schema: public; Owner: admin
131751 --
131752
131753 REVOKE ALL ON SEQUENCE rsncode_rsncode_id_seq FROM PUBLIC;
131754 REVOKE ALL ON SEQUENCE rsncode_rsncode_id_seq FROM admin;
131755 GRANT ALL ON SEQUENCE rsncode_rsncode_id_seq TO admin;
131756 GRANT ALL ON SEQUENCE rsncode_rsncode_id_seq TO xtrole;
131757
131758
131759 --
131760 -- TOC entry 10179 (class 0 OID 0)
131761 -- Dependencies: 758
131762 -- Name: sale; Type: ACL; Schema: public; Owner: admin
131763 --
131764
131765 REVOKE ALL ON TABLE sale FROM PUBLIC;
131766 REVOKE ALL ON TABLE sale FROM admin;
131767 GRANT ALL ON TABLE sale TO admin;
131768 GRANT ALL ON TABLE sale TO xtrole;
131769
131770
131771 --
131772 -- TOC entry 10180 (class 0 OID 0)
131773 -- Dependencies: 759
131774 -- Name: sale_sale_id_seq; Type: ACL; Schema: public; Owner: admin
131775 --
131776
131777 REVOKE ALL ON SEQUENCE sale_sale_id_seq FROM PUBLIC;
131778 REVOKE ALL ON SEQUENCE sale_sale_id_seq FROM admin;
131779 GRANT ALL ON SEQUENCE sale_sale_id_seq TO admin;
131780 GRANT ALL ON SEQUENCE sale_sale_id_seq TO xtrole;
131781
131782
131783 --
131784 -- TOC entry 10181 (class 0 OID 0)
131785 -- Dependencies: 760
131786 -- Name: salesaccnt_salesaccnt_id_seq; Type: ACL; Schema: public; Owner: admin
131787 --
131788
131789 REVOKE ALL ON SEQUENCE salesaccnt_salesaccnt_id_seq FROM PUBLIC;
131790 REVOKE ALL ON SEQUENCE salesaccnt_salesaccnt_id_seq FROM admin;
131791 GRANT ALL ON SEQUENCE salesaccnt_salesaccnt_id_seq TO admin;
131792 GRANT ALL ON SEQUENCE salesaccnt_salesaccnt_id_seq TO xtrole;
131793
131794
131795 --
131796 -- TOC entry 10183 (class 0 OID 0)
131797 -- Dependencies: 761
131798 -- Name: salescat_salescat_id_seq; Type: ACL; Schema: public; Owner: admin
131799 --
131800
131801 REVOKE ALL ON SEQUENCE salescat_salescat_id_seq FROM PUBLIC;
131802 REVOKE ALL ON SEQUENCE salescat_salescat_id_seq FROM admin;
131803 GRANT ALL ON SEQUENCE salescat_salescat_id_seq TO admin;
131804 GRANT ALL ON SEQUENCE salescat_salescat_id_seq TO xtrole;
131805
131806
131807 --
131808 -- TOC entry 10185 (class 0 OID 0)
131809 -- Dependencies: 762
131810 -- Name: saleshistory; Type: ACL; Schema: public; Owner: admin
131811 --
131812
131813 REVOKE ALL ON TABLE saleshistory FROM PUBLIC;
131814 REVOKE ALL ON TABLE saleshistory FROM admin;
131815 GRANT ALL ON TABLE saleshistory TO admin;
131816 GRANT ALL ON TABLE saleshistory TO xtrole;
131817
131818
131819 --
131820 -- TOC entry 10187 (class 0 OID 0)
131821 -- Dependencies: 763
131822 -- Name: saleshistorymisc; Type: ACL; Schema: public; Owner: admin
131823 --
131824
131825 REVOKE ALL ON TABLE saleshistorymisc FROM PUBLIC;
131826 REVOKE ALL ON TABLE saleshistorymisc FROM admin;
131827 GRANT ALL ON TABLE saleshistorymisc TO admin;
131828 GRANT ALL ON TABLE saleshistorymisc TO xtrole;
131829
131830
131831 --
131832 -- TOC entry 10188 (class 0 OID 0)
131833 -- Dependencies: 764
131834 -- Name: salesrep_salesrep_id_seq; Type: ACL; Schema: public; Owner: admin
131835 --
131836
131837 REVOKE ALL ON SEQUENCE salesrep_salesrep_id_seq FROM PUBLIC;
131838 REVOKE ALL ON SEQUENCE salesrep_salesrep_id_seq FROM admin;
131839 GRANT ALL ON SEQUENCE salesrep_salesrep_id_seq TO admin;
131840 GRANT ALL ON SEQUENCE salesrep_salesrep_id_seq TO xtrole;
131841
131842
131843 --
131844 -- TOC entry 10190 (class 0 OID 0)
131845 -- Dependencies: 765
131846 -- Name: saletype_saletype_id_seq; Type: ACL; Schema: public; Owner: admin
131847 --
131848
131849 REVOKE ALL ON SEQUENCE saletype_saletype_id_seq FROM PUBLIC;
131850 REVOKE ALL ON SEQUENCE saletype_saletype_id_seq FROM admin;
131851 GRANT ALL ON SEQUENCE saletype_saletype_id_seq TO admin;
131852 GRANT ALL ON SEQUENCE saletype_saletype_id_seq TO xtrole;
131853
131854
131855 --
131856 -- TOC entry 10192 (class 0 OID 0)
131857 -- Dependencies: 766
131858 -- Name: schemaord; Type: ACL; Schema: public; Owner: admin
131859 --
131860
131861 REVOKE ALL ON TABLE schemaord FROM PUBLIC;
131862 REVOKE ALL ON TABLE schemaord FROM admin;
131863 GRANT ALL ON TABLE schemaord TO admin;
131864 GRANT ALL ON TABLE schemaord TO xtrole;
131865
131866
131867 --
131868 -- TOC entry 10194 (class 0 OID 0)
131869 -- Dependencies: 767
131870 -- Name: schemaord_schemaord_id_seq; Type: ACL; Schema: public; Owner: admin
131871 --
131872
131873 REVOKE ALL ON SEQUENCE schemaord_schemaord_id_seq FROM PUBLIC;
131874 REVOKE ALL ON SEQUENCE schemaord_schemaord_id_seq FROM admin;
131875 GRANT ALL ON SEQUENCE schemaord_schemaord_id_seq TO admin;
131876 GRANT ALL ON SEQUENCE schemaord_schemaord_id_seq TO xtrole;
131877
131878
131879 --
131880 -- TOC entry 10196 (class 0 OID 0)
131881 -- Dependencies: 768
131882 -- Name: sequence; Type: ACL; Schema: public; Owner: admin
131883 --
131884
131885 REVOKE ALL ON TABLE sequence FROM PUBLIC;
131886 REVOKE ALL ON TABLE sequence FROM admin;
131887 GRANT ALL ON TABLE sequence TO admin;
131888 GRANT ALL ON TABLE sequence TO xtrole;
131889
131890
131891 --
131892 -- TOC entry 10198 (class 0 OID 0)
131893 -- Dependencies: 769
131894 -- Name: shift_shift_id_seq; Type: ACL; Schema: public; Owner: admin
131895 --
131896
131897 REVOKE ALL ON SEQUENCE shift_shift_id_seq FROM PUBLIC;
131898 REVOKE ALL ON SEQUENCE shift_shift_id_seq FROM admin;
131899 GRANT ALL ON SEQUENCE shift_shift_id_seq TO admin;
131900 GRANT ALL ON SEQUENCE shift_shift_id_seq TO xtrole;
131901
131902
131903 --
131904 -- TOC entry 10200 (class 0 OID 0)
131905 -- Dependencies: 770
131906 -- Name: shipchrg_shipchrg_id_seq; Type: ACL; Schema: public; Owner: admin
131907 --
131908
131909 REVOKE ALL ON SEQUENCE shipchrg_shipchrg_id_seq FROM PUBLIC;
131910 REVOKE ALL ON SEQUENCE shipchrg_shipchrg_id_seq FROM admin;
131911 GRANT ALL ON SEQUENCE shipchrg_shipchrg_id_seq TO admin;
131912 GRANT ALL ON SEQUENCE shipchrg_shipchrg_id_seq TO xtrole;
131913
131914
131915 --
131916 -- TOC entry 10202 (class 0 OID 0)
131917 -- Dependencies: 771
131918 -- Name: shipdatasum; Type: ACL; Schema: public; Owner: admin
131919 --
131920
131921 REVOKE ALL ON TABLE shipdatasum FROM PUBLIC;
131922 REVOKE ALL ON TABLE shipdatasum FROM admin;
131923 GRANT ALL ON TABLE shipdatasum TO admin;
131924 GRANT ALL ON TABLE shipdatasum TO xtrole;
131925
131926
131927 --
131928 -- TOC entry 10203 (class 0 OID 0)
131929 -- Dependencies: 772
131930 -- Name: shipform_shipform_id_seq; Type: ACL; Schema: public; Owner: admin
131931 --
131932
131933 REVOKE ALL ON SEQUENCE shipform_shipform_id_seq FROM PUBLIC;
131934 REVOKE ALL ON SEQUENCE shipform_shipform_id_seq FROM admin;
131935 GRANT ALL ON SEQUENCE shipform_shipform_id_seq TO admin;
131936 GRANT ALL ON SEQUENCE shipform_shipform_id_seq TO xtrole;
131937
131938
131939 --
131940 -- TOC entry 10205 (class 0 OID 0)
131941 -- Dependencies: 773
131942 -- Name: shiphead_shiphead_id_seq; Type: ACL; Schema: public; Owner: admin
131943 --
131944
131945 REVOKE ALL ON SEQUENCE shiphead_shiphead_id_seq FROM PUBLIC;
131946 REVOKE ALL ON SEQUENCE shiphead_shiphead_id_seq FROM admin;
131947 GRANT ALL ON SEQUENCE shiphead_shiphead_id_seq TO admin;
131948 GRANT ALL ON SEQUENCE shiphead_shiphead_id_seq TO xtrole;
131949
131950
131951 --
131952 -- TOC entry 10207 (class 0 OID 0)
131953 -- Dependencies: 774
131954 -- Name: shipitem_shipitem_id_seq; Type: ACL; Schema: public; Owner: admin
131955 --
131956
131957 REVOKE ALL ON SEQUENCE shipitem_shipitem_id_seq FROM PUBLIC;
131958 REVOKE ALL ON SEQUENCE shipitem_shipitem_id_seq FROM admin;
131959 GRANT ALL ON SEQUENCE shipitem_shipitem_id_seq TO admin;
131960 GRANT ALL ON SEQUENCE shipitem_shipitem_id_seq TO xtrole;
131961
131962
131963 --
131964 -- TOC entry 10208 (class 0 OID 0)
131965 -- Dependencies: 775
131966 -- Name: shipment_number_seq; Type: ACL; Schema: public; Owner: admin
131967 --
131968
131969 REVOKE ALL ON SEQUENCE shipment_number_seq FROM PUBLIC;
131970 REVOKE ALL ON SEQUENCE shipment_number_seq FROM admin;
131971 GRANT ALL ON SEQUENCE shipment_number_seq TO admin;
131972 GRANT ALL ON SEQUENCE shipment_number_seq TO xtrole;
131973
131974
131975 --
131976 -- TOC entry 10209 (class 0 OID 0)
131977 -- Dependencies: 776
131978 -- Name: shipto; Type: ACL; Schema: public; Owner: admin
131979 --
131980
131981 REVOKE ALL ON TABLE shipto FROM PUBLIC;
131982 REVOKE ALL ON TABLE shipto FROM admin;
131983 GRANT ALL ON TABLE shipto TO admin;
131984 GRANT ALL ON TABLE shipto TO xtrole;
131985
131986
131987 --
131988 -- TOC entry 10210 (class 0 OID 0)
131989 -- Dependencies: 777
131990 -- Name: shipto_shipto_id_seq; Type: ACL; Schema: public; Owner: admin
131991 --
131992
131993 REVOKE ALL ON SEQUENCE shipto_shipto_id_seq FROM PUBLIC;
131994 REVOKE ALL ON SEQUENCE shipto_shipto_id_seq FROM admin;
131995 GRANT ALL ON SEQUENCE shipto_shipto_id_seq TO admin;
131996 GRANT ALL ON SEQUENCE shipto_shipto_id_seq TO xtrole;
131997
131998
131999 --
132000 -- TOC entry 10211 (class 0 OID 0)
132001 -- Dependencies: 778
132002 -- Name: shipvia_shipvia_id_seq; Type: ACL; Schema: public; Owner: admin
132003 --
132004
132005 REVOKE ALL ON SEQUENCE shipvia_shipvia_id_seq FROM PUBLIC;
132006 REVOKE ALL ON SEQUENCE shipvia_shipvia_id_seq FROM admin;
132007 GRANT ALL ON SEQUENCE shipvia_shipvia_id_seq TO admin;
132008 GRANT ALL ON SEQUENCE shipvia_shipvia_id_seq TO xtrole;
132009
132010
132011 --
132012 -- TOC entry 10212 (class 0 OID 0)
132013 -- Dependencies: 779
132014 -- Name: shipzone_shipzone_id_seq; Type: ACL; Schema: public; Owner: admin
132015 --
132016
132017 REVOKE ALL ON SEQUENCE shipzone_shipzone_id_seq FROM PUBLIC;
132018 REVOKE ALL ON SEQUENCE shipzone_shipzone_id_seq FROM admin;
132019 GRANT ALL ON SEQUENCE shipzone_shipzone_id_seq TO admin;
132020 GRANT ALL ON SEQUENCE shipzone_shipzone_id_seq TO xtrole;
132021
132022
132023 --
132024 -- TOC entry 10214 (class 0 OID 0)
132025 -- Dependencies: 780
132026 -- Name: sitetype_sitetype_id_seq; Type: ACL; Schema: public; Owner: admin
132027 --
132028
132029 REVOKE ALL ON SEQUENCE sitetype_sitetype_id_seq FROM PUBLIC;
132030 REVOKE ALL ON SEQUENCE sitetype_sitetype_id_seq FROM admin;
132031 GRANT ALL ON SEQUENCE sitetype_sitetype_id_seq TO admin;
132032 GRANT ALL ON SEQUENCE sitetype_sitetype_id_seq TO xtrole;
132033
132034
132035 --
132036 -- TOC entry 10216 (class 0 OID 0)
132037 -- Dependencies: 781
132038 -- Name: sltrans; Type: ACL; Schema: public; Owner: admin
132039 --
132040
132041 REVOKE ALL ON TABLE sltrans FROM PUBLIC;
132042 REVOKE ALL ON TABLE sltrans FROM admin;
132043 GRANT ALL ON TABLE sltrans TO admin;
132044 GRANT ALL ON TABLE sltrans TO xtrole;
132045
132046
132047 --
132048 -- TOC entry 10218 (class 0 OID 0)
132049 -- Dependencies: 783
132050 -- Name: sopack; Type: ACL; Schema: public; Owner: admin
132051 --
132052
132053 REVOKE ALL ON TABLE sopack FROM PUBLIC;
132054 REVOKE ALL ON TABLE sopack FROM admin;
132055 GRANT ALL ON TABLE sopack TO admin;
132056 GRANT ALL ON TABLE sopack TO xtrole;
132057
132058
132059 --
132060 -- TOC entry 10219 (class 0 OID 0)
132061 -- Dependencies: 784
132062 -- Name: sopack_sopack_id_seq; Type: ACL; Schema: public; Owner: admin
132063 --
132064
132065 REVOKE ALL ON SEQUENCE sopack_sopack_id_seq FROM PUBLIC;
132066 REVOKE ALL ON SEQUENCE sopack_sopack_id_seq FROM admin;
132067 GRANT ALL ON SEQUENCE sopack_sopack_id_seq TO admin;
132068 GRANT ALL ON SEQUENCE sopack_sopack_id_seq TO xtrole;
132069
132070
132071 --
132072 -- TOC entry 10225 (class 0 OID 0)
132073 -- Dependencies: 785
132074 -- Name: source; Type: ACL; Schema: public; Owner: admin
132075 --
132076
132077 REVOKE ALL ON TABLE source FROM PUBLIC;
132078 REVOKE ALL ON TABLE source FROM admin;
132079 GRANT ALL ON TABLE source TO admin;
132080 GRANT ALL ON TABLE source TO xtrole;
132081
132082
132083 --
132084 -- TOC entry 10227 (class 0 OID 0)
132085 -- Dependencies: 786
132086 -- Name: source_source_id_seq; Type: ACL; Schema: public; Owner: admin
132087 --
132088
132089 REVOKE ALL ON SEQUENCE source_source_id_seq FROM PUBLIC;
132090 REVOKE ALL ON SEQUENCE source_source_id_seq FROM admin;
132091 GRANT ALL ON SEQUENCE source_source_id_seq TO admin;
132092 GRANT ALL ON SEQUENCE source_source_id_seq TO xtrole;
132093
132094
132095 --
132096 -- TOC entry 10229 (class 0 OID 0)
132097 -- Dependencies: 787
132098 -- Name: state; Type: ACL; Schema: public; Owner: admin
132099 --
132100
132101 REVOKE ALL ON TABLE state FROM PUBLIC;
132102 REVOKE ALL ON TABLE state FROM admin;
132103 GRANT ALL ON TABLE state TO admin;
132104 GRANT ALL ON TABLE state TO xtrole;
132105
132106
132107 --
132108 -- TOC entry 10231 (class 0 OID 0)
132109 -- Dependencies: 788
132110 -- Name: state_state_id_seq; Type: ACL; Schema: public; Owner: admin
132111 --
132112
132113 REVOKE ALL ON SEQUENCE state_state_id_seq FROM PUBLIC;
132114 REVOKE ALL ON SEQUENCE state_state_id_seq FROM admin;
132115 GRANT ALL ON SEQUENCE state_state_id_seq TO admin;
132116 GRANT ALL ON SEQUENCE state_state_id_seq TO xtrole;
132117
132118
132119 --
132120 -- TOC entry 10232 (class 0 OID 0)
132121 -- Dependencies: 789
132122 -- Name: status; Type: ACL; Schema: public; Owner: admin
132123 --
132124
132125 REVOKE ALL ON TABLE status FROM PUBLIC;
132126 REVOKE ALL ON TABLE status FROM admin;
132127 GRANT ALL ON TABLE status TO admin;
132128 GRANT ALL ON TABLE status TO xtrole;
132129
132130
132131 --
132132 -- TOC entry 10234 (class 0 OID 0)
132133 -- Dependencies: 790
132134 -- Name: status_status_id_seq; Type: ACL; Schema: public; Owner: admin
132135 --
132136
132137 REVOKE ALL ON SEQUENCE status_status_id_seq FROM PUBLIC;
132138 REVOKE ALL ON SEQUENCE status_status_id_seq FROM admin;
132139 GRANT ALL ON SEQUENCE status_status_id_seq TO admin;
132140 GRANT ALL ON SEQUENCE status_status_id_seq TO xtrole;
132141
132142
132143 --
132144 -- TOC entry 10236 (class 0 OID 0)
132145 -- Dependencies: 791
132146 -- Name: stdjrnl; Type: ACL; Schema: public; Owner: admin
132147 --
132148
132149 REVOKE ALL ON TABLE stdjrnl FROM PUBLIC;
132150 REVOKE ALL ON TABLE stdjrnl FROM admin;
132151 GRANT ALL ON TABLE stdjrnl TO admin;
132152 GRANT ALL ON TABLE stdjrnl TO xtrole;
132153
132154
132155 --
132156 -- TOC entry 10238 (class 0 OID 0)
132157 -- Dependencies: 792
132158 -- Name: stdjrnl_stdjrnl_id_seq; Type: ACL; Schema: public; Owner: admin
132159 --
132160
132161 REVOKE ALL ON SEQUENCE stdjrnl_stdjrnl_id_seq FROM PUBLIC;
132162 REVOKE ALL ON SEQUENCE stdjrnl_stdjrnl_id_seq FROM admin;
132163 GRANT ALL ON SEQUENCE stdjrnl_stdjrnl_id_seq TO admin;
132164 GRANT ALL ON SEQUENCE stdjrnl_stdjrnl_id_seq TO xtrole;
132165
132166
132167 --
132168 -- TOC entry 10240 (class 0 OID 0)
132169 -- Dependencies: 793
132170 -- Name: stdjrnlgrp; Type: ACL; Schema: public; Owner: admin
132171 --
132172
132173 REVOKE ALL ON TABLE stdjrnlgrp FROM PUBLIC;
132174 REVOKE ALL ON TABLE stdjrnlgrp FROM admin;
132175 GRANT ALL ON TABLE stdjrnlgrp TO admin;
132176 GRANT ALL ON TABLE stdjrnlgrp TO xtrole;
132177
132178
132179 --
132180 -- TOC entry 10242 (class 0 OID 0)
132181 -- Dependencies: 794
132182 -- Name: stdjrnlgrp_stdjrnlgrp_id_seq; Type: ACL; Schema: public; Owner: admin
132183 --
132184
132185 REVOKE ALL ON SEQUENCE stdjrnlgrp_stdjrnlgrp_id_seq FROM PUBLIC;
132186 REVOKE ALL ON SEQUENCE stdjrnlgrp_stdjrnlgrp_id_seq FROM admin;
132187 GRANT ALL ON SEQUENCE stdjrnlgrp_stdjrnlgrp_id_seq TO admin;
132188 GRANT ALL ON SEQUENCE stdjrnlgrp_stdjrnlgrp_id_seq TO xtrole;
132189
132190
132191 --
132192 -- TOC entry 10244 (class 0 OID 0)
132193 -- Dependencies: 795
132194 -- Name: stdjrnlgrpitem; Type: ACL; Schema: public; Owner: admin
132195 --
132196
132197 REVOKE ALL ON TABLE stdjrnlgrpitem FROM PUBLIC;
132198 REVOKE ALL ON TABLE stdjrnlgrpitem FROM admin;
132199 GRANT ALL ON TABLE stdjrnlgrpitem TO admin;
132200 GRANT ALL ON TABLE stdjrnlgrpitem TO xtrole;
132201
132202
132203 --
132204 -- TOC entry 10246 (class 0 OID 0)
132205 -- Dependencies: 796
132206 -- Name: stdjrnlgrpitem_stdjrnlgrpitem_id_seq; Type: ACL; Schema: public; Owner: admin
132207 --
132208
132209 REVOKE ALL ON SEQUENCE stdjrnlgrpitem_stdjrnlgrpitem_id_seq FROM PUBLIC;
132210 REVOKE ALL ON SEQUENCE stdjrnlgrpitem_stdjrnlgrpitem_id_seq FROM admin;
132211 GRANT ALL ON SEQUENCE stdjrnlgrpitem_stdjrnlgrpitem_id_seq TO admin;
132212 GRANT ALL ON SEQUENCE stdjrnlgrpitem_stdjrnlgrpitem_id_seq TO xtrole;
132213
132214
132215 --
132216 -- TOC entry 10248 (class 0 OID 0)
132217 -- Dependencies: 797
132218 -- Name: stdjrnlitem; Type: ACL; Schema: public; Owner: admin
132219 --
132220
132221 REVOKE ALL ON TABLE stdjrnlitem FROM PUBLIC;
132222 REVOKE ALL ON TABLE stdjrnlitem FROM admin;
132223 GRANT ALL ON TABLE stdjrnlitem TO admin;
132224 GRANT ALL ON TABLE stdjrnlitem TO xtrole;
132225
132226
132227 --
132228 -- TOC entry 10250 (class 0 OID 0)
132229 -- Dependencies: 798
132230 -- Name: stdjrnlitem_stdjrnlitem_id_seq; Type: ACL; Schema: public; Owner: admin
132231 --
132232
132233 REVOKE ALL ON SEQUENCE stdjrnlitem_stdjrnlitem_id_seq FROM PUBLIC;
132234 REVOKE ALL ON SEQUENCE stdjrnlitem_stdjrnlitem_id_seq FROM admin;
132235 GRANT ALL ON SEQUENCE stdjrnlitem_stdjrnlitem_id_seq TO admin;
132236 GRANT ALL ON SEQUENCE stdjrnlitem_stdjrnlitem_id_seq TO xtrole;
132237
132238
132239 --
132240 -- TOC entry 10252 (class 0 OID 0)
132241 -- Dependencies: 799
132242 -- Name: subaccnt; Type: ACL; Schema: public; Owner: admin
132243 --
132244
132245 REVOKE ALL ON TABLE subaccnt FROM PUBLIC;
132246 REVOKE ALL ON TABLE subaccnt FROM admin;
132247 GRANT ALL ON TABLE subaccnt TO admin;
132248 GRANT ALL ON TABLE subaccnt TO xtrole;
132249
132250
132251 --
132252 -- TOC entry 10254 (class 0 OID 0)
132253 -- Dependencies: 800
132254 -- Name: subaccnt_subaccnt_id_seq; Type: ACL; Schema: public; Owner: admin
132255 --
132256
132257 REVOKE ALL ON SEQUENCE subaccnt_subaccnt_id_seq FROM PUBLIC;
132258 REVOKE ALL ON SEQUENCE subaccnt_subaccnt_id_seq FROM admin;
132259 GRANT ALL ON SEQUENCE subaccnt_subaccnt_id_seq TO admin;
132260 GRANT ALL ON SEQUENCE subaccnt_subaccnt_id_seq TO xtrole;
132261
132262
132263 --
132264 -- TOC entry 10256 (class 0 OID 0)
132265 -- Dependencies: 801
132266 -- Name: subaccnttype; Type: ACL; Schema: public; Owner: admin
132267 --
132268
132269 REVOKE ALL ON TABLE subaccnttype FROM PUBLIC;
132270 REVOKE ALL ON TABLE subaccnttype FROM admin;
132271 GRANT ALL ON TABLE subaccnttype TO admin;
132272 GRANT ALL ON TABLE subaccnttype TO xtrole;
132273
132274
132275 --
132276 -- TOC entry 10258 (class 0 OID 0)
132277 -- Dependencies: 802
132278 -- Name: subaccnttype_subaccnttype_id_seq; Type: ACL; Schema: public; Owner: admin
132279 --
132280
132281 REVOKE ALL ON SEQUENCE subaccnttype_subaccnttype_id_seq FROM PUBLIC;
132282 REVOKE ALL ON SEQUENCE subaccnttype_subaccnttype_id_seq FROM admin;
132283 GRANT ALL ON SEQUENCE subaccnttype_subaccnttype_id_seq TO admin;
132284 GRANT ALL ON SEQUENCE subaccnttype_subaccnttype_id_seq TO xtrole;
132285
132286
132287 --
132288 -- TOC entry 10259 (class 0 OID 0)
132289 -- Dependencies: 803
132290 -- Name: tax_tax_id_seq; Type: ACL; Schema: public; Owner: admin
132291 --
132292
132293 REVOKE ALL ON SEQUENCE tax_tax_id_seq FROM PUBLIC;
132294 REVOKE ALL ON SEQUENCE tax_tax_id_seq FROM admin;
132295 GRANT ALL ON SEQUENCE tax_tax_id_seq TO admin;
132296 GRANT ALL ON SEQUENCE tax_tax_id_seq TO xtrole;
132297
132298
132299 --
132300 -- TOC entry 10264 (class 0 OID 0)
132301 -- Dependencies: 804
132302 -- Name: taxass; Type: ACL; Schema: public; Owner: admin
132303 --
132304
132305 REVOKE ALL ON TABLE taxass FROM PUBLIC;
132306 REVOKE ALL ON TABLE taxass FROM admin;
132307 GRANT ALL ON TABLE taxass TO admin;
132308 GRANT ALL ON TABLE taxass TO xtrole;
132309
132310
132311 --
132312 -- TOC entry 10266 (class 0 OID 0)
132313 -- Dependencies: 805
132314 -- Name: taxass_taxass_id_seq; Type: ACL; Schema: public; Owner: admin
132315 --
132316
132317 REVOKE ALL ON SEQUENCE taxass_taxass_id_seq FROM PUBLIC;
132318 REVOKE ALL ON SEQUENCE taxass_taxass_id_seq FROM admin;
132319 GRANT ALL ON SEQUENCE taxass_taxass_id_seq TO admin;
132320 GRANT ALL ON SEQUENCE taxass_taxass_id_seq TO xtrole;
132321
132322
132323 --
132324 -- TOC entry 10268 (class 0 OID 0)
132325 -- Dependencies: 806
132326 -- Name: taxauth_taxauth_id_seq; Type: ACL; Schema: public; Owner: admin
132327 --
132328
132329 REVOKE ALL ON SEQUENCE taxauth_taxauth_id_seq FROM PUBLIC;
132330 REVOKE ALL ON SEQUENCE taxauth_taxauth_id_seq FROM admin;
132331 GRANT ALL ON SEQUENCE taxauth_taxauth_id_seq TO admin;
132332 GRANT ALL ON SEQUENCE taxauth_taxauth_id_seq TO xtrole;
132333
132334
132335 --
132336 -- TOC entry 10274 (class 0 OID 0)
132337 -- Dependencies: 807
132338 -- Name: taxclass; Type: ACL; Schema: public; Owner: admin
132339 --
132340
132341 REVOKE ALL ON TABLE taxclass FROM PUBLIC;
132342 REVOKE ALL ON TABLE taxclass FROM admin;
132343 GRANT ALL ON TABLE taxclass TO admin;
132344 GRANT ALL ON TABLE taxclass TO xtrole;
132345
132346
132347 --
132348 -- TOC entry 10276 (class 0 OID 0)
132349 -- Dependencies: 808
132350 -- Name: taxclass_taxclass_id_seq; Type: ACL; Schema: public; Owner: admin
132351 --
132352
132353 REVOKE ALL ON SEQUENCE taxclass_taxclass_id_seq FROM PUBLIC;
132354 REVOKE ALL ON SEQUENCE taxclass_taxclass_id_seq FROM admin;
132355 GRANT ALL ON SEQUENCE taxclass_taxclass_id_seq TO admin;
132356 GRANT ALL ON SEQUENCE taxclass_taxclass_id_seq TO xtrole;
132357
132358
132359 --
132360 -- TOC entry 10278 (class 0 OID 0)
132361 -- Dependencies: 378
132362 -- Name: taxhist_taxhist_id_seq; Type: ACL; Schema: public; Owner: admin
132363 --
132364
132365 REVOKE ALL ON SEQUENCE taxhist_taxhist_id_seq FROM PUBLIC;
132366 REVOKE ALL ON SEQUENCE taxhist_taxhist_id_seq FROM admin;
132367 GRANT ALL ON SEQUENCE taxhist_taxhist_id_seq TO admin;
132368 GRANT ALL ON SEQUENCE taxhist_taxhist_id_seq TO xtrole;
132369
132370
132371 --
132372 -- TOC entry 10287 (class 0 OID 0)
132373 -- Dependencies: 809
132374 -- Name: taxrate; Type: ACL; Schema: public; Owner: admin
132375 --
132376
132377 REVOKE ALL ON TABLE taxrate FROM PUBLIC;
132378 REVOKE ALL ON TABLE taxrate FROM admin;
132379 GRANT ALL ON TABLE taxrate TO admin;
132380 GRANT ALL ON TABLE taxrate TO xtrole;
132381
132382
132383 --
132384 -- TOC entry 10289 (class 0 OID 0)
132385 -- Dependencies: 810
132386 -- Name: taxrate_taxrate_id_seq; Type: ACL; Schema: public; Owner: admin
132387 --
132388
132389 REVOKE ALL ON SEQUENCE taxrate_taxrate_id_seq FROM PUBLIC;
132390 REVOKE ALL ON SEQUENCE taxrate_taxrate_id_seq FROM admin;
132391 GRANT ALL ON SEQUENCE taxrate_taxrate_id_seq TO admin;
132392 GRANT ALL ON SEQUENCE taxrate_taxrate_id_seq TO xtrole;
132393
132394
132395 --
132396 -- TOC entry 10291 (class 0 OID 0)
132397 -- Dependencies: 811
132398 -- Name: taxreg_taxreg_id_seq; Type: ACL; Schema: public; Owner: admin
132399 --
132400
132401 REVOKE ALL ON SEQUENCE taxreg_taxreg_id_seq FROM PUBLIC;
132402 REVOKE ALL ON SEQUENCE taxreg_taxreg_id_seq FROM admin;
132403 GRANT ALL ON SEQUENCE taxreg_taxreg_id_seq TO admin;
132404 GRANT ALL ON SEQUENCE taxreg_taxreg_id_seq TO xtrole;
132405
132406
132407 --
132408 -- TOC entry 10293 (class 0 OID 0)
132409 -- Dependencies: 812
132410 -- Name: taxtype_taxtype_id_seq; Type: ACL; Schema: public; Owner: admin
132411 --
132412
132413 REVOKE ALL ON SEQUENCE taxtype_taxtype_id_seq FROM PUBLIC;
132414 REVOKE ALL ON SEQUENCE taxtype_taxtype_id_seq FROM admin;
132415 GRANT ALL ON SEQUENCE taxtype_taxtype_id_seq TO admin;
132416 GRANT ALL ON SEQUENCE taxtype_taxtype_id_seq TO xtrole;
132417
132418
132419 --
132420 -- TOC entry 10295 (class 0 OID 0)
132421 -- Dependencies: 813
132422 -- Name: taxzone_taxzone_id_seq; Type: ACL; Schema: public; Owner: admin
132423 --
132424
132425 REVOKE ALL ON SEQUENCE taxzone_taxzone_id_seq FROM PUBLIC;
132426 REVOKE ALL ON SEQUENCE taxzone_taxzone_id_seq FROM admin;
132427 GRANT ALL ON SEQUENCE taxzone_taxzone_id_seq TO admin;
132428 GRANT ALL ON SEQUENCE taxzone_taxzone_id_seq TO xtrole;
132429
132430
132431 --
132432 -- TOC entry 10296 (class 0 OID 0)
132433 -- Dependencies: 814
132434 -- Name: terms_terms_id_seq; Type: ACL; Schema: public; Owner: admin
132435 --
132436
132437 REVOKE ALL ON SEQUENCE terms_terms_id_seq FROM PUBLIC;
132438 REVOKE ALL ON SEQUENCE terms_terms_id_seq FROM admin;
132439 GRANT ALL ON SEQUENCE terms_terms_id_seq TO admin;
132440 GRANT ALL ON SEQUENCE terms_terms_id_seq TO xtrole;
132441
132442
132443 --
132444 -- TOC entry 10298 (class 0 OID 0)
132445 -- Dependencies: 815
132446 -- Name: todoitem_todoitem_id_seq; Type: ACL; Schema: public; Owner: admin
132447 --
132448
132449 REVOKE ALL ON SEQUENCE todoitem_todoitem_id_seq FROM PUBLIC;
132450 REVOKE ALL ON SEQUENCE todoitem_todoitem_id_seq FROM admin;
132451 GRANT ALL ON SEQUENCE todoitem_todoitem_id_seq TO admin;
132452 GRANT ALL ON SEQUENCE todoitem_todoitem_id_seq TO xtrole;
132453
132454
132455 --
132456 -- TOC entry 10299 (class 0 OID 0)
132457 -- Dependencies: 816
132458 -- Name: trgthist; Type: ACL; Schema: public; Owner: admin
132459 --
132460
132461 REVOKE ALL ON TABLE trgthist FROM PUBLIC;
132462 REVOKE ALL ON TABLE trgthist FROM admin;
132463 GRANT ALL ON TABLE trgthist TO admin;
132464 GRANT ALL ON TABLE trgthist TO xtrole;
132465
132466
132467 --
132468 -- TOC entry 10301 (class 0 OID 0)
132469 -- Dependencies: 817
132470 -- Name: trialbal; Type: ACL; Schema: public; Owner: admin
132471 --
132472
132473 REVOKE ALL ON TABLE trialbal FROM PUBLIC;
132474 REVOKE ALL ON TABLE trialbal FROM admin;
132475 GRANT ALL ON TABLE trialbal TO admin;
132476 GRANT ALL ON TABLE trialbal TO xtrole;
132477
132478
132479 --
132480 -- TOC entry 10303 (class 0 OID 0)
132481 -- Dependencies: 818
132482 -- Name: trialbal_trialbal_id_seq; Type: ACL; Schema: public; Owner: admin
132483 --
132484
132485 REVOKE ALL ON SEQUENCE trialbal_trialbal_id_seq FROM PUBLIC;
132486 REVOKE ALL ON SEQUENCE trialbal_trialbal_id_seq FROM admin;
132487 GRANT ALL ON SEQUENCE trialbal_trialbal_id_seq TO admin;
132488 GRANT ALL ON SEQUENCE trialbal_trialbal_id_seq TO xtrole;
132489
132490
132491 --
132492 -- TOC entry 10305 (class 0 OID 0)
132493 -- Dependencies: 819
132494 -- Name: uom_uom_id_seq; Type: ACL; Schema: public; Owner: admin
132495 --
132496
132497 REVOKE ALL ON SEQUENCE uom_uom_id_seq FROM PUBLIC;
132498 REVOKE ALL ON SEQUENCE uom_uom_id_seq FROM admin;
132499 GRANT ALL ON SEQUENCE uom_uom_id_seq TO admin;
132500 GRANT ALL ON SEQUENCE uom_uom_id_seq TO xtrole;
132501
132502
132503 --
132504 -- TOC entry 10307 (class 0 OID 0)
132505 -- Dependencies: 820
132506 -- Name: uomconv; Type: ACL; Schema: public; Owner: admin
132507 --
132508
132509 REVOKE ALL ON TABLE uomconv FROM PUBLIC;
132510 REVOKE ALL ON TABLE uomconv FROM admin;
132511 GRANT ALL ON TABLE uomconv TO admin;
132512 GRANT ALL ON TABLE uomconv TO xtrole;
132513
132514
132515 --
132516 -- TOC entry 10309 (class 0 OID 0)
132517 -- Dependencies: 821
132518 -- Name: uomconv_uomconv_id_seq; Type: ACL; Schema: public; Owner: admin
132519 --
132520
132521 REVOKE ALL ON SEQUENCE uomconv_uomconv_id_seq FROM PUBLIC;
132522 REVOKE ALL ON SEQUENCE uomconv_uomconv_id_seq FROM admin;
132523 GRANT ALL ON SEQUENCE uomconv_uomconv_id_seq TO admin;
132524 GRANT ALL ON SEQUENCE uomconv_uomconv_id_seq TO xtrole;
132525
132526
132527 --
132528 -- TOC entry 10311 (class 0 OID 0)
132529 -- Dependencies: 822
132530 -- Name: uomtype; Type: ACL; Schema: public; Owner: admin
132531 --
132532
132533 REVOKE ALL ON TABLE uomtype FROM PUBLIC;
132534 REVOKE ALL ON TABLE uomtype FROM admin;
132535 GRANT ALL ON TABLE uomtype TO admin;
132536 GRANT ALL ON TABLE uomtype TO xtrole;
132537
132538
132539 --
132540 -- TOC entry 10313 (class 0 OID 0)
132541 -- Dependencies: 823
132542 -- Name: uomtype_uomtype_id_seq; Type: ACL; Schema: public; Owner: admin
132543 --
132544
132545 REVOKE ALL ON SEQUENCE uomtype_uomtype_id_seq FROM PUBLIC;
132546 REVOKE ALL ON SEQUENCE uomtype_uomtype_id_seq FROM admin;
132547 GRANT ALL ON SEQUENCE uomtype_uomtype_id_seq TO admin;
132548 GRANT ALL ON SEQUENCE uomtype_uomtype_id_seq TO xtrole;
132549
132550
132551 --
132552 -- TOC entry 10315 (class 0 OID 0)
132553 -- Dependencies: 824
132554 -- Name: urlinfo_url_id_seq; Type: ACL; Schema: public; Owner: admin
132555 --
132556
132557 REVOKE ALL ON SEQUENCE urlinfo_url_id_seq FROM PUBLIC;
132558 REVOKE ALL ON SEQUENCE urlinfo_url_id_seq FROM admin;
132559 GRANT ALL ON SEQUENCE urlinfo_url_id_seq TO admin;
132560 GRANT ALL ON SEQUENCE urlinfo_url_id_seq TO xtrole;
132561
132562
132563 --
132564 -- TOC entry 10317 (class 0 OID 0)
132565 -- Dependencies: 825
132566 -- Name: usrpref; Type: ACL; Schema: public; Owner: admin
132567 --
132568
132569 REVOKE ALL ON TABLE usrpref FROM PUBLIC;
132570 REVOKE ALL ON TABLE usrpref FROM admin;
132571 GRANT ALL ON TABLE usrpref TO admin;
132572 GRANT ALL ON TABLE usrpref TO xtrole;
132573
132574
132575 --
132576 -- TOC entry 10318 (class 0 OID 0)
132577 -- Dependencies: 826
132578 -- Name: usr; Type: ACL; Schema: public; Owner: admin
132579 --
132580
132581 REVOKE ALL ON TABLE usr FROM PUBLIC;
132582 REVOKE ALL ON TABLE usr FROM admin;
132583 GRANT ALL ON TABLE usr TO admin;
132584 GRANT ALL ON TABLE usr TO xtrole;
132585
132586
132587 --
132588 -- TOC entry 10320 (class 0 OID 0)
132589 -- Dependencies: 827
132590 -- Name: usr_bak; Type: ACL; Schema: public; Owner: admin
132591 --
132592
132593 REVOKE ALL ON TABLE usr_bak FROM PUBLIC;
132594 REVOKE ALL ON TABLE usr_bak FROM admin;
132595 GRANT ALL ON TABLE usr_bak TO admin;
132596 GRANT ALL ON TABLE usr_bak TO xtrole;
132597
132598
132599 --
132600 -- TOC entry 10321 (class 0 OID 0)
132601 -- Dependencies: 828
132602 -- Name: usr_usr_id_seq; Type: ACL; Schema: public; Owner: admin
132603 --
132604
132605 REVOKE ALL ON SEQUENCE usr_usr_id_seq FROM PUBLIC;
132606 REVOKE ALL ON SEQUENCE usr_usr_id_seq FROM admin;
132607 GRANT ALL ON SEQUENCE usr_usr_id_seq TO admin;
132608 GRANT ALL ON SEQUENCE usr_usr_id_seq TO xtrole;
132609
132610
132611 --
132612 -- TOC entry 10323 (class 0 OID 0)
132613 -- Dependencies: 829
132614 -- Name: usrgrp_usrgrp_id_seq; Type: ACL; Schema: public; Owner: admin
132615 --
132616
132617 REVOKE ALL ON SEQUENCE usrgrp_usrgrp_id_seq FROM PUBLIC;
132618 REVOKE ALL ON SEQUENCE usrgrp_usrgrp_id_seq FROM admin;
132619 GRANT ALL ON SEQUENCE usrgrp_usrgrp_id_seq TO admin;
132620 GRANT ALL ON SEQUENCE usrgrp_usrgrp_id_seq TO xtrole;
132621
132622
132623 --
132624 -- TOC entry 10324 (class 0 OID 0)
132625 -- Dependencies: 830
132626 -- Name: usrpref_usrpref_id_seq; Type: ACL; Schema: public; Owner: admin
132627 --
132628
132629 REVOKE ALL ON SEQUENCE usrpref_usrpref_id_seq FROM PUBLIC;
132630 REVOKE ALL ON SEQUENCE usrpref_usrpref_id_seq FROM admin;
132631 GRANT ALL ON SEQUENCE usrpref_usrpref_id_seq TO admin;
132632 GRANT ALL ON SEQUENCE usrpref_usrpref_id_seq TO xtrole;
132633
132634
132635 --
132636 -- TOC entry 10325 (class 0 OID 0)
132637 -- Dependencies: 831
132638 -- Name: usrpriv_usrpriv_id_seq; Type: ACL; Schema: public; Owner: admin
132639 --
132640
132641 REVOKE ALL ON SEQUENCE usrpriv_usrpriv_id_seq FROM PUBLIC;
132642 REVOKE ALL ON SEQUENCE usrpriv_usrpriv_id_seq FROM admin;
132643 GRANT ALL ON SEQUENCE usrpriv_usrpriv_id_seq TO admin;
132644 GRANT ALL ON SEQUENCE usrpriv_usrpriv_id_seq TO xtrole;
132645
132646
132647 --
132648 -- TOC entry 10326 (class 0 OID 0)
132649 -- Dependencies: 832
132650 -- Name: vend; Type: ACL; Schema: public; Owner: admin
132651 --
132652
132653 REVOKE ALL ON TABLE vend FROM PUBLIC;
132654 REVOKE ALL ON TABLE vend FROM admin;
132655 GRANT ALL ON TABLE vend TO admin;
132656 GRANT SELECT,INSERT,REFERENCES,DELETE,TRIGGER,UPDATE ON TABLE vend TO xtrole;
132657
132658
132659 --
132660 -- TOC entry 10327 (class 0 OID 0)
132661 -- Dependencies: 833
132662 -- Name: vend_vend_id_seq; Type: ACL; Schema: public; Owner: admin
132663 --
132664
132665 REVOKE ALL ON SEQUENCE vend_vend_id_seq FROM PUBLIC;
132666 REVOKE ALL ON SEQUENCE vend_vend_id_seq FROM admin;
132667 GRANT ALL ON SEQUENCE vend_vend_id_seq TO admin;
132668 GRANT ALL ON SEQUENCE vend_vend_id_seq TO xtrole;
132669
132670
132671 --
132672 -- TOC entry 10328 (class 0 OID 0)
132673 -- Dependencies: 834
132674 -- Name: vendaddr; Type: ACL; Schema: public; Owner: admin
132675 --
132676
132677 REVOKE ALL ON TABLE vendaddr FROM PUBLIC;
132678 REVOKE ALL ON TABLE vendaddr FROM admin;
132679 GRANT ALL ON TABLE vendaddr TO admin;
132680 GRANT ALL ON TABLE vendaddr TO xtrole;
132681
132682
132683 --
132684 -- TOC entry 10329 (class 0 OID 0)
132685 -- Dependencies: 835
132686 -- Name: vendaddr_vendaddr_id_seq; Type: ACL; Schema: public; Owner: admin
132687 --
132688
132689 REVOKE ALL ON SEQUENCE vendaddr_vendaddr_id_seq FROM PUBLIC;
132690 REVOKE ALL ON SEQUENCE vendaddr_vendaddr_id_seq FROM admin;
132691 GRANT ALL ON SEQUENCE vendaddr_vendaddr_id_seq TO admin;
132692 GRANT ALL ON SEQUENCE vendaddr_vendaddr_id_seq TO xtrole;
132693
132694
132695 --
132696 -- TOC entry 10331 (class 0 OID 0)
132697 -- Dependencies: 836
132698 -- Name: vendtype_vendtype_id_seq; Type: ACL; Schema: public; Owner: admin
132699 --
132700
132701 REVOKE ALL ON SEQUENCE vendtype_vendtype_id_seq FROM PUBLIC;
132702 REVOKE ALL ON SEQUENCE vendtype_vendtype_id_seq FROM admin;
132703 GRANT ALL ON SEQUENCE vendtype_vendtype_id_seq TO admin;
132704 GRANT ALL ON SEQUENCE vendtype_vendtype_id_seq TO xtrole;
132705
132706
132707 --
132708 -- TOC entry 10333 (class 0 OID 0)
132709 -- Dependencies: 837
132710 -- Name: vodist; Type: ACL; Schema: public; Owner: admin
132711 --
132712
132713 REVOKE ALL ON TABLE vodist FROM PUBLIC;
132714 REVOKE ALL ON TABLE vodist FROM admin;
132715 GRANT ALL ON TABLE vodist TO admin;
132716 GRANT ALL ON TABLE vodist TO xtrole;
132717
132718
132719 --
132720 -- TOC entry 10334 (class 0 OID 0)
132721 -- Dependencies: 838
132722 -- Name: vodist_vodist_id_seq; Type: ACL; Schema: public; Owner: admin
132723 --
132724
132725 REVOKE ALL ON SEQUENCE vodist_vodist_id_seq FROM PUBLIC;
132726 REVOKE ALL ON SEQUENCE vodist_vodist_id_seq FROM admin;
132727 GRANT ALL ON SEQUENCE vodist_vodist_id_seq TO admin;
132728 GRANT ALL ON SEQUENCE vodist_vodist_id_seq TO xtrole;
132729
132730
132731 --
132732 -- TOC entry 10336 (class 0 OID 0)
132733 -- Dependencies: 839
132734 -- Name: vohead; Type: ACL; Schema: public; Owner: admin
132735 --
132736
132737 REVOKE ALL ON TABLE vohead FROM PUBLIC;
132738 REVOKE ALL ON TABLE vohead FROM admin;
132739 GRANT ALL ON TABLE vohead TO admin;
132740 GRANT ALL ON TABLE vohead TO xtrole;
132741
132742
132743 --
132744 -- TOC entry 10337 (class 0 OID 0)
132745 -- Dependencies: 840
132746 -- Name: vohead_vohead_id_seq; Type: ACL; Schema: public; Owner: admin
132747 --
132748
132749 REVOKE ALL ON SEQUENCE vohead_vohead_id_seq FROM PUBLIC;
132750 REVOKE ALL ON SEQUENCE vohead_vohead_id_seq FROM admin;
132751 GRANT ALL ON SEQUENCE vohead_vohead_id_seq TO admin;
132752 GRANT ALL ON SEQUENCE vohead_vohead_id_seq TO xtrole;
132753
132754
132755 --
132756 -- TOC entry 10338 (class 0 OID 0)
132757 -- Dependencies: 841
132758 -- Name: voheadtax; Type: ACL; Schema: public; Owner: admin
132759 --
132760
132761 REVOKE ALL ON TABLE voheadtax FROM PUBLIC;
132762 REVOKE ALL ON TABLE voheadtax FROM admin;
132763 GRANT ALL ON TABLE voheadtax TO admin;
132764 GRANT ALL ON TABLE voheadtax TO xtrole;
132765
132766
132767 --
132768 -- TOC entry 10340 (class 0 OID 0)
132769 -- Dependencies: 842
132770 -- Name: voitem; Type: ACL; Schema: public; Owner: admin
132771 --
132772
132773 REVOKE ALL ON TABLE voitem FROM PUBLIC;
132774 REVOKE ALL ON TABLE voitem FROM admin;
132775 GRANT ALL ON TABLE voitem TO admin;
132776 GRANT ALL ON TABLE voitem TO xtrole;
132777
132778
132779 --
132780 -- TOC entry 10341 (class 0 OID 0)
132781 -- Dependencies: 843
132782 -- Name: voitem_voitem_id_seq; Type: ACL; Schema: public; Owner: admin
132783 --
132784
132785 REVOKE ALL ON SEQUENCE voitem_voitem_id_seq FROM PUBLIC;
132786 REVOKE ALL ON SEQUENCE voitem_voitem_id_seq FROM admin;
132787 GRANT ALL ON SEQUENCE voitem_voitem_id_seq TO admin;
132788 GRANT ALL ON SEQUENCE voitem_voitem_id_seq TO xtrole;
132789
132790
132791 --
132792 -- TOC entry 10342 (class 0 OID 0)
132793 -- Dependencies: 844
132794 -- Name: voitemtax; Type: ACL; Schema: public; Owner: admin
132795 --
132796
132797 REVOKE ALL ON TABLE voitemtax FROM PUBLIC;
132798 REVOKE ALL ON TABLE voitemtax FROM admin;
132799 GRANT ALL ON TABLE voitemtax TO admin;
132800 GRANT ALL ON TABLE voitemtax TO xtrole;
132801
132802
132803 --
132804 -- TOC entry 10343 (class 0 OID 0)
132805 -- Dependencies: 845
132806 -- Name: warehous; Type: ACL; Schema: public; Owner: admin
132807 --
132808
132809 REVOKE ALL ON TABLE warehous FROM PUBLIC;
132810 REVOKE ALL ON TABLE warehous FROM admin;
132811 GRANT ALL ON TABLE warehous TO admin;
132812 GRANT ALL ON TABLE warehous TO xtrole;
132813
132814
132815 --
132816 -- TOC entry 10344 (class 0 OID 0)
132817 -- Dependencies: 846
132818 -- Name: warehous_warehous_id_seq; Type: ACL; Schema: public; Owner: admin
132819 --
132820
132821 REVOKE ALL ON SEQUENCE warehous_warehous_id_seq FROM PUBLIC;
132822 REVOKE ALL ON SEQUENCE warehous_warehous_id_seq FROM admin;
132823 GRANT ALL ON SEQUENCE warehous_warehous_id_seq TO admin;
132824 GRANT ALL ON SEQUENCE warehous_warehous_id_seq TO xtrole;
132825
132826
132827 --
132828 -- TOC entry 10346 (class 0 OID 0)
132829 -- Dependencies: 847
132830 -- Name: whsezone_whsezone_id_seq; Type: ACL; Schema: public; Owner: admin
132831 --
132832
132833 REVOKE ALL ON SEQUENCE whsezone_whsezone_id_seq FROM PUBLIC;
132834 REVOKE ALL ON SEQUENCE whsezone_whsezone_id_seq FROM admin;
132835 GRANT ALL ON SEQUENCE whsezone_whsezone_id_seq TO admin;
132836 GRANT ALL ON SEQUENCE whsezone_whsezone_id_seq TO xtrole;
132837
132838
132839 --
132840 -- TOC entry 10347 (class 0 OID 0)
132841 -- Dependencies: 848
132842 -- Name: wo_wo_id_seq; Type: ACL; Schema: public; Owner: admin
132843 --
132844
132845 REVOKE ALL ON SEQUENCE wo_wo_id_seq FROM PUBLIC;
132846 REVOKE ALL ON SEQUENCE wo_wo_id_seq FROM admin;
132847 GRANT ALL ON SEQUENCE wo_wo_id_seq TO admin;
132848 GRANT ALL ON SEQUENCE wo_wo_id_seq TO xtrole;
132849
132850
132851 --
132852 -- TOC entry 10348 (class 0 OID 0)
132853 -- Dependencies: 849
132854 -- Name: womatl_womatl_id_seq; Type: ACL; Schema: public; Owner: admin
132855 --
132856
132857 REVOKE ALL ON SEQUENCE womatl_womatl_id_seq FROM PUBLIC;
132858 REVOKE ALL ON SEQUENCE womatl_womatl_id_seq FROM admin;
132859 GRANT ALL ON SEQUENCE womatl_womatl_id_seq TO admin;
132860 GRANT ALL ON SEQUENCE womatl_womatl_id_seq TO xtrole;
132861
132862
132863 --
132864 -- TOC entry 10350 (class 0 OID 0)
132865 -- Dependencies: 850
132866 -- Name: womatlpost; Type: ACL; Schema: public; Owner: admin
132867 --
132868
132869 REVOKE ALL ON TABLE womatlpost FROM PUBLIC;
132870 REVOKE ALL ON TABLE womatlpost FROM admin;
132871 GRANT ALL ON TABLE womatlpost TO admin;
132872 GRANT ALL ON TABLE womatlpost TO xtrole;
132873
132874
132875 --
132876 -- TOC entry 10352 (class 0 OID 0)
132877 -- Dependencies: 851
132878 -- Name: womatlpost_womatlpost_id_seq; Type: ACL; Schema: public; Owner: admin
132879 --
132880
132881 REVOKE ALL ON SEQUENCE womatlpost_womatlpost_id_seq FROM PUBLIC;
132882 REVOKE ALL ON SEQUENCE womatlpost_womatlpost_id_seq FROM admin;
132883 GRANT ALL ON SEQUENCE womatlpost_womatlpost_id_seq TO admin;
132884 GRANT ALL ON SEQUENCE womatlpost_womatlpost_id_seq TO xtrole;
132885
132886
132887 --
132888 -- TOC entry 10355 (class 0 OID 0)
132889 -- Dependencies: 852
132890 -- Name: womatlvar; Type: ACL; Schema: public; Owner: admin
132891 --
132892
132893 REVOKE ALL ON TABLE womatlvar FROM PUBLIC;
132894 REVOKE ALL ON TABLE womatlvar FROM admin;
132895 GRANT ALL ON TABLE womatlvar TO admin;
132896 GRANT ALL ON TABLE womatlvar TO xtrole;
132897
132898
132899 --
132900 -- TOC entry 10356 (class 0 OID 0)
132901 -- Dependencies: 853
132902 -- Name: womatlvar_womatlvar_id_seq; Type: ACL; Schema: public; Owner: admin
132903 --
132904
132905 REVOKE ALL ON SEQUENCE womatlvar_womatlvar_id_seq FROM PUBLIC;
132906 REVOKE ALL ON SEQUENCE womatlvar_womatlvar_id_seq FROM admin;
132907 GRANT ALL ON SEQUENCE womatlvar_womatlvar_id_seq TO admin;
132908 GRANT ALL ON SEQUENCE womatlvar_womatlvar_id_seq TO xtrole;
132909
132910
132911 --
132912 -- TOC entry 10357 (class 0 OID 0)
132913 -- Dependencies: 854
132914 -- Name: xcalitem_xcalitem_id_seq; Type: ACL; Schema: public; Owner: admin
132915 --
132916
132917 REVOKE ALL ON SEQUENCE xcalitem_xcalitem_id_seq FROM PUBLIC;
132918 REVOKE ALL ON SEQUENCE xcalitem_xcalitem_id_seq FROM admin;
132919 GRANT ALL ON SEQUENCE xcalitem_xcalitem_id_seq TO admin;
132920 GRANT ALL ON SEQUENCE xcalitem_xcalitem_id_seq TO xtrole;
132921
132922
132923 --
132924 -- TOC entry 10359 (class 0 OID 0)
132925 -- Dependencies: 855
132926 -- Name: xsltmap; Type: ACL; Schema: public; Owner: admin
132927 --
132928
132929 REVOKE ALL ON TABLE xsltmap FROM PUBLIC;
132930 REVOKE ALL ON TABLE xsltmap FROM admin;
132931 GRANT ALL ON TABLE xsltmap TO admin;
132932 GRANT ALL ON TABLE xsltmap TO xtrole;
132933
132934
132935 --
132936 -- TOC entry 10361 (class 0 OID 0)
132937 -- Dependencies: 856
132938 -- Name: xsltmap_xsltmap_id_seq; Type: ACL; Schema: public; Owner: admin
132939 --
132940
132941 REVOKE ALL ON SEQUENCE xsltmap_xsltmap_id_seq FROM PUBLIC;
132942 REVOKE ALL ON SEQUENCE xsltmap_xsltmap_id_seq FROM admin;
132943 GRANT ALL ON SEQUENCE xsltmap_xsltmap_id_seq TO admin;
132944 GRANT ALL ON SEQUENCE xsltmap_xsltmap_id_seq TO xtrole;
132945
132946
132947 --
132948 -- TOC entry 10363 (class 0 OID 0)
132949 -- Dependencies: 857
132950 -- Name: yearperiod; Type: ACL; Schema: public; Owner: admin
132951 --
132952
132953 REVOKE ALL ON TABLE yearperiod FROM PUBLIC;
132954 REVOKE ALL ON TABLE yearperiod FROM admin;
132955 GRANT ALL ON TABLE yearperiod TO admin;
132956 GRANT ALL ON TABLE yearperiod TO xtrole;
132957
132958
132959 --
132960 -- TOC entry 10365 (class 0 OID 0)
132961 -- Dependencies: 858
132962 -- Name: yearperiod_yearperiod_id_seq; Type: ACL; Schema: public; Owner: admin
132963 --
132964
132965 REVOKE ALL ON SEQUENCE yearperiod_yearperiod_id_seq FROM PUBLIC;
132966 REVOKE ALL ON SEQUENCE yearperiod_yearperiod_id_seq FROM admin;
132967 GRANT ALL ON SEQUENCE yearperiod_yearperiod_id_seq TO admin;
132968 GRANT ALL ON SEQUENCE yearperiod_yearperiod_id_seq TO xtrole;
132969
132970
132971 SET search_path = te, pg_catalog;
132972
132973 --
132974 -- TOC entry 10366 (class 0 OID 0)
132975 -- Dependencies: 859
132976 -- Name: pkgcmd; Type: ACL; Schema: te; Owner: admin
132977 --
132978
132979 REVOKE ALL ON TABLE pkgcmd FROM PUBLIC;
132980 REVOKE ALL ON TABLE pkgcmd FROM admin;
132981 GRANT ALL ON TABLE pkgcmd TO admin;
132982 GRANT ALL ON TABLE pkgcmd TO xtrole;
132983
132984
132985 --
132986 -- TOC entry 10367 (class 0 OID 0)
132987 -- Dependencies: 860
132988 -- Name: pkgcmdarg; Type: ACL; Schema: te; Owner: admin
132989 --
132990
132991 REVOKE ALL ON TABLE pkgcmdarg FROM PUBLIC;
132992 REVOKE ALL ON TABLE pkgcmdarg FROM admin;
132993 GRANT ALL ON TABLE pkgcmdarg TO admin;
132994 GRANT ALL ON TABLE pkgcmdarg TO xtrole;
132995
132996
132997 --
132998 -- TOC entry 10368 (class 0 OID 0)
132999 -- Dependencies: 861
133000 -- Name: pkgimage; Type: ACL; Schema: te; Owner: admin
133001 --
133002
133003 REVOKE ALL ON TABLE pkgimage FROM PUBLIC;
133004 REVOKE ALL ON TABLE pkgimage FROM admin;
133005 GRANT ALL ON TABLE pkgimage TO admin;
133006 GRANT ALL ON TABLE pkgimage TO xtrole;
133007
133008
133009 --
133010 -- TOC entry 10369 (class 0 OID 0)
133011 -- Dependencies: 862
133012 -- Name: pkgmetasql; Type: ACL; Schema: te; Owner: admin
133013 --
133014
133015 REVOKE ALL ON TABLE pkgmetasql FROM PUBLIC;
133016 REVOKE ALL ON TABLE pkgmetasql FROM admin;
133017 GRANT ALL ON TABLE pkgmetasql TO admin;
133018 GRANT ALL ON TABLE pkgmetasql TO xtrole;
133019
133020
133021 --
133022 -- TOC entry 10370 (class 0 OID 0)
133023 -- Dependencies: 863
133024 -- Name: pkgpriv; Type: ACL; Schema: te; Owner: admin
133025 --
133026
133027 REVOKE ALL ON TABLE pkgpriv FROM PUBLIC;
133028 REVOKE ALL ON TABLE pkgpriv FROM admin;
133029 GRANT ALL ON TABLE pkgpriv TO admin;
133030 GRANT ALL ON TABLE pkgpriv TO xtrole;
133031
133032
133033 --
133034 -- TOC entry 10371 (class 0 OID 0)
133035 -- Dependencies: 864
133036 -- Name: pkgreport; Type: ACL; Schema: te; Owner: admin
133037 --
133038
133039 REVOKE ALL ON TABLE pkgreport FROM PUBLIC;
133040 REVOKE ALL ON TABLE pkgreport FROM admin;
133041 GRANT ALL ON TABLE pkgreport TO admin;
133042 GRANT ALL ON TABLE pkgreport TO xtrole;
133043
133044
133045 --
133046 -- TOC entry 10372 (class 0 OID 0)
133047 -- Dependencies: 865
133048 -- Name: pkgscript; Type: ACL; Schema: te; Owner: admin
133049 --
133050
133051 REVOKE ALL ON TABLE pkgscript FROM PUBLIC;
133052 REVOKE ALL ON TABLE pkgscript FROM admin;
133053 GRANT ALL ON TABLE pkgscript TO admin;
133054 GRANT ALL ON TABLE pkgscript TO xtrole;
133055
133056
133057 --
133058 -- TOC entry 10373 (class 0 OID 0)
133059 -- Dependencies: 866
133060 -- Name: pkguiform; Type: ACL; Schema: te; Owner: admin
133061 --
133062
133063 REVOKE ALL ON TABLE pkguiform FROM PUBLIC;
133064 REVOKE ALL ON TABLE pkguiform FROM admin;
133065 GRANT ALL ON TABLE pkguiform TO admin;
133066 GRANT ALL ON TABLE pkguiform TO xtrole;
133067
133068
133069 --
133070 -- TOC entry 10375 (class 0 OID 0)
133071 -- Dependencies: 867
133072 -- Name: tecustrate; Type: ACL; Schema: te; Owner: admin
133073 --
133074
133075 REVOKE ALL ON TABLE tecustrate FROM PUBLIC;
133076 REVOKE ALL ON TABLE tecustrate FROM admin;
133077 GRANT ALL ON TABLE tecustrate TO admin;
133078 GRANT ALL ON TABLE tecustrate TO xtrole;
133079
133080
133081 --
133082 -- TOC entry 10377 (class 0 OID 0)
133083 -- Dependencies: 869
133084 -- Name: teemp; Type: ACL; Schema: te; Owner: admin
133085 --
133086
133087 REVOKE ALL ON TABLE teemp FROM PUBLIC;
133088 REVOKE ALL ON TABLE teemp FROM admin;
133089 GRANT ALL ON TABLE teemp TO admin;
133090 GRANT ALL ON TABLE teemp TO xtrole;
133091
133092
133093 --
133094 -- TOC entry 10379 (class 0 OID 0)
133095 -- Dependencies: 870
133096 -- Name: teemp_teemp_id_seq; Type: ACL; Schema: te; Owner: admin
133097 --
133098
133099 REVOKE ALL ON SEQUENCE teemp_teemp_id_seq FROM PUBLIC;
133100 REVOKE ALL ON SEQUENCE teemp_teemp_id_seq FROM admin;
133101 GRANT ALL ON SEQUENCE teemp_teemp_id_seq TO admin;
133102 GRANT ALL ON SEQUENCE teemp_teemp_id_seq TO xtrole;
133103
133104
133105 --
133106 -- TOC entry 10381 (class 0 OID 0)
133107 -- Dependencies: 871
133108 -- Name: teexp; Type: ACL; Schema: te; Owner: admin
133109 --
133110
133111 REVOKE ALL ON TABLE teexp FROM PUBLIC;
133112 REVOKE ALL ON TABLE teexp FROM admin;
133113 GRANT ALL ON TABLE teexp TO admin;
133114 GRANT ALL ON TABLE teexp TO xtrole;
133115
133116
133117 --
133118 -- TOC entry 10382 (class 0 OID 0)
133119 -- Dependencies: 872
133120 -- Name: timesheet_seq; Type: ACL; Schema: te; Owner: admin
133121 --
133122
133123 REVOKE ALL ON SEQUENCE timesheet_seq FROM PUBLIC;
133124 REVOKE ALL ON SEQUENCE timesheet_seq FROM admin;
133125 GRANT ALL ON SEQUENCE timesheet_seq TO admin;
133126 GRANT ALL ON SEQUENCE timesheet_seq TO xtrole;
133127
133128
133129 --
133130 -- TOC entry 10384 (class 0 OID 0)
133131 -- Dependencies: 873
133132 -- Name: tehead; Type: ACL; Schema: te; Owner: admin
133133 --
133134
133135 REVOKE ALL ON TABLE tehead FROM PUBLIC;
133136 REVOKE ALL ON TABLE tehead FROM admin;
133137 GRANT ALL ON TABLE tehead TO admin;
133138 GRANT ALL ON TABLE tehead TO xtrole;
133139
133140
133141 --
133142 -- TOC entry 10386 (class 0 OID 0)
133143 -- Dependencies: 874
133144 -- Name: tehead_tehead_id_seq; Type: ACL; Schema: te; Owner: admin
133145 --
133146
133147 REVOKE ALL ON SEQUENCE tehead_tehead_id_seq FROM PUBLIC;
133148 REVOKE ALL ON SEQUENCE tehead_tehead_id_seq FROM admin;
133149 GRANT ALL ON SEQUENCE tehead_tehead_id_seq TO admin;
133150 GRANT ALL ON SEQUENCE tehead_tehead_id_seq TO xtrole;
133151
133152
133153 --
133154 -- TOC entry 10391 (class 0 OID 0)
133155 -- Dependencies: 875
133156 -- Name: teitem; Type: ACL; Schema: te; Owner: admin
133157 --
133158
133159 REVOKE ALL ON TABLE teitem FROM PUBLIC;
133160 REVOKE ALL ON TABLE teitem FROM admin;
133161 GRANT ALL ON TABLE teitem TO admin;
133162 GRANT ALL ON TABLE teitem TO xtrole;
133163
133164
133165 --
133166 -- TOC entry 10393 (class 0 OID 0)
133167 -- Dependencies: 876
133168 -- Name: teitem_teitem_id_seq; Type: ACL; Schema: te; Owner: admin
133169 --
133170
133171 REVOKE ALL ON SEQUENCE teitem_teitem_id_seq FROM PUBLIC;
133172 REVOKE ALL ON SEQUENCE teitem_teitem_id_seq FROM admin;
133173 GRANT ALL ON SEQUENCE teitem_teitem_id_seq TO admin;
133174 GRANT ALL ON SEQUENCE teitem_teitem_id_seq TO xtrole;
133175
133176
133177 --
133178 -- TOC entry 10395 (class 0 OID 0)
133179 -- Dependencies: 877
133180 -- Name: teprj; Type: ACL; Schema: te; Owner: admin
133181 --
133182
133183 REVOKE ALL ON TABLE teprj FROM PUBLIC;
133184 REVOKE ALL ON TABLE teprj FROM admin;
133185 GRANT ALL ON TABLE teprj TO admin;
133186 GRANT ALL ON TABLE teprj TO xtrole;
133187
133188
133189 --
133190 -- TOC entry 10397 (class 0 OID 0)
133191 -- Dependencies: 878
133192 -- Name: teprj_teprj_id_seq; Type: ACL; Schema: te; Owner: admin
133193 --
133194
133195 REVOKE ALL ON SEQUENCE teprj_teprj_id_seq FROM PUBLIC;
133196 REVOKE ALL ON SEQUENCE teprj_teprj_id_seq FROM admin;
133197 GRANT ALL ON SEQUENCE teprj_teprj_id_seq TO admin;
133198 GRANT ALL ON SEQUENCE teprj_teprj_id_seq TO xtrole;
133199
133200
133201 --
133202 -- TOC entry 10399 (class 0 OID 0)
133203 -- Dependencies: 879
133204 -- Name: teprjtask; Type: ACL; Schema: te; Owner: admin
133205 --
133206
133207 REVOKE ALL ON TABLE teprjtask FROM PUBLIC;
133208 REVOKE ALL ON TABLE teprjtask FROM admin;
133209 GRANT ALL ON TABLE teprjtask TO admin;
133210 GRANT ALL ON TABLE teprjtask TO xtrole;
133211
133212
133213 --
133214 -- TOC entry 10401 (class 0 OID 0)
133215 -- Dependencies: 880
133216 -- Name: teprjtask_teprjtask_id_seq; Type: ACL; Schema: te; Owner: admin
133217 --
133218
133219 REVOKE ALL ON SEQUENCE teprjtask_teprjtask_id_seq FROM PUBLIC;
133220 REVOKE ALL ON SEQUENCE teprjtask_teprjtask_id_seq FROM admin;
133221 GRANT ALL ON SEQUENCE teprjtask_teprjtask_id_seq TO admin;
133222 GRANT ALL ON SEQUENCE teprjtask_teprjtask_id_seq TO xtrole;
133223
133224
133225 SET search_path = xtdesktop, pg_catalog;
133226
133227 --
133228 -- TOC entry 10402 (class 0 OID 0)
133229 -- Dependencies: 881
133230 -- Name: pkgcmd; Type: ACL; Schema: xtdesktop; Owner: admin
133231 --
133232
133233 REVOKE ALL ON TABLE pkgcmd FROM PUBLIC;
133234 REVOKE ALL ON TABLE pkgcmd FROM admin;
133235 GRANT ALL ON TABLE pkgcmd TO admin;
133236 GRANT ALL ON TABLE pkgcmd TO xtrole;
133237
133238
133239 --
133240 -- TOC entry 10403 (class 0 OID 0)
133241 -- Dependencies: 882
133242 -- Name: pkgcmdarg; Type: ACL; Schema: xtdesktop; Owner: admin
133243 --
133244
133245 REVOKE ALL ON TABLE pkgcmdarg FROM PUBLIC;
133246 REVOKE ALL ON TABLE pkgcmdarg FROM admin;
133247 GRANT ALL ON TABLE pkgcmdarg TO admin;
133248 GRANT ALL ON TABLE pkgcmdarg TO xtrole;
133249
133250
133251 --
133252 -- TOC entry 10404 (class 0 OID 0)
133253 -- Dependencies: 883
133254 -- Name: pkgimage; Type: ACL; Schema: xtdesktop; Owner: admin
133255 --
133256
133257 REVOKE ALL ON TABLE pkgimage FROM PUBLIC;
133258 REVOKE ALL ON TABLE pkgimage FROM admin;
133259 GRANT ALL ON TABLE pkgimage TO admin;
133260 GRANT ALL ON TABLE pkgimage TO xtrole;
133261
133262
133263 --
133264 -- TOC entry 10405 (class 0 OID 0)
133265 -- Dependencies: 884
133266 -- Name: pkgmetasql; Type: ACL; Schema: xtdesktop; Owner: admin
133267 --
133268
133269 REVOKE ALL ON TABLE pkgmetasql FROM PUBLIC;
133270 REVOKE ALL ON TABLE pkgmetasql FROM admin;
133271 GRANT ALL ON TABLE pkgmetasql TO admin;
133272 GRANT ALL ON TABLE pkgmetasql TO xtrole;
133273
133274
133275 --
133276 -- TOC entry 10406 (class 0 OID 0)
133277 -- Dependencies: 885
133278 -- Name: pkgpriv; Type: ACL; Schema: xtdesktop; Owner: admin
133279 --
133280
133281 REVOKE ALL ON TABLE pkgpriv FROM PUBLIC;
133282 REVOKE ALL ON TABLE pkgpriv FROM admin;
133283 GRANT ALL ON TABLE pkgpriv TO admin;
133284 GRANT ALL ON TABLE pkgpriv TO xtrole;
133285
133286
133287 --
133288 -- TOC entry 10407 (class 0 OID 0)
133289 -- Dependencies: 886
133290 -- Name: pkgreport; Type: ACL; Schema: xtdesktop; Owner: admin
133291 --
133292
133293 REVOKE ALL ON TABLE pkgreport FROM PUBLIC;
133294 REVOKE ALL ON TABLE pkgreport FROM admin;
133295 GRANT ALL ON TABLE pkgreport TO admin;
133296 GRANT ALL ON TABLE pkgreport TO xtrole;
133297
133298
133299 --
133300 -- TOC entry 10408 (class 0 OID 0)
133301 -- Dependencies: 887
133302 -- Name: pkgscript; Type: ACL; Schema: xtdesktop; Owner: admin
133303 --
133304
133305 REVOKE ALL ON TABLE pkgscript FROM PUBLIC;
133306 REVOKE ALL ON TABLE pkgscript FROM admin;
133307 GRANT ALL ON TABLE pkgscript TO admin;
133308 GRANT ALL ON TABLE pkgscript TO xtrole;
133309
133310
133311 --
133312 -- TOC entry 10409 (class 0 OID 0)
133313 -- Dependencies: 888
133314 -- Name: pkguiform; Type: ACL; Schema: xtdesktop; Owner: admin
133315 --
133316
133317 REVOKE ALL ON TABLE pkguiform FROM PUBLIC;
133318 REVOKE ALL ON TABLE pkguiform FROM admin;
133319 GRANT ALL ON TABLE pkguiform TO admin;
133320 GRANT ALL ON TABLE pkguiform TO xtrole;
133321
133322
133323 -- Completed on 2014-03-27 11:30:55 EDT
133324
133325 --
133326 -- PostgreSQL database dump complete
133327 --
133328