Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CREATE OR REPLACE FUNCTION add_deposit_to_client_cards()
- RETURNS void AS
- $BODY$
- DECLARE
- client_id_ uuid;
- restaurant_id_ uuid;
- card_id_ uuid;
- deposit_ numeric;
- cn integer;
- BEGIN
- cn = 0;
- -- Берем всех клиентов у которых есть депозит
- -- Уникальность идет по колонкам (client_id, restaurant_id)
- -- У большинства клиентов from_restaurant_id равен null - это клиенты с этого ресторана
- -- Конверт делаем для всех даже у кого нет депозита, поскольку возможно его уже потратили, историю надо перенести тоже
- for client_id_, restaurant_id_, deposit_ in
- select client_id, restaurant_id, deposit from restaurant.client_restaurants
- loop
- -- Берем карту клиента у которая принадлежит этому ресторану а точнее из этого ресторана с большим процентом накопления
- -- Карта должна быть без акции
- select id from restaurant.client_cards where is_active and marketing_event_id is null and
- restaurant_id = restaurant_id_ and from_restaurant_id = restaurant_id_ and client_id = client_id_
- order by accumulation_account desc limit 1 into card_id_;
- if ( card_id_ is null ) then
- -- Если карты нет то создадим новую и сбросим туда депозит
- insert into restaurant.client_cards(id, restaurant_id, from_restaurant_id, client_id, deposit, created_at, updated_at)
- values (uuid_generate_v1(), restaurant_id_, restaurant_id_, client_id_, deposit_, now(), now()) returning id
- into card_id_;
- else
- -- Если есть такая карта то обновим депозит на ней
- update restaurant.client_cards set deposit = deposit_ where id = card_id_;
- end if;
- -- Поскольку таблица новая, а депозит переносится только на карту с этого ресторана, то сразу делаем insert
- insert into restaurant.client_card_deposits (id, restaurant_id, client_card_id, deposit, created_at, updated_at)
- values(uuid_generate_v1(), restaurant_id_, card_id_, deposit_, now(), now());
- -- Поскольку мы переносим весь депозит на одну карту то сразу обновим все транзакции по депозу на эту карту
- -- from_restaurant_id = restaurant_id_ - потому что именно для этого ресторана производится расчет тогда как
- -- restaurant_id - это откуда был выполнен запрос
- update restaurant.client_deposit_modifies set client_card_id = card_id_
- where from_restaurant_id = restaurant_id_ and client_id = client_id_;
- cn = cn + 1;
- if ( (cn % 10000) = 0 ) then
- raise notice 'count: %', cn;
- end if;
- end loop;
- END
- $BODY$
- LANGUAGE plpgsql VOLATILE
- COST 100;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement