Advertisement
madrahimov

Untitled

Jun 18th, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.10 KB | None | 0 0
  1. CREATE OR REPLACE FUNCTION add_deposit_to_client_cards()
  2. RETURNS void AS
  3. $BODY$
  4. DECLARE
  5. client_id_ uuid;
  6. restaurant_id_ uuid;
  7. card_id_ uuid;
  8. deposit_ numeric;
  9. cn integer;
  10. BEGIN
  11. cn = 0;
  12. -- Берем всех клиентов у которых есть депозит
  13. -- Уникальность идет по колонкам (client_id, restaurant_id)
  14. -- У большинства клиентов from_restaurant_id равен null - это клиенты с этого ресторана
  15. -- Конверт делаем для всех даже у кого нет депозита, поскольку возможно его уже потратили, историю надо перенести тоже
  16. for client_id_, restaurant_id_, deposit_ in
  17. select client_id, restaurant_id, deposit from restaurant.client_restaurants
  18. loop
  19. -- Берем карту клиента у которая принадлежит этому ресторану а точнее из этого ресторана с большим процентом накопления
  20. -- Карта должна быть без акции
  21. select id from restaurant.client_cards where is_active and marketing_event_id is null and
  22. restaurant_id = restaurant_id_ and from_restaurant_id = restaurant_id_ and client_id = client_id_
  23. order by accumulation_account desc limit 1 into card_id_;
  24. if ( card_id_ is null ) then
  25. -- Если карты нет то создадим новую и сбросим туда депозит
  26. insert into restaurant.client_cards(id, restaurant_id, from_restaurant_id, client_id, deposit, created_at, updated_at)
  27. values (uuid_generate_v1(), restaurant_id_, restaurant_id_, client_id_, deposit_, now(), now()) returning id
  28. into card_id_;
  29. else
  30. -- Если есть такая карта то обновим депозит на ней
  31. update restaurant.client_cards set deposit = deposit_ where id = card_id_;
  32. end if;
  33.  
  34. -- Поскольку таблица новая, а депозит переносится только на карту с этого ресторана, то сразу делаем insert
  35. insert into restaurant.client_card_deposits (id, restaurant_id, client_card_id, deposit, created_at, updated_at)
  36. values(uuid_generate_v1(), restaurant_id_, card_id_, deposit_, now(), now());
  37.  
  38. -- Поскольку мы переносим весь депозит на одну карту то сразу обновим все транзакции по депозу на эту карту
  39. -- from_restaurant_id = restaurant_id_ - потому что именно для этого ресторана производится расчет тогда как
  40. -- restaurant_id - это откуда был выполнен запрос
  41. update restaurant.client_deposit_modifies set client_card_id = card_id_
  42. where from_restaurant_id = restaurant_id_ and client_id = client_id_;
  43.  
  44. cn = cn + 1;
  45. if ( (cn % 10000) = 0 ) then
  46. raise notice 'count: %', cn;
  47. end if;
  48. end loop;
  49. END
  50. $BODY$
  51. LANGUAGE plpgsql VOLATILE
  52. COST 100;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement