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