migrate.py 21.7 KB
Newer Older
Skia's avatar
Skia committed
1 2 3 4
import MySQLdb
import os
import django
import random
5
import datetime
Skia's avatar
Skia committed
6
from io import StringIO
7
from pytz import timezone
Skia's avatar
Skia committed
8
from os import listdir
Skia's avatar
Skia committed
9 10

os.environ["DJANGO_SETTINGS_MODULE"] = "sith.settings"
Skia's avatar
Skia committed
11
os.environ['DJANGO_COLORS'] = 'nocolor'
Skia's avatar
Skia committed
12 13 14 15
django.setup()

from django.db import IntegrityError
from django.conf import settings
Skia's avatar
Skia committed
16 17
from django.core.management import call_command
from django.db import connection
18
from django.forms import ValidationError
Skia's avatar
Skia committed
19
from django.core.files import File
Skia's avatar
Skia committed
20

Skia's avatar
Skia committed
21

Skia's avatar
Skia committed
22 23
from core.models import User, SithFile
from club.models import Club, Membership
24
from counter.models import Customer, Counter, Selling, Refilling, Product, ProductType, Permanency
Skia's avatar
Skia committed
25
from subscription.models import Subscription, Subscriber
26
from eboutic.models import Invoice, InvoiceItem
Skia's avatar
Skia committed
27 28 29 30 31 32 33 34

db = MySQLdb.connect(
        host="ae-db",
        user="taiste_rw",
        passwd=input("password: "),
        db="ae2-taiste",
        charset='utf8',
        use_unicode=True)
Skia's avatar
Skia committed
35 36 37 38 39 40

def reset_index(*args):
    sqlcmd = StringIO()
    call_command("sqlsequencereset", *args, stdout=sqlcmd)
    cursor = connection.cursor()
    cursor.execute(sqlcmd.getvalue())
Skia's avatar
Skia committed
41 42 43 44 45 46

def to_unicode(s):
    if s:
        return bytes(s, 'cp1252', errors="replace").decode('utf-8', errors='replace')
    return ""

Skia's avatar
Skia committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

def migrate_users():
    SEX = {'1': 'MAN', '2': 'WOMAN', None: 'MAN'}
    TSHIRT = {
            None: '-',
            '': '-',
            'NULL': '-',
            'XS': 'XS',
            'S': 'S',
            'M': 'M',
            'L': 'L',
            'XL': 'XL',
            'XXL': 'XXL',
            'XXXL': 'XXXL',
            }
    ROLE = {
            'doc': 'DOCTOR',
            'etu': 'STUDENT',
            'anc': 'FORMER STUDENT',
            'ens': 'TEACHER',
            'adm': 'ADMINISTRATIVE',
            'srv': 'SERVICE',
            'per': 'AGENT',
            None: '',
            }
    DEPARTMENTS = {
            'tc': 'TC',
            'gi': 'GI',
            'gesc': 'GESC',
            'na': 'NA',
            'mc': 'MC',
            'imap': 'IMAP',
            'huma': 'HUMA',
            'edim': 'EDIM',
            'ee': 'EE',
            'imsi': 'IMSI',
            'truc': 'NA',
            None: 'NA',
            }

    def get_random_free_email():
Skia's avatar
Skia committed
88
        email = "no_email_%s@git.an" % random.randrange(4000, 40000)
Skia's avatar
Skia committed
89 90 91 92
        while User.objects.filter(email=email).exists():
            email = "no_email_%s@git.an" % random.randrange(4000, 40000)
        return email

93
    c = db.cursor(MySQLdb.cursors.SSDictCursor)
Skia's avatar
Skia committed
94 95 96
    c.execute("""
    SELECT *
    FROM utilisateurs utl
Skia's avatar
Skia committed
97
    LEFT JOIN utl_etu ue
Skia's avatar
Skia committed
98
    ON ue.id_utilisateur = utl.id_utilisateur
Skia's avatar
Skia committed
99
    LEFT JOIN utl_etu_utbm ueu
Skia's avatar
Skia committed
100
    ON ueu.id_utilisateur = utl.id_utilisateur
Skia's avatar
Skia committed
101
    LEFT JOIN utl_extra uxtra
Skia's avatar
Skia committed
102
    ON uxtra.id_utilisateur = utl.id_utilisateur
Skia's avatar
Skia committed
103
    LEFT JOIN loc_ville ville
Skia's avatar
Skia committed
104
    ON utl.id_ville = ville.id_ville
105
    -- WHERE utl.id_utilisateur = 9360
Skia's avatar
Skia committed
106 107 108 109
    """)
    User.objects.filter(id__gt=0).delete()
    print("Users deleted")

