models.py 63.1 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7
"""Members modelsmain page."""
from django.db import models
from outils.common_imports import *
from outils.images_imports import *

from outils.common import OdooAPI
from outils.common import CouchDB
8
from outils.common import Verification
Administrator committed
9 10
from products.models import OFF
from envelops.models import CagetteEnvelops
11
import shifts.fonctions
Administrator committed
12 13

import sys
14
import pytz
Administrator committed
15 16
import locale
import re
17
import dateutil.parser
Etienne Freiss committed
18
from datetime import date
Administrator committed
19 20 21 22 23

FUNDRAISING_CAT_ID = {'A': 1, 'B': 2, 'C': 3}

class CagetteMember(models.Model):
    """Class to handle cagette Odoo member."""
24
    m_default_fields = ['name', 'parent_name', 'sex', 'image_medium', 'active',
25
                        'barcode_base', 'barcode', 'shift_type',
26
                        'is_associated_people', 'is_member', 'shift_type',
Administrator committed
27 28 29
                        'display_ftop_points', 'display_std_points',
                        'is_exempted', 'cooperative_state', 'date_alert_stop']

30
    m_short_default_fields = ['name', 'barcode_base']
31

Administrator committed
32 33 34 35 36
    def __init__(self, id):
        """Init with odoo id."""
        self.id = int(id)
        self.o_api = OdooAPI()

37 38
    @staticmethod
    def get_new_password_link(data):
39
        result = {}
40 41 42 43 44 45 46 47 48 49
        if 'email' in data:
            email = data['email'].strip()
            validator = validators.EmailValidator()
            try:
                validator(email)
                api = OdooAPI()
                cond = [['email', '=', email]]
                m_res = api.search_read('res.partner', cond, ['id'])
                if m_res and 'id' in m_res[0]:
                    res = api.execute('res.partner', 'send_new_password_email', [m_res[0]['id']])
50 51 52 53 54
                    if 'error' in res:
                        result['error'] = res['error']
                else:
                    result['error'] = 'get_new_password_link django error : res_partner not found'

55
            except Exception as e:
56 57 58 59 60 61 62
                result['error'] = 'get_new_password_link error while calling odoo api : ' + str(e)
                if "Only users with the following access level are currently allowed to do that" in str(e):
                    result['error'] += (" Il s'agit peut-être d'un problème de permissions de l'utilisateur api : "
                                        "donnez lui le droit Administration/Settings (Configuration en français)")
        else:
            result['error'] = 'get_new_password_link django error : no email in data'
        return result
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

    @staticmethod
    def set_new_password(received_pwd, token):
        if len(token) > 32 and len(received_pwd) >= 10:
            api = OdooAPI()
            db_uuid = api.get_system_param('database.uuid')
            cond = [['reset_password_token', '=', token.replace(db_uuid,'')]]
            res_m = api.search_read('res.partner', cond, ['id'])
            if res_m:
                import argon2
                ph = argon2.PasswordHasher()
                fields = {'hashed_password': ph.hash(received_pwd),
                          'reset_password_token': ''}
                api.update('res.partner', [res_m[0]['id']], fields)
            else:
                raise Exception('Invalid token')
        else:
            raise Exception('Invalid arguments')
        return 'successful_reset_password'

    def get_preferences(self, key=None):
        preferences = {}
        
        try:
            cond = [['id', '=', self.id]]
            fields = ['external_apps_preferences']
            res = self.o_api.search_read('res.partner', cond, fields)
            if res:
                stored_pref = res[0]['external_apps_preferences']
                if stored_pref:
                    p = json.loads(stored_pref)
                    if key is None:
                        preferences = p
                    elif key in p:
                        preferences = p[key]
        except Exception as e:
            preferences['error'] = str(e)
        coop_logger.info("retrieved pref = %s", str(preferences))
        return preferences

    def set_preferences(self, data):
        return self.o_api.update('res.partner', [self.id], {'external_apps_preferences': json.dumps(data)})

Administrator committed
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
    def update_from_ajax(self, request):
        result = {}
        try:
            fields = {}
            for key, value in request.POST.items():
                fields[key] = value
            result['update'] = self.o_api.update('res.partner', [self.id], fields)
        except Exception as e:
            result['error'] = str(e)
        return result

    def set_odoo_image(self, image):
        """Record base64 image associated to member."""
        api = OdooAPI()
        f = {'image': image}
        return api.update('res.partner', [self.id], f)

    def attach_message(self, body):
        params = {'message_type': 'comment', 'subtype': 'mail.mt_comment', 'body': body}
        return self.o_api.execute('res.partner', 'message_post', [self.id], params)

    def get_image(self):
        image = ''
        cond = [['id', '=', self.id]]
        fields = ['image_medium']
        res = self.o_api.search_read('res.partner', cond, fields)
        if res and len(res) == 1:
            image = res[0]['image_medium']
        return image

136 137 138 139 140 141 142 143
    def get_member_points(self, shift_type):
        points_field = 'final_standard_point' if shift_type == "standard" else 'final_ftop_point'

        cond = [['id', '=', self.id]]
        fields = ['id', points_field]
        res = self.o_api.search_read('res.partner', cond, fields)

        if res and len(res) == 1:
144
            return int(res[0][points_field])
145 146 147
        else:
            return None

148 149 150 151 152 153 154 155 156 157 158
    def update_member_points(self, data):
        """
            ex:
            data = {
                'name': reason,
                'shift_id': False,
                'type': stype,
                'partner_id': self.id,
                'point_qty': pts
            }
        """
159

160 161 162 163
        try:
            return self.o_api.create('shift.counter.event', data)
        except Exception as e:
            print(str(e))
Etienne Freiss committed
164 165 166 167 168


# # # BDM
    def save_partner_info(self, partner_id, fieldsDatas):
        return self.o_api.update('res.partner', partner_id,  fieldsDatas)
Damien Moulard committed
169

Administrator committed
170 171 172 173 174 175 176 177
    @staticmethod
    def retrieve_data_according_keys(keys, full=False):
        api = OdooAPI()
        cond = []
        for k in keys:
            cond.append([k, '=', keys[k]])
        if full is True:
            fields = ['image_medium', 'barcode_base', 'barcode', 'create_date',
178
                      'cooperative_state', 'name', 'birthdate_date', 'street', 'street2',
Administrator committed
179 180 181 182
                      'zip', 'city', 'email', 'mobile', 'phone', 'total_partner_owned_share',
                      'amount_subscription', 'active_tmpl_reg_line_count', 'is_exempted',
                      'shift_type', 'current_template_name',
                      'final_standard_point', 'final_ftop_point',
183
                      'date_alert_stop', 'sex']
Administrator committed
184
        else:
185
            fields = ['name', 'email', 'birthdate_date',
Administrator committed
186 187 188 189 190 191
                      'sex', 'country_id', 'total_partner_owned_share',
                      'barcode_base', 'tmpl_reg_line_ids']
        return api.search_read('res.partner', cond, fields, 1, 0,
                                     'id DESC')

    @staticmethod
192
    def get_credentials(request, external=False, with_id=False):
Administrator committed
193 194 195 196 197 198 199 200 201
        import hashlib

        data = {}

        login = request.POST.get('login')
        password = request.POST.get('password')
        fp = request.POST.get('fp') #  fingerprint (prevent using stolen cookies)
        if login and password:
            api = OdooAPI()
202
            login = login.strip()
