aonestar
.public
Tables
(current)
Columns
Constraints
Relationships
Orphan Tables
Anomalies
Routines
sp_split_transaction
Parameters
Name
Type
Mode
trn_id
integer
IN
amounts
t_money[]
IN
user_name
text
IN (DEFAULT NULL)
Definition
DECLARE result_data jsonb = '[]'; splitted int[]; verify_result json; item record; _folio_item_id int; _split_id int; _amount t_money; _tran_amount t_money; _split_total t_money; --is_first bool = true; _sqlstate TEXT; _detail TEXT; _hint TEXT; _context TEXT; _msg_text TEXT; BEGIN CALL sp_check_transaction(trn_id, 'split', true); _tran_amount = (SELECT amount FROM transactions WHERE id = trn_id); _split_total = (SELECT sum(amt) FROM unnest(amounts) amt); IF (_split_total > _tran_amount) OR (_split_total = _tran_amount AND fn_length(amounts) = 1) THEN RETURN fn_result_error('30401', 'Invalid split amount'); ELSEIF (_split_total < _tran_amount) THEN amounts = amounts || (_tran_amount - _split_total)::t_money; END IF; FOR item IN (SELECT * FROM unnest(amounts) WITH ORDINALITY AS itm(amount, idx)) LOOP IF item.idx = 1 THEN UPDATE transactions SET amount = item.amount, splitted = TRUE, splitted_src = $1 WHERE id = $1 RETURNING id INTO _split_id; ELSE INSERT INTO transactions (amount, splitted, splitted_src, folio_item, post_type, post_date, post_time, tran_type, dept_id, description, qty, reference, remark, post_user, post_shift, post_source, tax_code, card_id, transfer_in, transfer_src, transfer_des, original_folio_id, post_flag, charge_date) SELECT item.amount, TRUE, $1, folio_item, post_type, post_date, post_time, tran_type, dept_id, description, qty, reference, remark, post_user, post_shift, post_source, tax_code, card_id, transfer_in, transfer_src, transfer_des, original_folio_id, post_flag, charge_date FROM transactions WHERE id = $1 RETURNING id INTO _split_id; END IF; splitted = splitted || _split_id; PERFORM sp_log_trans(_split_id, 'Split', 'Split '||_tran_amount::TEXT||' to '||amounts::TEXT, user_name); result_data = result_data || fn_get_transaction_js(_split_id, false)::jsonb; -- is_first = FALSE; END LOOP; PERFORM sp_recalc_folio_balance((SELECT folio_item FROM transactions WHERE id = $1)); RETURN fn_result_success(result_data); EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS _msg_text = MESSAGE_TEXT, _sqlstate = RETURNED_SQLSTATE, _detail = PG_EXCEPTION_DETAIL, _hint = PG_EXCEPTION_HINT, _context = PG_EXCEPTION_CONTEXT; RETURN fn_handle_error(_sqlstate, _msg_text, _detail, _hint, _context, format('sp_split_transaction(%L, %L)', $1, $2)); END;