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