203 204
            cond = [['email', '=', login]]
            if getattr(settings, 'ALLOW_NON_MEMBER_TO_CONNECT', False) is False:
205
                cond.append('|')
206
                cond.append(['is_member', '=', True])
207
                # TODO : consider replacing is_associated_people by suppleant_member_id to exclude mineurs rattachés
208 209
                cond.append(['is_associated_people', '=', True])

210 211 212
            fields = ['name', 'email', 'birthdate_date', 'create_date', 'cooperative_state', 'is_associated_people', 'barcode_base']
            if getattr(settings, 'USE_MEMBERS_CUSTOM_PASSWORD', False) is True:
                fields.append('hashed_password')
Administrator committed
213 214
            res = api.search_read('res.partner', cond, fields)
            if (res and len(res) >= 1):
215
                coop_id = None
216
                hashed_password = None
217
                # TODO : add comment to explain why there is a loop here
218 219
                for item in res:
                    coop = item
220 221 222 223
                    if 'hashed_password' in item:
                        hashed_password = item['hashed_password']
                    if item["birthdate_date"] is not False:
                        coop_birthdate = item['birthdate_date']
224
                        coop_state = item['cooperative_state']
225
                    # TODO : consider replacing is_associated_people check by suppleant_member_id to exclude mineurs rattachés
226
                    if item["is_associated_people"] == True:
227
                        coop_id = item['id']
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
                secret_verified = False
                if hashed_password:
                    import argon2
                    ph = argon2.PasswordHasher()
                    try:
                        ph.verify(hashed_password, password)
                        secret_verified = True
                    except Exception as e:
                        coop_logger.info("Wrong password : %s", str(e))
                else:
                    y, m, d = coop_birthdate.split('-')
                    password = password.replace('/', '')
                    if (password == d + m + y):
                        secret_verified = True
                if secret_verified is True:
244 245
                    if coop_id is None:
                        coop_id = coop['id']
246
                    data['id'] = coop_id
247 248 249
                    auth_token_seed = fp + coop['create_date']
                    data['auth_token'] = hashlib.sha256(auth_token_seed.encode('utf-8')).hexdigest()
                    data['token'] = hashlib.sha256(coop['create_date'].encode('utf-8')).hexdigest()
250
                    data['coop_state'] = coop_state
251 252 253 254 255 256 257 258 259
                    if external is True:
                        from outils.functions import extract_firstname_lastname
                        name_sep = getattr(settings, 'SUBSCRIPTION_NAME_SEP', ' ')
                        name_elts = extract_firstname_lastname(coop['name'], name_sep)
                        data['lastname'] = name_elts['lastname']
                        if name_elts['firstname'] != name_elts['lastname']:
                            data['firstname'] = name_elts['firstname']
                        else:
                            data['firstname'] = ''
260
                        data['coop_num'] = coop['barcode_base']
261

Administrator committed
262 263 264 265 266 267 268 269 270 271
                if not ('auth_token' in data):
                    data['failure'] = True
                    data['msg'] = "Erreur dans le mail ou le mot de passe"
                    data['errnum'] = 1
            else:
                data['failure'] = True
                data['msg'] = "Erreur dans le mail ou le mot de passe"
                data['errnum'] = 2
                #  data['res'] = res

272
        elif external is False and 'token' in request.COOKIES and 'id' in request.COOKIES:
Administrator committed
273 274 275 276 277 278 279 280 281
            api = OdooAPI()
            cond = [['id', '=', request.COOKIES['id']]]
            fields = ['create_date','email']
            res = api.search_read('res.partner', cond, fields)
            if (res and len(res) == 1):
                login = res[0]['email']
                calc_token = hashlib.sha256(res[0]['create_date'].encode('utf-8')).hexdigest()
                if calc_token == request.COOKIES['token']:
                    data['success'] = True
282 283
                    if with_id is True:
                        data['id'] = res[0]['id']
Administrator committed
284 285 286 287 288 289
                else:
                    data['failure'] = True
                    data['errnum'] = 3
        else:
            data['failure'] = True
        if not ('failure' in data):
290 291 292 293 294
            if external is False:
                data['login'] = login
                c_db_data = CagetteMember.get_couchdb_data(login)
                if len(c_db_data) > 0 and 'validation_state' in c_db_data:
                    data['validation_state'] = c_db_data['validation_state']
Administrator committed
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
        #  print(str(data))
        return data

    @staticmethod
    def send_new_password_link(request):
        result = {}
        email = request.POST.get('email')
        if len(email) > 5 and '@' in email:
            api = OdooAPI()
            cond = [['email', '=', email]]
            fields = ['create_date']
            res = api.search_read('res.partner', cond, fields)
            if (res and len(res) == 1):

                result['msg'] = 'Trouvé ' + str(res[0]['create_date'])
        else:
            result['error'] = 'Email non valide'

        return result

    def get_data(self, full=False):
        """Get member data using Odoo API."""
        return CagetteMember.retrieve_data_according_keys({'id':self.id}, full)

    @staticmethod
    def standalone_create_envelops(request):
        res = {}
        fields = {'checks': []}
        try:
            checks = request.POST.getlist("checks[]")
            if len(checks) > 0:
                for c in checks:
                    fields['checks'].append(int(c))
            for key, value in request.POST.items():
                if key != "checks[]":
                    fields[key] = value
            res = CagetteEnvelops().create_or_update_envelops(fields)
        except Exception as e:
            res['error'] = str(e)
        return res

    def add_pts(self, stype, pts, reason):
        fields = {'name': reason,
                  'shift_id': False,
                  'type': stype,
                  'partner_id': self.id,
                  'point_qty': pts
                 }
        return self.o_api.create('shift.counter.event', fields)

    def add_first_point(self, stype):
        """To prevent members to have -1 point if service is too close to subscription"""
        ltype = 'standard'
        if (stype == 2):
            ltype = 'ftop'
        self.add_pts(ltype, 1, 'Point de bienvenue')

    def generate_barcode(self):
        return self.o_api.execute('res.partner', 'generate_barcode', [self.id])

    def generate_base_and_barcode(self, data=None):
        """Call Odoo methods to generate base and barcode numbers."""
        res1 = res2 = 0
        try:
            if hasattr(settings, 'SUBSCRIPTION_INPUT_BARCODE') and not (data is None):
                # Below code no more useful since LGDS use random barcode
                # import re
                # p = '0420(......)00.'
                # exp = re.compile(p)
                # match = exp.match(data['m_barcode'])
                # base = int(match.group(1))
                f = {'barcode': data['m_barcode']}
                res1 = self.o_api.execute('res.partner', 'generate_base', [self.id])
                res2 = self.o_api.update('res.partner', [self.id], f)

            else:
                res1 = self.o_api.execute('res.partner', 'generate_base', [self.id])
                res2 = self.generate_barcode()
        except Exception as e:
            print(str(e))
        return (res1 and res2)

    def create_capital_subscription_invoice(self, amount, date):
        """Make CapitalFundraisingWizard entities creation."""
        api = OdooAPI()
380 381 382 383 384 385

        if getattr(settings, 'ASK_FOR_CAPITAL_PAYMENT', True) is True:
            shares_qty = int(int(amount) / settings.PARTS_A_PRICE_UNIT)
        else:
            shares_qty = 1

