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
|
module Persistence.Payment
( count
, find
, getRange
, listActivePage
, listModifiedPunctualSince
, listActiveMonthlyOrderedByName
, create
, createMany
, edit
, delete
, searchCategory
, repartition
, getPreAndPostPaymentRepartition
, usedCategories
) where
import Data.Map (Map)
import qualified Data.Map as M
import qualified Data.Maybe as Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Calendar (Day)
import qualified Data.Time.Calendar as Calendar
import Data.Time.Clock (UTCTime)
import Data.Time.Clock (getCurrentTime)
import Database.SQLite.Simple (FromRow (fromRow),
NamedParam ((:=)), ToRow)
import qualified Database.SQLite.Simple as SQLite
import Database.SQLite.Simple.ToField (ToField (toField))
import Prelude hiding (id, until)
import Common.Model (CategoryId, Frequency (..),
Payment (..), PaymentId,
User (..), UserId)
import qualified Common.Util.Text as TextUtil
import Model.Query (Query (Query))
import Persistence.Frequency (FrequencyField (..))
import qualified Persistence.Income as IncomePersistence
import qualified Persistence.Util as PersistenceUtil
fields :: Text
fields = T.intercalate "," $
[ "id"
, "user_id"
, "name"
, "cost"
, "date"
, "category"
, "frequency"
, "created_at"
, "edited_at"
, "deleted_at"
]
newtype Row = Row Payment
instance FromRow Row where
fromRow = Row <$> (Payment <$>
SQLite.field <*>
SQLite.field <*>
SQLite.field <*>
SQLite.field <*>
SQLite.field <*>
SQLite.field <*>
(fmap (\(FrequencyField f) -> f) $ SQLite.field) <*>
SQLite.field <*>
SQLite.field <*>
SQLite.field)
newtype InsertRow = InsertRow Payment
instance ToRow InsertRow where
toRow (InsertRow p) =
[ toField (_payment_user p)
, toField (_payment_name p)
, toField (_payment_cost p)
, toField (_payment_date p)
, toField (_payment_category p)
, toField (FrequencyField (_payment_frequency p))
, toField (_payment_createdAt p)
]
data Count = Count Int
instance FromRow Count where
fromRow = Count <$> SQLite.field
count :: Frequency -> Text -> Query Int
count frequency search =
Query (\conn ->
(\[Count n] -> n) <$>
SQLite.queryNamed
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT COUNT(*)"
, "FROM payment"
, "WHERE"
, "deleted_at IS NULL"
, "AND frequency = :frequency"
, "AND (" <> PersistenceUtil.formatKeyForSearch "name" <> " LIKE :search OR cost LIKE :search)"
])
[ ":frequency" := FrequencyField frequency
, ":search" := "%" <> TextUtil.formatSearch search <> "%"
]
)
find :: PaymentId -> Query (Maybe Payment)
find paymentId =
Query (\conn -> do
fmap (\(Row p) -> p) . Maybe.listToMaybe <$>
SQLite.queryNamed
conn
(SQLite.Query $ "SELECT " <> fields <> " FROM payment WHERE id = :id")
[ "id" := paymentId
]
)
data RangeRow = RangeRow (Day, Day)
instance FromRow RangeRow where
fromRow = (\f t -> RangeRow (f, t)) <$> SQLite.field <*> SQLite.field
getRange :: Query (Maybe (Day, Day))
getRange =
Query (\conn -> do
fmap (\(RangeRow (f, t)) -> (f, t)) . Maybe.listToMaybe <$>
SQLite.queryNamed
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT MIN(date), MAX(date)"
, "FROM payment"
, "WHERE"
, "frequency = :frequency"
, "AND deleted_at IS NULL"
])
[ ":frequency" := FrequencyField Punctual
]
)
listActivePage :: Frequency -> Int -> Int -> Text -> Query [Payment]
listActivePage frequency page perPage search =
Query (\conn ->
map (\(Row p) -> p) <$>
SQLite.queryNamed
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT"
, fields
, "FROM payment"
, "WHERE"
, "deleted_at IS NULL"
, "AND frequency = :frequency"
, "AND (" <> PersistenceUtil.formatKeyForSearch "name" <> " LIKE :search OR cost LIKE :search)"
, "ORDER BY date DESC"
, "LIMIT :limit"
, "OFFSET :offset"
]
)
[ ":frequency" := FrequencyField frequency
, ":search" := "%" <> TextUtil.formatSearch search <> "%"
, ":limit" := perPage
, ":offset" := (page - 1) * perPage
]
)
listModifiedPunctualSince :: UTCTime -> Query [Payment]
listModifiedPunctualSince since =
Query (\conn ->
map (\(Row i) -> i) <$>
SQLite.queryNamed
conn
(SQLite.Query . T.intercalate " " $
[ "SELECT " <> fields
, "FROM payment"
, "WHERE"
, "frequency = :frequency"
, "AND (created_at >= :since OR edited_at >= :since OR deleted_at >= :since)"
])
[ ":frequency" := FrequencyField Punctual
, ":since" := since
]
)
listActiveMonthlyOrderedByName :: Query [Payment]
listActiveMonthlyOrderedByName =
Query (\conn -> do
map (\(Row p) -> p) <$>
SQLite.queryNamed
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT"
, fields
, "FROM payment"
, "WHERE deleted_at IS NULL AND frequency = :frequency"
, "ORDER BY name DESC"
])
[ ":frequency" := FrequencyField Monthly
]
)
create :: UserId -> Text -> Int -> Day -> CategoryId -> Frequency -> Query ()
create userId name cost date category frequency =
Query (\conn -> do
currentTime <- getCurrentTime
SQLite.executeNamed
conn
(SQLite.Query $ T.intercalate " "
[ "INSERT INTO payment (user_id, name, cost, date, category, frequency, created_at)"
, "VALUES (:userId, :name, :cost, :date, :category, :frequency, :currentTime)"
])
[ ":userId" := userId
, ":name" := name
, ":cost" := cost
, ":date" := date
, ":category" := category
, ":frequency" := FrequencyField frequency
, ":currentTime" := currentTime
]
)
createMany :: [Payment] -> Query ()
createMany payments =
Query (\conn ->
SQLite.executeMany
conn
(SQLite.Query $ T.intercalate ""
[ "INSERT INTO payment (user_id, name, cost, date, category, frequency, created_at)"
, "VALUES (?, ?, ?, ?, ?, ?, ?)"
])
(map InsertRow payments)
)
edit :: UserId -> PaymentId -> Text -> Int -> Day -> CategoryId -> Frequency -> Query Bool
edit userId paymentId name cost date category frequency =
Query (\conn -> do
payment <- fmap (\(Row p) -> p) . Maybe.listToMaybe <$>
SQLite.queryNamed
conn
(SQLite.Query $
"SELECT " <> fields <> " FROM payment WHERE id = :paymentId and user_id = :userId")
[ ":paymentId" := paymentId
, ":userId" := userId
]
if Maybe.isJust payment then
do
currentTime <- getCurrentTime
SQLite.executeNamed
conn
(SQLite.Query $ T.intercalate " "
[ "UPDATE"
, " payment"
, "SET"
, " edited_at = :editedAt,"
, " name = :name,"
, " cost = :cost,"
, " date = :date,"
, " category = :category,"
, " frequency = :frequency"
, "WHERE"
, " id = :id"
, " AND user_id = :userId"
])
[ ":editedAt" := currentTime
, ":name" := name
, ":cost" := cost
, ":date" := date
, ":category" := category
, ":frequency" := FrequencyField frequency
, ":id" := paymentId
, ":userId" := userId
]
return True
else
return False
)
delete :: UserId -> PaymentId -> Query ()
delete userId paymentId =
Query (\conn ->
SQLite.executeNamed
conn
"UPDATE payment SET deleted_at = datetime('now') WHERE id = :id AND user_id = :userId"
[ ":id" := paymentId
, ":userId" := userId
]
)
data CategoryIdRow = CategoryIdRow CategoryId
instance FromRow CategoryIdRow where
fromRow = CategoryIdRow <$> SQLite.field
searchCategory :: Text -> Query (Maybe CategoryId)
searchCategory paymentName =
Query (\conn ->
fmap (\(CategoryIdRow d) -> d) . Maybe.listToMaybe <$>
SQLite.queryNamed
conn
(SQLite.Query . T.intercalate " " $
[ "SELECT category"
, "FROM payment"
, "WHERE deleted_at is NULL AND name LIKE :name"
, "ORDER BY edited_at, created_at"
, "LIMIT 1"
])
[ ":name" := "%" <> paymentName <> "%"
]
)
usedCategories :: Query [CategoryId]
usedCategories =
Query (\conn -> do
map (\(CategoryIdRow p) -> p) <$>
SQLite.query_
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT DISTINCT category"
, "FROM payment"
, "WHERE deleted_at IS NULL"
])
)
data UserCostRow = UserCostRow (UserId, Int)
instance FromRow UserCostRow where
fromRow = do
user <- SQLite.field
cost <- SQLite.field
return $ UserCostRow (user, cost)
repartition :: Frequency -> Text -> Day -> Day -> Query (Map UserId Int)
repartition frequency search from to =
Query (\conn ->
M.fromList . fmap (\(UserCostRow r) -> r) <$> SQLite.queryNamed
conn
(SQLite.Query . T.intercalate " " $
[ "SELECT user_id, SUM(cost)"
, "FROM payment"
, "WHERE"
, "deleted_at IS NULL"
, "AND frequency = :frequency"
, "AND (" <> PersistenceUtil.formatKeyForSearch "name" <> " LIKE :search OR cost LIKE :search)"
, "AND date >= :from"
, "AND date < :to"
, "GROUP BY user_id"
])
[ ":frequency" := FrequencyField frequency
, ":search" := "%" <> TextUtil.formatSearch search <> "%"
, ":from" := from
, ":to" := to
]
)
getPreAndPostPaymentRepartition :: Maybe (Day, Day) -> [User] -> Query (Map UserId Int, Map UserId Int)
getPreAndPostPaymentRepartition paymentRange users = do
case paymentRange of
Just (from, to) -> do
incomeDefinedForAll <- IncomePersistence.definedForAll (_user_id <$> users)
(,)
<$> (repartition Punctual "" from (Maybe.fromMaybe (Calendar.addDays 1 to) incomeDefinedForAll))
<*> (case incomeDefinedForAll of
Just d -> repartition Punctual "" d (Calendar.addDays 1 to)
Nothing -> return M.empty)
Nothing ->
return (M.empty, M.empty)
|