-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathentitlement_manager_inkind.py
More file actions
504 lines (441 loc) · 20 KB
/
Copy pathentitlement_manager_inkind.py
File metadata and controls
504 lines (441 loc) · 20 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
# Part of OpenSPP. See LICENSE file for full copyright and licensing details.
import logging
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.addons.job_worker.delay import group
_logger = logging.getLogger(__name__)
class EntitlementManager(models.Model):
_inherit = "spp.program.entitlement.manager"
@api.model
def _selection_manager_ref_id(self):
selection = super()._selection_manager_ref_id()
new_manager = ("spp.program.entitlement.manager.inkind", "In-Kind")
if new_manager not in selection:
selection.append(new_manager)
return selection
class SPPInKindEntitlementManager(models.Model):
_name = "spp.program.entitlement.manager.inkind"
_inherit = [
"spp.base.program.entitlement.manager",
"spp.manager.source.mixin",
]
_description = "In-Kind Entitlement Manager"
# Set to False so that the UI will not display the payment management components
IS_CASH_ENTITLEMENT = False
@api.model
def _default_warehouse_id(self):
return self.env["stock.warehouse"].search([("company_id", "=", self.env.company.id)], limit=1)
# In-Kind Entitlement Manager
is_evaluate_single_item = fields.Boolean("Evaluate one item", default=False)
entitlement_item_ids = fields.One2many(
"spp.program.entitlement.manager.inkind.item",
"entitlement_id",
"Entitlement Items",
)
# Inventory integration fields
manage_inventory = fields.Boolean(default=False)
warehouse_id = fields.Many2one(
"stock.warehouse",
string="Warehouse",
required=True,
default=_default_warehouse_id,
check_company=True,
)
company_id = fields.Many2one("res.company", string="Company", related="program_id.company_id")
# Group able to validate the payment
entitlement_validation_group_id = fields.Many2one("res.groups", string="Entitlement Validation Group")
def prepare_entitlements(self, cycle, beneficiaries):
"""Prepare In-Kind Entitlements.
This method is used to prepare the in-kind entitlement list of the beneficiaries.
:param cycle: The cycle.
:param beneficiaries: The beneficiaries.
:return:
"""
if not self.entitlement_item_ids:
raise UserError(_("There are no items entered for this entitlement manager."))
all_beneficiaries_ids = beneficiaries.mapped("partner_id.id")
for rec in self.entitlement_item_ids:
if rec.condition:
# Filter res.partner based on entitlement condition and get ids
domain = [("id", "in", all_beneficiaries_ids)]
domain += self._safe_eval(rec.condition)
beneficiaries_ids = self.env["res.partner"].search(domain).ids
# Check if single evaluation
if self.is_evaluate_single_item:
# Remove beneficiaries_ids from all_beneficiaries_ids
for bid in beneficiaries_ids:
if bid in all_beneficiaries_ids:
all_beneficiaries_ids.remove(bid)
else:
beneficiaries_ids = all_beneficiaries_ids
# Get beneficiaries_with_entitlements to prevent generating
# the same entitlement for beneficiaries
beneficiaries_with_entitlements = (
self.env["spp.entitlement.inkind"]
.search(
[
("cycle_id", "=", cycle.id),
("partner_id", "in", beneficiaries_ids),
("inkind_item_id", "=", rec.id),
]
)
.mapped("partner_id.id")
)
entitlements_to_create = [
beneficiaries_id
for beneficiaries_id in beneficiaries_ids
if beneficiaries_id not in beneficiaries_with_entitlements
]
entitlement_start_validity = cycle.start_date
entitlement_end_validity = cycle.end_date
beneficiaries_with_entitlements_to_create = self.env["res.partner"].browse(entitlements_to_create)
# Prefetch related fields to avoid N+1 queries
if rec.multiplier_field:
beneficiaries_with_entitlements_to_create.mapped(rec.multiplier_field.name)
# Prefetch product_id and uom_id to avoid N+1 queries in inner loop
# Note: rec is the entitlement item, not in the loop
_ = rec.product_id # Access to ensure it's prefetched
_ = rec.uom_id # Access to ensure it's prefetched
entitlements = []
for beneficiary_id in beneficiaries_with_entitlements_to_create:
multiplier = 1
if rec.multiplier_field:
# Get the multiplier value from multiplier_field else return the default multiplier=1
multiplier = beneficiary_id.mapped(rec.multiplier_field.name)
if multiplier:
multiplier = multiplier[0] or 1
if rec.max_multiplier > 0 and multiplier > rec.max_multiplier:
multiplier = rec.max_multiplier
quantity = multiplier * rec.quantity
entitlement_fields = {
"cycle_id": cycle.id,
"partner_id": beneficiary_id.id,
"total_amount": rec.product_id.list_price * quantity,
"product_id": rec.product_id.id,
"quantity": quantity,
"unit_price": rec.product_id.list_price,
"uom_id": rec.uom_id.id,
"manage_inventory": self.manage_inventory,
"warehouse_id": self.warehouse_id and self.warehouse_id.id or None,
"inkind_item_id": rec.id,
"state": "draft",
"valid_from": entitlement_start_validity,
"valid_until": entitlement_end_validity,
}
# Check if there are additional fields to be added in entitlements
addl_fields = self._get_addl_entitlement_fields(beneficiary_id)
if addl_fields:
entitlement_fields.update(addl_fields)
entitlements.append(entitlement_fields)
if entitlements:
self.env["spp.entitlement.inkind"].create(entitlements)
def _get_addl_entitlement_fields(self, beneficiary_id):
"""
This function must be overriden to add additional field to be written in the entitlements.
Add the id_number from the beneficiaries based on the id_type configured in entitlement manager.
"""
retval = None
if self.id_type_id:
id_docs = beneficiary_id.reg_ids.filtered(lambda a: a.id_type_id.id == self.id_type_id.id)
if id_docs:
id_number = id_docs[0].value
retval = {
"id_number": id_number,
}
return retval
def set_pending_validation_entitlements(self, cycle):
"""Set In-Kind Entitlements to Pending Validation.
In-kind Entitlement Manager :meth:`set_pending_validation_entitlements`.
Set entitlements to pending_validation in a cycle.
:param cycle: A recordset of cycle
:return:
"""
# Get the number of entitlements in cycle
entitlements_count = cycle.get_entitlements(
["draft"],
entitlement_model="spp.entitlement.inkind",
count=True,
)
if entitlements_count < self.MIN_ROW_JOB_QUEUE:
self._set_pending_validation_entitlements(cycle)
else:
self._set_pending_validation_entitlements_async(cycle, entitlements_count)
def _set_pending_validation_entitlements_async(self, cycle, entitlements_count):
"""Set Entitlements to Pending Validation
In-kind Entitlement Manager :meth:`_set_pending_validation_entitlements_async`
Asynchronous setting of entitlements to pending_validation in a cycle using `job_queue`
:param cycle: A recordset of cycle
:param entitlements_count: Integer - total number of entitlements to process
:return:
"""
_logger.debug("Set entitlements to pending validation asynchronously")
cycle.message_post(
body=_(
"Setting %s entitlements to pending validation has started.",
entitlements_count,
)
)
cycle.write(
{
"is_locked": True,
"locked_reason": _("Set entitlements to pending validation for cycle."),
}
)
jobs = []
for i in range(0, entitlements_count, self.MAX_ROW_JOB_QUEUE):
jobs.append(
self.delayable(channel="entitlement_approval")._set_pending_validation_entitlements(
cycle, offset=i, limit=self.MAX_ROW_JOB_QUEUE
)
)
main_job = group(*jobs)
main_job.on_done(self.delayable().mark_job_as_done(cycle, _("Entitlements Set to Pending Validation.")))
main_job.on_error(
self.delayable().mark_job_as_failed(cycle, _("Setting entitlements to pending validation failed."))
)
main_job.delay()
def _set_pending_validation_entitlements(self, cycle, offset=0, limit=None):
"""Set In-Kind Entitlements to Pending Validation.
In-kind Entitlement Manager :meth:`_set_pending_validation_entitlements`.
Set entitlements to pending_validation in a cycle.
:param cycle: A recordset of cycle
:param offset: An integer value to be used in :meth:`cycle.get_entitlements` for setting the query offset
:param limit: An integer value to be used in :meth:`cycle.get_entitlements` for setting the query limit
:return:
"""
# Get the entitlements in the cycle
entitlements = cycle.get_entitlements(
["draft"],
entitlement_model="spp.entitlement.inkind",
offset=offset,
limit=limit,
)
# Submit for approval to create approval review records (like cash entitlements)
if not self.approval_definition_id:
raise ValidationError(_("The entitlement approval definition is not specified!"))
else:
entitlements.action_submit_for_approval()
def validate_entitlements(self, cycle):
"""Validate In-Kind Entitlements.
In-Kind Entitlement Manager :meth:`validate_entitlements`.
Validate entitlements in a cycle
:param cycle: A recordset of cycle
:return:
"""
# Get the number of entitlements in cycle
entitlements_count = cycle.get_entitlements(
["draft", "pending_validation"],
entitlement_model="spp.entitlement.inkind",
count=True,
)
if entitlements_count < self.MIN_ROW_JOB_QUEUE:
err, message = self._validate_entitlements(cycle)
if err > 0:
kind = "danger"
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"title": _("Entitlement"),
"message": message,
"sticky": True,
"type": kind,
"next": {
"type": "ir.actions.act_window_close",
},
},
}
else:
kind = "success"
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"title": _("Entitlement"),
"message": _("Entitlements are validated and approved."),
"sticky": True,
"type": kind,
"next": {
"type": "ir.actions.act_window_close",
},
},
}
else:
self._validate_entitlements_async(cycle, entitlements_count)
def _validate_entitlements_async(self, cycle, entitlements_count):
"""Validate Entitlements
In-kind Entitlement Manager :meth:`_validate_entitlements_async`
Asynchronous validation of entitlements in a cycle using `job_queue`
:param cycle: A recordset of cycle
:param entitlements: A recordset of entitlements to validate
:param entitlements_count: Integer count of entitlements to validate
:return:
"""
_logger.debug("Validate entitlements asynchronously")
cycle.message_post(body=_("Validate %s entitlements started.", entitlements_count))
cycle.write(
{
"is_locked": True,
"locked_reason": _("Validate and approve entitlements for cycle."),
}
)
jobs = []
for i in range(0, entitlements_count, self.MAX_ROW_JOB_QUEUE):
jobs.append(
self.delayable(channel="entitlement_approval")._validate_entitlements(
cycle, offset=i, limit=self.MAX_ROW_JOB_QUEUE
)
)
main_job = group(*jobs)
main_job.on_done(self.delayable().mark_job_as_done(cycle, _("Entitlements Validated and Approved.")))
main_job.on_error(
self.delayable().mark_job_as_failed(cycle, _("Validation and approval of entitlements failed."))
)
main_job.delay()
def _validate_entitlements(self, cycle, offset=0, limit=None):
"""Validate In-Kind Entitlements.
In-Kind Entitlement Manager :meth:`_validate_entitlements`.
Validate entitlements in a cycle.
:param cycle: A recordset of cycle
:param offset: An integer value to be used in :meth:`cycle.get_entitlements` for setting the query offset
:param limit: An integer value to be used in :meth:`cycle.get_entitlements` for setting the query limit
:return err: Integer number of errors
:return message: String description of the error
"""
# Get the entitlements in the cycle
entitlements = cycle.get_entitlements(
["draft", "pending_validation"],
entitlement_model="spp.entitlement.inkind",
offset=offset,
limit=limit,
)
err, message = self.approve_entitlements(entitlements)
return err, message
def cancel_entitlements(self, cycle):
"""Cancel In-Kind Entitlements.
In-Kind Entitlement Manager :meth:`cancel_entitlements`
Cancel entitlements in a cycle.
:param cycle: A recordset of cycle
:return:
"""
# Get the total number of entitlements
entitlements_count = cycle.get_entitlements(
["draft", "pending_validation", "approved"],
entitlement_model="spp.entitlement.inkind",
count=True,
)
# Get the entitlements
entitlements = cycle.get_entitlements(
["draft", "pending_validation", "approved"],
entitlement_model="spp.entitlement.inkind",
)
if entitlements_count < self.MIN_ROW_JOB_QUEUE:
self._cancel_entitlements(entitlements)
else:
self._cancel_entitlements_async(cycle, entitlements, entitlements_count)
def _cancel_entitlements(self, entitlements):
"""Cancel In-Kind Entitlements.
In-Kind Entitlement Manager :meth:`_cancel_entitlements`.
Cancel entitlements in a cycle.
:param entitlements: A recordset of entitlements to cancel
:return:
"""
entitlements.update({"state": "cancelled"})
def approve_entitlements(self, entitlements):
"""Approve In-Kind Entitlements.
In-Kind Entitlement Manager :meth:`_approve_entitlements`.
Approve selected entitlements.
:param entitlements: Selected entitlements to approve
:return state_err: Integer number of errors
:return message: String description of the errors
"""
state_err = 0
message = ""
sw = 0
# Prefetch related fields to avoid N+1 queries in loop
entitlements.mapped("cycle_id.program_id")
entitlements.mapped("partner_id")
for rec in entitlements:
if rec.state in ("draft", "pending_validation"):
if rec.manage_inventory:
# TODO: check if there is enough stocks to allocate
rec._action_launch_stock_rule()
# Use the approval mixin's method to properly set all audit fields
if hasattr(rec, "_do_approve"):
rec._do_approve(auto=True)
# Update entitlement-specific fields
rec.update(
{
"state": "approved",
"date_approved": fields.Date.today(),
}
)
# Force recompute of approval_state
rec._compute_approval_state()
else:
state_err += 1
if sw == 0:
sw = 1
message = _("Entitlement State Error! Entitlements not in 'pending validation' state:\n")
message += _("Program ID: %(prg_id)s, Beneficiary ID: %(partner_id)s.\n") % {
"prg_id": rec.cycle_id.program_id.id,
"partner_id": rec.partner_id.id,
}
return (state_err, message)
def open_entitlements_form(self, cycle):
self.ensure_one()
action = {
"name": _("In-Kind Entitlements"),
"type": "ir.actions.act_window",
"res_model": "spp.entitlement.inkind",
"context": {
"create": False,
"default_cycle_id": cycle.id,
},
"view_mode": "list,form",
"views": [
[self.env.ref("spp_programs.view_entitlement_inkind_tree").id, "list"],
[
self.env.ref("spp_programs.view_entitlement_inkind_form").id,
"form",
],
],
"domain": [("cycle_id", "=", cycle.id)],
}
return action
def open_entitlement_form(self, rec):
return {
"name": "Entitlement",
"view_mode": "form",
"res_model": "spp.entitlement.inkind",
"res_id": rec.id,
"view_id": self.env.ref("spp_programs.view_entitlement_inkind_form").id,
"type": "ir.actions.act_window",
"target": "new",
}
class SPPInKindEntitlementItem(models.Model):
_name = "spp.program.entitlement.manager.inkind.item"
_description = "In-Kind Entitlement Manager Items"
_order = "sequence,id"
sequence = fields.Integer(default=1000)
entitlement_id = fields.Many2one("spp.program.entitlement.manager.inkind", "In-kind Entitlement", required=True)
product_id = fields.Many2one("product.product", "Product", domain=[("type", "=", "consu")], required=True)
# non-mandatory field to store a domain that is used to verify if this item is valid for a beneficiary
# For example, it could be: [('is_woman_headed_household, '=', True)]
# If the condition is not met, this calculation is not used
condition = fields.Char("Condition Domain")
# any field that is an integer of `res.partner`
# It could be the number of members, children, elderly, or any other metrics.
# if no multiplier field is set, it is considered as 1.
multiplier_field = fields.Many2one(
"ir.model.fields",
"Multiplier",
domain=[("model_id.model", "=", "res.partner"), ("ttype", "=", "integer")],
)
max_multiplier = fields.Integer(
default=0,
string="Maximum number",
help="0 means no limit",
)
quantity = fields.Integer("Quantity", default=1, required=True)
uom_id = fields.Many2one("uom.uom", "Unit of Measure", related="product_id.uom_id", store=True)