Administrator committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        f1 = {'type': 'out_invoice',
              'date_invoice': date,
              'journal_id': settings.CAP_JOURNAL_ID,
              'account_id': settings.CAP_APPELE_NON_VERSE_ACCOUNT_ID,
              # 'payment_term_id':
              'partner_id': self.id,
              'is_capital_fundraising': True,
              'fundraising_category_id': settings.FUNDRAISING_CAT_ID,
              'state': 'open'
              }
        invoice_id = api.create('account.invoice', f1)
        f2 = {'invoice_id': invoice_id,
              'uom_id': settings.UNITE_UOM_ID,
              'product_id': settings.PARTS_A_PRODUCT_ID,
              'price_unit': settings.PARTS_A_PRICE_UNIT,
              'name': 'Parts A',
402
              'quantity': shares_qty,
Administrator committed
403 404 405 406 407 408 409 410 411 412 413
              'account_id': settings.CAP_INVOICE_LINE_ACCOUNT_ID
              }
        invoice_line_id = api.create('account.invoice.line', f2)
        api.execute('account.invoice',
                    'action_move_create',
                    [invoice_id])
        api.execute('account.invoice',
                    'assign_ownshare_to_invoice',
                    [invoice_id])
        return [invoice_id, invoice_line_id]

414
    def create_coop_shift_subscription(self, shift_t_id, stype, call_nb=1):
Administrator committed
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
        """Store coop shift subscription."""
        # Get shift template ticket corresponding to given shift temp. id
        sti = None
        shift_type = 'standard'
        if stype == 2:
            shift_type = 'ftop'
        cond = [['shift_template_id', '=', int(shift_t_id)],
                ['shift_type', '=', shift_type]]
        fields = ['seats_reserved', 'seats_max']
        stt = self.o_api.search_read('shift.template.ticket', cond, fields)
        if len(stt) > 0:
            sti = stt[0]['id']  # shift_ticket_id
            seats_reserved = int(stt[0]['seats_reserved'])
            seats_max = int(stt[0]['seats_max'])
            # if (seats_reserved == seats_max):
            # TODO
        if not (sti is None):
            try:
                today = datetime.date.today().strftime("%Y-%m-%d")
                st_r_fields = {'partner_id': self.id,
                               'shift_template_id': int(shift_t_id),
                               'shift_ticket_id': int(sti),
                               'state': 'open',
                               'date_begin': today
                               }
                st_r_id = self.o_api.create('shift.template.registration',
                                            st_r_fields)
442 443 444 445 446 447
            except Exception as ex:
                if 'seules les inscriptions ABCD sont possibles' in str(ex) and call_nb < 2:
                    return self.create_coop_shift_subscription(shift_t_id, 1, call_nb + 1)
                else:
                    coop_logger.error("Error while creating shift.template.registration : %s, (fields =%s)", str(ex), str(st_r_fields))
                    st_r_id = None
Administrator committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

        return st_r_id

    @staticmethod
    def exists(mail):
        api = OdooAPI()
        cond = [['email', 'ilike', str(mail)]]
        fields = ['email']
        res = api.search_read('res.partner', cond, fields, 1, 0, 'id DESC')
        if (res and len(res) == 1):
            answer = True
        else:
            answer = False
        return answer

Etienne Freiss committed
463 464 465 466
    @staticmethod
    def is_associated(id_parent):
        api = OdooAPI()
        cond = [['parent_id', '=', int(id_parent)]]
467
        fields = ['id','name','parent_id','birthdate_date','suppleant_member_id']
Etienne Freiss committed
468 469
        res = api.search_read('res.partner', cond, fields, 10, 0, 'id DESC')
        for partner in res:
470 471 472
            if partner['suppleant_member_id']:
                return True
        return False
Etienne Freiss committed
473

Administrator committed
474 475 476 477 478 479
    @staticmethod
    def finalize_coop_creation(post_data):
        """ Update coop data. """
        res = {}
        # First, update couchdb data
        c_db = CouchDB(arg_db='member')
480
        # shift_template = json.loads(post_data['shift_template'])
Administrator committed
481 482 483 484 485 486 487 488 489 490 491 492 493
        received_data = {'birthdate': post_data['birthdate'],
                         'city': post_data['city'],
                         'zip': post_data['zip'],
                         'firstname': post_data['firstname'],
                         'lastname': post_data['lastname'],
                         'odoo_id': post_data['odoo_id'],
                         'address': post_data['address'],
                         'mobile': post_data['mobile'],
                         'country': post_data['country'],
                         'validation_state': 'done'
                         }
        if ('sex' in post_data):
            received_data['sex'] = post_data['sex']
494 495
        if ('function' in post_data):
            received_data['function'] = post_data['function']
Administrator committed
496 497 498
        if 'street2' in post_data:
            received_data['street2'] = post_data['street2']
        if 'phone' in post_data:
499
            received_data['phone'] = format_phone_number(post_data['phone'])
Administrator committed
500 501 502 503 504 505 506 507 508
        r = c_db.updateDoc(received_data, 'odoo_id')
        if r:
            if ('odoo_id' in r):
                try:
                    # Update res.partner with received data
                    partner_id = CagetteMember.create_from_buffered_data(received_data)

                except Exception as e:
                    res['error'] = 'Erreur maj membre dans Odoo'
509
                    coop_logger.error("Pb avec couchDB (1): %s \n %s", str(received_data), str(e))
Administrator committed
510
        else:
511 512
            res['error'] = 'Pb avec couchDB'
            coop_logger.error("Pb avec couchDB (B): %s", str(received_data))
Administrator committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        return res

    @staticmethod
    def latest_coop_id():
        """Return the last barcode base recorded in Odoo database."""
        api = OdooAPI()
        cond = [['is_member', '=', True],
                ['total_partner_owned_share', '>', 0]]
        fields = ['barcode_base']
        return api.search_read('res.partner', cond, fields, 1, 0, 'id DESC')

    @staticmethod
    def create_from_buffered_data(post_data):
        """
            Create member or update its data in odoo and return its partner_id.
            At creation:
             Capital subscription and shift subscription will be stored!
             Fill accounting envelops with payment data.
             Send welcome mail for new members.

        """
        # WARNING : Very sensitive data
        #           Very touching step :
        #           couchdb data should reflect Odoo state
        res = {}
        api = OdooAPI()
        c_db = CouchDB(arg_db='member')
        partner_id = None
        name_sep = getattr(settings, 'SUBSCRIPTION_NAME_SEP', ' ')
        ask_4_sex = getattr(settings, 'SUBSCRIPTION_ASK_FOR_SEX', False)
543
        ask_4_job = getattr(settings, 'SUBSCRIPTION_ASK_FOR_JOB', False)
Administrator committed
544
        concat_order = getattr(settings, 'CONCAT_NAME_ORDER', 'FL')
545
        ask_for_capital_payment = getattr(settings, 'ASK_FOR_CAPITAL_PAYMENT', True)
Administrator committed
546
        sex = 'o'
547
        function = ''
Administrator committed
548 549 550

        if ask_4_sex is True:
            sex = post_data['sex']
551 552
        if ask_4_job is True:
            function = post_data['function']
