summaryrefslogtreecommitdiff
path: root/sql/modules/Payment.sql
blob: 175cac400ff6635b404ee4000eba49cbbe2a7629 (plain)
  1. CREATE TYPE payment_vc_info AS (
  2. id int,
  3. name text,
  4. entity_class int,
  5. discount int
  6. );
  7. CREATE OR REPLACE FUNCTION payment_get_entity_accounts
  8. (in_account_class int,
  9. in_vc_name text,
  10. in_vc_idn int)
  11. returns SETOF payment_vc_info AS
  12. $$
  13. DECLARE out_entity payment_vc_info;
  14. BEGIN
  15. FOR out_entity IN
  16. SELECT ec.id, cp.legal_name as name, e.entity_class, ec.discount_account_id
  17. FROM entity e
  18. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  19. JOIN company cp ON (cp.entity_id = e.id)
  20. WHERE ec.entity_class = in_account_class
  21. AND (cp.legal_name ilike coalesce('%'||in_vc_name||'%','%%') OR cp.tax_id = in_vc_idn)
  22. LOOP
  23. RETURN NEXT out_entity;
  24. END LOOP;
  25. END;
  26. $$ LANGUAGE PLPGSQL;
  27. -- payment_get_open_accounts and the option to get all accounts need to be
  28. -- refactored and redesigned. -- CT
  29. CREATE OR REPLACE FUNCTION payment_get_open_accounts(in_account_class int)
  30. returns SETOF entity AS
  31. $$
  32. DECLARE out_entity entity%ROWTYPE;
  33. BEGIN
  34. FOR out_entity IN
  35. SELECT ec.id, cp.legal_name as name, e.entity_class, e.created
  36. FROM entity e
  37. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  38. JOIN company cp ON (cp.entity_id = e.id)
  39. WHERE ec.entity_class = in_account_class
  40. -- AND CASE WHEN in_account_class = 1 THEN
  41. -- e.id IN (SELECT entity_id FROM ap
  42. -- WHERE amount <> paid
  43. -- GROUP BY entity_id)
  44. -- WHEN in_account_class = 2 THEN
  45. -- e.id IN (SELECT entity_id FROM ar
  46. -- WHERE amount <> paid
  47. -- GROUP BY entity_id)
  48. -- END
  49. LOOP
  50. RETURN NEXT out_entity;
  51. END LOOP;
  52. END;
  53. $$ LANGUAGE PLPGSQL;
  54. COMMENT ON FUNCTION payment_get_open_accounts(int) IS
  55. $$ This function takes a single argument (1 for vendor, 2 for customer as
  56. always) and returns all entities with open accounts of the appropriate type. $$;
  57. CREATE OR REPLACE FUNCTION payment_get_all_accounts(in_account_class int)
  58. RETURNS SETOF entity AS
  59. $$
  60. DECLARE out_entity entity%ROWTYPE;
  61. BEGIN
  62. FOR out_entity IN
  63. SELECT ec.id,
  64. e.name, e.entity_class, e.created
  65. FROM entity e
  66. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  67. WHERE e.entity_class = in_account_class
  68. LOOP
  69. RETURN NEXT out_entity;
  70. END LOOP;
  71. END;
  72. $$ LANGUAGE PLPGSQL;
  73. COMMENT ON FUNCTION payment_get_open_accounts(int) IS
  74. $$ This function takes a single argument (1 for vendor, 2 for customer as
  75. always) and returns all entities with accounts of the appropriate type. $$;
  76. CREATE TYPE payment_invoice AS (
  77. invoice_id int,
  78. invnumber text,
  79. invoice_date date,
  80. amount numeric,
  81. amount_fx numeric,
  82. discount numeric,
  83. discount_fx numeric,
  84. due numeric,
  85. due_fx numeric,
  86. exchangerate numeric
  87. );
  88. CREATE OR REPLACE FUNCTION payment_get_open_invoices
  89. (in_account_class int,
  90. in_entity_credit_id int,
  91. in_curr char(3),
  92. in_datefrom date,
  93. in_dateto date,
  94. in_amountfrom numeric,
  95. in_amountto numeric,
  96. in_department_id int)
  97. RETURNS SETOF payment_invoice AS
  98. $$
  99. DECLARE payment_inv payment_invoice;
  100. BEGIN
  101. FOR payment_inv IN
  102. SELECT a.id AS invoice_id, a.invnumber AS invnumber,
  103. a.transdate AS invoice_date, a.amount AS amount,
  104. a.amount/
  105. (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
  106. THEN 1
  107. ELSE
  108. (CASE WHEN in_account_class =1
  109. THEN ex.buy
  110. ELSE ex.sell END)
  111. END) as amount_fx,
  112. (CASE WHEN c.discount_terms < extract('days' FROM age(a.transdate))
  113. THEN 0
  114. ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
  115. END) AS discount,
  116. (CASE WHEN c.discount_terms < extract('days' FROM age(a.transdate))
  117. THEN 0
  118. ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
  119. END)/
  120. (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
  121. THEN 1
  122. ELSE
  123. (CASE WHEN in_account_class =1
  124. THEN ex.buy
  125. ELSE ex.sell END)
  126. END) as discount_fx,
  127. ac.due - (CASE WHEN c.discount_terms < extract('days' FROM age(a.transdate))
  128. THEN 0
  129. ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
  130. END) AS due,
  131. (ac.due - (CASE WHEN c.discount_terms < extract('days' FROM age(a.transdate))
  132. THEN 0
  133. ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
  134. END))/
  135. (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
  136. THEN 1
  137. ELSE
  138. (CASE WHEN in_account_class =1
  139. THEN ex.buy
  140. ELSE ex.sell END)
  141. END) AS due_fx,
  142. (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
  143. THEN 1
  144. ELSE
  145. (CASE WHEN in_account_class =1
  146. THEN ex.buy
  147. ELSE ex.sell END)
  148. END) AS exchangerate
  149. FROM (SELECT id, invnumber, transdate, amount, entity_id,
  150. 1 as invoice_class, paid, curr,
  151. entity_credit_account, department_id
  152. FROM ap
  153. UNION
  154. SELECT id, invnumber, transdate, amount, entity_id,
  155. 2 AS invoice_class, paid, curr,
  156. entity_credit_account, department_id
  157. FROM ar
  158. ) a
  159. JOIN (SELECT trans_id, chart_id, sum(CASE WHEN in_account_class = 1 THEN amount
  160. WHEN in_account_class = 2
  161. THEN amount * -1
  162. END) as due
  163. FROM acc_trans
  164. GROUP BY trans_id, chart_id) ac ON (ac.trans_id = a.id)
  165. JOIN chart ON (chart.id = ac.chart_id)
  166. LEFT JOIN exchangerate ex ON ( ex.transdate = a.transdate AND ex.curr = a.curr )
  167. JOIN entity_credit_account c ON (c.id = a.entity_credit_account
  168. OR (a.entity_credit_account IS NULL and a.entity_id = c.entity_id))
  169. WHERE ((chart.link = 'AP' AND in_account_class = 1)
  170. OR (chart.link = 'AR' AND in_account_class = 2))
  171. AND a.invoice_class = in_account_class
  172. AND c.entity_class = in_account_class
  173. AND c.id = in_entity_credit_id
  174. AND a.amount - a.paid <> 0
  175. AND a.curr = in_curr
  176. AND (a.transdate >= in_datefrom
  177. OR in_datefrom IS NULL)
  178. AND (a.transdate <= in_dateto
  179. OR in_dateto IS NULL)
  180. AND (a.amount >= in_amountfrom
  181. OR in_amountfrom IS NULL)
  182. AND (a.amount <= in_amountto
  183. OR in_amountto IS NULL)
  184. AND (a.department_id = in_department_id
  185. OR in_department_id IS NULL)
  186. AND due <> 0
  187. GROUP BY a.invnumber, a.transdate, a.amount, amount_fx, discount, discount_fx, ac.due, a.id, c.discount_terms, ex.buy, ex.sell, a.curr
  188. LOOP
  189. RETURN NEXT payment_inv;
  190. END LOOP;
  191. END;
  192. $$ LANGUAGE PLPGSQL;
  193. COMMENT ON FUNCTION payment_get_open_invoices(int, int, char(3), date, date, numeric, numeric, int) IS
  194. $$ This function takes three arguments:
  195. Type: 1 for vendor, 2 for customer
  196. Entity_id: The entity_id of the customer or vendor
  197. Currency: 3 characters for currency ('USD' for example).
  198. Returns all open invoices for the entity in question. $$;
  199. CREATE TYPE payment_contact_invoice AS (
  200. contact_id int,
  201. econtrol_code text,
  202. eca_description text,
  203. contact_name text,
  204. account_number text,
  205. total_due numeric,
  206. invoices text[],
  207. has_vouchers int
  208. );
  209. CREATE OR REPLACE FUNCTION payment_get_all_contact_invoices
  210. (in_account_class int, in_business_id int, in_currency char(3),
  211. in_date_from date, in_date_to date, in_batch_id int,
  212. in_ar_ap_accno text, in_meta_number text)
  213. RETURNS SETOF payment_contact_invoice AS
  214. $$
  215. DECLARE payment_item payment_contact_invoice;
  216. BEGIN
  217. FOR payment_item IN
  218. SELECT c.id AS contact_id, e.control_code as econtrol_code,
  219. c.description as eca_description,
  220. e.name AS contact_name,
  221. c.meta_number AS account_number,
  222. sum (coalesce(p.due, 0) -
  223. CASE WHEN c.discount_terms
  224. > extract('days' FROM age(a.transdate))
  225. THEN 0
  226. ELSE (coalesce(p.due, 0)) * coalesce(c.discount, 0) / 100
  227. END) AS total_due,
  228. compound_array(ARRAY[[
  229. a.id::text, a.invnumber, a.transdate::text,
  230. a.amount::text, (a.amount - p.due)::text,
  231. (CASE WHEN c.discount_terms
  232. > extract('days' FROM age(a.transdate))
  233. THEN 0
  234. ELSE (a.amount - coalesce((a.amount - p.due), 0)) * coalesce(c.discount, 0) / 100
  235. END)::text,
  236. (coalesce(p.due, 0) -
  237. (CASE WHEN c.discount_terms
  238. > extract('days' FROM age(a.transdate))
  239. THEN 0
  240. ELSE (coalesce(p.due, 0)) * coalesce(c.discount, 0) / 100
  241. END))::text]]),
  242. sum(case when a.batch_id = in_batch_id then 1
  243. else 0 END),
  244. bool_and(lock_record(a.id, (select max(session_id) FROM "session" where users_id = (
  245. select id from users WHERE username =
  246. SESSION_USER))))
  247. FROM entity e
  248. JOIN entity_credit_account c ON (e.id = c.entity_id)
  249. JOIN (SELECT ap.id, invnumber, transdate, amount, entity_id,
  250. paid, curr, 1 as invoice_class,
  251. entity_credit_account, on_hold, v.batch_id,
  252. approved
  253. FROM ap
  254. LEFT JOIN (select * from voucher where batch_class = 1) v
  255. ON (ap.id = v.trans_id)
  256. WHERE in_account_class = 1
  257. AND (v.batch_class = 1 or v.batch_id IS NULL)
  258. UNION
  259. SELECT ar.id, invnumber, transdate, amount, entity_id,
  260. paid, curr, 2 as invoice_class,
  261. entity_credit_account, on_hold, v.batch_id,
  262. approved
  263. FROM ar
  264. LEFT JOIN (select * from voucher where batch_class = 2) v
  265. ON (ar.id = v.trans_id)
  266. WHERE in_account_class = 2
  267. AND (v.batch_class = 2 or v.batch_id IS NULL)
  268. ORDER BY transdate
  269. ) a ON (a.entity_credit_account = c.id)
  270. JOIN transactions t ON (a.id = t.id)
  271. JOIN (SELECT trans_id,
  272. sum(CASE WHEN in_account_class = 1 THEN amount
  273. WHEN in_account_class = 2
  274. THEN amount * -1
  275. END) AS due
  276. FROM acc_trans
  277. JOIN chart ON (chart.id = acc_trans.chart_id)
  278. WHERE ((chart.link = 'AP' AND in_account_class = 1)
  279. OR (chart.link = 'AR' AND in_account_class = 2))
  280. GROUP BY trans_id) p ON (a.id = p.trans_id)
  281. WHERE a.batch_id = in_batch_id
  282. OR (a.invoice_class = in_account_class
  283. AND a.approved
  284. AND c.business_id =
  285. coalesce(in_business_id, c.business_id)
  286. AND ((a.transdate >= COALESCE(in_date_from, a.transdate)
  287. AND a.transdate <= COALESCE(in_date_to, a.transdate)))
  288. AND c.entity_class = in_account_class
  289. AND a.curr = in_currency
  290. AND a.entity_credit_account = c.id
  291. AND p.due <> 0
  292. AND a.amount <> a.paid
  293. AND NOT a.on_hold
  294. AND NOT (t.locked_by IS NOT NULL AND t.locked_by IN
  295. (select "session_id" FROM "session"
  296. WHERE users_id IN
  297. (select id from users
  298. where username <> SESSION_USER)))
  299. AND EXISTS (select trans_id FROM acc_trans
  300. WHERE trans_id = a.id AND
  301. chart_id = (SELECT id frOM chart
  302. WHERE accno
  303. = in_ar_ap_accno)
  304. ))
  305. GROUP BY c.id, e.name, c.meta_number, c.threshold,
  306. e.control_code, c.description
  307. HAVING (in_meta_number IS NULL
  308. OR in_meta_number = c.meta_number) AND
  309. (sum(p.due) >= c.threshold
  310. OR sum(case when a.batch_id = in_batch_id then 1
  311. else 0 END) > 0)
  312. ORDER BY c.meta_number ASC
  313. LOOP
  314. RETURN NEXT payment_item;
  315. END LOOP;
  316. END;
  317. $$ LANGUAGE plpgsql;
  318. COMMENT ON FUNCTION payment_get_all_contact_invoices
  319. (in_account_class int, in_business_id int, in_currency char(3),
  320. in_date_from date, in_date_to date, in_batch_id int,
  321. in_ar_ap_accno text, in_meta_number text) IS
  322. $$
  323. This function takes the following arguments (all prefaced with in_ in the db):
  324. account_class: 1 for vendor, 2 for customer
  325. business_type: integer of business.id.
  326. currency: char(3) of currency (for example 'USD')
  327. date_from, date_to: These dates are inclusive.
  328. 1;3B
  329. batch_id: For payment batches, where fees are concerned.
  330. ar_ap_accno: The AR/AP account number.
  331. This then returns a set of contact information with a 2 dimensional array
  332. cnsisting of outstanding invoices.
  333. $$;
  334. CREATE OR REPLACE FUNCTION payment_bulk_queue
  335. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  336. in_ar_ap_accno text, in_cash_accno text,
  337. in_payment_date date, in_account_class int)
  338. returns int as
  339. $$
  340. BEGIN
  341. INSERT INTO payments_queue
  342. (transactions, batch_id, source, total, ar_ap_accno, cash_accno,
  343. payment_date, account_class)
  344. VALUES
  345. (in_transactions, in_batch_id, in_source, in_total, in_ar_ap_accno,
  346. in_cash_accno, in_payment_date, in_account_class);
  347. RETURN array_upper(in_transactions, 1) -
  348. array_lower(in_transactions, 1);
  349. END;
  350. $$ LANGUAGE PLPGSQL;
  351. CREATE OR REPLACE FUNCTION job__process_payment(in_job_id int)
  352. RETURNS bool AS $$
  353. DECLARE
  354. queue_record RECORD;
  355. t_auth_name text;
  356. t_counter int;
  357. BEGIN
  358. -- TODO: Move the set session authorization into a utility function
  359. SELECT entered_by INTO t_auth_name FROM pending_job
  360. WHERE id = in_job_id;
  361. EXECUTE 'SET SESSION AUTHORIZATION ' || quote_ident(t_auth_name);
  362. t_counter := 0;
  363. FOR queue_record IN
  364. SELECT *
  365. FROM payments_queue WHERE job_id = in_job_id
  366. LOOP
  367. PERFORM payment_bulk_post
  368. (queue_record.transactions, queue_record.batch_id,
  369. queue_record.source, queue_record.total,
  370. queue_record.ar_ap_accno,
  371. queue_record.cash_accno,
  372. queue_record.payment_date,
  373. queue_record.account_class);
  374. t_counter := t_counter + 1;
  375. RAISE NOTICE 'Processed record %, starting transaction %',
  376. t_counter, queue_record.transactions[1][1];
  377. END LOOP;
  378. DELETE FROM payments_queue WHERE job_id = in_job_id;
  379. UPDATE pending_job
  380. SET completed_at = timeofday()::timestamp,
  381. success = true
  382. WHERE id = in_job_id;
  383. RETURN TRUE;
  384. END;
  385. $$ language plpgsql;
  386. CREATE OR REPLACE FUNCTION job__create(in_batch_class int, in_batch_id int)
  387. RETURNS int AS
  388. $$
  389. BEGIN
  390. INSERT INTO pending_job (batch_class, batch_id)
  391. VALUES (coalesce(in_batch_class, 3), in_batch_id);
  392. RETURN currval('pending_job_id_seq');
  393. END;
  394. $$ LANGUAGE PLPGSQL;
  395. CREATE TYPE job__status AS (
  396. completed int, -- 1 for completed, 0 for no
  397. success int, -- 1 for success, 0 for no
  398. completed_at timestamp,
  399. error_condition text -- error if not successful
  400. );
  401. CREATE OR REPLACE FUNCTION job__status(in_job_id int) RETURNS job__status AS
  402. $$
  403. DECLARE out_row job__status;
  404. BEGIN
  405. SELECT (completed_at IS NULL)::INT, success::int, completed_at,
  406. error_condition
  407. INTO out_row
  408. FROM pending_job
  409. WHERE id = in_job_id;
  410. RETURN out_row;
  411. END;
  412. $$ language plpgsql;
  413. CREATE OR REPLACE FUNCTION payment_bulk_post
  414. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  415. in_ar_ap_accno text, in_cash_accno text,
  416. in_payment_date date, in_account_class int)
  417. RETURNS int AS
  418. $$
  419. DECLARE
  420. out_count int;
  421. t_voucher_id int;
  422. t_trans_id int;
  423. t_amount numeric;
  424. t_ar_ap_id int;
  425. t_cash_id int;
  426. BEGIN
  427. IF in_batch_id IS NULL THEN
  428. -- t_voucher_id := NULL;
  429. RAISE EXCEPTION 'Bulk Post Must be from Batch!';
  430. ELSE
  431. INSERT INTO voucher (batch_id, batch_class, trans_id)
  432. values (in_batch_id, 3, in_transactions[1][1]);
  433. t_voucher_id := currval('voucher_id_seq');
  434. END IF;
  435. CREATE TEMPORARY TABLE bulk_payments_in (id int, amount numeric);
  436. select id into t_ar_ap_id from chart where accno = in_ar_ap_accno;
  437. select id into t_cash_id from chart where accno = in_cash_accno;
  438. FOR out_count IN
  439. array_lower(in_transactions, 1) ..
  440. array_upper(in_transactions, 1)
  441. LOOP
  442. EXECUTE $E$
  443. INSERT INTO bulk_payments_in(id, amount)
  444. VALUES ($E$ || quote_literal(in_transactions[out_count][1])
  445. || $E$, $E$ ||
  446. quote_literal(in_transactions[out_count][2])
  447. || $E$)$E$;
  448. END LOOP;
  449. EXECUTE $E$
  450. INSERT INTO acc_trans
  451. (trans_id, chart_id, amount, approved, voucher_id, transdate,
  452. source)
  453. SELECT id,
  454. case when $E$ || quote_literal(in_account_class) || $E$ = 1
  455. THEN $E$ || t_cash_id || $E$
  456. WHEN $E$ || quote_literal(in_account_class) || $E$ = 2
  457. THEN $E$ || t_ar_ap_id || $E$
  458. ELSE -1 END,
  459. amount,
  460. CASE
  461. WHEN $E$|| t_voucher_id || $E$ IS NULL THEN true
  462. ELSE false END,
  463. $E$ || t_voucher_id || $E$, $E$|| quote_literal(in_payment_date)
  464. ||$E$ , $E$ ||COALESCE(quote_literal(in_source), 'NULL') ||$E$
  465. FROM bulk_payments_in $E$;
  466. EXECUTE $E$
  467. INSERT INTO acc_trans
  468. (trans_id, chart_id, amount, approved, voucher_id, transdate,
  469. source)
  470. SELECT id,
  471. case when $E$ || quote_literal(in_account_class) || $E$ = 1
  472. THEN $E$ || t_ar_ap_id || $E$
  473. WHEN $E$ || quote_literal(in_account_class) || $E$ = 2
  474. THEN $E$ || t_cash_id || $E$
  475. ELSE -1 END,
  476. amount * -1,
  477. CASE
  478. WHEN $E$|| t_voucher_id || $E$ IS NULL THEN true
  479. ELSE false END,
  480. $E$ || t_voucher_id || $E$, $E$|| quote_literal(in_payment_date)
  481. ||$E$ , $E$ ||COALESCE(quote_literal(in_source), 'null') ||$E$
  482. FROM bulk_payments_in $E$;
  483. EXECUTE $E$
  484. UPDATE ap
  485. set paid = paid + (select amount from bulk_payments_in b
  486. where b.id = ap.id)
  487. where id in (select id from bulk_payments_in) $E$;
  488. EXECUTE $E$ DROP TABLE bulk_payments_in $E$;
  489. perform unlock_all();
  490. return out_count;
  491. END;
  492. $$ language plpgsql;
  493. COMMENT ON FUNCTION payment_bulk_post
  494. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  495. in_ar_ap_accno text, in_cash_accno text,
  496. in_payment_date date, in_account_class int)
  497. IS
  498. $$ Note that in_transactions is a two-dimensional numeric array. Of each
  499. sub-array, the first element is the (integer) transaction id, and the second
  500. is the amount for that transaction. $$;
  501. --
  502. -- WE NEED A PAYMENT TABLE
  503. --
  504. CREATE TABLE payment (
  505. id serial primary key,
  506. reference text NOT NULL,
  507. gl_id integer references gl(id),
  508. payment_class integer NOT NULL,
  509. payment_date date default current_date,
  510. closed bool default FALSE,
  511. entity_credit_id integer references entity_credit_account(id),
  512. employee_id integer references entity_employee(entity_id),
  513. currency char(3),
  514. notes text,
  515. department_id integer default 0);
  516. COMMENT ON TABLE payment IS $$ This table will store the main data on a payment, prepayment, overpayment, et$$;
  517. COMMENT ON COLUMN payment.reference IS $$ This field will store the code for both receipts and payment order $$;
  518. COMMENT ON COLUMN payment.closed IS $$ This will store the current state of a payment/receipt order $$;
  519. COMMENT ON COLUMN payment.gl_id IS $$ A payment should always be linked to a GL movement $$;
  520. CREATE INDEX payment_id_idx ON payment(id);
  521. CREATE TABLE payment_links (
  522. payment_id integer references Payment(id),
  523. entry_id integer references acc_trans(entry_id),
  524. type integer);
  525. COMMENT ON TABLE payment_links IS $$
  526. An explanation to the type field.
  527. * A type 0 means the link is referencing an ar/ap and was created
  528. using an overpayment movement after the receipt was created
  529. * A type 1 means the link is referencing an ar/ap and was made
  530. on the payment creation, its not the product of an overpayment movement
  531. * A type 2 means the link is not referencing an ar/ap and its the product
  532. of the overpayment logic
  533. With this ideas in order we can do the following
  534. To get the payment amount we will sum the entries with type > 0.
  535. To get the linked amount we will sum the entries with type < 2.
  536. The overpayment account can be obtained from the entries with type = 2.
  537. This reasoning is hacky and i hope it can dissapear when we get to 1.4 - D.M.
  538. $$;
  539. CREATE OR REPLACE FUNCTION payment_post
  540. (in_datepaid date,
  541. in_account_class int,
  542. in_entity_credit_id int,
  543. in_curr char(3),
  544. in_notes text,
  545. in_department_id int,
  546. in_gl_description text,
  547. in_cash_account_id int[],
  548. in_amount numeric[],
  549. in_cash_approved bool[],
  550. in_source text[],
  551. in_memo text[],
  552. in_transaction_id int[],
  553. in_op_amount numeric[],
  554. in_op_cash_account_id int[],
  555. in_op_source text[],
  556. in_op_memo text[],
  557. in_op_account_id int[],
  558. in_approved bool)
  559. RETURNS INT AS
  560. $$
  561. DECLARE var_payment_id int;
  562. DECLARE var_gl_id int;
  563. DECLARE var_entry record;
  564. DECLARE var_entry_id int[];
  565. DECLARE out_count int;
  566. DECLARE coa_id record;
  567. DECLARE var_employee int;
  568. DECLARE var_account_id int;
  569. DECLARE default_currency char(3);
  570. DECLARE current_exchangerate numeric;
  571. DECLARE old_exchangerate numeric;
  572. DECLARE tmp_amount numeric;
  573. BEGIN
  574. SELECT * INTO default_currency FROM defaults_get_defaultcurrency();
  575. SELECT * INTO current_exchangerate FROM currency_get_exchangerate(in_curr, in_datepaid, in_account_class);
  576. SELECT INTO var_employee entity_id FROM users WHERE username = SESSION_USER LIMIT 1;
  577. --
  578. -- WE HAVE TO INSERT THE PAYMENT, USING THE GL INFORMATION
  579. -- THE ID IS GENERATED BY payment_id_seq
  580. --
  581. INSERT INTO payment (reference, payment_class, payment_date,
  582. employee_id, currency, notes, department_id, entity_credit_id)
  583. VALUES ((CASE WHEN in_account_class = 1 THEN
  584. setting_increment('rcptnumber') -- I FOUND THIS ON sql/modules/Settings.sql
  585. ELSE -- and it is very usefull
  586. setting_increment('paynumber')
  587. END),
  588. in_account_class, in_datepaid, var_employee,
  589. in_curr, in_notes, in_department_id, in_entity_credit_id);
  590. SELECT currval('payment_id_seq') INTO var_payment_id; -- WE'LL NEED THIS VALUE TO USE payment_link table
  591. -- WE'LL NEED THIS VALUE TO JOIN WITH PAYMENT
  592. -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
  593. --
  594. -- FIRST WE SHOULD INSERT THE CASH ACCOUNTS
  595. --
  596. -- WE SHOULD HAVE THE DATA STORED AS (ACCNO, AMOUNT), SO
  597. FOR out_count IN
  598. array_lower(in_cash_account_id, 1) ..
  599. array_upper(in_cash_account_id, 1)
  600. LOOP
  601. INSERT INTO acc_trans (chart_id, amount,
  602. trans_id, transdate, approved, source, memo)
  603. VALUES (in_cash_account_id[out_count],
  604. CASE WHEN in_account_class = 1 THEN in_amount[out_count]*current_exchangerate
  605. ELSE (in_amount[out_count]*current_exchangerate)* - 1
  606. END,
  607. in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  608. in_source[out_count], in_memo[out_count]);
  609. INSERT INTO payment_links
  610. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 1);
  611. END LOOP;
  612. -- NOW LETS HANDLE THE AR/AP ACCOUNTS
  613. -- WE RECEIVED THE TRANSACTIONS_ID AND WE CAN OBTAIN THE ACCOUNT FROM THERE
  614. FOR out_count IN
  615. array_lower(in_transaction_id, 1) ..
  616. array_upper(in_transaction_id, 1)
  617. LOOP
  618. SELECT INTO var_account_id chart_id FROM acc_trans as ac
  619. JOIN chart as c ON (c.id = ac.chart_id)
  620. WHERE
  621. trans_id = in_transaction_id[out_count] AND
  622. ( c.link = 'AP' OR c.link = 'AR' );
  623. -- We need to know the exchangerate of this transaction
  624. IF (current_exchangerate = 1 ) THEN
  625. old_exchangerate := 1;
  626. ELSIF (in_account_class = 1) THEN
  627. SELECT buy INTO old_exchangerate
  628. FROM exchangerate e
  629. JOIN ap a on (a.transdate = e.transdate )
  630. WHERE a.id = in_transaction_id[out_count];
  631. ELSE
  632. SELECT sell INTO old_exchangerate
  633. FROM exchangerate e
  634. JOIN ar a on (a.transdate = e.transdate )
  635. WHERE a.id = in_transaction_id[out_count];
  636. END IF;
  637. -- Now we post the AP/AR transaction
  638. INSERT INTO acc_trans (chart_id, amount,
  639. trans_id, transdate, approved, source, memo)
  640. VALUES (var_account_id,
  641. CASE WHEN in_account_class = 1 THEN
  642. (in_amount[out_count]*old_exchangerate) * -1
  643. ELSE in_amount[out_count]*old_exchangerate
  644. END,
  645. in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  646. in_source[out_count], in_memo[out_count]);
  647. -- Lets set the gain/loss, if tmp_amount equals zero then we dont need to post
  648. -- any transaction
  649. tmp_amount := in_amount[out_count]*current_exchangerate - in_amount[out_count]*old_exchangerate;
  650. IF (tmp_amount < 0) THEN
  651. IF (in_account_class = 1) THEN
  652. INSERT INTO acc_trans (chart_id, amount, trans_id, transdate, approved, source)
  653. VALUES (CAST((select value from defaults where setting_key like 'fxloss_accno_id') AS INT),
  654. tmp_amount, in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  655. in_source[out_count]);
  656. ELSE
  657. INSERT INTO acc_trans (chart_id, amount, trans_id, transdate, approved, source)
  658. VALUES (CAST((select value from defaults where setting_key like 'fxgain_accno_id') AS INT),
  659. tmp_amount, in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  660. in_source[out_count]);
  661. END IF;
  662. ELSIF (tmp_amount > 0) THEN
  663. IF (in_account_class = 1) THEN
  664. INSERT INTO acc_trans (chart_id, amount, trans_id, transdate, approved, source)
  665. VALUES (CAST((select value from defaults where setting_key like 'fxgain_accno_id') AS INT),
  666. tmp_amount, in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  667. in_source[out_count]);
  668. ELSE
  669. INSERT INTO acc_trans (chart_id, amount, trans_id, transdate, approved, source)
  670. VALUES (CAST((select value from defaults where setting_key like 'fxloss_accno_id') AS INT),
  671. tmp_amount, in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  672. in_source[out_count]);
  673. END IF;
  674. END IF;
  675. -- Now we set the links
  676. INSERT INTO payment_links
  677. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 1);
  678. END LOOP;
  679. --
  680. -- WE NEED TO HANDLE THE OVERPAYMENTS NOW
  681. --
  682. --
  683. -- FIRST WE HAVE TO MAKE THE GL TO HOLD THE OVERPAYMENT TRANSACTIONS
  684. -- THE ID IS GENERATED BY gl_id_seq
  685. --
  686. IF (array_upper(in_op_cash_account_id, 1) > 0) THEN
  687. INSERT INTO gl (reference, description, transdate,
  688. person_id, notes, approved, department_id)
  689. VALUES (setting_increment('glnumber'),
  690. in_gl_description, in_datepaid, var_employee,
  691. in_notes, in_approved, in_department_id);
  692. SELECT currval('id') INTO var_gl_id;
  693. --
  694. -- WE NEED TO SET THE GL_ID FIELD ON PAYMENT'S TABLE
  695. --
  696. UPDATE payment SET gl_id = var_gl_id
  697. WHERE id = var_payment_id;
  698. -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
  699. --
  700. -- FIRST WE SHOULD INSERT THE OVERPAYMENT CASH ACCOUNTS
  701. --
  702. FOR out_count IN
  703. array_lower(in_op_cash_account_id, 1) ..
  704. array_upper(in_op_cash_account_id, 1)
  705. LOOP
  706. INSERT INTO acc_trans (chart_id, amount,
  707. trans_id, transdate, approved, source, memo)
  708. VALUES (in_op_cash_account_id[out_count],
  709. CASE WHEN in_account_class = 2 THEN in_op_amount[out_count]
  710. ELSE in_op_amount[out_count] * - 1
  711. END,
  712. var_gl_id, in_datepaid, coalesce(in_approved, true),
  713. in_op_source[out_count], in_op_memo[out_count]);
  714. INSERT INTO payment_links
  715. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 2);
  716. END LOOP;
  717. -- NOW LETS HANDLE THE OVERPAYMENT ACCOUNTS
  718. FOR out_count IN
  719. array_lower(in_op_account_id, 1) ..
  720. array_upper(in_op_account_id, 1)
  721. LOOP
  722. INSERT INTO acc_trans (chart_id, amount,
  723. trans_id, transdate, approved, source, memo)
  724. VALUES (in_op_account_id[out_count],
  725. CASE WHEN in_account_class = 2 THEN in_op_amount[out_count] * -1
  726. ELSE in_op_amount[out_count]
  727. END,
  728. var_gl_id, in_datepaid, coalesce(in_approved, true),
  729. in_op_source[out_count], in_op_memo[out_count]);
  730. INSERT INTO payment_links
  731. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 2);
  732. END LOOP;
  733. END IF;
  734. return var_payment_id;
  735. END;
  736. $$ LANGUAGE PLPGSQL;
  737. -- I HAVE TO MAKE A COMMENT ON THIS FUNCTION
  738. -- Move this to the projects module when we start on that. CT
  739. CREATE OR REPLACE FUNCTION project_list_open(in_date date)
  740. RETURNS SETOF project AS
  741. $$
  742. DECLARE out_project project%ROWTYPE;
  743. BEGIN
  744. FOR out_project IN
  745. SELECT * from project
  746. WHERE startdate <= in_date AND enddate >= in_date
  747. AND completed = 0
  748. LOOP
  749. return next out_project;
  750. END LOOP;
  751. END;
  752. $$ language plpgsql;
  753. comment on function project_list_open(in_date date) is
  754. $$ This function returns all projects that were open as on the date provided as
  755. the argument.$$;
  756. -- Move this to the projects module when we start on that. CT
  757. CREATE OR REPLACE FUNCTION department_list(in_role char)
  758. RETURNS SETOF department AS
  759. $$
  760. DECLARE out_department department%ROWTYPE;
  761. BEGIN
  762. FOR out_department IN
  763. SELECT * from department
  764. WHERE role = coalesce(in_role, role)
  765. LOOP
  766. return next out_department;
  767. END LOOP;
  768. END;
  769. $$ language plpgsql;
  770. -- Move this into another module.
  771. comment on function department_list(in_role char) is
  772. $$ This function returns all department that match the role provided as
  773. the argument.$$;
  774. CREATE OR REPLACE FUNCTION payments_get_open_currencies(in_account_class int)
  775. RETURNS SETOF char(3) AS
  776. $$
  777. DECLARE resultrow record;
  778. BEGIN
  779. FOR resultrow IN
  780. SELECT DISTINCT curr FROM ar
  781. UNION
  782. SELECT DISTINCT curr FROM ap
  783. ORDER BY curr
  784. LOOP
  785. return next resultrow.curr;
  786. END LOOP;
  787. END;
  788. $$ language plpgsql;
  789. CREATE OR REPLACE FUNCTION currency_get_exchangerate(in_currency char(3), in_date date, in_account_class int)
  790. RETURNS NUMERIC AS
  791. $$
  792. DECLARE
  793. out_exrate exchangerate.buy%TYPE;
  794. default_currency char(3);
  795. BEGIN
  796. SELECT * INTO default_currency FROM defaults_get_defaultcurrency();
  797. IF default_currency = in_currency THEN
  798. RETURN 1;
  799. END IF;
  800. IF in_account_class = 1 THEN
  801. SELECT buy INTO out_exrate
  802. FROM exchangerate
  803. WHERE transdate = in_date AND curr = in_currency;
  804. ELSE
  805. SELECT sell INTO out_exrate
  806. FROM exchangerate
  807. WHERE transdate = in_date AND curr = in_currency;
  808. END IF;
  809. RETURN out_exrate;
  810. END;
  811. $$ language plpgsql;
  812. COMMENT ON FUNCTION currency_get_exchangerate(in_currency char(3), in_date date, in_account_class int) IS
  813. $$ This function return the exchange rate of a given currency, date and exchange rate class (buy or sell). $$;
  814. --
  815. -- payment_location_result has the same arch as location_result, except for one field
  816. -- This should be unified on the API when we get things working - David Mora
  817. --
  818. CREATE TYPE payment_location_result AS (
  819. id int,
  820. line_one text,
  821. line_two text,
  822. line_three text,
  823. city text,
  824. state text,
  825. mail_code text,
  826. country text,
  827. class text
  828. );
  829. --
  830. -- payment_get_vc_info has the same arch as company__list_locations, except for the filtering capabilities
  831. -- This should be unified on the API when we get things working - David Mora
  832. --
  833. CREATE OR REPLACE FUNCTION payment_get_vc_info(in_entity_credit_id int, in_location_class_id int)
  834. RETURNS SETOF payment_location_result AS
  835. $$
  836. DECLARE out_row payment_location_result;
  837. BEGIN
  838. FOR out_row IN
  839. SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
  840. l.state, l.mail_code, c.name, lc.class
  841. FROM location l
  842. JOIN company_to_location ctl ON (ctl.location_id = l.id)
  843. JOIN company cp ON (ctl.company_id = cp.id)
  844. JOIN location_class lc ON (ctl.location_class = lc.id)
  845. JOIN country c ON (c.id = l.country_id)
  846. JOIN entity_credit_account ec ON (ec.entity_id = cp.entity_id)
  847. WHERE ec.id = in_entity_credit_id AND
  848. lc.id = in_location_class_id
  849. ORDER BY lc.id, l.id, c.name
  850. LOOP
  851. RETURN NEXT out_row;
  852. END LOOP;
  853. END;
  854. $$ LANGUAGE PLPGSQL;
  855. COMMENT ON FUNCTION payment_get_vc_info(in_entity_id int, in_location_class_id int) IS
  856. $$ This function returns vendor or customer info $$;
  857. CREATE TYPE payment_record AS (
  858. amount numeric,
  859. meta_number text,
  860. credit_id int,
  861. company_paid text,
  862. accounts text[],
  863. source text,
  864. date_paid date
  865. );
  866. CREATE OR REPLACE FUNCTION payment__search
  867. (in_source text, in_date_from date, in_date_to date, in_credit_id int,
  868. in_cash_accno text, in_account_class int)
  869. RETURNS SETOF payment_record AS
  870. $$
  871. DECLARE
  872. out_row payment_record;
  873. BEGIN
  874. FOR out_row IN
  875. select sum(CASE WHEN c.entity_class = 1 then a.amount
  876. ELSE a.amount * -1 END), c.meta_number,
  877. c.id, co.legal_name,
  878. compound_array(ARRAY[ARRAY[ch.id::text, ch.accno,
  879. ch.description]]), a.source, a.transdate
  880. FROM entity_credit_account c
  881. JOIN ( select entity_credit_account, id
  882. FROM ar WHERE in_account_class = 2
  883. UNION
  884. SELECT entity_credit_account, id
  885. FROM ap WHERE in_account_class = 1
  886. ) arap ON (arap.entity_credit_account = c.id)
  887. JOIN acc_trans a ON (arap.id = a.trans_id)
  888. JOIN chart ch ON (ch.id = a.chart_id)
  889. JOIN company co ON (c.entity_id = co.entity_id)
  890. WHERE (ch.accno = in_cash_accno)
  891. AND (c.id = in_credit_id OR in_credit_id IS NULL)
  892. AND (a.transdate >= in_date_from
  893. OR in_date_from IS NULL)
  894. AND (a.transdate <= in_date_to OR in_date_to IS NULL)
  895. AND (source = in_source OR in_source IS NULL)
  896. GROUP BY c.meta_number, c.id, co.legal_name, a.transdate,
  897. a.source
  898. ORDER BY a.transdate, c.meta_number, a.source
  899. LOOP
  900. RETURN NEXT out_row;
  901. END LOOP;
  902. END;
  903. $$ language plpgsql;
  904. CREATE OR REPLACE FUNCTION payment__reverse
  905. (in_source text, in_date_paid date, in_credit_id int, in_cash_accno text,
  906. in_date_reversed date, in_account_class int, in_batch_id int)
  907. RETURNS INT
  908. AS $$
  909. DECLARE
  910. pay_row record;
  911. t_voucher_id int;
  912. t_voucher_inserted bool;
  913. BEGIN
  914. IF in_batch_id IS NOT NULL THEN
  915. t_voucher_id := nextval('voucher_id_seq');
  916. t_voucher_inserted := FALSE;
  917. END IF;
  918. FOR pay_row IN
  919. SELECT a.*, c.ar_ap_account_id
  920. FROM acc_trans a
  921. JOIN (select id, entity_credit_account
  922. FROM ar WHERE in_account_class = 2
  923. UNION
  924. SELECT id, entity_credit_account
  925. FROM ap WHERE in_account_class = 1
  926. ) arap ON (a.trans_id = arap.id)
  927. JOIN entity_credit_account c
  928. ON (arap.entity_credit_account = c.id)
  929. JOIN chart ch ON (a.chart_id = ch.id)
  930. WHERE coalesce(source, '') = coalesce(in_source, '')
  931. AND transdate = in_date_paid
  932. AND in_credit_id = c.id
  933. AND in_cash_accno = ch.accno
  934. LOOP
  935. IF in_batch_id IS NOT NULL
  936. AND t_voucher_inserted IS NOT TRUE
  937. THEN
  938. INSERT INTO voucher
  939. (id, trans_id, batch_id, batch_class)
  940. VALUES
  941. (t_voucher_id, pay_row.trans_id, in_batch_id,
  942. CASE WHEN in_account_class = 1 THEN 4
  943. WHEN in_account_class = 2 THEN 7
  944. END);
  945. t_voucher_inserted := TRUE;
  946. END IF;
  947. INSERT INTO acc_trans
  948. (trans_id, chart_id, amount, transdate, source, memo, approved,
  949. voucher_id)
  950. VALUES
  951. (pay_row.trans_id, pay_row.chart_id, pay_row.amount * -1,
  952. in_date_reversed, in_source, 'Reversing ' ||
  953. COALESCE(in_source, ''),
  954. case when in_batch_id is not null then false
  955. else true end, t_voucher_id);
  956. INSERT INTO acc_trans
  957. (trans_id, chart_id, amount, transdate, source, memo, approved,
  958. voucher_id)
  959. VALUES
  960. (pay_row.trans_id, pay_row.ar_ap_account_id, pay_row.amount,
  961. in_date_reversed, in_source, 'Reversing ' ||
  962. COALESCE(in_source, ''),
  963. case when in_batch_id is not null then false
  964. else true end, t_voucher_id);
  965. IF in_account_class = 1 THEN
  966. UPDATE ap SET paid = amount -
  967. (SELECT sum(a.amount)
  968. FROM acc_trans a
  969. JOIN chart c ON (a.chart_id = c.id)
  970. WHERE c.link = 'AP'
  971. AND trans_id = pay_row.trans_id
  972. )
  973. WHERE id = pay_row.trans_id;
  974. ELSIF in_account_class = 2 THEN
  975. update ar SET paid = amount -
  976. (SELECT sum(a.amount)
  977. FROM acc_trans a
  978. JOIN chart c ON (a.chart_id = c.id)
  979. WHERE c.link = 'AR'
  980. AND trans_id = pay_row.trans_id
  981. ) * -1
  982. WHERE id = pay_row.trans_id;
  983. ELSE
  984. RAISE EXCEPTION 'Unknown account class for payments %',
  985. in_account_class;
  986. END IF;
  987. END LOOP;
  988. RETURN 1;
  989. END;
  990. $$ LANGUAGE PLPGSQL;
  991. CREATE OR REPLACE FUNCTION payments_set_exchangerate(in_account_class int,
  992. in_exchangerate numeric, in_curr char(3), in_datepaid date )
  993. RETURNS INT
  994. AS $$
  995. DECLARE current_exrate exchangerate%ROWTYPE;
  996. BEGIN
  997. select * INTO current_exrate
  998. FROM exchangerate
  999. WHERE transdate = in_date;
  1000. IF current_exrate.transdate = in_date THEN
  1001. IF in_account_class = 1 THEN
  1002. UPDATE exchangerate set buy = in_exchangerate where transdate = in_date;
  1003. ELSE
  1004. UPDATE exchangerate set sell = in_exchangerate where transdate = in_date;
  1005. END IF;
  1006. RETURN 0;
  1007. ELSE
  1008. IF in_account_class = 1 THEN
  1009. INSERT INTO exchangerate (curr, transdate, buy) values (in_currency, in_date, in_exchangerate);
  1010. ELSE
  1011. INSERT INTO exchangerate (curr, transdate, sell) values (in_currency, in_date, in_exchangerate);
  1012. END IF;
  1013. RETURN 0;
  1014. END IF;
  1015. END;
  1016. $$ language plpgsql;
  1017. CREATE TYPE payment_header_item AS (
  1018. payment_id int,
  1019. payment_reference int,
  1020. payment_date date,
  1021. legal_name text,
  1022. amount numeric,
  1023. employee_first_name text,
  1024. employee_last_name text,
  1025. currency char(3),
  1026. notes text
  1027. );
  1028. -- I NEED TO PLACE THE COMPANY TELEPHONE AND ALL THAT STUFF
  1029. CREATE OR REPLACE FUNCTION payment_gather_header_info(in_account_class int, in_payment_id int)
  1030. RETURNS SETOF payment_header_item AS
  1031. $$
  1032. DECLARE out_payment payment_header_item;
  1033. BEGIN
  1034. FOR out_payment IN
  1035. SELECT p.id as payment_id, p.reference as payment_reference, p.payment_date,
  1036. c.legal_name as legal_name, am.amount as amount, em.first_name, em.last_name, p.currency, p.notes
  1037. FROM payment p
  1038. JOIN employee em ON (em.entity_id = p.employee_id)
  1039. JOIN company c ON (c.entity_id = p.entity_id)
  1040. JOIN ( SELECT sum(a.amount) as amount
  1041. FROM acc_trans a
  1042. JOIN chart c ON (a.chart_id = c.id)
  1043. JOIN payment_links pl ON (pl.entry_id=a.entry_id)
  1044. WHERE
  1045. ( ((c.link like '%AP_paid%' OR c.link like '%AP_discount%') AND in_account_class = 1)
  1046. OR ((c.link like '%AR_paid%' OR c.link like '%AR_discount%') AND in_account_class = 2))
  1047. AND pl.payment_id = in_payment_id ) am ON (1=1)
  1048. WHERE p.id = in_payment_id
  1049. LOOP
  1050. RETURN NEXT out_payment;
  1051. END LOOP;
  1052. END;
  1053. $$ language plpgsql;
  1054. COMMENT ON FUNCTION payment_gather_header_info(int,int) IS
  1055. $$ This function finds a payment based on the id and retrieves the record,
  1056. it is usefull for printing payments :) $$;
  1057. CREATE TYPE payment_line_item AS (
  1058. payment_id int,
  1059. entry_id int,
  1060. link_type int,
  1061. trans_id int,
  1062. invoice_number int,
  1063. chart_id int,
  1064. chart_accno int,
  1065. chart_description text,
  1066. chart_link text,
  1067. amount int,
  1068. trans_date date,
  1069. source text,
  1070. cleared bool,
  1071. fx_transaction bool,
  1072. project_id int,
  1073. memo text,
  1074. invoice_id int,
  1075. approved bool,
  1076. cleared_on date,
  1077. reconciled_on date
  1078. );
  1079. CREATE OR REPLACE FUNCTION payment_gather_line_info(in_account_class int, in_payment_id int)
  1080. RETURNS SETOF payment_line_item AS
  1081. $$
  1082. DECLARE out_payment_line payment_line_item;
  1083. BEGIN
  1084. FOR out_payment_line IN
  1085. SELECT pl.payment_id, ac.entry_id, pl.type as link_type, ac.trans_id, a.invnumber as invoice_number,
  1086. ac.chart_id, ch.accno as chart_accno, ch.description as chart_description, ch.link as chart_link,
  1087. ac.amount, ac.transdate as trans_date, ac.source, ac.cleared_on, ac.fx_transaction, ac.project_id,
  1088. ac.memo, ac.invoice_id, ac.approved, ac.cleared_on, ac.reconciled_on
  1089. FROM acc_trans ac
  1090. JOIN payment_links pl ON (pl.entry_id = ac.entry_id )
  1091. JOIN chart ch ON (ch.id = ac.chart_id)
  1092. LEFT JOIN (SELECT id,invnumber
  1093. FROM ar WHERE in_account_class = 2
  1094. UNION
  1095. SELECT id,invnumber
  1096. FROM ap WHERE in_account_class = 1
  1097. ) a ON (ac.trans_id = a.id)
  1098. WHERE pl.payment_id = in_payment_id
  1099. LOOP
  1100. RETURN NEXT out_payment_line;
  1101. END LOOP;
  1102. END;
  1103. $$ language plpgsql;
  1104. COMMENT ON FUNCTION payment_gather_line_info(int,int) IS
  1105. $$ This function finds a payment based on the id and retrieves all the line records,
  1106. it is usefull for printing payments and build reports :) $$;