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
|
module Persistence.Payment
( count
, find
, getRange
, listActivePage
, listModifiedSince
, listActiveMonthlyOrderedByName
, create
, createMany
, edit
, delete
, searchCategory
, repartition
, getPreAndPostPaymentRepartition
) 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), Only (Only),
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 Model.Query (Query (Query))
import Persistence.Frequency (FrequencyField (..))
import qualified Persistence.Income as IncomePersistence
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.query
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT COUNT(*)"
, "FROM payment"
, "WHERE"
, "deleted_at IS NULL"
, "AND frequency = ?"
, "AND name LIKE ?"
])
(FrequencyField frequency, "%" <> search <> "%")
)
find :: PaymentId -> Query (Maybe Payment)
find paymentId =
Query (\conn -> do
fmap (\(Row p) -> p) . Maybe.listToMaybe <$>
SQLite.query
conn
(SQLite.Query $ "SELECT " <> fields <> " FROM payment WHERE id = ?")
(Only 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.query
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT MIN(date), MAX(date)"
, "FROM payment"
, "WHERE"
, "frequency = ?"
, "AND deleted_at IS NULL"
])
(Only (FrequencyField Punctual))
)
listActivePage :: Frequency -> Int -> Int -> Text -> Query [Payment]
listActivePage frequency page perPage search =
Query (\conn ->
map (\(Row p) -> p) <$>
SQLite.query
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT"
, fields
, "FROM payment"
, "WHERE"
, "deleted_at IS NULL"
, "AND frequency = ?"
, "AND name LIKE ?"
, "ORDER BY date DESC"
, "LIMIT ?"
, "OFFSET ?"
]
)
(FrequencyField frequency, "%" <> search <> "%", perPage, (page - 1) * perPage)
)
listModifiedSince :: UTCTime -> Query [Payment]
listModifiedSince since =
Query (\conn ->
map (\(Row i) -> i) <$>
SQLite.query
conn
(SQLite.Query . T.intercalate " " $
[ "SELECT *"
, "FROM payment"
, "WHERE"
, "created_at >= ?"
, "OR edited_at >= ?"
, "OR deleted_at >= ?"
])
(Only since)
)
listActiveMonthlyOrderedByName :: Query [Payment]
listActiveMonthlyOrderedByName =
Query (\conn -> do
map (\(Row p) -> p) <$>
SQLite.query
conn
(SQLite.Query $ T.intercalate " "
[ "SELECT"
, fields
, "FROM payment"
, "WHERE deleted_at IS NULL AND frequency = ?"
, "ORDER BY name DESC"
])
(Only (FrequencyField Monthly))
)
create :: UserId -> Text -> Int -> Day -> CategoryId -> Frequency -> Query Payment
create userId name cost date category frequency =
Query (\conn -> do
time <- getCurrentTime
SQLite.execute
conn
(SQLite.Query $ T.intercalate " "
[ "INSERT INTO payment (user_id, name, cost, date, category, frequency, created_at)"
, "VALUES (?, ?, ?, ?, ?, ?, ?)"
])
(userId, name, cost, date, category, FrequencyField frequency, time)
paymentId <- SQLite.lastInsertRowId conn
return $ Payment
{ _payment_id = paymentId
, _payment_user = userId
, _payment_name = name
, _payment_cost = cost
, _payment_date = date
, _payment_category = category
, _payment_frequency = frequency
, _payment_createdAt = time
, _payment_editedAt = Nothing
, _payment_deletedAt = Nothing
}
)
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 (Maybe Payment)
edit userId paymentId name cost date category frequency =
Query (\conn -> do
mbPayment <- fmap (\(Row p) -> p) . Maybe.listToMaybe <$>
SQLite.query
conn
(SQLite.Query $ "SELECT " <> fields <> " FROM payment WHERE id = ? and user_id = ?")
(paymentId, userId)
case mbPayment of
Just payment -> do
now <- getCurrentTime
SQLite.execute
conn
(SQLite.Query $ T.intercalate " "
[ "UPDATE"
, " payment"
, "SET"
, " edited_at = ?,"
, " name = ?,"
, " cost = ?,"
, " date = ?,"
, " category = ?,"
, " frequency = ?"
, "WHERE"
, " id = ?"
, " AND user_id = ?"
])
( now
, name
, cost
, date
, category
, FrequencyField frequency
, paymentId
, userId
)
return . Just $ Payment
{ _payment_id = paymentId
, _payment_user = userId
, _payment_name = name
, _payment_cost = cost
, _payment_date = date
, _payment_category = category
, _payment_frequency = frequency
, _payment_createdAt = _payment_createdAt payment
, _payment_editedAt = Just now
, _payment_deletedAt = Nothing
}
Nothing ->
return Nothing
)
delete :: UserId -> PaymentId -> Query ()
delete userId paymentId =
Query (\conn ->
SQLite.execute
conn
"UPDATE payment SET deleted_at = datetime('now') WHERE id = ? AND user_id = ?"
(paymentId, 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.query
conn
"SELECT category FROM payment WHERE name LIKE ? LIMIT 1"
(Only $ "%" <> paymentName <> "%")
)
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.query
conn
(SQLite.Query . T.intercalate " " $
[ "SELECT user_id, SUM(cost)"
, "FROM payment"
, "WHERE"
, "deleted_at IS NULL"
, "AND frequency = ?"
, "AND name LIKE ?"
, "AND date >= ?"
, "AND date < ?"
, "GROUP BY user_id"
])
(FrequencyField frequency, "%" <> search <> "%", from, 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)
|