Administrator committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575

        # With input type="date", transmitted value is YYYY-mm-dd
        # But, it could be dd/mm/YYYY if not supported by browser
        well_formatted_dob = True
        birthdate = post_data['birthdate']
        try:
            i = birthdate.index('/')
            b_elts = birthdate.split('/')
            birthdate = b_elts[2] + '-' + b_elts[1] + '-' + b_elts[0]
        except:
            # Birthdate should be '-' separated values
            try:
                i = birthdate.index('-')
            except:
                well_formatted_dob = False

        if (well_formatted_dob is True):
            # Prepare data for odoo
            if concat_order == 'LF':
                name = post_data['lastname'] + name_sep + post_data['firstname']
            else:
                name = post_data['firstname'] + name_sep + post_data['lastname']
            f = {'name': name,
576
                 'birthdate_date': birthdate,
Administrator committed
577 578 579 580
                 'sex': sex,
                 'street': post_data['address'],
                 'zip': post_data['zip'],
                 'city': post_data['city'],
581
                 'phone': format_phone_number(post_data['mobile']), # Because list view default show Phone and people mainly gives mobile
582 583
                 'barcode_rule_id': settings.COOP_BARCODE_RULE_ID,
                 'function': function
Administrator committed
584 585 586 587 588 589
                 }
            if ('_id' in post_data):
                f['email'] = post_data['_id']
            if ('country' in post_data):
                if (post_data['country'].lower() == 'france' or
                   post_data['country'] == ''):
590
                    f['country_id'] = getattr(settings, 'FRANCE_ID', 75)
Administrator committed
591 592 593 594
            if 'street2' in post_data:
                f['street2'] = post_data['street2']
            if ('phone' in post_data) and len(post_data['phone']) > 0:
                if len(f['phone']) == 0:
595
                    f['phone'] = format_phone_number(post_data['phone'])
Administrator committed
596 597
                else:
                    f['mobile'] = f['phone']
598
                    f['phone'] = format_phone_number(post_data['phone'])
Administrator committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

            # Create coop
            if not ('odoo_id' in post_data):
                partner_id = api.create('res.partner', f)
                try:
                    id = int(partner_id)
                except:
                    id = 0
                if (id > 0):    # Coop succesfuly created
                    # Update couchdb (rest of data updated on client side)
                    update_data = {'_id': post_data['_id'],
                                   'email': post_data['_id'],
                                   'odoo_id': id}

                    r = c_db.updateDoc(update_data, '_id')
                    if r:
                        # Check if we proceed to capital subscription
                        m = CagetteMember(partner_id)
                        owned_share = 0
                        existing_data = m.get_data()

                        if (len(existing_data) > 0):
                            owned_share = existing_data[0]['total_partner_owned_share']

                        if (owned_share > 0):
                            # form has already been submitted
                            # Subscription, shift and payment data won't be saved
                            res['subs'] = [-1, -1]
                            res['bc'] = False
                            res['shift'] = None
                            res['envelop'] = None
                        else:
                            # New member
                            # Create capital subscription, base & barcode
633 634 635 636
                            if 'shares_euros' in post_data:
                                shares_euros = post_data['shares_euros']
                            elif getattr(settings, 'ASK_FOR_CAPITAL_PAYMENT', True) is False:
                                shares_euros = 0
Administrator committed
637 638
                            today = datetime.date.today().strftime("%Y-%m-%d")
                            res['subs'] = \
639
                                m.create_capital_subscription_invoice(shares_euros, today)
Administrator committed
640 641
                            res['bc'] = m.generate_base_and_barcode(post_data)

Etienne Freiss committed
642 643 644 645 646 647 648 649 650
                            # if the new member is associated with an already existing member 
                            # then we put the state in "associated" and we create the "associated" member
                            if 'is_associated_people' in post_data and 'parent_id' in post_data :
                                fields = {}
                                fields['cooperative_state'] = 'associated'
                                api.update('res.partner', [partner_id], fields)
                                associated_member = {
                                    'email': post_data['_id'],
                                    'name': name,
651
                                    'birthdate_date': birthdate,
Etienne Freiss committed
652 653 654 655 656
                                    'sex': sex,
                                    'street': post_data['address'],
                                    'zip': post_data['zip'],
                                    'city': post_data['city'],
                                    'phone': format_phone_number(post_data['mobile']), # Because list view default show Phone and people mainly gives mobile
657
                                    'barcode_rule_id': settings.ASSOCIATE_BARCODE_RULE_ID,
658 659
                                    'parent_id': post_data['parent_id'],
                                    'suppleant_member_id': partner_id,
660 661
                                    'is_associated_people': True,
                                    'function': function
Etienne Freiss committed
662 663
                                    }
                                associated_member_id = api.create('res.partner', associated_member)
664 665
                                am = CagetteMember(associated_member_id)
                                res['bca'] = am.generate_base_and_barcode(post_data)
Etienne Freiss committed
666 667 668 669
                            # If it's an new associated member with a new partner. Link will be made by the user in BDM/admin
                            # We add the associated member to the "associate" shift template so we can find them in Odoo
                            elif 'is_associated_people' not in post_data or 'is_associated_people' in post_data and 'parent_id' not in post_data:
                                # Create shift suscription if is not associated
670 671 672 673 674 675 676 677
                                try:
                                    shift_template = json.loads(post_data['shift_template'])
                                    shift_t_id = shift_template['data']['id']
                                    stype = shift_template['data']['type']
                                    res['shift'] = \
                                        m.create_coop_shift_subscription(shift_t_id, stype)
                                except Exception as no_shift_e:
                                    coop_logger.error("Pas de créneau défini : %s \n %s", str(post_data), str(no_shift_e))
Etienne Freiss committed
678
                                # m.add_first_point(stype) # Not needed anymore
Administrator committed
679 680 681 682 683 684 685 686 687 688

                            # Update couchdb do with new data
                            try:
                                updated_data = m.get_data()
                                update_data['barcode_base'] = updated_data[0]['barcode_base']
                                res['bc'] = update_data['barcode_base']
                                update_data['odoo_state'] = 'done'
                                c_db.updateDoc(update_data, '_id')
                            except Exception as e:
                                res['error'] = 'Erreur après souscription du capital'
689 690
                                coop_logger.error("Erreur après souscription : %s \n %s", str(res), str(e))

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
                            if ask_for_capital_payment is True:
                                # Create or update envelop(s) with coop payment data
                                payment_data = {
                                    'partner_id': partner_id,
                                    'partner_name': post_data['firstname'] + ' ' + post_data['lastname'],
                                    'payment_meaning': post_data['payment_meaning'],
                                    'shares_euros': post_data['shares_euros'],
                                    'checks_nb': post_data['checks_nb']     # is 0 if payment is cash
                                }

                                if ('checks' in post_data):
                                    payment_data['checks'] = json.loads(post_data['checks'])
                                else:
                                    payment_data['checks'] = []
                                if payment_data['payment_meaning'] == 'cash' or payment_data['payment_meaning'] == 'ch':
                                    res['envelop'] = CagetteEnvelops().create_or_update_envelops(payment_data)
                                else:
                                    p_data = {'partner_id': partner_id, 'type': payment_data['payment_meaning'], 'amount': post_data['shares_euros']}
                                    res['envelop'] = CagetteEnvelops().save_payment(p_data)
Administrator committed
710 711 712 713 714 715 716 717 718 719 720 721 722
                        # Send welcome mail
                        try:
                            api.execute('res.partner', 'send_welcome_email', [partner_id])
                        except Exception as e:
                            res['error'] = 'Erreur envoie mail invitation'
                        # from outils.common import CagetteMail
                        # try:
                        #     CagetteMail.sendWelcome(f['email'])
                        # except Exception as e:
                        #     res['error'] = 'Erreur envoie mail invitation'
                    else:
                        res['error'] = 'Pb avec couchDB'
                        res['data'] = update_data
