Skip to content

Commit

Permalink
[IMP] *: factor out code with preupdate and postupdate
Browse files Browse the repository at this point in the history
  • Loading branch information
atp-odoo authored and rco-odoo committed Apr 17, 2019
1 parent 3d2d6f9 commit 6f632d8
Show file tree
Hide file tree
Showing 20 changed files with 64 additions and 216 deletions.
17 changes: 3 additions & 14 deletions addons/base_iban/models/res_partner_bank.py
Expand Up @@ -67,25 +67,14 @@ def get_bban(self):
raise UserError(_("Cannot compute the BBAN because the account number is not an IBAN."))
return get_bban_from_iban(self.acc_number)

@api.model
def create(self, vals):
if vals.get('acc_number'):
try:
validate_iban(vals['acc_number'])
vals['acc_number'] = pretty_iban(normalize_iban(vals['acc_number']))
except ValidationError:
pass
return super(ResPartnerBank, self).create(vals)

@api.multi
def write(self, vals):
if vals.get('acc_number'):
@api.preupdate('acc_number')
def _preupdate_acc_number(self, vals):
if vals['acc_number']:
try:
validate_iban(vals['acc_number'])
vals['acc_number'] = pretty_iban(normalize_iban(vals['acc_number']))
except ValidationError:
pass
return super(ResPartnerBank, self).write(vals)

@api.one
@api.constrains('acc_number')
Expand Down
12 changes: 2 additions & 10 deletions addons/decimal_precision/models/decimal_precision.py
Expand Up @@ -26,17 +26,9 @@ def clear_cache(self):
""" Deprecated, use `clear_caches` instead. """
self.clear_caches()

@api.model_create_multi
def create(self, vals_list):
res = super(DecimalPrecision, self).create(vals_list)
@api.postupdate()
def _postupdate_caches(self, vals):
self.clear_caches()
return res

@api.multi
def write(self, data):
res = super(DecimalPrecision, self).write(data)
self.clear_caches()
return res

@api.multi
def unlink(self):
Expand Down
14 changes: 5 additions & 9 deletions addons/event/models/event.py
Expand Up @@ -289,22 +289,18 @@ def name_get(self):
result.append((event.id, '%s (%s)' % (event.name, ' - '.join(dates))))
return result

@api.postupdate('organizer_id')
def _postupdate_organizer_id(self, vals):
if vals['organizer_id']:
self.message_subscribe([vals['organizer_id']])

@api.model
def create(self, vals):
res = super(EventEvent, self).create(vals)
if res.organizer_id:
res.message_subscribe([res.organizer_id.id])
if res.auto_confirm:
res.button_confirm()
return res

@api.multi
def write(self, vals):
res = super(EventEvent, self).write(vals)
if vals.get('organizer_id'):
self.message_subscribe([vals['organizer_id']])
return res

