summaryrefslogtreecommitdiff
path: root/lib/handler.ml
diff options
context:
space:
mode:
Diffstat (limited to 'lib/handler.ml')
-rw-r--r--lib/handler.ml32
1 files changed, 25 insertions, 7 deletions
diff --git a/lib/handler.ml b/lib/handler.ml
index a4d8cae..fb075ff 100644
--- a/lib/handler.ml
+++ b/lib/handler.ml
@@ -1,5 +1,10 @@
open Piaf
+let valid_debit value limit balance =
+ let balance_after_op = balance - value in
+ not (balance_after_op <= limit * -1)
+;;
+
let create_transaction client_id (db_pool : Query.pool) (request : Request.t) =
Caqti_eio.Pool.use
(fun conn ->
@@ -7,22 +12,35 @@ let create_transaction client_id (db_pool : Query.pool) (request : Request.t) =
Option.join @@ Result.to_option @@ Query.find_client client_id conn
in
match client_opt with
- | Some _client ->
+ | Some client ->
let insert_result =
let body = Result.to_option @@ Body.to_string request.body in
- let json = Option.map Yojson.Safe.from_string body in
+ let json =
+ Option.map
+ (fun str ->
+ try Yojson.Safe.from_string str with
+ | _ -> `Null)
+ body
+ in
let decoded_op = Option.bind json (Utils.Decoder.decode Operation.decoder) in
match decoded_op with
- | Some op ->
- (match Query.execute_operation ~client_id ~op conn with
+ | Some (`Credit { value = _value; description = _desc } as op) ->
+ (match Query.execute_transaction ~client_id ~op conn with
| Ok _ as ok -> ok
| Error e -> Error (`DB e))
+ | Some (`Debit { value; description = _desc } as op) ->
+ if valid_debit value client.mov_limit client.balance
+ then (
+ match Query.execute_transaction ~client_id ~op conn with
+ | Ok _ as ok -> ok
+ | Error e -> Error (`DB e))
+ else Error `InvalidValue
| None -> Error (`Decoder "Invalid operation")
in
(match insert_result with
| Ok () ->
let json : Yojson.Safe.t =
- `Assoc [ "limite", `Int 100000; "saldo", `Int (-9098) ]
+ `Assoc [ "limite", `Int client.mov_limit; "saldo", `Int client.balance ]
in
Ok (Response.of_string ~body:(Yojson.Safe.to_string json) `OK)
| Error _ -> Ok (Response.create (`Code 422)))
@@ -39,7 +57,7 @@ let get_balance client_id (db_pool : Query.pool) (_request : Request.t) =
Option.join @@ Result.to_option @@ Query.find_client client_id conn
in
match client_opt with
- | Some _client ->
+ | Some client ->
let client_balance_opt =
Option.join @@ Result.to_option @@ Query.balance client_id conn
in
@@ -52,7 +70,7 @@ let get_balance client_id (db_pool : Query.pool) (_request : Request.t) =
`String
(Format.asprintf "%a" (Ptime.pp_rfc3339 ~tz_offset_s:(-10800) ()) time)
in
- let limit = `Int 100000 in
+ let limit = `Int client.mov_limit in
`Assoc [ "total", total; "data_extrato", date; "limite", limit ]
in
let last_transactions = `List [] in