\q
--
-- PostgreSQL database dump
--

-- Dumped from database version 15.13
-- Dumped by pg_dump version 15.13

SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: pally; Type: SCHEMA; Schema: -; Owner: postgres
--

CREATE SCHEMA pally;


ALTER SCHEMA pally OWNER TO postgres;

--
-- Name: create_invoice(numeric, text, vgate.pally_currency); Type: FUNCTION; Schema: pally; Owner: postgres
--

CREATE FUNCTION pally.create_invoice(amount numeric, order_id text, currency vgate.pally_currency) RETURNS json
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE
    shop_id TEXT := common.get_setting('app.pally_shop_id')::TEXT;
    api_url TEXT := common.get_setting('app.pally_api_url')::TEXT;
    api_token TEXT := common.get_setting('app.pally_api_token')::TEXT;
    reuquest_url TEXT;
    data JSONB;
    response JSON;
BEGIN
    reuquest_url := format('%s/bill/create', api_url);
    RAISE NOTICE 'order_id: %', order_id;
    RAISE NOTICE 'shop_id: %, api_url: %, api_token: %', shop_id, api_url, api_token;

    data := jsonb_build_object(
        'amount', amount,
        'currency_in', currency,
        'shop_id', shop_id,
        'order_id', order_id,
        'success_url', format('https://%s', common.get_setting('app.realm')),
        'fail_url', format('https://%s', common.get_setting('app.realm'))
    );

    SELECT content::json
    FROM http((
        'POST',
        reuquest_url,
        ARRAY[('Authorization', format('Bearer %s', api_token))::http_header],
        'application/json',
        data::VARCHAR
    )::http_request)
    INTO response;

    IF (response->>'success')::BOOLEAN != true THEN
        RAISE EXCEPTION 'Pally error: %', response::TEXT;
    END IF;

    RAISE NOTICE 'response: %', response;

    /*
        {
          "bill_id": "...",
          "link_page_url": "...",
          "link_url": "...",
          "success": "..." // true or false
        }
    */
    RETURN response;
END
$$;


ALTER FUNCTION pally.create_invoice(amount numeric, order_id text, currency vgate.pally_currency) OWNER TO postgres;

--
-- PostgreSQL database dump complete
--