723
                        coop_logger.error("Pb couchDB (C) : %s", str(res))
Administrator committed
724 725
                else:
                    res['error'] = 'Erreur creation membre odoo'
726
                    coop_logger.error("Pb couchDB (D) : %s", str(res))
Administrator committed
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
            # Update coop data
            else:
                odoo_id = int(post_data['odoo_id'])
                if (api.update('res.partner', [odoo_id], f) is True):
                    partner_id = odoo_id

        return partner_id

    @staticmethod
    def create_from_cvs_row(data):
        """
            Create member or update its data in odoo and return its partner_id.
            At creation:
             Capital subscription
        """
        res = {}
        api = OdooAPI()
        partner_id = None

        well_formatted_dob = True
        birthdate = data['date de naissance']
        try:
            i = birthdate.index('/')
            b_elts = birthdate.split('/')
            birthdate = b_elts[2] + '-' + b_elts[1] + '-' + b_elts[0]
        except:
            # Birthdate should be '-' separated values
            try:
                i = birthdate.index('-')
            except:
                well_formatted_dob = False

        if (well_formatted_dob is True):
            # Prepare data for odoo
            f = {'name': data['Prénom'] + ' ' + data['Nom'],
762
                 'birthdate_date': birthdate,
Administrator committed
763 764 765 766
                 'sex': 'o',
                 'street': data['adresse rue'],
                 'zip': data['code postal'],
                 'city': data['ville'],
767
                 'country_id': getattr(settings, 'FRANCE_ID', 75),
Administrator committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
                 'phone': data['tel'],
                 'email': data['mail'],
                 'barcode_rule_id': settings.COOP_BARCODE_RULE_ID
                 }
            partner_id = api.create('res.partner', f)
            try:
                id = int(partner_id)
            except:
                id = 0
            if (id > 0):    # Coop succesfuly created
                res['id'] = partner_id
                m = CagetteMember(partner_id)
                shares_euros = int(float(data['Nb de parts']) * 10)
                res['subs'] = m.create_capital_subscription_invoice(shares_euros, data['date inscription'])
                res['bc'] = m.generate_base_and_barcode(data)
            else:
                res['error'] = 'Unable to create member from ' + str(data)
        return res

    @staticmethod
    def store_warning_msg(post_data):
        """Store in couchDB database the warning new coop has written."""
        c_db = CouchDB(arg_db='member')
        data = {
            '_id': post_data['_id'],
            'coop_msg': post_data['msg']
        }
        r = c_db.updateDoc(data, '_id')
        return r

    @staticmethod
    def get_couchdb_data(email):
        """Retrieve couchDB data corresponding to given email."""
        c_db = CouchDB(arg_db='member')
        try:
            doc = c_db.getDocById(email)
        except:
            doc = []
        return doc

    @staticmethod
    def get_state_fr(coop_state):
        """Return french version of given coop_state."""
811

Administrator committed
812 813 814 815 816
        if coop_state == 'alert':
            fr_state = 'En alerte'
        elif coop_state == 'delay':
            fr_state = 'Délai accordé'
        elif coop_state == 'suspended':
817
            fr_state = 'Rattrapage'
Administrator committed
818 819 820 821 822 823 824 825 826 827 828 829
        elif coop_state == 'not_concerned':
            fr_state = 'Non concerné(e)'
        elif coop_state == 'blocked':
            fr_state = 'Bloqué(e)'
        elif coop_state == 'unpayed':
            fr_state = 'Impayé constaté'
        elif coop_state == 'unsubscribed':
            fr_state = 'Désinscrit(e)'
        elif coop_state == 'up_to_date':
            fr_state = 'A jour'
        elif coop_state == 'exempted':
            fr_state = 'Exempté(e)'
Félicie committed
830 831 832 833
        elif coop_state == 'associated':
            fr_state = 'En binôme'
        elif coop_state == 'gone':
            fr_state = 'Parti(e)'
834 835
        elif coop_state == 'vacation':
            fr_state = 'En vacances'
Administrator committed
836 837 838 839 840 841 842 843 844 845 846
        else:
            fr_state = 'Inconnu'
        return fr_state

    @staticmethod
    def get_members_next_shift(ids):
        """Retrieve next shift for given members ids."""
        api = OdooAPI()
        cond = [['partner_id', 'in', ids],
                ['date_begin', '>=', datetime.datetime.now().isoformat()],
                ['state', '=', 'open']]
847
        fields = ['shift_type', 'date_begin', 'partner_id', 'date_end', 'shift_ticket_id']
Administrator committed
848

849
        res = api.search_read('shift.registration', cond, fields, 2500, 0, 'date_begin ASC')
Administrator committed
850 851 852 853
        shifts = {}
        locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')

        if len(res) > 0:
854
            local_tz = pytz.timezone('Europe/Paris')
Administrator committed
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
            for s in res:
                date, t = s['date_begin'].split(' ')
                year, month, day = date.split('-')
                hour, minute, second = t.split(':')
                if int(hour) < 21:
                    start = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), int(second), tzinfo=pytz.utc)
                    start_date = start.astimezone(local_tz)
                    s['start'] = start_date.strftime("%A %d %B %Y à %Hh%M")
                    if not (s['partner_id'][0] in shifts):
                        shifts[s['partner_id'][0]] = []
                    shifts[s['partner_id'][0]].append(s)

        return shifts

    @staticmethod
    def add_next_shifts_to_members(members):
        """Next shifts are added to members data."""
        ids = []
        m_list = []
        for m in members:
            ids.append(m['id'])

        shifts = CagetteMember.get_members_next_shift(ids)

        for m in members:
            s = []
            if m['id'] in shifts:
                s = shifts[m['id']]
            m['shifts'] = s
            m_list.append(m)
        return m_list

    @staticmethod
888
    def search(k_type, key, shift_id=None, search_type="full"):
Administrator committed
889 890 891 892 893 894 895 896 897 898
        """Search member according 3 types of key."""
        api = OdooAPI()
        if k_type == 'id':
            cond = [['id', '=', int(key)]]
        elif k_type == 'barcode_base':
            cond = [['barcode_base', '=', str(key)]]
        elif k_type == 'barcode':
            cond = [['barcode', '=', str(key)]]
        else:
            cond = [['name', 'ilike', str(key)]]
899
        cond.append('|')
François C. committed
900
        cond.append(['is_member', '=', True])
901
        #TODO : replace is_associated_people check by suppleant_member_id check to exclude mineurs rattachés
902
        if search_type != 'members' and search_type != 'envelops':
Etienne Freiss committed
903 904 905
            cond.append(['is_associated_people', '=', True])
        else:
            cond.append(['is_associated_people', '=', False])
906 907
        if search_type != 'envelops':
            cond.append(['cooperative_state', '!=', 'associated'])
Administrator committed
908
        # cond.append(['cooperative_state', '!=', 'unsubscribed'])
909