Skia's avatar
Skia committed
110
    for u in c:
Skia's avatar
Skia committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        try:
            new = User(
                    id=u['id_utilisateur'],
                    last_name=to_unicode(u['nom_utl']) or "Bou",
                    first_name=to_unicode(u['prenom_utl']) or "Bi",
                    email=u['email_utl'],
                    second_email=u['email_utbm'] or "",
                    date_of_birth=u['date_naissance_utl'],
                    last_update=u['date_maj_utl'],
                    nick_name=to_unicode(u['surnom_utbm']),
                    sex=SEX[u['sexe_utl']],
                    tshirt_size=TSHIRT[u['taille_tshirt_utl']],
                    role=ROLE[u['role_utbm']],
                    department=DEPARTMENTS[u['departement_utbm']],
                    dpt_option=to_unicode(u['filiere_utbm']),
                    semester=u['semestre_utbm'] or 0,
                    quote=to_unicode(u['citation']),
                    school=to_unicode(u['nom_ecole_etudiant']),
                    promo=u['promo_utbm'] or 0,
                    forum_signature=to_unicode(u['signature_utl']),
                    address=(to_unicode(u['addresse_utl']) + ", " + to_unicode(u['cpostal_ville']) + " " + to_unicode(u['nom_ville'])),
                    parent_address=(to_unicode(u['adresse_parents']) + ", " + to_unicode(u['cpostal_parents']) + " " + to_unicode(u['ville_parents'])),
                    phone=u['tel_portable_utl'] or "",
                    parent_phone=u['tel_parents'] or "",
            )
            new.generate_username()
Skia's avatar
Skia committed
137
            new.save()
Skia's avatar
Skia committed
138 139 140 141 142 143 144 145
        except IntegrityError as e:
            if "Key (email)" in repr(e):
                new.email = get_random_free_email()
                new.save()
                print("New email generated")
            else:
                print("FAIL for user %s: %s" % (u['id_utilisateur'], repr(e)))
        except Exception as e:
Skia's avatar
Skia committed
146
            print("FAIL for user %s: %s" % (u['id_utilisateur'], repr(e)))
Skia's avatar
Skia committed
147
    c.close()
Skia's avatar
Skia committed
148

Skia's avatar
Skia committed
149 150
def migrate_profile_pict():
    PROFILE_ROOT = "/data/matmatronch/"
Skia's avatar
Skia committed
151

Skia's avatar
Skia committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    profile = SithFile.objects.filter(parent=None, name="profiles").first()
    profile.children.all().delete()
    print("Profiles pictures deleted")
    for filename in listdir(PROFILE_ROOT):
        if filename.split('.')[-2] != "mini":
            try:
                uid = filename.split('.')[0].split('-')[0]
                user = User.objects.filter(id=int(uid)).first()
                if user:
                    f = File(open(PROFILE_ROOT + '/' + filename, 'rb'))
                    f.name = f.name.split('/')[-1]
                    t = filename.split('.')[1]
                    new_file = SithFile(parent=profile, name=filename,
                            file=f, owner=user, is_folder=False, mime_type="image/jpeg", size=f.size)
                    if t == "identity":
                        new_file.save()
                        user.profile_pict = new_file
                        user.save()
                    elif t == "blouse":
                        new_file.save()
                        user.scrub_pict = new_file
                        user.save()
                    else:
                        new_file.save()
                        user.avatar_pict = new_file
                        user.save()
            except Exception as e:
                print(repr(e))

def migrate_clubs():
182
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
Skia's avatar
Skia committed
183 184 185 186 187 188 189 190 191 192 193
    cur.execute("""
    SELECT *
    FROM asso asso
    WHERE nom_unix_asso <> "ae"
        AND nom_unix_asso <> "bdf"
        AND nom_unix_asso <> "laverie"
    """)
    # club = cur.fetchone()
    # for k,v in club.items():
    #     print("%40s | %40s" % (k, v))

