kvs_purchase.erl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. -module(kvs_purchase).
  2. -copyright('Synrc Research Center s.r.o.').
  3. -include_lib("kvs/include/products.hrl").
  4. -include_lib("kvs/include/purchases.hrl").
  5. -include_lib("kvs/include/config.hrl").
  6. -include_lib("kvs/include/accounts.hrl").
  7. -include_lib("kvs/include/feed_state.hrl").
  8. -compile(export_all).
  9. solvent(UId, ProductId) ->
  10. {ok, Credit} = kvs_accounts:balance(UId, currency),
  11. {ok, #product{price = Price}} = kvs:get(product, ProductId),
  12. Credit >= Price.
  13. buy(UId, ProductId) ->
  14. {ok, #product{price = Price}} = kvs:get(product, ProductId),
  15. kvs_accounts:transaction(UId, currency, -Price, "Buy " ++ ProductId ++ " for "++ integer_to_list(Price)),
  16. kvs:put(#user_product{username=UId, timestamp=now(), product_id = ProductId}).
  17. give(UId, ProductId) ->
  18. kvs:put(#user_product{username=UId, timestamp=now(), product_id = ProductId}).
  19. products(UId) -> DBA=?DBA, DBA:products(UId).
  20. handle_notice(["kvs_purchase", "user", UId, "buy"] = Route,
  21. Message, #state{owner = Owner, type =Type} = State) ->
  22. error_logger:info_msg(" queue_action(~p): buy_gift: Owner=~p, Route=~p, Message=~p", [self(), {Type, Owner}, Route, Message]),
  23. {GId} = Message,
  24. buy(UId, GId),
  25. {noreply, State};
  26. handle_notice(["kvs_purchase", "user", UId, "give"] = Route,
  27. Message, #state{owner = Owner, type =Type} = State) ->
  28. error_logger:info_msg(" queue_action(~p): give_gift: Owner=~p, Route=~p, Message=~p", [self(), {Type, Owner}, Route, Message]),
  29. {GId} = Message,
  30. give(UId, GId),
  31. {noreply, State};
  32. handle_notice(R,_,S) -> error_logger:info_msg("Unhandled PURCHASE notice ~p", [R]), {noreply, S}.