910
        if search_type == "full" or search_type == 'members' or search_type == "manage_shift_registrations":
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
            fields = CagetteMember.m_default_fields
            if not shift_id is None:
                CagetteMember.m_default_fields.append('tmpl_reg_line_ids')
            res = api.search_read('res.partner', cond, fields)
            members = []
            if len(res) > 0:
                for m in res:
                    keep_it = False
                    if not shift_id is None and len(shift_id) > 0:
                        # Only member registred to shift_id will be returned
                        if len(m['tmpl_reg_line_ids']) > 0:
                            cond = [['id', '=', m['tmpl_reg_line_ids'][0]]]
                            fields = ['shift_template_id']
                            shift_templ_res = api.search_read('shift.template.registration.line', cond, fields)
                            if (len(shift_templ_res) > 0
                                and
                                int(shift_templ_res[0]['shift_template_id'][0]) == int(shift_id)):
                                keep_it = True
                    else:
                        keep_it = True
                    if keep_it is True:
                        try:
                            img_code = base64.b64decode(m['image_medium'])
                            extension = imghdr.what('', img_code)
                            m['image_extension'] = extension
                        except Exception as e:
                            coop_logger.info("Img error : %s", e)
                        m['state'] = m['cooperative_state']
                        m['cooperative_state'] = \
                            CagetteMember.get_state_fr(m['cooperative_state'])
                        # member = CagetteMember(m['id'], m['email'])
                        # m['next_shifts'] = member.get_next_shift()
                        if not m['parent_name'] is False:
944
                            m['name'] += ' (suppléant.e de son binôme ' + m['parent_name'] + ')'
945 946 947 948
                            del m['parent_name']
                        members.append(m)

            return CagetteMember.add_next_shifts_to_members(members)
949 950 951
        elif search_type == "makeups_data":
            fields = CagetteMember.m_short_default_fields
            fields = fields + ['shift_type', 'makeups_to_do', 'display_ftop_points', 'display_std_points', 'shift_type']
952
            cond.append(['shift_type', '=', 'standard'])
953
            res = api.search_read('res.partner', cond, fields)
954
            CagetteMembers.add_makeups_to_come_to_member_data(api, res)
955
            return res
956 957
        elif search_type == "shift_template_data":
            fields = CagetteMember.m_short_default_fields
958
            fields = fields + ['id', 'makeups_to_do', 'cooperative_state','parent_name']
959 960 961
            res = api.search_read('res.partner', cond, fields)

            if res:
962 963 964 965
                for partner in res:
                    c = [['partner_id', '=', int(partner['id'])], ['state', 'in', ('draft', 'open')]]
                    f = ['shift_template_id']
                    shift_template_reg = api.search_read('shift.template.registration', c, f)
966

967 968 969 970
                    if shift_template_reg:
                        partner['shift_template_id'] = shift_template_reg[0]['shift_template_id']
                    else:
                        partner['shift_template_id'] = None
971 972 973
                    if not partner['parent_name'] is False:
                        partner['name'] += ' (suppléant.e de son binôme ' + partner['parent_name'] + ')'
                        del partner['parent_name']
974 975

            return res
976
        else:
977
            # TODO differentiate envelops & subscription_data searches
978
            fields = CagetteMember.m_short_default_fields
979
            fields = fields + ['total_partner_owned_share', 'amount_subscription']
980 981
            res = api.search_read('res.partner', cond, fields)
            return res
Administrator committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

    @staticmethod
    def remove_data_from_CouchDB(request):
        res = {}
        try:
            email = request.POST.get("email","")
            if len(email) > 0:
                is_connected_user = CagetteUser.are_credentials_ok(request)
                can_be_deleted = False
                coop = CagetteMember.retrieve_data_according_keys({'email':email})
                if len(coop) > 0:
                    coop = coop[0]
                    if (len(coop['tmpl_reg_line_ids']) > 0 and coop['total_partner_owned_share']):
                        #no need to be connected to delete it
                        can_be_deleted = True
                    else:
                        if not is_connected_user:
                            message = 'L\'inscription de ce membre n\'a pas été correctement finalisée, il ne peut être archivé.' + "\n"
                            if len(coop['tmpl_reg_line_ids']) == 0:
                                message += 'Il n\'est inscrit à aucun créneau. Veuillez en ajouter un sur Odoo.'+ "\n"
                            if coop['total_partner_owned_share'] == 0:
                                message += 'Le capital souscrit n\'a pas été enregistré. Veuillez le faire sur Odoo.'
                            res['msg'] = message

                else:
                    if is_connected_user is False:
                        res['msg'] = 'Aucun membre connu avec cet email'

                # if demand comes from a connected user, it can be deleted
                if is_connected_user:
                    can_be_deleted = True
                else:
                    if can_be_deleted is False:
                        res['msg'] = 'Seul un utilisateur connecté peut faire cette suppression'

                if can_be_deleted is True:
                    c_db = CouchDB(arg_db='member')
                    doc = c_db.getDocById(email)    # email is the id for members doc
                    res['action'] = c_db.delete(doc)
            else:
                res['msg'] = 'No email'
        except Exception as e:
            coop_logger.error("Remove data from couchDB : %s", str(e))
            res['msg'] = 'Oups ! Erreur Remove data from couchDB'
        return res

    @staticmethod
    def remove_from_mess_list(request):
        res = {}
        try:
1032
            _id = request.POST.get("id", "")
Administrator committed
1033 1034 1035 1036 1037 1038 1039
            c_db = CouchDB(arg_db='member_mess')
            doc = c_db.getDocById(_id)
            res['action'] = c_db.delete(doc)
        except Exception as e:
            res['error'] = str(e)
        return res

1040 1041 1042 1043 1044
    def search_associated_people(self):
        """ Search for an associated partner """
        res = {}

        c = [["parent_id", "=", self.id]]
1045
        f = ["id", "name", "barcode_base", 'suppleant_member_id']
1046 1047 1048

        res = self.o_api.search_read('res.partner', c, f)

1049 1050 1051 1052
        for partner in res:
            if partner['suppleant_member_id']:
                return partner
        return None
1053

1054 1055
    def update_member_makeups(self, member_data):
        api = OdooAPI()
1056 1057
        makeups_to_do = int(member_data["target_makeups_nb"])
        f = {'makeups_to_do': makeups_to_do}
1058 1059 1060 1061 1062
        res_item = api.update('res.partner', [self.id], f)
        res = {
            'mid': self.id,
            'update': res_item
        }
1063 1064
        # No need to manually call status recompute after that because when we use this method,
        # we always call an odoo method that triggers status update after that
1065 1066
        return res

1067

1068 1069 1070
    def get_makeup_registrations_ids_on_shift_template(self, shift_template_id):
        """ Get the makeup registrations that are on a shift template """
        makeup_reg_ids = []
1071
        res_shift_ids = shifts.fonctions.get_scheduled_makeups(self.o_api, partner_ids=[self.id])
1072 1073 1074 1075 1076 1077 1078 1079 1080
        for shift_reg in res_shift_ids:
            c = [["id", "=", int(shift_reg['shift_id'][0])]]
            f = ['shift_template_id']
            shift = self.o_api.search_read("shift.shift", c, f)[0]
            if shift['shift_template_id'][0] == shift_template_id:
                makeup_reg_ids.append(shift_reg["id"])
        return makeup_reg_ids


1081 1082
    def get_shift_template_registration_ids(self):
        c = [['partner_id', '=', self.id]]
1083
        f = ['id']
1084
        return [x['id'] for x in self.o_api.search_read("shift.template.registration", c, f)]
1085 1086


1087 1088 1089 1090
    def unsubscribe_member_but_exogenous_makeups(self):
        return self.o_api.execute(
            'shift.template.registration',
            'unlink_but_exogenous_makeups',
1091
            self.get_shift_template_registration_ids()
1092
        )
1093 1094


1095 1096 1097 1098
    def unsubscribe_member(self):
        return self.o_api.execute(
            'shift.template.registration',
            'unlink',
1099
            self.get_shift_template_registration_ids()
1100
        )