Skia's avatar
Skia committed
194
    for c in cur:
Skia's avatar
Skia committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208
        try:
            new = Club(
                    id=c['id_asso'],
                    name=to_unicode(c['nom_asso']),
                    unix_name=to_unicode(c['nom_unix_asso']),
                    address=to_unicode(c['adresse_postale']),
                    )
            new.save()
        except Exception as e:
                print("FAIL for club %s: %s" % (c['nom_unix_asso'], repr(e)))
    cur.execute("""
    SELECT *
    FROM asso
    """)
Skia's avatar
Skia committed
209
    for c in cur:
Skia's avatar
Skia committed
210 211 212 213 214 215 216
        club = Club.objects.filter(id=c['id_asso']).first()
        parent = Club.objects.filter(id=c['id_asso_parent']).first()
        club.parent = parent
        club.save()
    cur.close()

def migrate_club_memberships():
217
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
Skia's avatar
Skia committed
218 219 220 221 222 223 224
    cur.execute("""
    SELECT *
    FROM asso_membre
    """)

    Membership.objects.all().delete()
    print("Memberships deleted")
Skia's avatar
Skia committed
225
    for m in cur:
Skia's avatar
Skia committed
226
        try:
Skia's avatar
Skia committed
227 228 229 230 231 232 233 234 235 236 237 238
            club = Club.objects.filter(id=m['id_asso']).first()
            user = User.objects.filter(id=m['id_utilisateur']).first()
            if club and user:
                new = Membership(
                        club=club,
                        user=user,
                        start_date=m['date_debut'],
                        end_date=m['date_fin'],
                        role=m['role'],
                        description=to_unicode(m['desc_role']),
                        )
                new.save()
Skia's avatar
Skia committed
239
        except Exception as e:
Skia's avatar
Skia committed
240 241 242
                print("FAIL for club membership %s: %s" % (m['id_asso'], repr(e)))
    cur.close()

Skia's avatar
Skia committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
def migrate_subscriptions():
    LOCATION = {
            5: "SEVENANS",
            6: "BELFORT",
            9: "MONTBELIARD",
            None: "SEVENANS",
            }
    TYPE = {
            0: 'un-semestre',
            1: 'deux-semestres',
            2: 'cursus-tronc-commun',
            3: 'cursus-branche',
            4: 'membre-honoraire',
            5: 'assidu',
            6: 'amicale/doceo',
            7: 'reseau-ut',
            8: 'crous',
            9: 'sbarro/esta',
            10: 'cursus-alternant',
            None: 'un-semestre',
            }
    PAYMENT = {
            1: "CHECK",
            2: "CARD",
            3: "CASH",
            4: "OTHER",
            5: "EBOUTIC",
            0: "OTHER",
            }
272
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
Skia's avatar
Skia committed
273 274 275 276 277 278 279 280 281
    cur.execute("""
    SELECT *
    FROM ae_cotisations
    """)

    Subscription.objects.all().delete()
    print("Subscriptions deleted")
    Customer.objects.all().delete()
    print("Customers deleted")
Skia's avatar
Skia committed
282
    for r in cur:
Skia's avatar
Skia committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        try:
            user = Subscriber.objects.filter(id=r['id_utilisateur']).first()
            if user:
                new = Subscription(
                        id=r['id_cotisation'],
                        member=user,
                        subscription_start=r['date_cotis'],
                        subscription_end=r['date_fin_cotis'],
                        subscription_type=TYPE[r['type_cotis']],
                        payment_method=PAYMENT[r['mode_paiement_cotis']],
                        location=LOCATION[r['id_comptoir']],
                        )
                new.save()
        except Exception as e:
                print("FAIL for subscription %s: %s" % (r['id_cotisation'], repr(e)))
    cur.close()

def update_customer_account():
301
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
Skia's avatar
Skia committed
302 303 304 305 306 307
    cur.execute("""
    SELECT *
    FROM ae_carte carte
    JOIN ae_cotisations cotis
    ON carte.id_cotisation = cotis.id_cotisation
    """)
