summaryrefslogtreecommitdiff
path: root/sql/modules/Payment.sql
blob: cab7a1de13c1718466fd47d195512aa247458833 (plain)
  1. -- payment_get_open_accounts and the option to get all accounts need to be
  2. -- refactored and redesigned. -- CT
  3. CREATE OR REPLACE FUNCTION payment_get_open_accounts(in_account_class int)
  4. returns SETOF entity AS
  5. $$
  6. DECLARE out_entity entity%ROWTYPE;
  7. BEGIN
  8. FOR out_entity IN
  9. SELECT ec.id, cp.legal_name as name, e.entity_class, e.created
  10. FROM entity e
  11. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  12. JOIN company cp ON (cp.entity_id = e.id)
  13. WHERE ec.entity_class = in_account_class
  14. AND CASE WHEN in_account_class = 1 THEN
  15. e.id IN (SELECT entity_id FROM ap
  16. WHERE amount <> paid
  17. GROUP BY entity_id)
  18. WHEN in_account_class = 2 THEN
  19. e.id IN (SELECT entity_id FROM ar
  20. WHERE amount <> paid
  21. GROUP BY entity_id)
  22. END
  23. LOOP
  24. RETURN NEXT out_entity;
  25. END LOOP;
  26. END;
  27. $$ LANGUAGE PLPGSQL;
  28. COMMENT ON FUNCTION payment_get_open_accounts(int) IS
  29. $$ This function takes a single argument (1 for vendor, 2 for customer as
  30. always) and returns all entities with open accounts of the appropriate type. $$;
  31. CREATE OR REPLACE FUNCTION payment_get_all_accounts(in_account_class int)
  32. RETURNS SETOF entity AS
  33. $$
  34. DECLARE out_entity entity%ROWTYPE;
  35. BEGIN
  36. FOR out_entity IN
  37. SELECT ec.id,
  38. e.name, e.entity_class, e.created
  39. FROM entity e
  40. JOIN entity_credit_account ec ON (ec.entity_id = e.id)
  41. WHERE e.entity_class = in_account_class
  42. LOOP
  43. RETURN NEXT out_entity;
  44. END LOOP;
  45. END;
  46. $$ LANGUAGE PLPGSQL;
  47. COMMENT ON FUNCTION payment_get_open_accounts(int) IS
  48. $$ This function takes a single argument (1 for vendor, 2 for customer as
  49. always) and returns all entities with accounts of the appropriate type. $$;
  50. CREATE TYPE payment_invoice AS (
  51. invoice_id int,
  52. invnumber text,
  53. invoice_date date,
  54. amount numeric,
  55. discount numeric,
  56. due numeric
  57. );
  58. CREATE OR REPLACE FUNCTION payment_get_open_invoices
  59. (in_account_class int,
  60. in_entity_credit_id int,
  61. in_curr char(3),
  62. in_datefrom date,
  63. in_dateto date,
  64. in_amountfrom numeric,
  65. in_amountto numeric,
  66. in_department_id int)
  67. RETURNS SETOF payment_invoice AS
  68. $$
  69. DECLARE payment_inv payment_invoice;
  70. BEGIN
  71. FOR payment_inv IN
  72. SELECT a.id AS invoice_id, a.invnumber,
  73. a.transdate AS invoice_date, a.amount,
  74. CASE WHEN discount_terms
  75. > extract('days' FROM age(a.transdate))
  76. THEN 0
  77. ELSE (a.amount - a.paid) * c.discount / 100
  78. END AS discount,
  79. a.amount - a.paid -
  80. CASE WHEN discount_terms
  81. > extract('days' FROM age(a.transdate))
  82. THEN 0
  83. ELSE (a.amount - a.paid) * c.discount / 100
  84. END
  85. AS due
  86. FROM (SELECT id, invnumber, transdate, amount, entity_id,
  87. 1 as invoice_class, paid, curr,
  88. entity_credit_account, department_id
  89. FROM ap
  90. UNION
  91. SELECT id, invnumber, transdate, amount, entity_id,
  92. 2 AS invoice_class, paid, curr,
  93. entity_credit_account, department_id
  94. FROM ar
  95. ) a
  96. JOIN entity_credit_account c ON (c.id = a.entity_credit_account
  97. OR (a.entity_credit_account IS NULL and
  98. a.entity_id = c.entity_id))
  99. WHERE a.invoice_class = in_account_class
  100. AND c.entity_class = in_account_class
  101. AND a.amount - a.paid <> 0
  102. AND a.curr = in_curr
  103. AND (a.transdate >= in_datefrom
  104. OR in_datefrom IS NULL)
  105. AND (a.transdate <= in_dateto
  106. OR in_dateto IS NULL)
  107. AND (a.amount >= in_amountfrom
  108. OR in_amountfrom IS NULL)
  109. AND (a.amount <= in_amountto
  110. OR in_amountto IS NULL)
  111. AND (a.department_id = in_department_id
  112. OR in_department_id IS NULL)
  113. LOOP
  114. RETURN NEXT payment_inv;
  115. END LOOP;
  116. END;
  117. $$ LANGUAGE PLPGSQL;
  118. COMMENT ON FUNCTION payment_get_open_invoices(int, int, char(3), date, date, numeric, numeric, int) IS
  119. $$ This function takes three arguments:
  120. Type: 1 for vendor, 2 for customer
  121. Entity_id: The entity_id of the customer or vendor
  122. Currency: 3 characters for currency ('USD' for example).
  123. Returns all open invoices for the entity in question. $$;
  124. CREATE TYPE payment_contact_invoice AS (
  125. contact_id int,
  126. contact_name text,
  127. account_number text,
  128. total_due numeric,
  129. invoices text[],
  130. has_vouchers int
  131. );
  132. CREATE OR REPLACE FUNCTION payment_get_all_contact_invoices
  133. (in_account_class int, in_business_id int, in_currency char(3),
  134. in_date_from date, in_date_to date, in_batch_id int,
  135. in_ar_ap_accno text)
  136. RETURNS SETOF payment_contact_invoice AS
  137. $$
  138. DECLARE payment_item payment_contact_invoice;
  139. BEGIN
  140. FOR payment_item IN
  141. SELECT c.id AS contact_id, e.name AS contact_name,
  142. c.meta_number AS account_number,
  143. sum(a.amount - a.paid) AS total_due,
  144. compound_array(ARRAY[[
  145. a.id::text, a.invnumber, a.transdate::text,
  146. a.amount::text, a.paid::text,
  147. (CASE WHEN c.discount_terms
  148. > extract('days' FROM age(a.transdate))
  149. THEN 0
  150. ELSE (a.amount - coalesce(a.paid, 0)) * coalesce(c.discount, 0) / 100
  151. END)::text,
  152. (a.amount - coalesce(a.paid, 0) -
  153. (CASE WHEN c.discount_terms
  154. > extract('days' FROM age(a.transdate))
  155. THEN 0
  156. ELSE (a.amount - coalesce(a.paid, 0)) * coalesce(c.discount, 0) / 100
  157. END))::text]]),
  158. sum(case when v.batch_id = in_batch_id then 1
  159. else 0 END),
  160. bool_and(lock_record(a.id, (select max(session_id) FROM "session" where users_id = (
  161. select id from users WHERE username =
  162. SESSION_USER))))
  163. FROM entity e
  164. JOIN entity_credit_account c ON (e.id = c.entity_id)
  165. JOIN (SELECT id, invnumber, transdate, amount, entity_id,
  166. paid, curr, 1 as invoice_class,
  167. entity_credit_account, on_hold
  168. FROM ap
  169. WHERE in_account_class = 1
  170. UNION
  171. SELECT id, invnumber, transdate, amount, entity_id,
  172. paid, curr, 2 as invoice_class,
  173. entity_credit_account, on_hold
  174. FROM ar
  175. WHERE in_account_class = 2
  176. ORDER BY transdate
  177. ) a ON (a.entity_credit_account = c.id)
  178. JOIN transactions t ON (a.id = t.id)
  179. LEFT JOIN voucher v ON (v.trans_id = a.id)
  180. WHERE v.batch_id = in_batch_id
  181. OR (a.invoice_class = in_account_class
  182. AND c.business_id =
  183. coalesce(in_business_id, c.business_id)
  184. AND ((a.transdate >= COALESCE(in_date_from, a.transdate)
  185. AND a.transdate <= COALESCE(in_date_to, a.transdate)))
  186. AND c.entity_class = in_account_class
  187. AND a.curr = in_currency
  188. AND a.entity_credit_account = c.id
  189. AND a.amount - a.paid <> 0
  190. AND NOT a.on_hold
  191. AND NOT (t.locked_by IS NOT NULL AND t.locked_by IN
  192. (select "session_id" FROM "session"
  193. WHERE users_id IN
  194. (select id from users
  195. where username <> SESSION_USER)))
  196. AND EXISTS (select trans_id FROM acc_trans
  197. WHERE trans_id = a.id AND
  198. chart_id = (SELECT id frOM chart
  199. WHERE accno
  200. = in_ar_ap_accno)
  201. ))
  202. GROUP BY c.id, e.name, c.meta_number, c.threshold
  203. HAVING sum(a.amount - a.paid) > c.threshold
  204. OR sum(case when v.batch_id = in_batch_id then 1
  205. else 0 END) > 0
  206. LOOP
  207. RETURN NEXT payment_item;
  208. END LOOP;
  209. END;
  210. $$ LANGUAGE plpgsql;
  211. COMMENT ON FUNCTION payment_get_all_contact_invoices
  212. (in_account_class int, in_business_type int, in_currency char(3),
  213. in_date_from date, in_date_to date, in_batch_id int,
  214. in_ar_ap_accno text) IS
  215. $$
  216. This function takes the following arguments (all prefaced with in_ in the db):
  217. account_class: 1 for vendor, 2 for customer
  218. business_type: integer of business.id.
  219. currency: char(3) of currency (for example 'USD')
  220. date_from, date_to: These dates are inclusive.
  221. 1;3B
  222. batch_id: For payment batches, where fees are concerned.
  223. ar_ap_accno: The AR/AP account number.
  224. This then returns a set of contact information with a 2 dimensional array
  225. cnsisting of outstanding invoices.
  226. $$;
  227. CREATE OR REPLACE FUNCTION payment_bulk_queue
  228. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  229. in_ar_ap_accno text, in_cash_accno text,
  230. in_payment_date date, in_account_class int)
  231. returns int as
  232. $$
  233. BEGIN
  234. INSERT INTO payments_queue
  235. (transactions, batch_id, source, total, ar_ap_accno, cash_accno,
  236. payment_date, account_class)
  237. VALUES
  238. (in_transactions, in_batch_id, in_source, in_total, in_ar_ap_accno,
  239. in_cash_accno, in_payment_date, in_account_class);
  240. RETURN array_upper(in_transactions, 1) -
  241. array_lower(in_transactions, 1);
  242. END;
  243. $$ LANGUAGE PLPGSQL;
  244. CREATE OR REPLACE FUNCTION job__process_payment(in_job_id int)
  245. RETURNS bool AS $$
  246. DECLARE
  247. queue_record RECORD;
  248. t_auth_name text;
  249. t_counter int;
  250. BEGIN
  251. -- TODO: Move the set session authorization into a utility function
  252. SELECT entered_by INTO t_auth_name FROM pending_job
  253. WHERE id = in_job_id;
  254. EXECUTE 'SET SESSION AUTHORIZATION ' || quote_ident(t_auth_name);
  255. t_counter := 0;
  256. FOR queue_record IN
  257. SELECT *
  258. FROM payments_queue WHERE job_id = in_job_id
  259. LOOP
  260. PERFORM payment_bulk_post
  261. (queue_record.transactions, queue_record.batch_id,
  262. queue_record.source, queue_record.total,
  263. queue_record.ar_ap_accno,
  264. queue_record.cash_accno,
  265. queue_record.payment_date,
  266. queue_record.account_class);
  267. t_counter := t_counter + 1;
  268. RAISE NOTICE 'Processed record %, starting transaction %',
  269. t_counter, queue_record.transactions[1][1];
  270. END LOOP;
  271. DELETE FROM payments_queue WHERE job_id = in_job_id;
  272. UPDATE pending_job
  273. SET completed_at = timeofday()::timestamp,
  274. success = true
  275. WHERE id = in_job_id;
  276. RETURN TRUE;
  277. END;
  278. $$ language plpgsql;
  279. CREATE OR REPLACE FUNCTION job__create(in_batch_class int, in_batch_id int)
  280. RETURNS int AS
  281. $$
  282. BEGIN
  283. INSERT INTO pending_job (batch_class, batch_id)
  284. VALUES (coalesce(in_batch_class, 3), in_batch_id);
  285. RETURN currval('pending_job_id_seq');
  286. END;
  287. $$ LANGUAGE PLPGSQL;
  288. CREATE TYPE job__status AS (
  289. completed int, -- 1 for completed, 0 for no
  290. success int, -- 1 for success, 0 for no
  291. completed_at timestamp,
  292. error_condition text -- error if not successful
  293. );
  294. CREATE OR REPLACE FUNCTION job__status(in_job_id int) RETURNS job__status AS
  295. $$
  296. DECLARE out_row job__status;
  297. BEGIN
  298. SELECT (completed_at IS NULL)::INT, success::int, completed_at,
  299. error_condition
  300. INTO out_row
  301. FROM pending_job
  302. WHERE id = in_job_id;
  303. RETURN out_row;
  304. END;
  305. $$ language plpgsql;
  306. CREATE OR REPLACE FUNCTION payment_bulk_post
  307. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  308. in_ar_ap_accno text, in_cash_accno text,
  309. in_payment_date date, in_account_class int)
  310. RETURNS int AS
  311. $$
  312. DECLARE
  313. out_count int;
  314. t_voucher_id int;
  315. t_trans_id int;
  316. t_amount numeric;
  317. t_ar_ap_id int;
  318. t_cash_id int;
  319. BEGIN
  320. IF in_batch_id IS NULL THEN
  321. -- t_voucher_id := NULL;
  322. RAISE EXCEPTION 'Bulk Post Must be from Batch!';
  323. ELSE
  324. INSERT INTO voucher (batch_id, batch_class, trans_id)
  325. values (in_batch_id, 3, in_transactions[1][1]);
  326. t_voucher_id := currval('voucher_id_seq');
  327. END IF;
  328. select id into t_ar_ap_id from chart where accno = in_ar_ap_accno;
  329. select id into t_cash_id from chart where accno = in_cash_accno;
  330. FOR out_count IN
  331. array_lower(in_transactions, 1) ..
  332. array_upper(in_transactions, 1)
  333. LOOP
  334. INSERT INTO acc_trans
  335. (trans_id, chart_id, amount, approved, voucher_id,
  336. transdate, source)
  337. VALUES
  338. (in_transactions[out_count][1],
  339. case when in_account_class = 1 THEN t_cash_id
  340. WHEN in_account_class = 2 THEN t_ar_ap_id
  341. ELSE -1 END,
  342. in_transactions[out_count][2],
  343. CASE WHEN t_voucher_id IS NULL THEN true
  344. ELSE false END,
  345. t_voucher_id, in_payment_date, in_source),
  346. (in_transactions[out_count][1],
  347. case when in_account_class = 1 THEN t_ar_ap_id
  348. WHEN in_account_class = 2 THEN t_cash_id
  349. ELSE -1 END,
  350. in_transactions[out_count][2]* -1,
  351. CASE WHEN t_voucher_id IS NULL THEN true
  352. ELSE false END,
  353. t_voucher_id, in_payment_date, in_source);
  354. UPDATE ap
  355. set paid = paid +in_transactions[out_count][2]
  356. where id =in_transactions[out_count][1];
  357. END LOOP;
  358. return out_count;
  359. END;
  360. $$ language plpgsql;
  361. COMMENT ON FUNCTION payment_bulk_post
  362. (in_transactions numeric[], in_batch_id int, in_source text, in_total numeric,
  363. in_ar_ap_accno text, in_cash_accno text,
  364. in_payment_date date, in_account_class int)
  365. IS
  366. $$ Note that in_transactions is a two-dimensional numeric array. Of each
  367. sub-array, the first element is the (integer) transaction id, and the second
  368. is the amount for that transaction. If the total of the amounts do not add up
  369. to in_total, then an error is generated. $$;
  370. CREATE OR REPLACE FUNCTION payment_post
  371. (in_payment_date date,
  372. in_account_class int,
  373. in_person_id int,
  374. in_currency char(3),
  375. in_notes text,
  376. in_department int,
  377. in_gl_description text,
  378. in_cash_accno int[],
  379. in_cash_amount int[],
  380. in_cash_approved bool[],
  381. in_cash_source text[],
  382. in_accno int[],
  383. in_amount int[],
  384. in_approved bool[],
  385. in_source text[],
  386. in_transaction_id int[],
  387. in_type int[],
  388. in_approved bool)
  389. RETURNS INT AS
  390. $$
  391. DECLARE var_payment_id int;
  392. DECLARE var_gl_id int;
  393. DECLARE var_entry_id int[];
  394. DECLARE out_count int;
  395. BEGIN
  396. -- FIRST WE HAVE TO INSERT THE PAYMENT
  397. -- THE ID IS GENERATED BY payment_id_seq
  398. --
  399. INSERT INTO payment (reference, payment_class, payment_date,
  400. person_id, currency, notes, department_id)
  401. VALUES ((CASE WHEN in_account_class = 1 THEN
  402. setting_increment('rcptnumber') -- I FOUND THIS ON sql/modules/Settings.sql
  403. ELSE -- and it is very usefull
  404. setting_increment('paynumber')
  405. END),
  406. in_account_class, in_payment_date, in_person_id,
  407. in_currency, in_notes, in_department);
  408. SELECT currval('payment_id_seq') INTO var_payment_id; -- WE'LL NEED THIS VALUE TO USE payment_link table
  409. -- SECOND WE HAVE TO MAKE THE GL TO HOLD THE TRANSACTIONS
  410. -- THE ID IS GENERATED BY gl_id_seq
  411. --
  412. INSERT INTO gl (reference, description, transdate,
  413. person_id, notes, approved, department_id)
  414. VALUES (setting_increment('glnumber'),
  415. in_gl_description, in_payment_date, in_person_id,
  416. in_notes, in_department, coalesce(in_approved, true));
  417. SELECT currval('id') INTO var_gl_id; -- WE'LL NEED THIS VALUE TO JOIN WITH PAYMENT
  418. -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
  419. --
  420. -- FIRST WE SHOULD INSERT THE CASH ACCOUNTS
  421. --
  422. -- WE SHOULD HAVE THE DATA STORED AS (ACCNO, AMOUNT), SO
  423. FOR out_count IN
  424. array_lower(in_cash_accno, 1) ..
  425. array_upper(in_cash_accno, 1)
  426. LOOP
  427. INSERT INTO acc_trans (chart_id, amount,
  428. trans_id, transdate, approved, source)
  429. VALUES ((SELECT id FROM chart WHERE accno = in_cash_accno[out_count]),
  430. CASE WHEN in_account_class = 2 THEN in_cash_amount[out_count] * -1
  431. ELSE in_cash_amount[out_count]
  432. END,
  433. var_gl_id, in_payment_date, coalesce(in_cash_approved[1], true),
  434. in_cash_source[out_count]);
  435. --SELECT currval('acc_trans_entry_id_seq') INTO var_entry_id[out_count];--WE'LL NEED THIS FOR THE PAYMENT_LINK
  436. END LOOP;
  437. --
  438. -- NOW LETS HANDLE THE AR/AP/OVERPAYMENT ACCOUNT
  439. --
  440. FOR var_count IN
  441. array_lower(in_accno, 1) ..
  442. array_upper(in_accno, 1)
  443. LOOP
  444. INSERT INTO acc_trans (chart_id, amount,
  445. trans_id, transdate, approved, source)
  446. VALUES ((SELECT id FROM chart WHERE accno = in_accno[out_count]),
  447. CASE WHEN in_account_class = 2 THEN in_amount[out_count] * -1
  448. ELSE in_amount[out_count]
  449. END,
  450. var_gl_id, in_payment_date, coalesce(in_approved[1], true),
  451. in_source[out_count]);
  452. --
  453. -- WE WILL INSERT THE LINK INTO PAYMENT_LINKS NOW
  454. --
  455. INSERT INTO payment_links
  456. VALUES (var_payment_id, currval(acc_trans_entry_id_seq),
  457. in_transaction_id[out_count], in_type[var_count]);
  458. END LOOP;
  459. return 0;
  460. END;
  461. $$ LANGUAGE PLPGSQL;
  462. -- I HAVE TO MAKE A COMMENT ON THIS FUNCTION
  463. -- Move this to the projects module when we start on that. CT
  464. CREATE OR REPLACE FUNCTION project_list_open(in_date date)
  465. RETURNS SETOF project AS
  466. $$
  467. DECLARE out_project project%ROWTYPE;
  468. BEGIN
  469. FOR out_project IN
  470. SELECT * from project
  471. WHERE startdate <= in_date AND enddate >= in_date
  472. AND completed = 0
  473. LOOP
  474. return next out_project;
  475. END LOOP;
  476. END;
  477. $$ language plpgsql;
  478. comment on function project_list_open(in_date date) is
  479. $$ This function returns all projects that were open as on the date provided as
  480. the argument.$$;
  481. -- Move this to the projects module when we start on that. CT
  482. CREATE OR REPLACE FUNCTION department_list(in_role char)
  483. RETURNS SETOF department AS
  484. $$
  485. DECLARE out_department department%ROWTYPE;
  486. BEGIN
  487. FOR out_department IN
  488. SELECT * from department
  489. WHERE role = coalesce(in_role, role)
  490. LOOP
  491. return next out_department;
  492. END LOOP;
  493. END;
  494. $$ language plpgsql;
  495. -- Move this into another module.
  496. comment on function department_list(in_role char) is
  497. $$ This function returns all department that match the role provided as
  498. the argument.$$;
  499. CREATE OR REPLACE FUNCTION payments_get_open_currencies(in_account_class int)
  500. RETURNS SETOF char(3) AS
  501. $$
  502. DECLARE resultrow record;
  503. BEGIN
  504. FOR resultrow IN
  505. SELECT curr AS curr FROM ar
  506. WHERE amount <> paid
  507. OR paid IS NULL
  508. AND in_account_class=2
  509. UNION
  510. SELECT curr FROM ap
  511. WHERE amount <> paid
  512. OR paid IS NULL
  513. AND in_account_class=1
  514. ORDER BY curr
  515. LOOP
  516. return next resultrow.curr;
  517. END LOOP;
  518. END;
  519. $$ language plpgsql;
  520. CREATE OR REPLACE FUNCTION currency_get_exchangerate(in_currency char(3), in_date date, in_account_class int)
  521. RETURNS NUMERIC AS
  522. $$
  523. DECLARE
  524. out_exrate exchangerate.buy%TYPE;
  525. BEGIN
  526. IF in_account_class = 1 THEN
  527. SELECT INTO out_exrate buy
  528. FROM exchangerate
  529. WHERE transdate = in_date AND curr = in_currency;
  530. ELSE
  531. SELECT INTO out_exrate sell
  532. FROM exchangerate
  533. WHERE transdate = in_date AND curr = in_currency;
  534. END IF;
  535. RETURN out_exrate;
  536. END;
  537. $$ language plpgsql;
  538. COMMENT ON FUNCTION currency_get_exchangerate(in_currency char(3), in_date date, in_account_class int) IS
  539. $$ This function return the exchange rate of a given currency, date and exchange rate class (buy or sell). $$;
  540. --
  541. -- payment_location_result has the same arch as location_result, except for one field
  542. -- This should be unified on the API when we get things working - David Mora
  543. --
  544. CREATE TYPE payment_location_result AS (
  545. id int,
  546. line_one text,
  547. line_two text,
  548. line_three text,
  549. city text,
  550. state text,
  551. country text,
  552. class text
  553. );
  554. --
  555. -- payment_get_vc_info has the same arch as company__list_locations, except for the filtering capabilities
  556. -- This should be unified on the API when we get things working - David Mora
  557. --
  558. CREATE OR REPLACE FUNCTION payment_get_vc_info(in_entity_id int, in_location_class_id int)
  559. RETURNS SETOF payment_location_result AS
  560. $$
  561. DECLARE out_row RECORD;
  562. BEGIN
  563. FOR out_row IN
  564. SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
  565. l.state, c.name, lc.class
  566. FROM location l
  567. JOIN company_to_location ctl ON (ctl.location_id = l.id)
  568. JOIN company cp ON (ctl.company_id = cp.id)
  569. JOIN location_class lc ON (ctl.location_class = lc.id)
  570. JOIN country c ON (c.id = l.country_id)
  571. WHERE cp.entity_id = in_entity_id AND
  572. lc.id = in_location_class_id
  573. ORDER BY lc.id, l.id, c.name
  574. LOOP
  575. RETURN NEXT out_row;
  576. END LOOP;
  577. END;
  578. $$ LANGUAGE PLPGSQL;
  579. COMMENT ON FUNCTION payment_get_vc_info(in_entity_id int, in_location_class_id int) IS
  580. $$ This function returns vendor or customer info $$;
  581. CREATE TYPE payment_record AS (
  582. amount numeric,
  583. meta_number text,
  584. credit_id int,
  585. company_paid text,
  586. accounts text[],
  587. source text,
  588. date_paid date
  589. );
  590. CREATE OR REPLACE FUNCTION payment__search
  591. (in_source text, in_date_from date, in_date_to date, in_credit_id int,
  592. in_cash_accno text, in_account_class int)
  593. RETURNS SETOF payment_record AS
  594. $$
  595. DECLARE
  596. out_row payment_record;
  597. BEGIN
  598. FOR out_row IN
  599. select sum(CASE WHEN c.entity_class = 1 then a.amount
  600. ELSE a.amount * -1 END), c.meta_number,
  601. c.id, co.legal_name,
  602. compound_array(ARRAY[ARRAY[ch.id::text, ch.accno,
  603. ch.description]]), a.source, a.transdate
  604. FROM entity_credit_account c
  605. JOIN ( select entity_credit_account, id
  606. FROM ar WHERE in_account_class = 2
  607. UNION
  608. SELECT entity_credit_account, id
  609. FROM ap WHERE in_account_class = 1
  610. ) arap ON (arap.entity_credit_account = c.id)
  611. JOIN acc_trans a ON (arap.id = a.trans_id)
  612. JOIN chart ch ON (ch.id = a.chart_id)
  613. JOIN company co ON (c.entity_id = co.entity_id)
  614. WHERE (ch.accno = in_cash_accno)
  615. AND (c.id = in_credit_id OR in_credit_id IS NULL)
  616. AND (a.transdate >= in_date_from
  617. OR in_date_from IS NULL)
  618. AND (a.transdate <= in_date_to OR in_date_to IS NULL)
  619. AND (source = in_source OR in_source IS NULL)
  620. GROUP BY c.meta_number, c.id, co.legal_name, a.transdate,
  621. a.source
  622. ORDER BY a.transdate, c.meta_number, a.source
  623. LOOP
  624. RETURN NEXT out_row;
  625. END LOOP;
  626. END;
  627. $$ language plpgsql;
  628. CREATE OR REPLACE FUNCTION payment__reverse
  629. (in_source text, in_date_paid date, in_credit_id int, in_cash_accno text,
  630. in_date_reversed date, in_account_class int, in_batch_id int)
  631. RETURNS INT
  632. AS $$
  633. DECLARE
  634. pay_row record;
  635. t_voucher_id int;
  636. t_voucher_inserted bool;
  637. BEGIN
  638. IF in_batch_id IS NOT NULL THEN
  639. t_voucher_id := nextval('voucher_id_seq');
  640. t_voucher_inserted := FALSE;
  641. END IF;
  642. FOR pay_row IN
  643. SELECT a.*, c.ar_ap_account_id
  644. FROM acc_trans a
  645. JOIN (select id, entity_credit_account
  646. FROM ar WHERE in_account_class = 2
  647. UNION
  648. SELECT id, entity_credit_account
  649. FROM ap WHERE in_account_class = 1
  650. ) arap ON (a.trans_id = arap.id)
  651. JOIN entity_credit_account c
  652. ON (arap.entity_credit_account = c.id)
  653. JOIN chart ch ON (a.chart_id = ch.id)
  654. WHERE coalesce(source, '') = coalesce(in_source, '')
  655. AND transdate = in_date_paid
  656. AND in_credit_id = c.id
  657. AND in_cash_accno = ch.accno
  658. LOOP
  659. IF in_batch_id IS NOT NULL
  660. AND t_voucher_inserted IS NOT TRUE
  661. THEN
  662. INSERT INTO voucher
  663. (id, trans_id, batch_id, batch_class)
  664. VALUES
  665. (t_voucher_id, pay_row.trans_id, in_batch_id,
  666. CASE WHEN in_account_class = 1 THEN 4
  667. WHEN in_account_class = 2 THEN 7
  668. END);
  669. t_voucher_inserted := TRUE;
  670. END IF;
  671. INSERT INTO acc_trans
  672. (trans_id, chart_id, amount, transdate, source, memo, approved,
  673. voucher_id)
  674. VALUES
  675. (pay_row.trans_id, pay_row.chart_id, pay_row.amount * -1,
  676. in_date_reversed, in_source, 'Reversing ' ||
  677. COALESCE(in_source, ''),
  678. case when in_batch_id is not null then false
  679. else true end, t_voucher_id),
  680. (pay_row.trans_id, pay_row.ar_ap_account_id, pay_row.amount,
  681. in_date_reversed, in_source, 'Reversing ' ||
  682. COALESCE(in_source, ''),
  683. case when in_batch_id is not null then false
  684. else true end, t_voucher_id);
  685. IF in_account_class = 1 THEN
  686. UPDATE ap SET paid = amount -
  687. (SELECT sum(a.amount)
  688. FROM acc_trans a
  689. JOIN chart c ON (a.chart_id = c.id)
  690. WHERE c.link = 'AP'
  691. AND trans_id = pay_row.trans_id
  692. )
  693. WHERE id = pay_row.trans_id;
  694. ELSIF in_account_class = 2 THEN
  695. update ar SET paid = amount -
  696. (SELECT sum(a.amount)
  697. FROM acc_trans a
  698. JOIN chart c ON (a.chart_id = c.id)
  699. WHERE c.link = 'AR'
  700. AND trans_id = pay_row.trans_id
  701. ) * -1
  702. WHERE id = pay_row.trans_id;
  703. ELSE
  704. RAISE EXCEPTION 'Unknown account class for payments %',
  705. in_account_class;
  706. END IF;
  707. END LOOP;
  708. RETURN 1;
  709. END;
  710. $$ LANGUAGE PLPGSQL;