diff options
author | Mateus Cruz <mateuscolvr@gmail.com> | 2024-02-05 23:28:09 -0300 |
---|---|---|
committer | Mateus Cruz <mateuscolvr@gmail.com> | 2024-02-05 23:28:09 -0300 |
commit | 372834401b0b08498286c92a206a48654ec86a71 (patch) | |
tree | d386911aa8152b86841540aae4e9e74fc062c408 | |
parent | bd700d5098c6b51db63cdabda81d676f5c354eda (diff) |
feat: add transaction serializer
-rw-r--r-- | lib/handler.ml | 8 | ||||
-rw-r--r-- | lib/query.ml | 14 | ||||
-rw-r--r-- | lib/serializer.ml | 16 |
3 files changed, 36 insertions, 2 deletions
diff --git a/lib/handler.ml b/lib/handler.ml index fb075ff..121a0c5 100644 --- a/lib/handler.ml +++ b/lib/handler.ml @@ -2,7 +2,7 @@ open Piaf let valid_debit value limit balance = let balance_after_op = balance - value in - not (balance_after_op <= limit * -1) + not (balance_after_op < limit * -1) ;; let create_transaction client_id (db_pool : Query.pool) (request : Request.t) = @@ -73,7 +73,11 @@ let get_balance client_id (db_pool : Query.pool) (_request : Request.t) = let limit = `Int client.mov_limit in `Assoc [ "total", total; "data_extrato", date; "limite", limit ] in - let last_transactions = `List [] in + let t = + Result.fold ~ok:Fun.id ~error:(fun _ -> []) + @@ Query.transactions client_id conn + in + let last_transactions = `List (List.map Serializer.transaction t) in `Assoc [ "saldo", balance; "ultimas_transacoes", last_transactions ] in Ok (Response.of_string ~body:(Yojson.Safe.to_string json) `OK) diff --git a/lib/query.ml b/lib/query.ml index 6e359ce..1fdc2c3 100644 --- a/lib/query.ml +++ b/lib/query.ml @@ -45,6 +45,19 @@ module Q = struct SELECT @int{value}, @ptime{now()} as time FROM balances WHERE client_id = %int{client_id} |sql}] ;; + + let transactions = + let open Operation in + [%rapper + get_many + {sql| + SELECT @int{id}, @int{client_id}, @int{value}, type as @Operation.TransactionType{transaction_type}, @string{description}, @ptime{created_at} FROM transactions + WHERE transactions.client_id = %int{client_id} + ORDER BY created_at DESC + LIMIT 10 + |sql} + record_out] + ;; end let ( let* ) = Result.bind @@ -66,3 +79,4 @@ let execute_transaction ~client_id ~(op : Operation.transaction_op) conn = let find_client id conn = Q.client ~id conn let balance client_id conn = Q.balance ~client_id conn +let transactions client_id conn = Q.transactions ~client_id conn diff --git a/lib/serializer.ml b/lib/serializer.ml new file mode 100644 index 0000000..35464ac --- /dev/null +++ b/lib/serializer.ml @@ -0,0 +1,16 @@ +let transaction (t : Operation.transaction) = + let transaction_type = + match t.transaction_type with + | `Credit -> "c" + | `Debit -> "d" + in + `Assoc + [ "valor", `Int t.value + ; "tipo", `String transaction_type + ; "descricao", `String t.description + ; ( "realizada_em" + , `String + (Format.asprintf "%a" (Ptime.pp_rfc3339 ~tz_offset_s:(-10800) ()) t.created_at) + ) + ] +;; |