Skia's avatar
Skia committed
308
    for r in cur:
Skia's avatar
Skia committed
309 310 311 312 313 314 315 316
        try:
            user = Customer.objects.filter(user_id=r['id_utilisateur']).first()
            if user:
                user.account_id = str(r['id_carte_ae']) + r['cle_carteae'].lower()
                user.save()
        except Exception as e:
                print("FAIL to update customer account for %s: %s" % (r['id_cotisation'], repr(e)))
    cur.close()
Skia's avatar
Skia committed
317

318 319 320 321 322 323 324
def migrate_counters():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_comptoir
    """)
    Counter.objects.all().delete()
Skia's avatar
Skia committed
325
    for r in cur:
326 327 328 329 330 331 332 333 334 335 336 337
        try:
            club = Club.objects.filter(id=r['id_assocpt']).first()
            new = Counter(
                    id=r['id_comptoir'],
                    name=to_unicode(r['nom_cpt']),
                    club=club,
                    type="OFFICE",
                    )
            new.save()
        except Exception as e:
                print("FAIL to migrate counter %s: %s" % (r['id_comptoir'], repr(e)))
    cur.close()
Skia's avatar
Skia committed
338 339 340
    eboutic = Counter.objects.filter(id=3).first()
    eboutic.type = "EBOUTIC"
    eboutic.save()
341

Skia's avatar
Skia committed
342 343 344 345 346 347 348 349 350
def reset_customer_amount():
    Refilling.objects.all().delete()
    Selling.objects.all().delete()
    Invoice.objects.all().delete()
    for c in Customer.objects.all():
        c.amount = 0
        c.save()
    print("Customer amount reset")

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
def migrate_refillings():
    BANK = {
            0: "OTHER",
            1: "SOCIETE-GENERALE",
            2: "BANQUE-POPULAIRE",
            3: "BNP",
            4: "CAISSE-EPARGNE",
            5: "CIC",
            6: "CREDIT-AGRICOLE",
            7: "CREDIT-MUTUEL",
            8: "CREDIT-LYONNAIS",
            9: "LA-POSTE",
            100: "OTHER",
            None: "OTHER",
            }
366 367 368 369 370
    PAYMENT = {
            2: "CARD",
            1: "CASH",
            0: "CHECK",
            }
371 372 373 374 375 376 377
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_rechargements
    """)
    root_cust = Customer.objects.filter(user__id=0).first()
    mde = Counter.objects.filter(id=1).first()
378 379 380 381 382 383
    threshold_date = datetime.datetime(year=2006, month=3, day=21, hour=22, minute=17)
    Refilling.objects.filter(payment_method="CASH").delete()
    Refilling.objects.filter(payment_method="CHECK").delete()
    Refilling.objects.filter(date__lte=threshold_date.replace(tzinfo=timezone('Europe/Paris'))).delete()
    print("Sith account refillings deleted")
    fail = 100
Skia's avatar
Skia committed
384
    for r in cur:
385 386
        if r['type_paiement_rech'] == 2 and r['date_rech'] > threshold_date:
            continue # There are no invoices before threshold_date when paid with credit card
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        try:
            cust = Customer.objects.filter(user__id=r['id_utilisateur']).first()
            user = User.objects.filter(id=r['id_utilisateur']).first()
            if not cust:
                if not user:
                    cust = root_cust
                else:
                    cust = Customer(user=user, amount=0, account_id=Customer.generate_account_id(fail))
                    cust.save()
                    fail += 1
            op = User.objects.filter(id=r['id_utilisateur_operateur']).first()
            counter = Counter.objects.filter(id=r['id_comptoir']).first()
            new = Refilling(
                    id=r['id_rechargement'],
                    counter=counter or mde,
Skia's avatar
Skia committed
402
                    customer=cust or root_cust,
403 404
                    operator=op or root_cust.user,
                    amount=r['montant_rech']/100,
405
                    payment_method=PAYMENT[r['type_paiement_rech']],
406
                    bank=BANK[r['banque_rech']],
407
                    date=r['date_rech'].replace(tzinfo=timezone('Europe/Paris')),
408 409 410 411 412 413 414 415 416 417 418 419 420 421
                    )
            new.save()
        except Exception as e:
                print("FAIL to migrate refilling %s for %s: %s" % (r['id_rechargement'], r['id_utilisateur'], repr(e)))
    cur.close()