1101 1102 1103 1104 1105

    def set_cooperative_state(self, state):
        f = {'cooperative_state': state}
        return self.o_api.update('res.partner', [self.id], f)

1106 1107 1108 1109 1110 1111
    def update_extra_shift_done(self, value):
        api = OdooAPI()
        res = {}

        f = { 'extra_shift_done': value }
        res_item = api.update('res.partner', [self.id], f)
1112 1113 1114 1115 1116 1117 1118
        res = {
            'mid': self.id,
            'update': res_item
        }

        return res

1119

1120 1121 1122 1123 1124 1125
    def has_state_unsubscribed_gone_or_associated(self):
        c = [['id', '=', self.id]]
        f = ['cooperative_state']
        state = self.o_api.search_read("res.partner", c, f)[0]["cooperative_state"]
        return state in ("unsubscribed", "gone", "associated")

Administrator committed
1126 1127 1128 1129 1130 1131 1132 1133 1134
class CagetteMembers(models.Model):
    """Class to manage operations on all members or part of them."""

    @staticmethod
    def get_problematic_members():
        """Search partner with missing elements"""
        api = OdooAPI()
        return []

1135

Administrator committed
1136 1137 1138 1139 1140 1141 1142 1143
    @staticmethod
    def raw_search(needle):
        """Search partner with missing elements"""
        res = []
        try:
            api = OdooAPI()
            cond = ['|', ('email', 'ilike', needle), ('display_name', 'ilike', needle)]
            fields = ['barcode_base', 'barcode', 'create_date',
1144
                      'cooperative_state', 'name', 'birthdate_date', 'street', 'street2',
Administrator committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
                      'zip', 'city', 'email', 'mobile', 'phone', 'total_partner_owned_share',
                      'amount_subscription', 'active_tmpl_reg_line_count',
                      'shift_type', 'current_template_name', 'sex']
            api_res = api.search_read('res.partner', cond, fields)
            if api_res:
                ids_in_env = CagetteEnvelops().get_ids_in_all()
                for c in api_res:
                    if not (str(c['id']) in ids_in_env):
                        c['envelops'] = False
                    else:
                        c['envelops'] = True
                res = api_res
        except Exception as e:
            res['error'] = str(e)
        return res

    @staticmethod
    def verify_subscription_state():
        """Verify couchDB and Odoo DB coherence."""
        c_db = CouchDB(arg_db='member')
        # Get all members with unregistrated shifts
        unregistrated_members = c_db.getAllDocs('odoo_state', 'done', False)
        partner_ids = []
        to_modify_in_couchDB = []
        for m in unregistrated_members:
            if 'odoo_id' in m:
                partner_ids.append(int(m['odoo_id']))
        if len(partner_ids) > 0:
            api = OdooAPI()
            cond = [['id', 'in', partner_ids]]
            f = ['total_partner_owned_share', 'name', 'barcode_base', 'tmpl_reg_line_ids']
            res = api.search_read('res.partner', cond, f)
            for p in res:
                if p['total_partner_owned_share'] > 0:
                    to_modify_in_couchDB.append(p)
        if len(to_modify_in_couchDB) > 0:
            for p in to_modify_in_couchDB:
                if len(p['tmpl_reg_line_ids']) > 0:
                    r = {'odoo_id': p['id'], 'odoo_state': 'done', 'barcode_base': p['barcode_base']}
                    c_db.updateDoc(r, 'odoo_id', ['shift_template'])

        return to_modify_in_couchDB

    @staticmethod
    def update_couchdb_barcodes():
        c_db = CouchDB(arg_db='member')
        # Get all members with 'done' state
        all_done = c_db.getAllDocs('odoo_state', 'done')
        partner_ids = []
        to_modify_in_couchDB = []
        for m in all_done:
            partner_ids.append(int(m['odoo_id']))
        if len(partner_ids) > 0:
            api = OdooAPI()
            cond = [['id', 'in', partner_ids]]
            f = ['barcode_base']
            res = api.search_read('res.partner', cond, f)

            for p in res:
                for m in all_done:
                    if (int(m['odoo_id']) == int(p['id'])):
                        try:
                            if int(m['barcode_base']) != int(p['barcode_base']):
                                m['barcode_base'] = p['barcode_base']
                                to_modify_in_couchDB.append(m)
                        except:
                            pass
            if len(to_modify_in_couchDB) > 0:
                for p in to_modify_in_couchDB:
                    r = {'odoo_id': p['odoo_id'],
                         'barcode_base': p['barcode_base']}
                    c_db.updateDoc(r, 'odoo_id')

        return to_modify_in_couchDB

    @staticmethod
    def _generate_inra_csv_data(odoo_result):
        data = {'lines': [], 'sum_up': ''}
        current_p = ''
        try:
            if (('purchases' in odoo_result) and len(odoo_result['purchases']) > 0):
                off = OFF()
                off_products = off.get_products()
                headers = ['date', 'coop_id', 'coop_num', 'coop_naissance', 'coop_ville',
                           'code-barre', 'nom_produit', 'qte', 'prix', 'remise',
                           'categ_id', 'nom_cat_cagette',
                           'off_qte', 'off_cat', 'off_labels',
                           'off_nutriscore', 'off_nova', 'off_nrj_100g',
                           'off_manufacture_places', 'off_origins']
                data['lines'].append(headers)
                coop_nums = []
                products = []
                remises = {}
                ca_ttc_panel = 0
                for p in odoo_result['purchases']:
                    current_p = p
                    if p['product_barcode'] in off_products:
                        off_pdt = off_products[p['product_barcode']]
                    else:
                        off_pdt = {'quantity': '', 'categories': '',
                                   'labels': '', 'nutrition_grade_fr': '', 'nova_group': '', 'energy_100g': '',
                                   'manufacturing_places': '', 'origins': ''}
                    pname = p['product_name'].replace(';', ' ')
                    cat_name = ''
                    if str(p['product_categ_id']) in odoo_result['pcat']:
                        cat_name = odoo_result['pcat'][str(p['product_categ_id'])]
                    line = [p['date_order'], p['coop_id'], p['coop_num'], p['coop_birthdate'], p['coop_city'],
                            p['product_barcode'], pname, p['product_qty'], p['product_price'], p['product_discount'],
                            p['product_categ_id'], cat_name,
                            off_pdt['quantity'], off_pdt['categories'], off_pdt['labels'],
                            off_pdt['nutrition_grade_fr'], off_pdt['nova_group'], off_pdt['energy_100g'],
                            off_pdt['manufacturing_places'], off_pdt['origins']]

                    ca_ttc_line = float(p['product_qty']) * float(p['product_price'])
                    if (int(p['product_discount']) > 0):
                        ca_ttc_line *= (100 - int(p['product_discount'])) / 100
                        if not (p['product_discount'] in remises):
                            remises[p['product_discount']] = 0
                        remises[p['product_discount']] += ca_ttc_line

                    ca_ttc_panel += ca_ttc_line
                    data['lines'].append(line)
                    if not (p['coop_num'] in coop_nums):
                        coop_nums.append(p['coop_num'])
                    if not (p['product_id'] in products):
                        products.append(p['product_id'])

                data['sum_up'] =  'Coopérateurs du panel ayant fait au moins 1 achat : ' + str(len(coop_nums)) + "\n"
                data['sum_up'] += 'Nb de références de produits achetés : ' + str(len(products)) + "\n"
                data['sum_up'] += 'CA TTC réalisé : ' + "{:.2f}".format(ca_ttc_panel) + "\n"
                for pc, val in remises.items():
                    data['sum_up'] += 'dont CA TTC remises ' + str(int(pc)) + '% : ' + "{:.2f}".format(val) + "\n"
        except Exception as e:
            data['error'] = str(e) + ' : produit en cours = ' + str(current_p)
        return data

    @staticmethod
    def get_inra_panel_purchases(request):
        api = OdooAPI()
        list_fpath = 'members/panel.csv'
        res = {'error': ''}
        try:
            nums = []
            with open(list_fpath) as fp:
                line = fp.readline()
                while line:
                    nums.append(line.strip())
                    line = fp.readline()
            if len(nums) > 0:
                params = {'partners_coop_num': nums}
                # num_slice = nums[0:1]
                month = request.POST.get('mois_month')
                year = request.POST.get('mois_year')
                try:
                    m = int(month)
                    y = int(year)
                    if (m < 10):
                        month = '0' + month
                    if (m > 0 and y > 0):
                        params['month'] = year + '-' + month
                    else:
                        today = datetime.date.today()
                        year = str(today.year)
                        month = str(today.month)
                        if (len(month) == 1):
                            month = '0' + month
                        params['month'] = year + '-' + month
                except Exception as e2:
                    res['error'] += str(e2)
                    pass
                odoo_result = api.execute('lacagette.pos_member_purchases', 'get_members_purchases', params)
                res['data'] = CagetteMembers._generate_inra_csv_data(odoo_result)
                if 'error' in res['data']:
                    res['error'] += res['data']['error']
                res['params'] = params

        except Exception as e:
            res['error'] += str(e)

        return res

    @staticmethod
    def get(cond, fields, o=0, l=5000):
        res = {}
        try:
            api = OdooAPI()
            res = api.search_read('res.partner', cond, fields, offset=o, limit=l)
        except Exception as e:
            res['error'] = str(e)
        return res

    @staticmethod
    def add_pts_to_everyone(mtype, ids, pts, reason):
        res = {}
        try:
            for mid in ids:
                m = CagetteMember(mid)
                res[str(mid)] = m.add_pts(mtype, pts, reason)
        except Exception as e:
            res['error'] = str(e)
        return res

