res_partner.py 7.81 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-

from openerp import _, api, models, fields
4
import datetime
5 6 7
import logging

_logger = logging.getLogger(__name__)
8

9 10 11 12 13
TARGET_STATUS_SELECTION = [
    ('unsubscribed', 'Unsubscribed'),
    ('suspended', 'Suspended')
]

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
EXTRA_COOPERATIVE_STATE_SELECTION = [
    ('not_concerned', 'Not Concerned'),
    ('unsubscribed', 'Unsubscribed'),
    ('exempted', 'Exempted'),
    ('vacation', 'On Vacation'),
    ('up_to_date', 'Up to date'),
    ('alert', 'Alert'),
    ('suspended', 'Suspended'),
    ('delay', 'Delay'),
    ('blocked', 'Blocked'),
    ('unpayed', 'Unpayed'),
    ('gone', 'Gone'),
    ('associated', 'Associated')
]

29 30 31 32 33 34 35 36
class ResPartner(models.Model):
    _inherit = 'res.partner'

    # Columns Section
    makeups_to_do = fields.Integer(
        "Number of make-ups to done",
        default= 0)

37 38
    target_status = fields.Selection(
                    selection=TARGET_STATUS_SELECTION, default='')
39

40 41 42
    cooperative_state = fields.Selection(
        selection=EXTRA_COOPERATIVE_STATE_SELECTION, default='not_concerned')

43 44 45 46
    extra_shift_done = fields.Integer(
        "Number of shift done with both of the associate",
        default= 0)

47 48 49 50
    @api.model
    def run_process_target_status(self):
        """Method called by cron task"""
        # final_ftop_point, target_status
51
        conf = self.env['ir.config_parameter']
52
        makeups_todo_after_unsubscribed = conf.get_param("lacagette_membership.makeups_to_do_after_unsubscribed")
53
        result = 'done'
54 55
        for p in self.env['res.partner']\
                         .search([('target_status', '!=', "")]):
56 57 58 59 60 61
            try:
                new_values = {'target_status': "", "date_alert_stop": False}
                final_points = p.final_ftop_point if p.shift_type == "ftop" else p.final_standard_point
                if final_points < 0:
                    new_values['cooperative_state'] = p.target_status
                    if new_values['cooperative_state'] == "unsubscribed":
62
                        new_values['makeups_to_do'] = makeups_todo_after_unsubscribed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

                        # Get points difference to set points to -2
                        current_points = p['final_' + p.shift_type + '_point']
                        target_points = -2

                        points_diff = abs(current_points - target_points)

                        if points_diff != 0:
                            if current_points > target_points:
                                points_update = - points_diff
                            else:
                                points_update = points_diff

                            data = {
                                'name': "Désinscription : passage à -2 pts",
                                'shift_id': False,
                                'type': p.shift_type,
                                'partner_id': p.id,
                                'point_qty': points_update
                            }

                            self.env['shift.counter.event'].create(data)

86 87 88 89
                        """
                        unlink model: "shift.template.registration"
                        to delete all future shifts linked to this coop.
                        """
90
                        now = datetime.datetime.now().isoformat()
91 92 93
                        for streg in self.env['shift.template.registration']\
                                    .search([('partner_id', '=', p.id)]):
                            streg.unlink()
94 95
                        for sreg in self.env['shift.registration']\
                                    .search([('partner_id', '=', p.id),
96
                                             ('date_begin', '>', now)]):
97
                            sreg.unlink()
98

99
                        # Close extensions
100 101 102 103 104
                        for ext in self.env['shift.extension']\
                                   .search([('partner_id', '=', p.id),
                                            ('date_start', '<=', now),
                                            ('date_stop', '>=', now)]):
                            ext.update({'date_stop': now})
105 106 107 108 109 110 111

                        try:
                            mail_template = self.env.ref('coop_membership.unsubscribe_email')
                            if mail_template:
                                mail_template.send_mail(p.id)
                        except Exception as e:
                            _logger.error("run_process_target_status - send mail : %s - Process not interrupted", str(e))
112 113 114
                p.update(new_values)
            except Exception as e:
                _logger.error("run_process_target_status : %s", str(e))
115 116
                result = 'error'
        return result
117 118 119 120 121 122 123 124 125

    #@api.onchange('cooperativestate') : could be used only if it is called from client
    @api.model
    def run_close_unnecessary_opened_extensions(self):
        """Method called by cron task"""
        sql = """
        SELECT s.id
        FROM shift_extension as s
        WHERE s.date_stop > now()
126
        AND partner_id IN (SELECT id FROM res_partner WHERE cooperative_state in ('up_to_date', 'unsubscribed'))
127 128 129 130 131 132 133 134
        """
        self.env.cr.execute(sql)
        extension_ids = self.env.cr.fetchall()
        if len(extension_ids) > 0:
            extension_model = self.env['shift.extension']
            today = datetime.datetime.now().strftime("%Y-%m-%d")
            for ext in  extension_model.search([('id', 'in', extension_ids)]):
                ext.update({'date_stop': today})
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

    @api.multi
    def can_have_extension(self):
        """Return if the member can ask for an extension"""
        answer = True
        conf = self.env['ir.config_parameter']
        max_nb = int(conf.get_param("lacagette_membership.max_successive_extensions"))
        if max_nb == 1:
            args = [('member_id', '=', self.id)]
            states = self.env['member.state.change']\
                    .search(args, order='write_date DESC', limit=2)
            """
            member.state.change may have no record for the current member
            """
            if len(states) > 0:
                if (len(states) == 1 and states[0]['state'] == 'delay'
                   or
                   len(states) == 2 and states[1]['state'] == 'delay'):
                    answer = False
            else:
                # need to load data
                member = self.env['res.partner'].search([('id', '=', self.id)])[0]
157
                # should exist an other way to do it , but haven't found it
158 159 160 161 162 163 164
                if member.cooperative_state != "up_to_date":
                    answer = False
        else:
            # TODO : Must have a look to previous extensions
            pass
        return answer

165 166

    def set_special_state(self, cr, uid, partner, context=None):
167 168
        if partner['state'] == 'cancel_special':
            partner['state'] = 'unsubscribed'
169 170
        return self.write(cr, uid, [partner['id']], {'cooperative_state': partner['state']} , context=context)

171 172 173 174
    def _write_state_change(self, state):
        data = {'member_id': self.id, 'state': state}
        self.env['member.state.change'].create(data)

Damien Moulard committed
175
    @api.multi
176
    def update(self, vals):
177
        _logger.info("valeurs recues pour update partner = %s", str(vals))
178 179 180
        state_to_record = ""
        if 'cooperative_state' in vals:
            state_to_record = vals['cooperative_state']
181

182 183
        elif 'current_cooperative_state' in vals:
            state_to_record = vals['current_cooperative_state']
184
            del vals['current_cooperative_state']
185 186
        if len(state_to_record) > 0:
            self._write_state_change(state_to_record)
187

188
        return super(ResPartner, self).update(vals)
189

190

Damien Moulard committed
191
    @api.multi
192
    def write(self, vals):
193
        _logger.info("valeurs recues pour write partner = %s", str(vals))
194 195
        if 'cooperative_state' in vals:
            self._write_state_change(vals['cooperative_state'])
196
        return super(ResPartner, self).write(vals)
197