def migrate_typeproducts():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_type_produit
    """)
    ProductType.objects.all().delete()
    print("Product types deleted")
Skia's avatar
Skia committed
422
    for r in cur:
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        try:
            new = ProductType(
                    id=r['id_typeprod'],
                    name=to_unicode(r['nom_typeprod']),
                    description=to_unicode(r['description_typeprod']),
                    )
            new.save()
        except Exception as e:
                print("FAIL to migrate product type %s: %s" % (r['nom_typeprod'], repr(e)))
    cur.close()

def migrate_products():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_produits
    """)
    Product.objects.all().delete()
    print("Product deleted")
Skia's avatar
Skia committed
442
    for r in cur:
443 444 445 446 447 448 449 450 451
        try:
            type = ProductType.objects.filter(id=r['id_typeprod']).first()
            club = Club.objects.filter(id=r['id_assocpt']).first()
            new = Product(
                    id=r['id_produit'],
                    product_type=type,
                    name=to_unicode(r['nom_prod']),
                    description=to_unicode(r['description_prod']),
                    code=to_unicode(r['cbarre_prod']),
452 453 454
                    purchase_price=r['prix_achat_prod']/100,
                    selling_price=r['prix_vente_prod']/100,
                    special_selling_price=r['prix_vente_barman_prod']/100,
455
                    club=club,
456 457
                    limit_age=r['mineur'] or 0,
                    tray=bool(r['plateau']),
458 459 460 461 462 463
                    )
            new.save()
        except Exception as e:
                print("FAIL to migrate product %s: %s" % (r['nom_prod'], repr(e)))
    cur.close()

Skia's avatar
Skia committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
def migrate_product_pict():
    FILE_ROOT = "/data/files/"

    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_produits
    WHERE id_file IS NOT NULL
    """)
    for r in cur:
        print(r['nom_prod'])
        try:
            prod = Product.objects.filter(id=r['id_produit']).first()
            if prod:
                f = File(open(FILE_ROOT + '/' + str(r['id_file']) + ".1", 'rb'))
                f.name = prod.name
                prod.icon = f
                prod.save()
        except Exception as e:
            print(repr(e))

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 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
def migrate_products_to_counter():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_mise_en_vente
    """)
    for r in cur:
        try:
            product = Product.objects.filter(id=r['id_produit']).first()
            counter = Counter.objects.filter(id=r['id_comptoir']).first()
            counter.products.add(product)
            counter.save()
        except Exception as e:
                print("FAIL to set product %s in counter %s: %s" % (product, counter, repr(e)))
    cur.close()

def migrate_invoices():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_vendu ven
    LEFT JOIN cpt_debitfacture fac
    ON ven.id_facture = fac.id_facture
    WHERE fac.mode_paiement = 'SG'
    """)
    Invoice.objects.all().delete()
    print("Invoices deleted")
    Refilling.objects.filter(payment_method="CARD").delete()
    print("Card refillings deleted")
    Selling.objects.filter(payment_method="CARD").delete()
    print("Card sellings deleted")
    root = User.objects.filter(id=0).first()
    for r in cur:
        try:
            product = Product.objects.filter(id=r['id_produit']).first()
            user = User.objects.filter(id=r['id_utilisateur_client']).first()
            i = Invoice.objects.filter(id=r['id_facture']).first() or Invoice(id=r['id_facture'])
            i.user = user or root
            for f in i._meta.local_fields:
                if f.name == "date":
                    f.auto_now = False
            i.date = r['date_facture'].replace(tzinfo=timezone('Europe/Paris'))
            i.save()
            InvoiceItem(invoice=i, product_id=product.id, product_name=product.name, type_id=product.product_type.id,
                    product_unit_price=r['prix_unit']/100, quantity=r['quantite']).save()
        except ValidationError as e:
            print(repr(e) + " for %s (%s)" % (customer, customer.user.id))
        except Exception as e:
            print("FAIL to migrate invoice %s: %s" % (r['id_facture'], repr(e)))
    cur.close()
    for i in Invoice.objects.all():
        for f in i._meta.local_fields:
            if f.name == "date":
                f.auto_now = False
        i.validate()

541 542 543 544 545 546 547 548 549
def migrate_sellings():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_vendu ven
    LEFT JOIN cpt_debitfacture fac
    ON ven.id_facture = fac.id_facture
    WHERE fac.mode_paiement = 'AE'
    """)
