-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.hs
More file actions
795 lines (704 loc) · 29.9 KB
/
Client.hs
File metadata and controls
795 lines (704 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Splitwise.Client
(
-- * Client
SplitwiseEnv(..)
, SplitwiseM
, runSplitwise
, runSplitwiseDebug
-- Raw requests
, makeRawRequest
, requestJSONBody
-- Logging
, SplitwiseLogger
, debugLogger
-- * Schema requests
-- ** User
, getCurrentUser
, getUser
, updateUser
-- ** Groups
, createGroup
, getGroups
, getGroup
, deleteGroup
, restoreGroup
, addUserIDToGroup
, addUserInfoToGroup
, removeUserFromGroup
-- ** Friends
, getFriends
, getFriend
, addFriend
, addFriends
, deleteFriend
-- ** Comments
, getExpenseComments
, createComment
, deleteComment
-- ** Notifications
, getNotifications
, getAllNotifications
-- ** Expenses
, getExpense
, deleteExpense
, restoreExpense
, getExpensesWithCursor
, getAllExpenses
, createEqualSplitExpense
, createSplitBySharesExpense
, updateExpense
-- ** Other
, getCurrencies
, getCategories
-- * JSON requests
-- ** User
, getCurrentUserJSON
, getUserJSON
, updateUserJSON
-- ** Groups
, getGroupsJSON
, getGroupJSON
, createGroupJSON
, deleteGroupJSON
, restoreGroupJSON
, addUserIDToGroupJSON
, addUserInfoToGroupJSON
, removeUserFromGroupJSON
-- ** Friends
, getFriendsJSON
, getFriendJSON
, addFriendJSON
, addFriendsJSON
, deleteFriendJSON
-- ** Comments
, getExpenseCommentsJSON
, createCommentJSON
, deleteCommentJSON
-- ** Notifications
, getNotificationsJSON
, getAllNotificationsJSON
-- ** Expenses
, getExpenseJSON
, getRawExpensesWithCursor
, getAllExpensesJSON
, createEqualSplitExpenseJSON
, createSplitBySharesExpenseJSON
, updateExpenseJSON
, deleteExpenseJSON
, restoreExpenseJSON
-- ** Other
, getCurrenciesJSON
, getCategoriesJSON
) where
import Control.Monad.Except
import Control.Monad.IO.Class
import Control.Monad.Loops
import Control.Monad.Reader (ask, MonadReader, ReaderT, runReaderT)
import Data.Aeson hiding (Object)
import Data.Aeson.Types (parseMaybe)
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Default
import Data.Aeson.Key (fromText)
import Data.Aeson.Schema
import qualified Data.Aeson.Schema as AS
import Data.Generics.Labels ()
import Data.Maybe
import Data.Text hiding (concat, concatMap, drop, filter, map, zip)
import qualified Data.Text as T
import qualified Network.HTTP.Types as HTTP
import Network.HTTP.Client
import Network.HTTP.Client.TLS (tlsManagerSettings)
import System.IO (hPutStrLn, stderr)
import Splitwise.Data.Cursors
import Splitwise.Data.Schema
import Splitwise.Data.Request
import Splitwise.Internal.Response
import Splitwise.Data.Parameters
import Splitwise.Data.Pagination
type SplitwiseLogger = Request -> Response LBS.ByteString -> IO ()
debugLogger :: SplitwiseLogger
debugLogger req resp = do
hPutStrLn stderr $ BS.unpack (method req) <> " " <> show (getUri req)
hPutStrLn stderr $ "Status: " <> show (HTTP.statusCode $ responseStatus resp)
let body = responseBody resp
case decode @Value body of
Just val -> LBS.hPutStrLn stderr $ encodePretty val
Nothing -> LBS.hPutStrLn stderr body
hPutStrLn stderr ""
data SplitwiseEnv = SplitwiseEnv
{ auth :: SplitwiseAuth
, manager :: Manager
, logger :: Maybe SplitwiseLogger
}
type SplitwiseM m = (MonadIO m, MonadError SplitwiseAPIError m, MonadReader SplitwiseEnv m)
runSplitwise :: SplitwiseAuth -> ExceptT SplitwiseAPIError (ReaderT SplitwiseEnv IO) a -> IO (Either SplitwiseAPIError a)
runSplitwise a action = do
mgr <- newManager tlsManagerSettings
let env = SplitwiseEnv { auth = a, manager = mgr, logger = Nothing }
runReaderT (runExceptT action) env
-- | Use this variant for debugging - will log responses
runSplitwiseDebug :: SplitwiseAuth -> ExceptT SplitwiseAPIError (ReaderT SplitwiseEnv IO) a -> IO (Either SplitwiseAPIError a)
runSplitwiseDebug a action = do
mgr <- newManager tlsManagerSettings
let env = SplitwiseEnv { auth = a, manager = mgr, logger = Just debugLogger }
runReaderT (runExceptT action) env
handleHTTPError :: Response LBS.ByteString -> SplitwiseAPIError
handleHTTPError response = case HTTP.statusCode . responseStatus $ response of
400 -> case eitherDecode @(Object ErrorListSchema) $ responseBody response of
Right r -> BadRequestError $ [get| .errors.base |] r
_ -> BadRequestError []
401 -> case eitherDecode @(Object SingleErrorSchema) $ responseBody response of
Right r -> UnAuthorizedError $ Just [get| r.error |]
_ -> UnAuthorizedError Nothing
403 -> case eitherDecode @(Object ErrorListSchema) $ responseBody response of
Right r -> ForbiddenError [get| r.errors.base |]
_ -> ForbiddenError []
404 -> case eitherDecode @(Object ErrorListSchema) $ responseBody response of
Right r -> NotFoundError [get| r.errors.base |]
_ -> NotFoundError []
x -> UnhandledStatusError x
performRequest :: SplitwiseM m => Request -> m (Response LBS.ByteString)
performRequest req = do
env <- ask
let finalReq = applyAuth env.auth $ applyAcceptJSON req
response <- liftIO $ httpLbs finalReq env.manager
liftIO $ mapM_ (\l -> l finalReq response) env.logger
case HTTP.statusCode . responseStatus $ response of
x | x >= 200 && x < 300 -> pure response
_ -> throwError $ handleHTTPError response
makeRequest :: (IsSchema s, SplitwiseM m) => Request -> m (AS.Object s)
makeRequest req = do
response <- performRequest req
case eitherDecode $ responseBody response of
Left errMsg -> throwError $ JSONParseError $ pack errMsg
Right r -> pure r
-- | Make a request and return the raw Aeson Value without schema decoding.
-- Use this with the request definitions from "Splitwise.Data.Request" to get
-- untyped JSON responses. For example:
--
-- @
-- raw <- makeRawRequest (getExpenseR 123)
-- @
makeRawRequest :: SplitwiseM m => Request -> m Value
makeRawRequest req = do
response <- performRequest req
case eitherDecode $ responseBody response of
Left errMsg -> throwError $ JSONParseError $ pack errMsg
Right r -> pure r
requestJSONBody :: forall a. ToJSON a => Request -> a -> Request
requestJSONBody request params =
(applyContentTypeJSON request) { requestBody }
where requestBody = RequestBodyLBS $ encode params
extractOrThrow :: SplitwiseM m
=> Maybe (Object BaseErrorList)
-> Maybe a
-> Text
-> m a
extractOrThrow (Just errors) _ _ = throwError $ ResponseError $ Just $ [get| .base |] errors
extractOrThrow Nothing payload errMsg = maybe (throwError $ JSONParseError errMsg) pure payload
-- Users
-- ==============================================
-- | Get information about the current user
--
-- [@GET /get_current_user@](https://dev.splitwise.com/#tag/users/paths/~1get_current_user/get)
getCurrentUser :: SplitwiseM m => m (Object CurrentUserSchema)
getCurrentUser = do
response :: Object CurrentUserResponseSchema <- makeRequest getCurrentUserR
pure $ [get| .user |] response
-- |Get information about another user
--
-- [@GET \/get_user\/{id}@](https://dev.splitwise.com/#tag/users/paths/~1get_user~1%7Bid%7D/get)
getUser :: SplitwiseM m
=> Int -- ^ userID
-> m (Object UserSchema)
getUser userID = do
response :: Object UserResponseSchema <- makeRequest $ getUserR userID
pure $ [get| .user |] response
-- | Update a user
--
-- [@POST \/update_user\/{id}@](https://dev.splitwise.com/#tag/users/paths/~1update_user~1%7Bid%7D/post)
updateUser :: SplitwiseM m
=> Int
-- ^ userID
-> UpdateUserParams
-- ^ user update parameters
-> m (Object UserSchema)
updateUser userID params = do
response :: Object UserResponseSchema <- makeRequest $ requestJSONBody (updateUserR userID) params
pure $ [get| .user |] response
-- Groups
-- ==============================================
-- | List the current user's groups
--
-- [@GET /get_groups@](https://dev.splitwise.com/#tag/groups/paths/~1get_groups/get)
getGroups :: SplitwiseM m => m [Object GroupSchema]
getGroups = do
response :: Object MultipleGroupsResponseSchema <- makeRequest getGroupsR
pure $ [get| .groups |] response
-- | Get information about a group
--
-- [@GET \/get_group\/{id}@](https://dev.splitwise.com/#tag/groups/paths/~1get_group~1%7Bid%7D/get)
getGroup :: SplitwiseM m
=> Int -- ^ groupID
-> m (Object GroupSchema)
getGroup groupID = do
response :: Object SingleGroupResponseSchema <- makeRequest $ getGroupR groupID
pure $ [get| .group |] response
-- | Create a group
--
-- [@POST /create_group@](https://dev.splitwise.com/#tag/groups/paths/~1create_group/post)
createGroup :: SplitwiseM m
=> CreateGroupParams -- ^ create group parameters
-> m (Object GroupSchema)
createGroup params = do
response :: Object SingleGroupResponseSchema <- makeRequest $ requestJSONBody createGroupR params
pure $ [get| .group |] response
-- | Delete a group
--
-- [@POST \/delete_group\/{id}@](https://dev.splitwise.com/#tag/groups/paths/~1delete_group~1%7Bid%7D/post)
deleteGroup :: SplitwiseM m
=> Int -- ^ groupID
-> m Bool
deleteGroup groupID = do
response :: Object SuccessResponseSchema <- makeRequest $ deleteGroupR groupID
pure $ [get| .success |] response
-- | Restore a deleted group
--
-- [@POST \/undelete_group\/{id}@](https://dev.splitwise.com/#tag/groups/paths/~1undelete_group~1%7Bid%7D/post)
restoreGroup :: SplitwiseM m
=> Int -- ^ groupID
-> m Bool
restoreGroup groupID = do
response :: Object SuccessResponseSchema <- makeRequest $ restoreGroupR groupID
pure $ [get| .success |] response
-- | Add a user to a group (generic helper)
addUserToGroup :: (SplitwiseM m, ToJSON a) => a -> m (Object UserSchema)
addUserToGroup params = do
response :: Object AddUserToGroupResponseSchema <- makeRequest $ requestJSONBody addUserToGroupR params
if [get| .success |] response then
maybe (throwError $ JSONParseError "Successful response, but no user object returned") pure ([get| .user |] response)
else
throwError $ ResponseError (fmap [get| .base |] ([get| .errors |] response))
-- | Add a user to a group, by userID
--
-- [@POST /add_user_to_group@](https://dev.splitwise.com/#tag/groups/paths/~1add_user_to_group/post)
addUserIDToGroup :: SplitwiseM m
=> AddUserIDToGroupParams -- ^ parameters
-> m (Object UserSchema)
addUserIDToGroup = addUserToGroup
-- | Add a user to a group by user info
--
-- [@POST /add_user_to_group@](https://dev.splitwise.com/#tag/groups/paths/~1add_user_to_group/post)
addUserInfoToGroup :: SplitwiseM m
=> AddUserInfoToGroupParams -- ^ parameters
-> m (Object UserSchema)
addUserInfoToGroup = addUserToGroup
-- | Remove a user from a group
--
-- [@POST /remove_user_from_group@](https://dev.splitwise.com/#tag/groups/paths/~1remove_user_from_group/post)
removeUserFromGroup :: SplitwiseM m
=> RemoveUserFromGroupParams -- ^ parameters
-> m Bool
removeUserFromGroup params = do
response :: Object SuccessResponseSchema <- makeRequest $ requestJSONBody removeUserFromGroupR params
pure $ [get| .success |] response
-- Friends
-- ==============================================
-- | List the current user's friends
--
-- [@GET /get_friends@](https://dev.splitwise.com/#tag/friends/paths/~1get_friends/get)
getFriends :: SplitwiseM m => m [Object FriendSchema]
getFriends = do
response :: Object MultipleFriendsResponseSchema <- makeRequest getFriendsR
pure $ [get| .friends |] response
-- | Get details about a friend
--
-- [@GET \/get_friend\/{id}@](https://dev.splitwise.com/#tag/friends/paths/~1get_friend~1%7Bid%7D/get)
getFriend :: SplitwiseM m
=> Int -- ^ friendID
-> m (Object FriendSchema)
getFriend friendID = do
response :: Object SingleFriendResponseSchema <- makeRequest $ getFriendR friendID
pure $ [get| .friend |] response
-- | Add a friend
--
-- [@POST /create_friend@](https://dev.splitwise.com/#tag/friends/paths/~1create_friend/post)
addFriend :: SplitwiseM m
=> AddFriendParams -- ^ parameters
-> m (Object FriendSchema)
addFriend params = do
response :: Object SingleFriendResponseSchema <- makeRequest $ requestJSONBody createFriendR params
pure $ [get| .friend |] response
-- | Convert a list of AddFriendParams to the special flat JSON structure required by Splitwise API
-- Example: [AddFriendParams "alan@example.org" (Just "Alan") (Just "Turing"), AddFriendParams "existing@example.com" Nothing Nothing]
-- Becomes: {"friends__0__first_name": "Alan", "friends__0__last_name": "Turing", "friends__0__email": "alan@example.org", "friends__1__email": "existing@example.com"}
addFriendsToJSON :: [AddFriendParams] -> Value
addFriendsToJSON friends = object $ concatMap friendToKeyValuePairs (zip [0..] friends)
where
friendToKeyValuePairs :: (Int, AddFriendParams) -> [(Key, Value)]
friendToKeyValuePairs (idx, AddFriendParams{..}) =
let indexStr = T.pack $ show idx
emailKey = fromText $ "users__" <> indexStr <> "__email"
firstNameKey = fromText $ "users__" <> indexStr <> "__first_name"
lastNameKey = fromText $ "users__" <> indexStr <> "__last_name"
in [ (emailKey, String email) ]
++ maybeToList (fmap (\fn -> (firstNameKey, String fn)) firstName)
++ maybeToList (fmap (\ln -> (lastNameKey, String ln)) lastName)
-- | Add multiple friends at once
--
-- [@POST /create_friends@](https://dev.splitwise.com/#tag/friends/paths/~1create_friends/post)
addFriends :: SplitwiseM m => [AddFriendParams] -> m [Object FriendSchema]
addFriends params = do
response :: Object AddMultipleFriendsResponseSchema <- makeRequest request
extractOrThrow ([get| .errors |] response) ([get| .users |] response)
"Successful response, but no user object returned"
where requestBody = RequestBodyLBS $ encode $ addFriendsToJSON params
request = (applyContentTypeJSON createFriendsR) { requestBody }
-- | Delete a friendship
--
-- [@POST \/delete_friend\/{id}@](https://dev.splitwise.com/#tag/friends/paths/~1create_friends/post)
deleteFriend :: SplitwiseM m
=> Int -- ^ friendID
-> m Bool
deleteFriend friendID = do
response :: Object SuccessResponseSchema <- makeRequest $ deleteFriendR friendID
pure $ [get| .success |] response
-- Expenses
-- ==============================================
-- | Get expense information
--
-- [@GET \/get_expense\/{id}@](https://dev.splitwise.com/#tag/expenses/paths/~1get_expense~1%7Bid%7D/get)
getExpense :: SplitwiseM m
=> Int -- ^ expenseID
-> m (Object ExpenseSchema)
getExpense expenseID = do
response :: Object SingleExpenseResponseSchema<- makeRequest $ getExpenseR expenseID
pure $ [get| .expense |] response
getExpensesWithCursor :: (SplitwiseM m, ExpensesCursor a) => a -> m (Expenses a (Object ExpenseSchema))
getExpensesWithCursor cursor = do
let params = expensesParams cursor
response :: Object MultipleExpensesResponseSchema <- makeRequest $ applyQuery getExpensesR (HTTP.toQuery params)
let es = [get| .expenses |] response
pure $ Expenses { expenses = es, cursor = cursor }
-- Get Expenses helper methods
getAllExpenses :: SplitwiseM m => GetExpensesQueryParams -> m [Object ExpenseSchema]
getAllExpenses params = do
expensesResult <- unfoldrM (unfoldWith allExpensesCursorNextState getExpensesWithCursor) (GoCursor $ mkAllExpensesCursor params)
pure $ concat expensesResult
-- | Create an expense an equally split expense
--
-- [@POST /create_expense@](https://dev.splitwise.com/#tag/expenses/paths/~1create_expense/post)
createEqualSplitExpense :: SplitwiseM m => CreateEqualSplitExpenseParams -> m [Object ExpenseSchema]
createEqualSplitExpense params = createExpense $ toUpdateExpenseParams params
-- | Create an expense a split by shares expense
--
-- [@POST /create_expense@](https://dev.splitwise.com/#tag/expenses/paths/~1create_expense/post)
createSplitBySharesExpense :: SplitwiseM m => CreateSplitBySharesExpenseParams -> m [Object ExpenseSchema]
createSplitBySharesExpense params = createExpense $ toUpdateExpenseParams params
createExpense :: SplitwiseM m => UpdateExpenseParams -> m [Object ExpenseSchema]
createExpense params = do
response :: Object CreateOrUpdateExpenseResponse <- makeRequest request
extractOrThrow ([get| .errors |] response) ([get| .expenses |] response)
"Successful response, but no expense object returned"
where request = requestJSONBody createExpenseR params
-- | Update an expense
--
-- [@POST /update_expense@](https://dev.splitwise.com/#tag/expenses/paths/~1update_expense~1%7Bid%7D/post)
updateExpense :: SplitwiseM m
=> Int -- ^ expenseID
-> UpdateExpenseParams -- ^ parameters
-> m [Object ExpenseSchema]
updateExpense expenseID params = do
response :: Object CreateOrUpdateExpenseResponse <- makeRequest $ requestJSONBody request params
extractOrThrow ([get| .errors |] response) ([get| .expenses |] response)
"Successful response, but no expense object returned"
where request = updateExpenseR expenseID
-- | Delete an expense
--
-- [@POST \/delete_expense\/{id}@](https://dev.splitwise.com/#tag/expenses/paths/~1delete_expense~1%7Bid%7D/post)
deleteExpense :: SplitwiseM m
=> Int -- ^ expenseID
-> m Bool
deleteExpense expenseID = do
response :: Object SuccessResponseSchema <- makeRequest $ deleteExpenseR expenseID
pure $ [get| .success |] response
-- | Restore a deleted expense
--
-- [@POST \/undelete_expenses\/{id}@](https://dev.splitwise.com/#tag/expenses/paths/~1undelete_expense~1%7Bid%7D/post)
restoreExpense :: SplitwiseM m
=> Int -- ^ expenseID
-> m Bool
restoreExpense expenseID = do
response :: Object SuccessResponseSchema <- makeRequest $ restoreExpenseR expenseID
pure $ [get| .success |] response
-- Comments
-- ==============================================
-- | Get comments on an expense
--
-- [@GET /get_comments@](https://dev.splitwise.com/#tag/comments/paths/~1get_comments/get)
getExpenseComments :: SplitwiseM m
=> Int -- ^ expenseID
-> m [Object CommentSchema]
getExpenseComments expenseID = do
response :: Object GetExpenseCommentsResponseSchema <- makeRequest $ getExpenseCommentsR expenseID
pure $ [get| .comments |] response
-- | Create a comment on an expense
--
-- [@POST /create_comment@](https://dev.splitwise.com/#tag/comments/paths/~1create_comment/post)
createComment :: SplitwiseM m
=> Int -- ^ expenseID
-> Text -- ^ comment text
-> m (Object CommentSchema)
createComment expenseID content = do
response :: Object SingleCommentResponseSchema <- makeRequest request
pure $ [get| .comment |] response
where requestBody = RequestBodyLBS $ encode $ object ["expense_id" .= expenseID, "content" .= content]
request = (applyContentTypeJSON createCommentR) { requestBody }
-- | Delete a comment on an expense
--
-- [@POST \/delete_comment\/{id}@](https://dev.splitwise.com/#tag/comments/paths/~1delete_comment~1%7Bid%7D/post)
deleteComment :: SplitwiseM m
=> Int -- ^ commentID
-> m (Object CommentSchema)
deleteComment commentID = do
response :: Object SingleCommentResponseSchema <- makeRequest $ deleteCommentR commentID
pure $ [get| .comment |] response
-- Notifications
-- ==============================================
-- | Get all notifications
-- NOTE: This endpoint isn't paginated and the server side sets (large) limits on number of notifications returned.
-- If you absolutely need _all_ notifications, use the getNotifications function below
--
-- [@GET /get_notifications@](https://dev.splitwise.com/#tag/notifications/paths/~1get_notifications/get)
getAllNotifications :: SplitwiseM m => m [Object NotificationSchema]
getAllNotifications = getNotifications def
getNotifications :: SplitwiseM m
=> GetNotificationsQuery
-> m [Object NotificationSchema]
getNotifications query = do
let request = applyQuery getNotificationsR (HTTP.toQuery query)
response :: Object NotificationsResponseSchema <- makeRequest request
pure $ [get| .notifications |] response
-- Other
-- ==============================================
-- | Get all currencies supported by Splitwise.
--
-- [@GET /get_currencies@](https://dev.splitwise.com/#tag/other/paths/~1get_currencies/get)
getCurrencies :: SplitwiseM m => m [Object CurrencySchema]
getCurrencies = do
response :: Object CurrenciesResponseSchema <- makeRequest getCurrenciesR
pure $ [get| .currencies[] |] response
-- | Get all categories allowed for expenses
--
-- [@GET /get_categories@](https://dev.splitwise.com/#tag/other/paths/~1get_categories/get)
getCategories :: SplitwiseM m => m [Object CategorySchema]
getCategories = do
response :: Object CategoriesResponseSchema <- makeRequest getCategoriesR
pure $ [get| .categories |] response
-- JSON variants
-- ==============================================
-- These mirror the typed API functions above but return raw Aeson Values.
-- | Get information about the current user
--
-- [@GET /get_current_user@](https://dev.splitwise.com/#tag/users/paths/~1get_current_user/get)
getCurrentUserJSON :: SplitwiseM m => m Value
getCurrentUserJSON = makeRawRequest getCurrentUserR
-- |Get information about another user
--
-- [@GET \/get_user\/{id}@](https://dev.splitwise.com/#tag/users/paths/~1get_user~1%7Bid%7D/get)
getUserJSON :: SplitwiseM m
=> Int -- ^ userID
-> m Value
getUserJSON userID = makeRawRequest $ getUserR userID
-- | Update a user
--
-- [@POST \/update_user\/{id}@](https://dev.splitwise.com/#tag/users/paths/~1update_user~1%7Bid%7D/post)
updateUserJSON :: SplitwiseM m
=> Int
-- ^ userID
-> UpdateUserParams
-- ^ update user parameters
-> m Value
updateUserJSON userID params = makeRawRequest $ requestJSONBody (updateUserR userID) params
-- | List the current user's groups
--
-- [@GET /get_groups@](https://dev.splitwise.com/#tag/groups/paths/~1get_groups/get)
getGroupsJSON :: SplitwiseM m => m Value
getGroupsJSON = makeRawRequest getGroupsR
-- | Get information about a group
--
-- [@GET \/get_group\/{id}@](https://dev.splitwise.com/#tag/groups/paths/~1get_group~1%7Bid%7D/get)
getGroupJSON :: SplitwiseM m
=> Int -- ^ groupID
-> m Value
getGroupJSON groupID = makeRawRequest $ getGroupR groupID
-- | Create a group
--
-- [@POST /create_group@](https://dev.splitwise.com/#tag/groups/paths/~1create_group/post)
createGroupJSON :: SplitwiseM m => CreateGroupParams -> m Value
createGroupJSON params = makeRawRequest $ requestJSONBody createGroupR params
-- | Delete a group
--
-- [@POST \/delete_group\/{id}@](https://dev.splitwise.com/#tag/groups/paths/~1delete_group~1%7Bid%7D/post)
deleteGroupJSON :: SplitwiseM m
=> Int -- ^ groupID
-> m Value
deleteGroupJSON groupID = makeRawRequest $ deleteGroupR groupID
-- | Restore a deleted group
--
-- [@POST \/undelete_group\/{id}@](https://dev.splitwise.com/#tag/groups/paths/~1undelete_group~1%7Bid%7D/post)
restoreGroupJSON :: SplitwiseM m
=> Int -- ^ groupID
-> m Value
restoreGroupJSON groupID = makeRawRequest $ restoreGroupR groupID
-- | Add a user to a group, by userID
--
-- [@POST /add_user_to_group@](https://dev.splitwise.com/#tag/groups/paths/~1add_user_to_group/post)
addUserIDToGroupJSON :: SplitwiseM m => AddUserIDToGroupParams -> m Value
addUserIDToGroupJSON params = makeRawRequest $ requestJSONBody addUserToGroupR params
-- | Add a user to a group by user info
--
-- [@POST /add_user_to_group@](https://dev.splitwise.com/#tag/groups/paths/~1add_user_to_group/post)
addUserInfoToGroupJSON :: SplitwiseM m => AddUserInfoToGroupParams -> m Value
addUserInfoToGroupJSON params = makeRawRequest $ requestJSONBody addUserToGroupR params
-- | Remove a user from a group
--
-- [@POST /remove_user_from_group@](https://dev.splitwise.com/#tag/groups/paths/~1remove_user_from_group/post)
removeUserFromGroupJSON :: SplitwiseM m => RemoveUserFromGroupParams -> m Value
removeUserFromGroupJSON params = makeRawRequest $ requestJSONBody removeUserFromGroupR params
-- | List the current user's friends
--
-- [@GET /get_friends@](https://dev.splitwise.com/#tag/friends/paths/~1get_friends/get)
getFriendsJSON :: SplitwiseM m => m Value
getFriendsJSON = makeRawRequest getFriendsR
-- | Get details about a friend
--
-- [@GET \/get_friend\/{id}@](https://dev.splitwise.com/#tag/friends/paths/~1get_friend~1%7Bid%7D/get)
getFriendJSON :: SplitwiseM m
=> Int -- ^ friendID
-> m Value
getFriendJSON friendID = makeRawRequest $ getFriendR friendID
-- | Add a friend
--
-- [@POST /create_friend@](https://dev.splitwise.com/#tag/friends/paths/~1create_friend/post)
addFriendJSON :: SplitwiseM m => AddFriendParams -> m Value
addFriendJSON params = makeRawRequest $ requestJSONBody createFriendR params
-- | Add multiple friends at once
--
-- [@POST /create_friends@](https://dev.splitwise.com/#tag/friends/paths/~1create_friends/post)
addFriendsJSON :: SplitwiseM m => [AddFriendParams] -> m Value
addFriendsJSON params = makeRawRequest request
where requestBody = RequestBodyLBS $ encode $ addFriendsToJSON params
request = (applyContentTypeJSON createFriendsR) { requestBody }
-- | Delete a friendship
--
-- [@POST \/delete_friend\/{id}@](https://dev.splitwise.com/#tag/friends/paths/~1create_friends/post)
deleteFriendJSON :: SplitwiseM m
=> Int -- ^ friendID
-> m Value
deleteFriendJSON friendID = makeRawRequest $ deleteFriendR friendID
-- | Get expense information
--
-- [@GET \/get_expense\/{id}@](https://dev.splitwise.com/#tag/expenses/paths/~1get_expense~1%7Bid%7D/get)
getExpenseJSON :: SplitwiseM m => Int -> m Value
getExpenseJSON expenseID = makeRawRequest $ getExpenseR expenseID
getRawExpensesWithCursor :: (SplitwiseM m, ExpensesCursor a) => a -> m (Expenses a Value)
getRawExpensesWithCursor cursor = do
let params = expensesParams cursor
raw <- makeRawRequest $ applyQuery getExpensesR (HTTP.toQuery params)
case parseMaybe (withObject "response" (.: "expenses")) raw of
Just es -> pure $ Expenses { expenses = es, cursor = cursor }
Nothing -> throwError $ JSONParseError "Expected object with 'expenses' array"
getAllExpensesJSON :: SplitwiseM m => GetExpensesQueryParams -> m [Value]
getAllExpensesJSON params = do
result <- unfoldrM (unfoldWith allExpensesCursorNextState getRawExpensesWithCursor) (GoCursor $ mkAllExpensesCursor params)
pure $ concat result
-- | Create an expense an equally split expense
--
-- [@POST /create_expense@](https://dev.splitwise.com/#tag/expenses/paths/~1create_expense/post)
createEqualSplitExpenseJSON :: SplitwiseM m => CreateEqualSplitExpenseParams -> m Value
createEqualSplitExpenseJSON params = makeRawRequest $ requestJSONBody createExpenseR $ toUpdateExpenseParams params
-- | Create an expense a split by shares expense
--
-- [@POST /create_expense@](https://dev.splitwise.com/#tag/expenses/paths/~1create_expense/post)
createSplitBySharesExpenseJSON :: SplitwiseM m => CreateSplitBySharesExpenseParams -> m Value
createSplitBySharesExpenseJSON params = makeRawRequest $ requestJSONBody createExpenseR $ toUpdateExpenseParams params
-- | Update an expense
--
-- [@POST /update_expense@](https://dev.splitwise.com/#tag/expenses/paths/~1update_expense~1%7Bid%7D/post)
updateExpenseJSON :: SplitwiseM m
=> Int -- ^ expenseID
-> UpdateExpenseParams -- ^ parameters
-> m Value
updateExpenseJSON expenseID params = makeRawRequest $ requestJSONBody (updateExpenseR expenseID) params
-- | Delete an expense
--
-- [@POST \/delete_expense\/{id}@](https://dev.splitwise.com/#tag/expenses/paths/~1delete_expense~1%7Bid%7D/post)
deleteExpenseJSON :: SplitwiseM m
=> Int -- ^ expenseID
-> m Value
deleteExpenseJSON expenseID = makeRawRequest $ deleteExpenseR expenseID
-- | Restore a deleted expense
--
-- [@POST \/undelete_expenses\/{id}@](https://dev.splitwise.com/#tag/expenses/paths/~1undelete_expense~1%7Bid%7D/post)
restoreExpenseJSON :: SplitwiseM m
=> Int -- ^ expenseID
-> m Value
restoreExpenseJSON expenseID = makeRawRequest $ restoreExpenseR expenseID
-- | Get comments on an expense
--
-- [@GET /get_comments@](https://dev.splitwise.com/#tag/comments/paths/~1get_comments/get)
getExpenseCommentsJSON :: SplitwiseM m
=> Int -- ^ expenseID
-> m Value
getExpenseCommentsJSON expenseID = makeRawRequest $ getExpenseCommentsR expenseID
-- | Create a comment on an expense
--
-- [@POST /create_comment@](https://dev.splitwise.com/#tag/comments/paths/~1create_comment/post)
createCommentJSON :: SplitwiseM m
=> Int -- ^ expenseID
-> Text -- ^ comment text
-> m Value
createCommentJSON expenseID content = makeRawRequest request
where requestBody = RequestBodyLBS $ encode $ object ["expense_id" .= expenseID, "content" .= content]
request = (applyContentTypeJSON createCommentR) { requestBody }
-- | Delete a comment on an expense
--
-- [@POST \/delete_comment\/{id}@](https://dev.splitwise.com/#tag/comments/paths/~1delete_comment~1%7Bid%7D/post)
deleteCommentJSON :: SplitwiseM m
=> Int -- ^ expenseID
-> m Value
deleteCommentJSON commentID = makeRawRequest $ deleteCommentR commentID
-- | Get all notifications
-- NOTE: This endpoint isn't paginated and the server side sets (large) limits on number of notifications returned.
-- If you absolutely need _all_ notifications, use the getNotificationsJSON function below
--
-- [@GET /get_notifications@](https://dev.splitwise.com/#tag/notifications/paths/~1get_notifications/get)
getNotificationsJSON :: SplitwiseM m => GetNotificationsQuery -> m Value
getNotificationsJSON query = makeRawRequest $ applyQuery getNotificationsR (HTTP.toQuery query)
getAllNotificationsJSON :: SplitwiseM m => m Value
getAllNotificationsJSON = getNotificationsJSON def
-- | Get all currencies supported by Splitwise.
--
-- [@GET /get_currencies@](https://dev.splitwise.com/#tag/other/paths/~1get_currencies/get)
getCurrenciesJSON :: SplitwiseM m => m Value
getCurrenciesJSON = makeRawRequest getCurrenciesR
-- | Get all categories allowed for expenses
--
-- [@GET /get_categories@](https://dev.splitwise.com/#tag/other/paths/~1get_categories/get)
getCategoriesJSON :: SplitwiseM m => m Value
getCategoriesJSON = makeRawRequest getCategoriesR