Browse Source

products purchases supports only secondary indexes

Maxim Sokhatsky 12 years ago
parent
commit
d09a9b8e8b
3 changed files with 29 additions and 1 deletions
  1. 1 1
      include/purchases.hrl
  2. 23 0
      src/kvs_purchase.erl
  3. 5 0
      src/store_riak.erl

+ 1 - 1
include/purchases.hrl

@@ -1,4 +1,4 @@
--record(user_products, {
+-record(user_product, {
         username,
         timestamp,
         product_id }).

+ 23 - 0
src/kvs_purchase.erl

@@ -0,0 +1,23 @@
+-module(kvs_purchase).
+-include_lib("kvs/include/products.hrl").
+-include_lib("kvs/include/purchases.hrl").
+-include_lib("kvs/include/log.hrl").
+-include_lib("kvs/include/accounts.hrl").
+-include_lib("kvs/include/feed_state.hrl").
+-compile(export_all).
+
+solvent(UId, ProductId) ->
+    {ok, Credit} = kvs_accounts:balance(UId, currency),
+    {ok, #product{price = Price}} = kvs:get(product, ProductId),
+    Credit >= Price.
+
+buy(UId, ProductId) ->
+    {ok, #product{price = Price, name = Name}} = kvs:get(product, ProductId),
+    kvs_accounts:transaction(UId, currency, -Price, "Buy " ++ Name ++ " for "++ integer_to_list(Price)),
+    kvs:put(#user_product{username=UId, timestamp=now(), product_id = ProductId}).
+
+give(UId, PId) ->
+    kvs:put(#user_product{username=UId, timestamp=now(), product_id = PId}).
+
+products(UId) ->
+    kvs:all_by_index(user_product, <<"user_bin">>, list_to_binary(UId)).

+ 5 - 0
src/store_riak.erl

@@ -10,6 +10,7 @@
 -include_lib("kvs/include/meetings.hrl").
 -include_lib("kvs/include/membership.hrl").
 -include_lib("kvs/include/payments.hrl").
+-include_lib("kvs/include/purchases.hrl").
 -include_lib("kvs/include/accounts.hrl").
 -include_lib("kvs/include/log.hrl").
 -include_lib("stdlib/include/qlc.hrl").
@@ -61,6 +62,10 @@ make_indices(#user{username=UId,zone=Zone}) -> [
     {<<"user_bin">>, key_to_bin(UId)},
     {<<"zone_bin">>, key_to_bin(Zone)}];
 
+make_indices(#user_product{username=UId,product_id=PId}) -> [
+    {<<"user_bin">>, key_to_bin(UId)},
+    {<<"product_id">>, key_to_bin(PId)}];
+
 make_indices(#comment{id={CID,EID},author_id=Who}) -> [
     {<<"comment_bin">>, key_to_bin({CID,EID})},
     {<<"author_bin">>, key_to_bin(Who)}];