1347
    @staticmethod
1348
    def get_makeups_members(ids=[]):
1349
        # 0 : fetch members with makeups_to_do > 0
1350 1351
        api = OdooAPI()
        cond = [['makeups_to_do','>', 0]]
1352 1353 1354 1355

        if len(ids) > 0:
            cond.append(['id','in', ids])

1356
        fields = ['id', 'name', 'display_std_points', 'display_ftop_points', 'shift_type', 'makeups_to_do']
1357
        res = api.search_read('res.partner', cond, fields)
1358 1359 1360 1361 1362

        # There are two things we need to do now :
        # 1 : fetching members with no makeups to do but with some makeups to come
        # 2 : providing makeups to come to all members

1363
        makeups_to_come_per_partner = shifts.fonctions.get_partners_with_makeups_to_come(api)
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

        # 1 : fetching members with no makeups to do but with some makeups to come
        cond = [['makeups_to_do', '=', 0], ['id', 'in', list(makeups_to_come_per_partner.keys())]]

        if len(ids) > 0:
            cond.append(['id','in', ids])

        res = res + api.search_read('res.partner', cond, fields)

        # 2 : providing makeups to come to all members
        for idx, partner in enumerate(res):
            if partner['id'] in makeups_to_come_per_partner:
                res[idx]['makeups_to_come'] = makeups_to_come_per_partner[partner['id']]
            else:
                res[idx]['makeups_to_come'] = 0

1380
        return res
Administrator committed
1381

1382
    @staticmethod
1383
    def add_makeups_to_come_to_member_data(api, res):
1384 1385
        if res:
            for idx, partner in enumerate(res):
1386
                res[idx]['makeups_to_come'] = len(shifts.fonctions.get_scheduled_makeups(api, partner_ids=[int(partner['id'])]))
1387

Félicie committed
1388 1389 1390
    @staticmethod
    def get_attached_members():
        api = OdooAPI()
1391 1392
        cond = [['is_associated_people', '=', True]]
        fields = ['id', 'name', 'parent_name', 'suppleant_member_id']
Félicie committed
1393
        res = api.search_read('res.partner', cond, fields)
1394 1395
        # Exclude mineurs rattachés
        return [x for x in res if res['suppleant_member_id']]
Félicie committed
1396

Administrator committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
class CagetteUser(models.Model):

    @staticmethod
    def get_credentials(request):
        import hashlib

        data = {}
        api = OdooAPI()
        login = request.POST.get('login')
        password = request.POST.get('password')

        if login and password:
            uid = api.authenticate(login, password)
            if not(uid is False):
                cond = [['id', '=', uid]]
                fields = ['active', 'cooperative_state', 'create_date', 'groups_id']
                try:
                    res = api.search_read('res.users', cond, fields)
                    if (res[0]['active'] is True):
                        tocode = res[0]['create_date'] + request.META.get('HTTP_USER_AGENT')
                        data['authtoken'] = hashlib.sha256(tocode.encode('utf-8')).hexdigest()
                        data['uid'] = uid
                        data['cooperative_state'] = res[0]['cooperative_state']
                        cond = [['id', 'in', res[0]['groups_id']]]
                        fields = ['full_name']
                        data['groups'] = api.search_read('res.groups', cond, fields)

                except Exception as e:
                    data['error'] = str(e)

        return data

    @staticmethod
    def are_credentials_ok(request):
        import hashlib
        answer = False
        if 'authtoken' in request.COOKIES and 'uid' in request.COOKIES:
            api = OdooAPI()
            cond = [['id', '=', request.COOKIES['uid']]]
            fields = ['active','create_date']
            try:
                res = api.search_read('res.users', cond, fields)
                if (res[0]['active'] is True):
                    tocode = res[0]['create_date'] + request.META.get('HTTP_USER_AGENT')
                    calc_authtoken = hashlib.sha256(tocode.encode('utf-8')).hexdigest()
                    if calc_authtoken == request.COOKIES['authtoken']:
                        answer = True
            except:
                pass

        return answer
1448

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    @staticmethod
    def get_preferences(request, key=None):
        preferences = {}
        try:
            api = OdooAPI()
            cond = [['id', '=', request.COOKIES['uid']]]
            fields = ['partner_id']
            res = api.search_read('res.users', cond, fields)
            if res:
                preferences = CagetteMember(res[0]['partner_id'][0]).get_preferences(key)
        except Exception as e:
            preferences['error'] = str(e)
        
        return preferences

    @staticmethod
    def set_preferences(request, data, key=None):
        """Be careful : if key is None, preferences will be overwritten by received data."""    
        res = {}
        if CagetteUser.are_credentials_ok(request):
            try:
                api = OdooAPI()
                cond = [['id', '=', request.COOKIES['uid']]]
                fields = ['partner_id']
                res_user = api.search_read('res.users', cond, fields)
                if res_user:
                    if key is None:
                        external_apps_preferences = data
                    else:
                        external_apps_preferences = CagetteUser.get_preferences(request)
                        external_apps_preferences[key] = data
                    CagetteMember(res_user[0]['partner_id'][0]).set_preferences(external_apps_preferences)
                    res['success'] = True
            except Exception as e:
                res['error'] = str(e)
        
1485
        return res