@api.multi
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
Expand Down
12 changes: 2 additions & 10 deletions addons/fetchmail/models/fetchmail.py
Expand Up @@ -80,17 +80,9 @@ def onchange_server_type(self):
openerp_mailgate: "|/path/to/openerp-mailgate.py --host=localhost -u %(uid)d -p PASSWORD -d %(dbname)s"
""" % conf

@api.model
def create(self, values):
res = super(FetchmailServer, self).create(values)
self._update_cron()
return res

@api.multi
def write(self, values):
res = super(FetchmailServer, self).write(values)
@api.postupdate()
def _postupdate_cron(self, vals):
self._update_cron()
return res

@api.multi
def unlink(self):
Expand Down
14 changes: 3 additions & 11 deletions addons/fetchmail/models/mail_mail.py
Expand Up @@ -10,16 +10,8 @@ class MailMail(models.Model):

fetchmail_server_id = fields.Many2one('fetchmail.server', "Inbound Mail Server", readonly=True, index=True, oldname='server_id')

@api.model
def create(self, values):
@api.preupdate()
def _preupdate_fetchmail_server_id(self, vals):
fetchmail_server_id = self.env.context.get('fetchmail_server_id')
if fetchmail_server_id:
values['fetchmail_server_id'] = fetchmail_server_id
return super(MailMail, self).create(values)

@api.multi
def write(self, values):
fetchmail_server_id = self.env.context.get('fetchmail_server_id')
if fetchmail_server_id:
values['fetchmail_server_id'] = fetchmail_server_id
return super(MailMail, self).write(values)
vals['fetchmail_server_id'] = fetchmail_server_id
14 changes: 5 additions & 9 deletions addons/fleet/models/fleet_vehicle.py
Expand Up @@ -202,18 +202,14 @@ def _onchange_model(self):
else:
self.image_medium = False

@api.model
def create(self, vals):
res = super(FleetVehicle, self).create(vals)
if 'driver_id' in vals and vals['driver_id']:
res.create_driver_history(vals['driver_id'])
return res
@api.postupdate('driver_id')
def _postupdate_driver_history(self, vals):
if vals['driver_id']:
self.create_driver_history(vals['driver_id'])

@api.multi
def write(self, vals):
res = super(FleetVehicle, self).write(vals)
if 'driver_id' in vals and vals['driver_id']:
self.create_driver_history(vals['driver_id'])
if 'active' in vals and not vals['active']:
self.mapped('log_contracts').write({'active': False})
return res
Expand All @@ -223,7 +219,7 @@ def create_driver_history(self, driver_id):
self.env['fleet.vehicle.assignation.log'].create({
'vehicle_id': vehicle.id,
'driver_id': driver_id,
'date_start': fields.Date.today(),
'date_start': fields.Date.today(),
})

@api.model
Expand Down
11 changes: 2 additions & 9 deletions addons/fleet/models/fleet_vehicle_model.py
Expand Up @@ -52,13 +52,6 @@ class FleetVehicleModelBrand(models.Model):
"resized as a 64x64px image, with aspect ratio preserved. "
"Use this field anywhere a small image is required.")

@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
tools.image_resize_images(vals)
return super(FleetVehicleModelBrand, self).create(vals_list)

@api.multi
def write(self, vals):
@api.preupdate('image', 'image_medium', 'image_small')
def _preupdate_images_size(self, vals):
tools.image_resize_images(vals)
return super(FleetVehicleModelBrand, self).write(vals)
19 changes: 4 additions & 15 deletions addons/gamification/models/challenge.py
Expand Up @@ -154,28 +154,17 @@ def _get_report_template(self):

return template.id if template else False

@api.model
def create(self, vals):
"""Overwrite the create method to add the user of groups"""

@api.preupdate('user_domain', 'user_ids')
def _preupdate_user_ids(self, vals):
if vals.get('user_domain'):
users = self._get_challenger_users(ustr(vals.get('user_domain')))

if not vals.get('user_ids'):
vals['user_ids'] = []
vals['user_ids'].extend((4, user.id) for user in users)

return super(Challenge, self).create(vals)

@api.multi
def write(self, vals):
if vals.get('user_domain'):
users = self._get_challenger_users(ustr(vals.get('user_domain')))

if not vals.get('user_ids'):
vals['user_ids'] = []
vals['user_ids'].extend((4, user.id) for user in users)

write_res = super(Challenge, self).write(vals)

if vals.get('report_message_frequency', 'never') != 'never':
Expand Down Expand Up @@ -363,7 +352,7 @@ def _generate_goals_from_challenge(self):
participant_user_ids = set(challenge.user_ids.ids)
user_squating_challenge_ids = user_with_goal_ids - participant_user_ids
if user_squating_challenge_ids:
# users that used to match the challenge
# users that used to match the challenge
Goals.search([
('challenge_id', '=', challenge.id),
('user_id', 'in', list(user_squating_challenge_ids))
Expand Down Expand Up @@ -451,7 +440,7 @@ def _get_serialized_challenge_lines(self, user=(), restrict_goals=(), restrict_t
'action': <{True,False}>,
'display_mode': <{progress,boolean}>,
'target': <challenge line target>,
'state': <gamification.goal state {draft,inprogress,reached,failed,canceled}>,
'state': <gamification.goal state {draft,inprogress,reached,failed,canceled}>,
'completeness': <percentage>,
'current': <current value>,
}
Expand Down
10 changes: 2 additions & 8 deletions addons/im_livechat/models/im_livechat_channel.py
Expand Up @@ -86,15 +86,9 @@ def _compute_nbr_channel(self):
for record in self:
record.nbr_channel = len(record.channel_ids)

@api.model
def create(self, vals):
@api.preupdate('image', 'image_medium', 'image_small')
def _preupdate_images_size(self, vals):
tools.image_resize_images(vals)
return super(ImLivechatChannel, self).create(vals)

@api.multi
def write(self, vals):
tools.image_resize_images(vals)
return super(ImLivechatChannel, self).write(vals)

# --------------------------
# Action Methods
Expand Down
15 changes: 6 additions & 9 deletions addons/mail/models/mail_alias.py
Expand Up @@ -87,6 +87,12 @@ def _check_alias_defaults(self):
except Exception:
raise ValidationError(_('Invalid expression, it must be a literal python dictionary definition e.g. "{\'field\': \'value\'}"'))

@api.preupdate('alias_name')
def _preupdate_alias_name(self, vals):
""""give a unique alias name if given alias name is already assigned"""
if vals['alias_name']:
vals['alias_name'] = self._clean_and_make_unique(vals.get('alias_name'), alias_ids=self.ids)

