nit: Added link to `CONTRIBUTING.md` from the README
[nit.git] / contrib / refund / src / refund_json.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2015 Alexandre Terrasa <alexandre@moz-code.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # JSON handling for `refund`.
18 module refund_json
19
20 import refund_base
21 import json::static
22
23 redef class RefundProcessor
24
25 redef fun process(input_file, output_file) do
26 self.output_file = output_file
27 var json = load_input(input_file)
28 var sheet = new ReclamationSheet.from_json(self, json)
29 var res = process_refunds(sheet)
30 write_output(res.to_pretty_json, output_file)
31 end
32
33 # Computes allowed refunds for a given `ReclamationSheet`.
34 fun process_refunds(sheet: ReclamationSheet): JsonObject do
35 # update stats
36 var stats = load_stats
37 stats.inc("total_treatments")
38 # compute refunds
39 current_refunds.clear
40 var json = new JsonObject
41 json["dossier"] = sheet.file.to_s
42 json["mois"] = sheet.month.to_s
43 var arr = new JsonArray
44 var sum = 0.0.to_dollar
45 for recl in sheet.recls do
46 var refund = process_refund(sheet, recl)
47 var obj = new JsonObject
48 obj["soin"] = recl.care_id
49 obj["date"] = recl.date.to_s
50 obj["montant"] = refund.to_s
51 arr.add obj
52 sum += refund
53 # update stats for care
54 stats.inc("total_{recl.care_id}")
55 end
56 save_stats(stats)
57 json["remboursements"] = arr
58 json["total"] = sum.to_s
59 return json
60 end
61
62 # Loads the input string and returns its content as a JsonObject.
63 #
64 # Dies if the file cannot be read or does not contain a valid JSONObject.
65 fun load_input(file: String): JsonObject do
66 if not file.file_exists then
67 die("File `{file}` not found.")
68 abort
69 end
70 var ptr = new FileReader.open(file)
71 var json = ptr.read_all.parse_json
72 if json isa JsonParseError then
73 die("Wrong input file ({json.message})")
74 abort
75 else if not json isa JsonObject then
76 die("Wrong input type (expected JsonObject got {json.class_name})")
77 abort
78 end
79 ptr.close
80 return json
81 end
82
83 # Writes `str` in path specified by `file`.
84 #
85 # Used to produce output and stats.
86 fun write_output(str: String, file: String) do
87 var ofs = new FileWriter.open(file)
88 ofs.write(str)
89 ofs.close
90 end
91
92 # UTILS
93
94 # Does `json` contains `key`? Dies otherwise.
95 private fun check_key(json: JsonObject, key: String) do
96 if json.has_key(key) then return
97 die("Malformed input (missing key {key})")
98 end
99
100 # Does `str` match the regex `re`.
101 private fun check_format(str, re: String): Bool do
102 return str.has(re.to_re)
103 end
104
105 redef fun die(msg) do
106 # save error
107 var obj = new JsonObject
108 obj["message"] = msg
109 write_output(obj.to_pretty_json, output_file)
110 # update stats
111 var stats = load_stats
112 stats.inc("total_reject")
113 save_stats(stats)
114 # leave
115 exit 1
116 end
117
118 redef fun show_stats do print load_stats.to_json.to_pretty_json
119
120 redef fun load_stats do
121 # If no stats found, return a new object
122 if not stats_file.file_exists then return new RefundStats
123 # Try to read from file
124 var ifs = new FileReader.open(stats_file)
125 var content = ifs.read_all.parse_json
126 ifs.close
127 # If file is corrupted, return a new object
128 if not content isa JsonObject then return new RefundStats
129 # Return file contained stats
130 return new RefundStats.from_json(content)
131 end
132
133 redef fun save_stats(stats: RefundStats) do
134 write_output(stats.to_json.to_pretty_json, stats_file)
135 end
136 end
137
138 redef class RefundStats
139
140 # Inits `self` from the content of a JsonObject
141 init from_json(json: JsonObject) do
142 for k, v in json do self[k] = v.as(Int)
143 end
144
145 # Outputs `self` as a JSON string.
146 fun to_json: JsonObject do
147 var obj = new JsonObject
148 for k, v in self do obj[k] = v
149 return obj
150 end
151 end
152
153 redef class ReclamationSheet
154
155 # Inits `self` from the content of a `JsonObject`.
156 init from_json(proc: RefundProcessor, json: JsonObject) do
157 file = new ReclFile.from_json(proc, json)
158 month = new ReclMonth.from_json(proc, json)
159 recls = parse_recls(proc, json)
160 init(file, month)
161 end
162
163 # Parses and checks the given `json` then returns an array of `Reclamation` instances.
164 private fun parse_recls(proc: RefundProcessor, json: JsonObject): Array[Reclamation] do
165 proc.check_key(json, "reclamations")
166 var res = new Array[Reclamation]
167 var recls = json["reclamations"]
168 if not recls isa JsonArray then
169 proc.die("Wrong type for `number` (expected JsonArray got {recls.class_name})")
170 abort
171 end
172 var i = 0
173 for obj in recls do
174 if not obj isa JsonObject then
175 proc.die("Wrong type for `reclamations#{i}` " +
176 "(expected JsonObject got {obj.class_name})")
177 abort
178 end
179 var recl = new Reclamation.from_json(proc, obj)
180 if not month.has(recl.date) then
181 proc.die("Wrong `mois` for `soin` with id `{recl.care_id}`")
182 abort
183 end
184 if file.contract.care_by_id(recl.care_id) == null then
185 proc.die("Unknown `soin` with id `{recl.care_id}`")
186 abort
187 end
188 res.add recl
189 i += 1
190 end
191 return res
192 end
193 end
194
195 redef class ReclFile
196 # Inits `self` from the content of a JsonObject.
197 init from_json(proc: RefundProcessor, json: JsonObject) do
198 proc.check_key(json, "dossier")
199 var id = json["dossier"]
200 if not id isa String then
201 proc.die("Wrong type for `dossier` (expected String got {id.class_name})")
202 abort
203 end
204 # Check format
205 parse_contract(proc, id)
206 parse_client(proc, id)
207 init(id)
208 end
209
210 # Tries to parse the contract from `file_id` string.
211 private fun parse_contract(proc: RefundProcessor, file_id: String) do
212 var kind = file_id.first.to_s
213 if not proc.check_format(kind, "^[A-E]\{1\}$") then
214 proc.die("Wrong contract (expected A, B, C, D or E got {kind})")
215 end
216 contract = contract_factory(proc, kind)
217 end
218
219 # Tries to parse the client number from the `file_id` string.
220 private fun parse_client(proc: RefundProcessor, file_id: String) do
221 var num = file_id.substring_from(1)
222 if not proc.check_format(num, "^[0-9]\{6\}$") then
223 proc.die("Wrong format for `number` (expected XXXXXX got {num})")
224 abort
225 end
226 client = new Client(num)
227 end
228 end
229
230 redef class ReclMonth
231 # Inits `self` from a `JsonObject`.
232 init from_json(proc: RefundProcessor, json: JsonObject) do
233 proc.check_key(json, "mois")
234 var month = json["mois"]
235 if not month isa String then
236 proc.die("Wrong type for `mois` (expected String got {month.class_name})")
237 return
238 end
239 if not proc.check_format(month, "^[0-9]\{4\}-[0-9]\{2\}$") then
240 proc.die("Wrong format for `mois` (expected AAAA-MM got {month})")
241 return
242 end
243 from_string(proc, month)
244 end
245
246 # Inits `self` from a string representation formatted as `AAAA-MM`.
247 init from_string(proc: RefundProcessor, str: String) do
248 var parts = str.split("-")
249 var year = parts[0].to_i
250 var month = parts[1].to_i
251 if month < 1 or month > 12 then
252 proc.die("Wrong format for `mois` (expected AAAA-MM got {str})")
253 return
254 end
255 date = new ReclDate(year, month, 1)
256 init(date)
257 end
258 end
259
260 redef class ReclDate
261 # Inits `self` from a `JsonObject`.
262 #
263 # Dies if the `json` input is invalid.
264 init from_json(proc: RefundProcessor, json: JsonObject) do
265 proc.check_key(json, "date")
266 var date = json["date"]
267 if not date isa String then
268 proc.die("Wrong type for `date` (expected String got {date.class_name})")
269 abort
270 end
271 if not proc.check_format(date, "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}$") then
272 proc.die("Wrong format for `date` (expected AAAA-MM-DD got {date})")
273 abort
274 end
275 from_string(proc, date)
276 end
277
278 # Inits `self` from its string representation formatted as `AAAA-MM`.
279 init from_string(proc: RefundProcessor, str: String) do
280 var parts = str.split("-")
281 year = parts[0].to_i
282 month = parts[1].to_i
283 day = parts[2].to_i
284 if month < 1 or month > 12 or day < 1 or day > 31 then
285 proc.die("Wrong format for `mois` (expected AAAA-MM got {str})")
286 abort
287 end
288 init(year, month, day)
289 end
290 end
291
292 redef class Reclamation
293 # Inits `self` from a `JsonObject`.
294 init from_json(proc: RefundProcessor, json: JsonObject) do
295 care_id = parse_care_id(proc, json)
296 date = new ReclDate.from_json(proc, json)
297 fees = parse_fees(proc, json)
298 init(care_id, date, fees)
299 end
300
301 # Inits `self` from its string representation formatted as `Int`.
302 private fun parse_care_id(proc: RefundProcessor, json: JsonObject): Int do
303 proc.check_key(json, "soin")
304 var id = json["soin"]
305 if not id isa Int then
306 proc.die("Wrong type for `soin` (expected Int got {id.class_name})")
307 abort
308 end
309 return id
310 end
311
312 # Inits `self` from its string representation formatted as `0.00$`.
313 private fun parse_fees(proc: RefundProcessor, json: JsonObject): Dollar do
314 proc.check_key(json, "montant")
315 var fees = json["montant"]
316 if not fees isa String then
317 proc.die("Wrong type for `fees` (expected String got {fees.class_name})")
318 abort
319 end
320 if not proc.check_format(fees, "^[0-9]+((\\.|\\,)[0-9]+)?\\$$") then
321 proc.die("Wrong format for `montant` (expected XX.XX$ got {fees})")
322 abort
323 end
324 return new Dollar.from_float(fees.basename("$").to_f)
325 end
326 end