summaryrefslogtreecommitdiff
path: root/models/crop-requirement.rkt
blob: dc3f3a0ae3e05716de1fcfd18723373da05872f5 (plain)
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
#lang racket

(provide crop-requirement
         crop-requirement?
         crop-requirement-id
         crop-requirement-profile
         crop-requirement-crop-id
         crop-requirement-value
         (rename-out [crop-requirement-nutrient-values crop-requirement-values])
         (contract-out
          [create-crop-requirement!
           (case-> (-> crop-requirement? crop-requirement?)
                   (-> string? nutrient-value-hash/c crop-requirement?)
                   (-> string? nutrient-value-hash/c crop? crop-requirement?))]
          [get-crop-requirements (-> (listof crop-requirement?))]
          [get-crop-requirement (->* () (#:id db-id? #:profile string?) (or/c crop-requirement? #f))]
          [get-crop-requirement-values (-> crop-requirement-or-id/c nutrient-value-hash/c)]
          [get-crop-requirement-value (-> crop-requirement-or-id/c nutrient? maybe-nutrient-value?)]
          [update-crop-requirement! (-> crop-requirement? void?)]
          [delete-crop-requirement! (-> crop-requirement-or-id/c void?)]
          [average-crop-requirement-nutrient-values
           (-> (hash/c crop-requirement? (between/c 0 100)) nutrient-value-hash/c)]))

(require db
         sql
         "../db/conn.rkt"
         "nutrient.rkt"
         "nutrient-value.rkt"
         "crop.rkt"
         "utils.rkt")

(struct crop-requirement (id profile crop-id nutrient-values)
  #:transparent
  #:guard (λ (id profile crop-id nutrient-values _)
            (values id profile (if (sql-null? crop-id) #f crop-id) nutrient-values)))

(define (crop-requirement-value cr nutrient)
  (hash-ref (crop-requirement-nutrient-values cr) nutrient #f))

(define crop-requirement-or-id/c (or/c crop-requirement? db-id?))

(define (->cr-id cr-or-id)
  (match cr-or-id
    [(? db-id? cr-or-id) cr-or-id]
    [(crop-requirement id _ _ _) id]))

;; CREATE

(define create-crop-requirement!
  (case-lambda
    [(cr) (create-crop-requirement!/cr cr)]
    [(profile nutrient-values)
     (create-crop-requirement!/cr (crop-requirement #f profile #f nutrient-values))]
    [(profile nutrient-values crop)
     (create-crop-requirement!/cr (crop-requirement #f profile (crop-id crop) nutrient-values))]))

(define (create-crop-requirement!/cr cr)
  (define profile (crop-requirement-profile cr))
  (define nutrient-values (crop-requirement-nutrient-values cr))
  (define crop-id (crop-requirement-crop-id cr))
  (with-tx (define cr-id
             (insert-id
              (query (current-conn)
                     (if crop-id
                         (insert #:into crop_requirements #:set [crop_id ,crop-id] [profile ,profile])
                         (insert #:into crop_requirements #:set [profile ,profile])))))
           (define nvs-id
             (insert-id (query (current-conn)
                               (insert #:into nutrient_value_sets
                                       #:set [crop_requirement_id ,cr-id]))))
           (insert-nutrient-values (current-conn) nvs-id nutrient-values)
           (crop-requirement cr-id profile crop-id nutrient-values)))

;; READ

(define joined
  (table-expr-qq (inner-join (inner-join (inner-join (as crop_requirements cr)
                                                     (as nutrient_value_sets nvs)
                                                     #:on (= nvs.crop_requirement_id cr.id))
                                         (as nutrient_values nv)
                                         #:on (= nv.value_set_id nvs.id))
                             (as nutrients n)
                             #:on (= n.id nv.nutrient_id))))

(define (grouped-row->crop-requirement grouped-row)
  (match-define (vector cr-id profile crop-id residuals) grouped-row)
  (crop-requirement cr-id profile crop-id (residuals->nutrient-value-hash residuals)))

(define (get-crop-requirements)
  (define grouped-rows
    (query-rows (current-conn)
                (select cr.id
                        cr.profile
                        cr.crop_id
                        n.id
                        n.canonical_name
                        n.french_name
                        n.formula
                        nv.value_ppm
                        #:from (TableExpr:AST ,joined)
                        #:order-by cr.id
                        #:asc)
                #:group '#(0 1 2)))
  (map grouped-row->crop-requirement grouped-rows))

(define (get-crop-requirement #:id [cr-id #f] #:profile [profile #f])
  (define where
    (cond
      [(and cr-id profile) (scalar-expr-qq (and (= cr.id ,cr-id) (= cr.profile ,profile)))]
      [cr-id (scalar-expr-qq (= cr.id ,cr-id))]
      [profile (scalar-expr-qq (= cr.profile ,profile))]
      [else (error 'get-crop-requirement "one of #:id or #:profile must be provided")]))
  (define grouped-rows
    (query-rows (current-conn)
                (select cr.id
                        cr.profile
                        cr.crop_id
                        n.id
                        n.canonical_name
                        n.french_name
                        n.formula
                        nv.value_ppm
                        #:from (TableExpr:AST ,joined)
                        #:where (ScalarExpr:AST ,where))
                #:group '#(0 1 2)))
  (match grouped-rows
    ['() #f]
    [(list grouped-row) (grouped-row->crop-requirement grouped-row)]
    [many (error 'get-crop-requirement "expected 1 crop requirement, got ~a" (length many))]))

(define (get-crop-requirement-values cr-or-id)
  (for/hash ([(nutrient-id canonical-name french-name formula value_ppm)
              (in-query (current-conn)
                        (select n.id
                                n.canonical_name
                                n.french_name
                                n.formula
                                nv.value_ppm
                                #:from (TableExpr:AST ,joined)
                                #:where (= cr.id ,(->cr-id cr-or-id))))])
    (values (nutrient nutrient-id canonical-name french-name formula) value_ppm)))

(define (get-crop-requirement-value cr-or-id nutrient)
  (query-maybe-value (current-conn)
                     (select value_ppm
                             #:from (TableExpr:AST ,joined)
                             #:where (and (= cr.id ,(->cr-id cr-or-id))
                                          (= nv.nutrient_id ,(nutrient-id nutrient))))))

;; UPDATE

(define (update-crop-requirement! cr)
  (define id
    (or (crop-requirement-id cr)
        (raise-argument-error 'update-crop-requirement! "db-id?" (crop-requirement-id cr))))
  (define profile (crop-requirement-profile cr))
  (define crop-id (crop-requirement-crop-id cr))
  (with-tx
   (query-exec
    (current-conn)
    (if crop-id
        (update crop_requirements #:set [profile ,profile] [crop_id ,crop-id] #:where [= id ,id])
        (update crop_requirements #:set [profile ,profile] #:where [= id ,id])))
   (define nvs-id
     (query-value (current-conn)
                  (select id #:from nutrient_value_sets #:where [= crop_requirement_id ,id])))
   (update-nutrient-values! (current-conn) nvs-id (crop-requirement-nutrient-values cr))))

;; DELETE

(define (delete-crop-requirement! cr-or-id)
  (query-exec (current-conn) (delete #:from crop_requirements #:where (= id ,(->cr-id cr-or-id)))))

;; Helpers

(define (average-crop-requirement-nutrient-values mix)
  (for/fold ([acc (hash)]) ([(crop-requirement percentage) (in-hash mix)])
    (define weight (/ percentage 100))
    (for/fold ([acc acc])
              ([(nutrient value) (in-hash (crop-requirement-nutrient-values crop-requirement))])
      (define contribution (* value weight))
      (hash-update acc nutrient (λ (old) (+ old contribution)) 0))))

(module+ test
  (require rackunit
           rackunit/text-ui
           "../db/conn.rkt"
           "../db/migrations.rkt"
           "../models/nutrient.rkt"
           "../models/crop.rkt")

  (define requirement-profile "Examplium Plant - Vegetative")

  (run-tests
   (test-suite "Crop requirement model"
     #:before (λ ()
                (connect! #:path 'memory)
                (migrate-all!)
                (create-nutrient! "Examplium" "Examplium" "Ex")
                (create-nutrient! "Ignorium" "Ignorium" "Ig")
                (create-nutrient! "Testium" "Testium" "Ts"))
     #:after (λ () (disconnect!))

     (test-case "Create requirement with profile and values"
       (define examplium (get-nutrient #:name "Examplium"))
       (define ignorium (get-nutrient #:name "Ignorium"))

       (create-crop-requirement! requirement-profile (hash examplium 150 ignorium 50))

       (check-equal? (length (get-crop-requirements)) 1)

       (define cr (get-crop-requirement #:profile requirement-profile))
       (check-true (crop-requirement? cr))
       (check-equal? (crop-requirement-profile cr) requirement-profile))

     (test-case "Create requirement with associated crop"
       (define test-crop (create-crop! (crop #f "testium-plant")))
       (define examplium (get-nutrient #:name "Examplium"))

       (define cr
         (create-crop-requirement! "Testium Plant - Fruiting" (hash examplium 200) test-crop))

       (check-equal? (crop-requirement-crop-id cr) (crop-id test-crop)))

     (test-case "Check all requirement values"
       (define examplium (get-nutrient #:name "Examplium"))
       (define ignorium (get-nutrient #:name "Ignorium"))

       (define cr (get-crop-requirement #:profile requirement-profile))

       (check-= (get-crop-requirement-value cr examplium) 150 0)
       (check-= (get-crop-requirement-value cr ignorium) 50 0)

       (define crv (crop-requirement-nutrient-values cr))

       (check-equal?
        (get-crop-requirement-values cr)
        crv
        "return value of get-crop-requirement-values ≠ crop-requirement-values struct accessor")

       (check-equal? (hash-count crv) 2)
       (check-= (hash-ref crv examplium) 150 0)
       (check-= (hash-ref crv ignorium) 50 0))

     (test-case "Get requirement by id"
       (define cr (get-crop-requirement #:profile requirement-profile))
       (define cr-by-id (get-crop-requirement #:id (crop-requirement-id cr)))

       (check-equal? cr cr-by-id))

     (test-case "Average crop requirement nutrient values"
       (define examplium (get-nutrient #:name "Examplium"))
       (define ignorium (get-nutrient #:name "Ignorium"))

       (define cr1 (get-crop-requirement #:profile requirement-profile))
       (define cr2 (create-crop-requirement! "Generic Growth" (hash examplium 100 ignorium 30)))

       (define mix (hash cr1 60 cr2 40))
       (define avg (average-crop-requirement-nutrient-values mix))

       ;; 150 * 0.6 + 100 * 0.4 = 90 + 40 = 130
       (check-= (hash-ref avg examplium) 130 0.01)
       ;; 50 * 0.6 + 30 * 0.4 = 30 + 12 = 42
       (check-= (hash-ref avg ignorium) 42 0.01))

     (test-case "Delete requirement and cascade to requirement values"
       (define cr (get-crop-requirement #:profile requirement-profile))
       (delete-crop-requirement! cr)
       (check-false (get-crop-requirement #:id (crop-requirement-id cr)))
       (check-equal? (length (get-crop-requirements))
                     2
                     "wrong number of crop requirements were deleted")
       (check-true (hash-empty? (get-crop-requirement-values cr)))))))
Copyright 2019--2026 Marius PETER