summaryrefslogtreecommitdiff
path: root/sql/modules/Payment.sql
blob: 24d1d730a89cb15f18e5b68e55b9fc40ea250bd9 (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. discount numeric,
  82. due numeric
  83. );
  84. CREATE OR REPLACE FUNCTION payment_get_open_invoices
  85. (in_account_class int,
  86. in_entity_credit_id int,
  87. in_curr char(3),
  88. in_datefrom date,
  89. in_dateto date,
  90. in_amountfrom numeric,
  91. in_amountto numeric,
  92. in_department_id int)
  93. RETURNS SETOF payment_invoice AS
  94. $$
  95. DECLARE payment_inv payment_invoice;
  96. BEGIN
  97. FOR payment_inv IN
  98. SELECT a.id AS invoice_id, a.invnumber AS invnumber,
  99. a.transdate AS invoice_date, a.amount AS amount,
  100. (CASE WHEN c.discount_terms < extract('days' FROM age(a.transdate))
  101. THEN 0
  102. ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
  103. END) AS discount, ac.due
  104. FROM (SELECT id, invnumber, transdate, amount, entity_id,
  105. 1 as invoice_class, paid, curr,
  106. entity_credit_account, department_id
  107. FROM ap
  108. UNION
  109. SELECT id, invnumber, transdate, amount, entity_id,
  110. 2 AS invoice_class, paid, curr,
  111. entity_credit_account, department_id
  112. FROM ar
  113. ) a
  114. JOIN (SELECT trans_id, chart_id, sum(CASE WHEN in_account_class = 1 THEN amount
  115. WHEN in_account_class = 2
  116. THEN amount * -1
  117. END) as due
  118. FROM acc_trans
  119. GROUP BY trans_id, chart_id) ac ON (ac.trans_id = a.id)
  120. JOIN chart ON (chart.id = ac.chart_id)
  121. JOIN entity_credit_account c ON (c.id = a.entity_credit_account
  122. OR (a.entity_credit_account IS NULL and a.entity_id = c.entity_id))
  123. WHERE ((chart.link = 'AP' AND in_account_class = 1)
  124. OR (chart.link = 'AR' AND in_account_class = 2))
  125. AND a.invoice_class = in_account_class
  126. AND c.entity_class = in_account_class
  127. AND c.id = in_entity_credit_id
  128. AND a.amount - a.paid <> 0
  129. AND a.curr = in_curr
  130. AND (a.transdate >= in_datefrom
  131. OR in_datefrom IS NULL)
  132. AND (a.transdate <= in_dateto
  133. OR in_dateto IS NULL)
  134. AND (a.amount >= in_amountfrom
  135. OR in_amountfrom IS NULL)
  136. AND (a.amount <= in_amountto
  137. OR in_amountto IS NULL)
  138. AND (a.department_id = in_department_id
  139. OR in_department_id IS NULL)
  140. AND due <> 0
  141. GROUP BY a.invnumber, a.transdate, a.amount, discount, ac.due, a.id, c.discount_terms
  142. LOOP
  143. RETURN NEXT payment_inv;
  144. END LOOP;
  145. END;
  146. $$ LANGUAGE PLPGSQL;
  147. COMMENT ON FUNCTION payment_get_open_invoices(int, int, char(3), date, date, numeric, numeric, int) IS
  148. $$ This function takes three arguments:
  149. Type: 1 for vendor, 2 for customer
  150. Entity_id: The entity_id of the customer or vendor
  151. Currency: 3 characters for currency ('USD' for example).
  152. Returns all open invoices for the entity in question. $$;
  153. CREATE TYPE payment_contact_invoice AS (
  154. contact_id int,
  155. econtrol_code text,
  156. eca_description text,
  157. contact_name text,
  158. account_number text,
  159. total_due numeric,
  160. invoices text[],
  161. has_vouchers int
  162. );
  163. CREATE OR REPLACE FUNCTION payment_get_all_contact_invoices
  164. (in_account_class int, in_business_id int, in_currency char(3),
  165. in_date_from date, in_date_to date, in_batch_id int,
  166. in_ar_ap_accno text, in_meta_number text)
  167. RETURNS SETOF payment_contact_invoice AS
  168. $$
  169. DECLARE payment_item payment_contact_invoice;
  170. BEGIN
  171. FOR payment_item IN
  172. SELECT c.id AS contact_id, e.control_code as econtrol_code,
  173. c.description as eca_description,
  174. e.name AS contact_name,
  175. c.meta_number AS account_number,
  176. sum (coalesce(p.due, 0) -
  177. CASE WHEN c.discount_terms
  178. > extract('days' FROM age(a.transdate))
  179. THEN 0
  180. ELSE (coalesce(p.due, 0)) * coalesce(c.discount, 0) / 100
  181. END) AS total_due,
  182. compound_array(ARRAY[[
  183. a.id::text, a.invnumber, a.transdate::text,
  184. a.amount::text, (a.amount - p.due)::text,
  185. (CASE WHEN c.discount_terms
  186. > extract('days' FROM age(a.transdate))
  187. THEN 0
  188. ELSE (a.amount - coalesce((a.amount - p.due), 0)) * coalesce(c.discount, 0) / 100
  189. END)::text,
  190. (coalesce(p.due, 0) -
  191. (CASE WHEN c.discount_terms
  192. > extract('days' FROM age(a.transdate))
  193. THEN 0
  194. ELSE (coalesce(p.due, 0)) * coalesce(c.discount, 0) / 100
  195. END))::text]]),
  196. sum(case when a.batch_id = in_batch_id then 1
  197. else 0 END),
  198. bool_and(lock_record(a.id, (select max(session_id) FROM "session" where users_id = (
  199. select id from users WHERE username =
  200. SESSION_USER))))
  201. FROM entity e
  202. JOIN entity_credit_account c ON (e.id = c.entity_id)
  203. JOIN (SELECT ap.id, invnumber, transdate, amount, entity_id,
  204. paid, curr, 1 as invoice_class,
  205. entity_credit_account, on_hold, v.batch_id
  206. FROM ap
  207. LEFT JOIN (select * from voucher where batch_class = 1) v
  208. ON (ap.id = v.trans_id)
  209. WHERE in_account_class = 1
  210. AND (v.batch_class = 1 or v.batch_id IS NULL)
  211. UNION
  212. SELECT ar.id, invnumber, transdate, amount, entity_id,
  213. paid, curr, 2 as invoice_class,
  214. entity_credit_account, on_hold, v.batch_id
  215. FROM ar
  216. LEFT JOIN (select * from voucher where batch_class = 2) v
  217. ON (ar.id = v.trans_id)
  218. WHERE in_account_class = 2
  219. AND (v.batch_class = 2 or v.batch_id IS NULL)
  220. ORDER BY transdate
  221. ) a ON (a.entity_credit_account = c.id)
  222. JOIN transactions t ON (a.id = t.id)
  223. JOIN (SELECT trans_id,
  224. sum(CASE WHEN in_account_class = 1 THEN amount
  225. WHEN in_account_class = 2
  226. THEN amount * -1
  227. END) AS due
  228. FROM acc_trans
  229. JOIN chart ON (chart.id = acc_trans.chart_id)
  230. WHERE ((chart.link = 'AP' AND in_account_class = 1)
  231. OR (chart.link = 'AR' AND in_account_class = 2))
  232. GROUP BY trans_id) p ON (a.id = p.trans_id)
  233. WHERE a.batch_id = in_batch_id
  234. OR (a.invoice_class = in_account_class
  235. AND c.business_id =
  236. coalesce(in_business_id, c.business_id)
  237. AND ((a.transdate >= COALESCE(in_date_from, a.transdate)
  238. AND a.transdate <= COALESCE(in_date_to, a.transdate)))
  239. AND c.entity_class = in_account_class
  240. AND a.curr = in_currency
  241. AND a.entity_credit_account = c.id
  242. AND p.due <> 0
  243. AND a.amount <> a.paid
  244. AND NOT a.on_hold
  245. AND NOT (t.locked_by IS NOT NULL AND t.locked_by IN
  246. (select "session_id" FROM "session"
  247. WHERE users_id IN
  248. (select id from users
  249. where username <> SESSION_USER)))
  250. AND EXISTS (select trans_id FROM acc_trans
  251. WHERE trans_id = a.id AND
  252. chart_id = (SELECT id frOM chart
  253. WHERE accno
  254. = in_ar_ap_accno)
  255. ))
  256. GROUP BY c.id, e.name, c.meta_number, c.threshold,
  257. e.control_code, c.description
  258. HAVING (in_meta_number IS NULL
  259. OR in_meta_number = c.meta_number) AND
  260. (sum(p.due) > c.threshold
  261. OR sum(case when a.batch_id = in_batch_id then 1
  262. else 0 END) > 0)
  263. ORDER BY c.meta_number ASC
  264. LOOP
  265. RETURN NEXT payment_item;
  266. END LOOP;
  267. END;
  268. $$ LANGUAGE plpgsql;
  269. COMMENT ON FUNCTION payment_get_all_contact_invoices
  270. (in_account_class int, in_business_id int, in_currency char(3),
  271. in_date_from date, in_date_to date, in_batch_id int,
  272. in_ar_ap_accno text, in_meta_number text) IS
  273. $$
  274. This function takes the following arguments (all prefaced with in_ in the db):
  275. account_class: 1 for vendor, 2 for customer
  276. business_type: integer of business.id.
  277. currency: char(3) of currency (for example 'USD')
  278. date_from, date_to: These dates are inclusive.
  279. 1;3B
  280. batch_id: For payment batches, where fees are concerned.
  281. ar_ap_accno: The AR/AP account number.
  282. This then returns a set of contact information with a 2 dimensional array
  283. cnsisting of outstanding invoices.
  284. $$;
  285. CREATE OR REPLACE FUNCTION payment_bulk_queue
  286. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  287. in_ar_ap_accno text, in_cash_accno text,
  288. in_payment_date date, in_account_class int)
  289. returns int as
  290. $$
  291. BEGIN
  292. INSERT INTO payments_queue
  293. (transactions, batch_id, source, total, ar_ap_accno, cash_accno,
  294. payment_date, account_class)
  295. VALUES
  296. (in_transactions, in_batch_id, in_source, in_total, in_ar_ap_accno,
  297. in_cash_accno, in_payment_date, in_account_class);
  298. RETURN array_upper(in_transactions, 1) -
  299. array_lower(in_transactions, 1);
  300. END;
  301. $$ LANGUAGE PLPGSQL;
  302. CREATE OR REPLACE FUNCTION job__process_payment(in_job_id int)
  303. RETURNS bool AS $$
  304. DECLARE
  305. queue_record RECORD;
  306. t_auth_name text;
  307. t_counter int;
  308. BEGIN
  309. -- TODO: Move the set session authorization into a utility function
  310. SELECT entered_by INTO t_auth_name FROM pending_job
  311. WHERE id = in_job_id;
  312. EXECUTE 'SET SESSION AUTHORIZATION ' || quote_ident(t_auth_name);
  313. t_counter := 0;
  314. FOR queue_record IN
  315. SELECT *
  316. FROM payments_queue WHERE job_id = in_job_id
  317. LOOP
  318. PERFORM payment_bulk_post
  319. (queue_record.transactions, queue_record.batch_id,
  320. queue_record.source, queue_record.total,
  321. queue_record.ar_ap_accno,
  322. queue_record.cash_accno,
  323. queue_record.payment_date,
  324. queue_record.account_class);
  325. t_counter := t_counter + 1;
  326. RAISE NOTICE 'Processed record %, starting transaction %',
  327. t_counter, queue_record.transactions[1][1];
  328. END LOOP;
  329. DELETE FROM payments_queue WHERE job_id = in_job_id;
  330. UPDATE pending_job
  331. SET completed_at = timeofday()::timestamp,
  332. success = true
  333. WHERE id = in_job_id;
  334. RETURN TRUE;
  335. END;
  336. $$ language plpgsql;
  337. CREATE OR REPLACE FUNCTION job__create(in_batch_class int, in_batch_id int)
  338. RETURNS int AS
  339. $$
  340. BEGIN
  341. INSERT INTO pending_job (batch_class, batch_id)
  342. VALUES (coalesce(in_batch_class, 3), in_batch_id);
  343. RETURN currval('pending_job_id_seq');
  344. END;
  345. $$ LANGUAGE PLPGSQL;
  346. CREATE TYPE job__status AS (
  347. completed int, -- 1 for completed, 0 for no
  348. success int, -- 1 for success, 0 for no
  349. completed_at timestamp,
  350. error_condition text -- error if not successful
  351. );
  352. CREATE OR REPLACE FUNCTION job__status(in_job_id int) RETURNS job__status AS
  353. $$
  354. DECLARE out_row job__status;
  355. BEGIN
  356. SELECT (completed_at IS NULL)::INT, success::int, completed_at,
  357. error_condition
  358. INTO out_row
  359. FROM pending_job
  360. WHERE id = in_job_id;
  361. RETURN out_row;
  362. END;
  363. $$ language plpgsql;
  364. CREATE OR REPLACE FUNCTION payment_bulk_post
  365. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  366. in_ar_ap_accno text, in_cash_accno text,
  367. in_payment_date date, in_account_class int)
  368. RETURNS int AS
  369. $$
  370. DECLARE
  371. out_count int;
  372. t_voucher_id int;
  373. t_trans_id int;
  374. t_amount numeric;
  375. t_ar_ap_id int;
  376. t_cash_id int;
  377. BEGIN
  378. IF in_batch_id IS NULL THEN
  379. -- t_voucher_id := NULL;
  380. RAISE EXCEPTION 'Bulk Post Must be from Batch!';
  381. ELSE
  382. INSERT INTO voucher (batch_id, batch_class, trans_id)
  383. values (in_batch_id, 3, in_transactions[1][1]);
  384. t_voucher_id := currval('voucher_id_seq');
  385. END IF;
  386. select id into t_ar_ap_id from chart where accno = in_ar_ap_accno;
  387. select id into t_cash_id from chart where accno = in_cash_accno;
  388. FOR out_count IN
  389. array_lower(in_transactions, 1) ..
  390. array_upper(in_transactions, 1)
  391. LOOP
  392. INSERT INTO acc_trans
  393. (trans_id, chart_id, amount, approved, voucher_id,
  394. transdate, source)
  395. VALUES
  396. (in_transactions[out_count][1],
  397. case when in_account_class = 1 THEN t_cash_id
  398. WHEN in_account_class = 2 THEN t_ar_ap_id
  399. ELSE -1 END,
  400. in_transactions[out_count][2],
  401. CASE WHEN t_voucher_id IS NULL THEN true
  402. ELSE false END,
  403. t_voucher_id, in_payment_date, in_source);
  404. INSERT INTO acc_trans
  405. (trans_id, chart_id, amount, approved, voucher_id,
  406. transdate, source)
  407. VALUES
  408. (in_transactions[out_count][1],
  409. case when in_account_class = 1 THEN t_ar_ap_id
  410. WHEN in_account_class = 2 THEN t_cash_id
  411. ELSE -1 END,
  412. in_transactions[out_count][2]* -1,
  413. CASE WHEN t_voucher_id IS NULL THEN true
  414. ELSE false END,
  415. t_voucher_id, in_payment_date, in_source);
  416. UPDATE ap
  417. set paid = paid +in_transactions[out_count][2]
  418. where id =in_transactions[out_count][1];
  419. END LOOP;
  420. return out_count;
  421. END;
  422. $$ language plpgsql;
  423. COMMENT ON FUNCTION payment_bulk_post
  424. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  425. in_ar_ap_accno text, in_cash_accno text,
  426. in_payment_date date, in_account_class int)
  427. IS
  428. $$ Note that in_transactions is a two-dimensional numeric array. Of each
  429. sub-array, the first element is the (integer) transaction id, and the second
  430. is the amount for that transaction. If the total of the amounts do not add up
  431. to in_total, then an error is generated. $$;
  432. --
  433. -- WE NEED A PAYMENT TABLE
  434. --
  435. CREATE TABLE payment (
  436. id serial primary key,
  437. reference text NOT NULL,
  438. gl_id integer references gl(id),
  439. payment_class integer NOT NULL,
  440. payment_date date default current_date,
  441. closed bool default FALSE,
  442. entity_id integer references entity(id),
  443. employee_id integer references entity_employee(entity_id),
  444. currency char(3),
  445. notes text,
  446. department_id integer default 0);
  447. COMMENT ON TABLE payment IS $$ This table will store the main data on a payment, prepayment, overpayment, et$$;
  448. COMMENT ON COLUMN payment.reference IS $$ This field will store the code for both receipts and payment order $$;
  449. COMMENT ON COLUMN payment.closed IS $$ This will store the current state of a payment/receipt order $$;
  450. COMMENT ON COLUMN payment.gl_id IS $$ A payment should always be linked to a GL movement $$;
  451. CREATE INDEX payment_id_idx ON payment(id);
  452. CREATE TABLE payment_links (
  453. payment_id integer references Payment(id),
  454. entry_id integer references acc_trans(entry_id),
  455. type integer);
  456. COMMENT ON TABLE payment_links IS $$
  457. An explanation to the type field.
  458. * A type 0 means the link is referencing an ar/ap and was created
  459. using an overpayment movement after the receipt was created
  460. * A type 1 means the link is referencing an ar/ap and was made
  461. on the payment creation, its not the product of an overpayment movement
  462. * A type 2 means the link is not referencing an ar/ap and its the product
  463. of the overpayment logic
  464. With this ideas in order we can do the following
  465. To get the payment amount we will sum the entries with type > 0.
  466. To get the linked amount we will sum the entries with type < 2.
  467. The overpayment account can be obtained from the entries with type = 2.
  468. This reasoning is hacky and i hope it can dissapear when we get to 1.4 - D.M.
  469. $$;
  470. CREATE OR REPLACE FUNCTION payment_post
  471. (in_datepaid date,
  472. in_account_class int,
  473. in_entity_id int,
  474. in_curr char(3),
  475. in_notes text,
  476. in_department_id int,
  477. in_gl_description text,
  478. in_cash_account_id int[],
  479. in_amount numeric[],
  480. in_cash_approved bool[],
  481. in_source text[],
  482. in_transaction_id int[],
  483. in_op_amount numeric[],
  484. in_op_cash_account_id int[],
  485. in_op_source text[],
  486. in_op_memo text[],
  487. in_op_account_id int[],
  488. in_approved bool)
  489. RETURNS INT AS
  490. $$
  491. DECLARE var_payment_id int;
  492. DECLARE var_gl_id int;
  493. DECLARE var_entry record;
  494. DECLARE var_entry_id int[];
  495. DECLARE out_count int;
  496. DECLARE coa_id record;
  497. DECLARE var_employee int;
  498. DECLARE var_account_id int;
  499. BEGIN
  500. SELECT INTO var_employee entity_id FROM users WHERE username = SESSION_USER LIMIT 1;
  501. --
  502. -- SECOND WE HAVE TO INSERT THE PAYMENT, USING THE GL INFORMATION
  503. -- THE ID IS GENERATED BY payment_id_seq
  504. --
  505. INSERT INTO payment (reference, payment_class, payment_date,
  506. employee_id, currency, notes, department_id, entity_id)
  507. VALUES ((CASE WHEN in_account_class = 1 THEN
  508. setting_increment('rcptnumber') -- I FOUND THIS ON sql/modules/Settings.sql
  509. ELSE -- and it is very usefull
  510. setting_increment('paynumber')
  511. END),
  512. in_account_class, in_datepaid, var_employee,
  513. in_curr, in_notes, in_department_id, in_entity_id);
  514. SELECT currval('payment_id_seq') INTO var_payment_id; -- WE'LL NEED THIS VALUE TO USE payment_link table
  515. -- WE'LL NEED THIS VALUE TO JOIN WITH PAYMENT
  516. -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
  517. --
  518. -- FIRST WE SHOULD INSERT THE CASH ACCOUNTS
  519. --
  520. -- WE SHOULD HAVE THE DATA STORED AS (ACCNO, AMOUNT), SO
  521. FOR out_count IN
  522. array_lower(in_cash_account_id, 1) ..
  523. array_upper(in_cash_account_id, 1)
  524. LOOP
  525. INSERT INTO acc_trans (chart_id, amount,
  526. trans_id, transdate, approved, source)
  527. VALUES (in_cash_account_id[out_count],
  528. CASE WHEN in_account_class = 1 THEN in_amount[out_count]
  529. ELSE in_amount[out_count]* - 1
  530. END,
  531. in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  532. in_source[out_count]);
  533. INSERT INTO payment_links
  534. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 1);
  535. END LOOP;
  536. -- NOW LETS HANDLE THE AR/AP ACCOUNTS
  537. -- WE RECEIVED THE TRANSACTIONS_ID AND WE CAN OBTAIN THE ACCOUNT FROM THERE
  538. FOR out_count IN
  539. array_lower(in_transaction_id, 1) ..
  540. array_upper(in_transaction_id, 1)
  541. LOOP
  542. SELECT INTO var_account_id chart_id FROM acc_trans as ac
  543. JOIN chart as c ON (c.id = ac.chart_id)
  544. WHERE
  545. trans_id = in_transaction_id[out_count] AND
  546. ( c.link = 'AP' OR c.link = 'AR' );
  547. INSERT INTO acc_trans (chart_id, amount,
  548. trans_id, transdate, approved, source)
  549. VALUES (var_account_id,
  550. CASE WHEN in_account_class = 1 THEN in_amount[out_count] * -1
  551. ELSE in_amount[out_count]
  552. END,
  553. in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
  554. in_source[out_count]);
  555. INSERT INTO payment_links
  556. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 1);
  557. END LOOP;
  558. --
  559. -- WE NEED TO HANDLE THE OVERPAYMENTS NOW
  560. --
  561. --
  562. -- FIRST WE HAVE TO MAKE THE GL TO HOLD THE OVERPAYMENT TRANSACTIONS
  563. -- THE ID IS GENERATED BY gl_id_seq
  564. --
  565. IF (array_upper(in_op_cash_account_id, 1) > 0) THEN
  566. INSERT INTO gl (reference, description, transdate,
  567. person_id, notes, approved, department_id)
  568. VALUES (setting_increment('glnumber'),
  569. in_gl_description, in_datepaid, var_employee,
  570. in_notes, in_approved, in_department_id);
  571. SELECT currval('id') INTO var_gl_id;
  572. --
  573. -- WE NEED TO SET THE GL_ID FIELD ON PAYMENT'S TABLE
  574. --
  575. UPDATE payment SET gl_id = var_gl_id
  576. WHERE id = var_payment_id;
  577. -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
  578. --
  579. -- FIRST WE SHOULD INSERT THE OVERPAYMENT CASH ACCOUNTS
  580. --
  581. FOR out_count IN
  582. array_lower(in_op_cash_account_id, 1) ..
  583. array_upper(in_op_cash_account_id, 1)
  584. LOOP
  585. INSERT INTO acc_trans (chart_id, amount,
  586. trans_id, transdate, approved, source)
  587. VALUES (in_op_cash_account_id[out_count],
  588. CASE WHEN in_account_class = 2 THEN in_op_amount[out_count]
  589. ELSE in_op_amount[out_count] * - 1
  590. END,
  591. var_gl_id, in_datepaid, coalesce(in_approved, true),
  592. in_op_source[out_count]);
  593. INSERT INTO payment_links
  594. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 2);
  595. END LOOP;
  596. -- NOW LETS HANDLE THE OVERPAYMENT ACCOUNTS
  597. FOR out_count IN
  598. array_lower(in_op_account_id, 1) ..
  599. array_upper(in_op_account_id, 1)
  600. LOOP
  601. INSERT INTO acc_trans (chart_id, amount,
  602. trans_id, transdate, approved, source, memo)
  603. VALUES (in_op_account_id[out_count],
  604. CASE WHEN in_account_class = 2 THEN in_op_amount[out_count] * -1
  605. ELSE in_op_amount[out_count]
  606. END,
  607. var_gl_id, in_datepaid, coalesce(in_approved, true),
  608. in_op_source[out_count], in_op_memo[out_count]);
  609. INSERT INTO payment_links
  610. VALUES (var_payment_id, currval('acc_trans_entry_id_seq'), 2);
  611. END LOOP;
  612. END IF;
  613. return 0;
  614. END;
  615. $$ LANGUAGE PLPGSQL;
  616. -- I HAVE TO MAKE A COMMENT ON THIS FUNCTION
  617. -- Move this to the projects module when we start on that. CT
  618. CREATE OR REPLACE FUNCTION project_list_open(in_date date)
  619. RETURNS SETOF project AS
  620. $$
  621. DECLARE out_project project%ROWTYPE;
  622. BEGIN
  623. FOR out_project IN
  624. SELECT * from project
  625. WHERE startdate <= in_date AND enddate >= in_date
  626. AND completed = 0
  627. LOOP
  628. return next out_project;
  629. END LOOP;
  630. END;
  631. $$ language plpgsql;
  632. comment on function project_list_open(in_date date) is
  633. $$ This function returns all projects that were open as on the date provided as
  634. the argument.$$;
  635. -- Move this to the projects module when we start on that. CT
  636. CREATE OR REPLACE FUNCTION department_list(in_role char)
  637. RETURNS SETOF department AS
  638. $$
  639. DECLARE out_department department%ROWTYPE;
  640. BEGIN
  641. FOR out_department IN
  642. SELECT * from department
  643. WHERE role = coalesce(in_role, role)
  644. LOOP
  645. return next out_department;
  646. END LOOP;
  647. END;
  648. $$ language plpgsql;
  649. -- Move this into another module.
  650. comment on function department_list(in_role char) is
  651. $$ This function returns all department that match the role provided as
  652. the argument.$$;
  653. CREATE OR REPLACE FUNCTION payments_get_open_currencies(in_account_class int)
  654. RETURNS SETOF char(3) AS
  655. $$
  656. DECLARE resultrow record;
  657. BEGIN
  658. FOR resultrow IN
  659. SELECT DISTINCT curr FROM ar
  660. UNION
  661. SELECT DISTINCT curr FROM ap
  662. ORDER BY curr
  663. LOOP
  664. return next resultrow.curr;
  665. END LOOP;
  666. END;
  667. $$ language plpgsql;
  668. CREATE OR REPLACE FUNCTION currency_get_exchangerate(in_currency char(3), in_date date, in_account_class int)
  669. RETURNS NUMERIC AS
  670. $$
  671. DECLARE
  672. out_exrate exchangerate.buy%TYPE;
  673. BEGIN
  674. IF in_account_class = 1 THEN
  675. SELECT buy INTO out_exrate
  676. FROM exchangerate
  677. WHERE transdate = in_date AND curr = in_currency;
  678. ELSE
  679. SELECT sell INTO out_exrate
  680. FROM exchangerate
  681. WHERE transdate = in_date AND curr = in_currency;
  682. END IF;
  683. RETURN out_exrate;
  684. END;
  685. $$ language plpgsql;
  686. COMMENT ON FUNCTION currency_get_exchangerate(in_currency char(3), in_date date, in_account_class int) IS
  687. $$ This function return the exchange rate of a given currency, date and exchange rate class (buy or sell). $$;
  688. --
  689. -- payment_location_result has the same arch as location_result, except for one field
  690. -- This should be unified on the API when we get things working - David Mora
  691. --
  692. CREATE TYPE payment_location_result AS (
  693. id int,
  694. line_one text,
  695. line_two text,
  696. line_three text,
  697. city text,
  698. state text,
  699. mail_code text,
  700. country text,
  701. class text
  702. );
  703. --
  704. -- payment_get_vc_info has the same arch as company__list_locations, except for the filtering capabilities
  705. -- This should be unified on the API when we get things working - David Mora
  706. --
  707. CREATE OR REPLACE FUNCTION payment_get_vc_info(in_entity_credit_id int, in_location_class_id int)
  708. RETURNS SETOF payment_location_result AS
  709. $$
  710. DECLARE out_row payment_location_result;
  711. BEGIN
  712. FOR out_row IN
  713. SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
  714. l.state, l.mail_code, c.name, lc.class
  715. FROM location l
  716. JOIN company_to_location ctl ON (ctl.location_id = l.id)
  717. JOIN company cp ON (ctl.company_id = cp.id)
  718. JOIN location_class lc ON (ctl.location_class = lc.id)
  719. JOIN country c ON (c.id = l.country_id)
  720. JOIN entity_credit_account ec ON (ec.entity_id = cp.entity_id)
  721. WHERE ec.id = in_entity_credit_id AND
  722. lc.id = in_location_class_id
  723. ORDER BY lc.id, l.id, c.name
  724. LOOP
  725. RETURN NEXT out_row;
  726. END LOOP;
  727. END;
  728. $$ LANGUAGE PLPGSQL;
  729. COMMENT ON FUNCTION payment_get_vc_info(in_entity_id int, in_location_class_id int) IS
  730. $$ This function returns vendor or customer info $$;
  731. CREATE TYPE payment_record AS (
  732. amount numeric,
  733. meta_number text,
  734. credit_id int,
  735. company_paid text,
  736. accounts text[],
  737. source text,
  738. date_paid date
  739. );
  740. CREATE OR REPLACE FUNCTION payment__search
  741. (in_source text, in_date_from date, in_date_to date, in_credit_id int,
  742. in_cash_accno text, in_account_class int)
  743. RETURNS SETOF payment_record AS
  744. $$
  745. DECLARE
  746. out_row payment_record;
  747. BEGIN
  748. FOR out_row IN
  749. select sum(CASE WHEN c.entity_class = 1 then a.amount
  750. ELSE a.amount * -1 END), c.meta_number,
  751. c.id, co.legal_name,
  752. compound_array(ARRAY[ARRAY[ch.id::text, ch.accno,
  753. ch.description]]), a.source, a.transdate
  754. FROM entity_credit_account c
  755. JOIN ( select entity_credit_account, id
  756. FROM ar WHERE in_account_class = 2
  757. UNION
  758. SELECT entity_credit_account, id
  759. FROM ap WHERE in_account_class = 1
  760. ) arap ON (arap.entity_credit_account = c.id)
  761. JOIN acc_trans a ON (arap.id = a.trans_id)
  762. JOIN chart ch ON (ch.id = a.chart_id)
  763. JOIN company co ON (c.entity_id = co.entity_id)
  764. WHERE (ch.accno = in_cash_accno)
  765. AND (c.id = in_credit_id OR in_credit_id IS NULL)
  766. AND (a.transdate >= in_date_from
  767. OR in_date_from IS NULL)
  768. AND (a.transdate <= in_date_to OR in_date_to IS NULL)
  769. AND (source = in_source OR in_source IS NULL)
  770. GROUP BY c.meta_number, c.id, co.legal_name, a.transdate,
  771. a.source
  772. ORDER BY a.transdate, c.meta_number, a.source
  773. LOOP
  774. RETURN NEXT out_row;
  775. END LOOP;
  776. END;
  777. $$ language plpgsql;
  778. CREATE OR REPLACE FUNCTION payment__reverse
  779. (in_source text, in_date_paid date, in_credit_id int, in_cash_accno text,
  780. in_date_reversed date, in_account_class int, in_batch_id int)
  781. RETURNS INT
  782. AS $$
  783. DECLARE
  784. pay_row record;
  785. t_voucher_id int;
  786. t_voucher_inserted bool;
  787. BEGIN
  788. IF in_batch_id IS NOT NULL THEN
  789. t_voucher_id := nextval('voucher_id_seq');
  790. t_voucher_inserted := FALSE;
  791. END IF;
  792. FOR pay_row IN
  793. SELECT a.*, c.ar_ap_account_id
  794. FROM acc_trans a
  795. JOIN (select id, entity_credit_account
  796. FROM ar WHERE in_account_class = 2
  797. UNION
  798. SELECT id, entity_credit_account
  799. FROM ap WHERE in_account_class = 1
  800. ) arap ON (a.trans_id = arap.id)
  801. JOIN entity_credit_account c
  802. ON (arap.entity_credit_account = c.id)
  803. JOIN chart ch ON (a.chart_id = ch.id)
  804. WHERE coalesce(source, '') = coalesce(in_source, '')
  805. AND transdate = in_date_paid
  806. AND in_credit_id = c.id
  807. AND in_cash_accno = ch.accno
  808. LOOP
  809. IF in_batch_id IS NOT NULL
  810. AND t_voucher_inserted IS NOT TRUE
  811. THEN
  812. INSERT INTO voucher
  813. (id, trans_id, batch_id, batch_class)
  814. VALUES
  815. (t_voucher_id, pay_row.trans_id, in_batch_id,
  816. CASE WHEN in_account_class = 1 THEN 4
  817. WHEN in_account_class = 2 THEN 7
  818. END);
  819. t_voucher_inserted := TRUE;
  820. END IF;
  821. INSERT INTO acc_trans
  822. (trans_id, chart_id, amount, transdate, source, memo, approved,
  823. voucher_id)
  824. VALUES
  825. (pay_row.trans_id, pay_row.chart_id, pay_row.amount * -1,
  826. in_date_reversed, in_source, 'Reversing ' ||
  827. COALESCE(in_source, ''),
  828. case when in_batch_id is not null then false
  829. else true end, t_voucher_id);
  830. INSERT INTO acc_trans
  831. (trans_id, chart_id, amount, transdate, source, memo, approved,
  832. voucher_id)
  833. VALUES
  834. (pay_row.trans_id, pay_row.ar_ap_account_id, pay_row.amount,
  835. in_date_reversed, in_source, 'Reversing ' ||
  836. COALESCE(in_source, ''),
  837. case when in_batch_id is not null then false
  838. else true end, t_voucher_id);
  839. IF in_account_class = 1 THEN
  840. UPDATE ap SET paid = amount -
  841. (SELECT sum(a.amount)
  842. FROM acc_trans a
  843. JOIN chart c ON (a.chart_id = c.id)
  844. WHERE c.link = 'AP'
  845. AND trans_id = pay_row.trans_id
  846. )
  847. WHERE id = pay_row.trans_id;
  848. ELSIF in_account_class = 2 THEN
  849. update ar SET paid = amount -
  850. (SELECT sum(a.amount)
  851. FROM acc_trans a
  852. JOIN chart c ON (a.chart_id = c.id)
  853. WHERE c.link = 'AR'
  854. AND trans_id = pay_row.trans_id
  855. ) * -1
  856. WHERE id = pay_row.trans_id;
  857. ELSE
  858. RAISE EXCEPTION 'Unknown account class for payments %',
  859. in_account_class;
  860. END IF;
  861. END LOOP;
  862. RETURN 1;
  863. END;
  864. $$ LANGUAGE PLPGSQL;