550 551
    Selling.objects.filter(payment_method="SITH_ACCOUNT").delete()
    print("Sith account selling deleted")
552 553 554 555
    for c in Customer.objects.all():
        c.amount = sum([r.amount for r in c.refillings.all()])
        c.save()
    print("Customer amount reset to sum of refillings")
Skia's avatar
Skia committed
556 557 558 559
    ae = Club.objects.filter(unix_name="ae").first()
    mde = Counter.objects.filter(id=1).first()
    root = User.objects.filter(id=0).first()
    beer = Product.objects.filter(id=1).first()
560 561
    for r in cur:
        try:
Skia's avatar
Skia committed
562 563 564 565 566
            product = Product.objects.filter(id=r['id_produit']).first() or beer
            club = Club.objects.filter(id=r['id_assocpt']).first() or ae
            counter = Counter.objects.filter(id=r['id_comptoir']).first() or mde
            op = User.objects.filter(id=r['id_utilisateur']).first() or root
            customer = Customer.objects.filter(user__id=r['id_utilisateur_client']).first() or root.customer
567
            new = Selling(
Skia's avatar
Skia committed
568
                    label=product.name or "Produit inexistant",
569 570 571 572 573 574 575
                    counter=counter,
                    club=club,
                    product=product,
                    seller=op,
                    customer=customer,
                    unit_price=r['prix_unit']/100,
                    quantity=r['quantite'],
576 577
                    payment_method="SITH_ACCOUNT",
                    date=r['date_facture'].replace(tzinfo=timezone('Europe/Paris')),
578 579 580
                    )
            new.save()
        except ValidationError as e:
Skia's avatar
Skia committed
581
            print(repr(e) + " for %s (%s)" % (customer, customer.user.id))
582 583 584 585
        except Exception as e:
            print("FAIL to migrate selling %s: %s" % (r['id_facture'], repr(e)))
    cur.close()

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
def migrate_permanencies():
    cur = db.cursor(MySQLdb.cursors.SSDictCursor)
    cur.execute("""
    SELECT *
    FROM cpt_tracking
    """)
    Permanency.objects.all().delete()
    print("Permanencies deleted")
    for r in cur:
        try:
            counter = Counter.objects.filter(id=r['id_comptoir']).first()
            user = User.objects.filter(id=r['id_utilisateur']).first()
            new = Permanency(
                    user=user,
                    counter=counter,
                    start=r['logged_time'].replace(tzinfo=timezone('Europe/Paris')),
                    end=r['closed_time'].replace(tzinfo=timezone('Europe/Paris')),
                    )
            new.save()
        except Exception as e:
            print("FAIL to migrate permanency: %s" % (repr(e)))
    cur.close()
608

Skia's avatar
Skia committed
609
def main():
Skia's avatar
Skia committed
610 611 612 613 614 615 616 617 618
    migrate_users()
    migrate_profile_pict()
    migrate_clubs()
    migrate_club_memberships()
    migrate_subscriptions()
    update_customer_account()
    migrate_counters()
    migrate_permanencies()
    migrate_typeproducts()
619
    migrate_products()
Skia's avatar
Skia committed
620
    migrate_product_pict()
621
    migrate_products_to_counter()
Skia's avatar
Skia committed
622
    reset_customer_amount()
Skia's avatar
Skia committed
623
    migrate_refillings()
Skia's avatar
Skia committed
624
    reset_index('counter')
625
    migrate_invoices()
Skia's avatar
Skia committed
626
    migrate_sellings()
627
    reset_index('core', 'club', 'subscription', 'accounting', 'eboutic', 'launderette', 'counter')
Skia's avatar
Skia committed
628

Skia's avatar
Skia committed
629 630
if __name__ == "__main__":
    main()