@api.model
def create(self, vals):
""" Creates an email.alias record according to the values provided in ``vals``,
Expand All @@ -97,8 +103,6 @@ def create(self, vals):
"""
model_name = self._context.get('alias_model_name')
parent_model_name = self._context.get('alias_parent_model_name')
if vals.get('alias_name'):
vals['alias_name'] = self._clean_and_make_unique(vals.get('alias_name'))
if model_name:
model = self.env['ir.model']._get(model_name)
vals['alias_model_id'] = model.id
Expand All @@ -107,13 +111,6 @@ def create(self, vals):
vals['alias_parent_model_id'] = model.id
return super(Alias, self).create(vals)

@api.multi
def write(self, vals):
""""give a unique alias name if given alias name is already assigned"""
if vals.get('alias_name') and self.ids:
vals['alias_name'] = self._clean_and_make_unique(vals.get('alias_name'), alias_ids=self.ids)
return super(Alias, self).write(vals)

@api.multi
def name_get(self):
"""Return the mail alias display alias_name, including the implicit
Expand Down
10 changes: 2 additions & 8 deletions addons/mail/models/mail_message_subtype.py
Expand Up @@ -41,15 +41,9 @@ class MailMessageSubtype(models.Model):
sequence = fields.Integer('Sequence', default=1, help="Used to order subtypes.")
hidden = fields.Boolean('Hidden', help="Hide the subtype in the follower options")

@api.model
def create(self, vals):
self.clear_caches()
return super(MailMessageSubtype, self).create(vals)

@api.multi
def write(self, vals):
@api.preupdate()
def _preupdate_caches(self, vals):
self.clear_caches()
return super(MailMessageSubtype, self).write(vals)

@api.multi
def unlink(self):
Expand Down
24 changes: 4 additions & 20 deletions addons/payment/models/payment_acquirer.py
Expand Up @@ -275,15 +275,9 @@ def _create_missing_journal_for_acquirers(self, company=None):
journals += acquirer.journal_id
return journals

@api.model
def create(self, vals):
image_resize_images(vals)
return super(PaymentAcquirer, self).create(vals)

@api.multi
def write(self, vals):
@api.preupdate('image', 'image_medium', 'image_small')
def _preupdate_images_size(self, vals):
image_resize_images(vals)
return super(PaymentAcquirer, self).write(vals)

@api.multi
def toggle_website_published(self):
Expand Down Expand Up @@ -520,22 +514,12 @@ class PaymentIcon(models.Model):
image_payment_form = fields.Binary(
"Image displayed on the payment form", attachment=True)

@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if 'image' in vals:
image = ustr(vals['image'] or '').encode('utf-8')
vals['image_payment_form'] = image_resize_image(image, size=(45,30))
vals['image'] = image_resize_image(image, size=(64,64))
return super(PaymentIcon, self).create(vals_list)

@api.multi
def write(self, vals):
@api.preupdate('image', 'image_payment_form')
def _preupdate_images_size(self, vals):
if 'image' in vals:
image = ustr(vals['image'] or '').encode('utf-8')
vals['image_payment_form'] = image_resize_image(image, size=(45,30))
vals['image'] = image_resize_image(image, size=(64,64))
return super(PaymentIcon, self).write(vals)

class PaymentTransaction(models.Model):
""" Transaction Model. Each specific acquirer can extend the model by adding
Expand Down
20 changes: 5 additions & 15 deletions addons/payment_transfer/models/payment.py
Expand Up @@ -50,21 +50,11 @@ def _format_transfer_data(self):
}
return post_msg

@api.model
def create(self, values):
""" Hook in create to create a default post_msg. This is done in create
to have access to the name and other creation values. If no post_msg
or a void post_msg is given at creation, generate a default one. """
if values.get('provider') == 'transfer' and not values.get('post_msg'):
values['post_msg'] = self._format_transfer_data()
return super(TransferPaymentAcquirer, self).create(values)

@api.multi
def write(self, values):
""" Hook in write to create a default post_msg. See create(). """
if all(not acquirer.post_msg and acquirer.provider != 'transfer' for acquirer in self) and values.get('provider') == 'transfer':
values['post_msg'] = self._format_transfer_data()
return super(TransferPaymentAcquirer, self).write(values)
@api.preupdate('provider', 'post_msg')
def _preupdate_post_msg(self, vals):
""" Hook in create and write to create a default post_msg."""
if vals.get('provider') == 'transfer' and not vals.get('post_msg'):
vals['post_msg'] = self._format_transfer_data()


class TransferPaymentTransaction(models.Model):
Expand Down
10 changes: 2 additions & 8 deletions addons/point_of_sale/models/pos_category.py
Expand Up @@ -31,15 +31,9 @@ def _check_category_recursion(self):
"resized as a 64x64px image, with aspect ratio preserved. "
"Use this field anywhere a small image is required.")

@api.model
def create(self, vals):
@api.preupdate('image', 'image_medium', 'image_small')
def _preupdate_images_size(self, vals):
tools.image_resize_images(vals)
return super(PosCategory, self).create(vals)

@api.multi
def write(self, vals):
tools.image_resize_images(vals)
return super(PosCategory, self).write(vals)

@api.multi
def name_get(self):
Expand Down
15 changes: 4 additions & 11 deletions addons/rating/models/rating.py
Expand Up @@ -85,17 +85,10 @@ def _compute_rating_text(self):
else:
rating.rating_text = 'no_rating'

@api.model
def create(self, values):
if values.get('res_model_id') and values.get('res_id'):
values.update(self._find_parent_data(values))
return super(Rating, self).create(values)

@api.multi
def write(self, values):
if values.get('res_model_id') and values.get('res_id'):
values.update(self._find_parent_data(values))
return super(Rating, self).write(values)
@api.preupdate('res_model_id', 'res_id')
def _preupdate_parent_data(self, vals):
if vals.get('res_model_id') and vals.get('res_id'):
vals.update(self._find_parent_data(vals))

def _find_parent_data(self, values):
""" Determine the parent res_model/res_id, based on the values to create or write """
Expand Down

0 comments on commit 6f632d8

Please sign in to comment.