django.db.utils.IntegrityError

Here are the examples of the python api django.db.utils.IntegrityError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

76 Examples 7

3 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_content_type_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')

        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=None,
                object_id=europe.pk,
                field='name',
                language='de',
                text='Europa',
            )

        self.assertEqual(
            error.exception.args[0],
            ('NOT NULL constraint failed: translations_translation' +
             '.content_type_id'),
        )

    def test_object_id_none(self):

3 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_object_id_none(self):
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=None,
                field='name',
                language='de',
                text='Europa',
            )

        self.assertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.object_id',
        )

    def test_content_object_none(self):

3 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_content_object_none(self):
        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_object=None,
                field='name',
                language='de',
                text='Europa',
            )

        self.assertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.object_id',
        )

    def test_field_none(self):

3 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_field_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field=None,
                language='de',
                text='Europa',
            )

        self.assertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.field',
        )

    def test_language_none(self):

3 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_language_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field='name',
                language=None,
                text='Europa',
            )

        self.assertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.language',
        )

    def test_text_none(self):

3 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_text_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field='name',
                language='de',
                text=None,
            )

        self.assertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.text',
        )

    def test_str(self):

3 Source : base.py
with MIT License
from chunky2808

    def execute(self, query, args=None):
        try:
            # args is None means no string interpolation
            return self.cursor.execute(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

    def executemany(self, query, args):

3 Source : base.py
with MIT License
from chunky2808

    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

    def __getattr__(self, attr):

3 Source : base.py
with Apache License 2.0
from lumanjiao

    def execute(self, query, params=None):
        query, params = self._fix_for_params(query, params)
        self._guess_input_sizes([params])
        try:
            return self.cursor.execute(query, self._param_generator(params))
        except Database.DatabaseError as e:
            # cx_Oracle   <  = 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

    def executemany(self, query, params=None):

3 Source : models.py
with MIT License
from PacktPublishing

    def clean(self):
        super().clean(self)
        if self.bookmark is None:
            if self.comment is None:
                raise IntegrityError(
                    'A like must be made to either a bookmark or a comment'
                )
        elif self.comment is not None:
            raise IntegrityError(
                'A like cannot be made to both a bookmark and a comment'
            )

3 Source : models.py
with MIT License
from PacktPublishing

    def clean(self):
        super().clean(self)
        if self.bookmark is None:
            if self.comment is None:
                raise IntegrityError('A like must be made to either a bookmark or a comment')
        elif self.comment is not None:
            raise IntegrityError('A like cannot be made to both a bookmark and a comment')

3 Source : test_report_downloader_base.py
with Apache License 2.0
from project-koku

    def test_process_manifest_db_record_race_no_provider(self, mock_get_manifest):
        """Test that the _process_manifest_db_record returns the correct manifest during a race for initial entry."""
        mock_get_manifest.side_effect = [None, None]
        side_effect_error = IntegrityError(
            """insert or update on table "reporting_awscostentrybill" violates foreign key constraint "reporting_awscostent_provider_id_a08725b3_fk_api_provi"
DETAIL:  Key (provider_id)=(fbe0593a-1b83-4182-b23e-08cd190ed939) is not present in table "api_provider".
"""  # noqa
        )  # noqa
        with patch.object(ReportManifestDBAccessor, "add", side_effect=side_effect_error):
            downloader = ReportDownloaderBase(provider_uuid=self.unkown_test_provider_uuid, cache_key=self.cache_key)
            with self.assertRaises(ReportDownloaderError):
                downloader._process_manifest_db_record(self.assembly_id, self.billing_start, 2, DateAccessor().today())

    def test_process_manifest_db_record_file_num_changed(self):

0 Source : base.py
with GNU General Public License v3.0
from Aghoreshwar

    def check_constraints(self, table_names=None):
        """
        Check each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint
        checks were off.

        Raise an IntegrityError on the first invalid foreign key reference
        encountered (if any) and provide detailed information about the
        invalid reference in the error message.

        Backends can override this method if they can more directly apply
        constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
        """
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor, table_name)
            for column_name, referenced_table_name, referenced_column_name in key_columns:
                cursor.execute(
                    """
                    SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                    LEFT JOIN `%s` as REFERRED
                    ON (REFERRING.`%s` = REFERRED.`%s`)
                    WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
                    """ % (
                        primary_key_column_name, column_name, table_name,
                        referenced_table_name, column_name, referenced_column_name,
                        column_name, referenced_column_name,
                    )
                )
                for bad_row in cursor.fetchall():
                    raise utils.IntegrityError(
                        "The row in table '%s' with primary key '%s' has an invalid "
                        "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
                        % (
                            table_name, bad_row[0], table_name, column_name,
                            bad_row[1], referenced_table_name, referenced_column_name,
                        )
                    )

    def is_usable(self):

0 Source : base.py
with GNU General Public License v3.0
from Aghoreshwar

    def check_constraints(self, table_names=None):
        """
        Check each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint
        checks were off.

        Raise an IntegrityError on the first invalid foreign key reference
        encountered (if any) and provide detailed information about the
        invalid reference in the error message.

        Backends can override this method if they can more directly apply
        constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
        """
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor, table_name)
            for column_name, referenced_table_name, referenced_column_name in key_columns:
                cursor.execute(
                    """
                    SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                    LEFT JOIN `%s` as REFERRED
                    ON (REFERRING.`%s` = REFERRED.`%s`)
                    WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
                    """
                    % (
                        primary_key_column_name, column_name, table_name,
                        referenced_table_name, column_name, referenced_column_name,
                        column_name, referenced_column_name,
                    )
                )
                for bad_row in cursor.fetchall():
                    raise utils.IntegrityError(
                        "The row in table '%s' with primary key '%s' has an "
                        "invalid foreign key: %s.%s contains a value '%s' that "
                        "does not have a corresponding value in %s.%s." % (
                            table_name, bad_row[0], table_name, column_name,
                            bad_row[1], referenced_table_name, referenced_column_name,
                        )
                    )

    def is_usable(self):

0 Source : test_models.py
with BSD 3-Clause "New" or "Revised" License
from bbmokhtari

    def test_uniqueness(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)
        Translation.objects.create(
            content_type=continent_ct,
            object_id=europe.pk,
            field='name',
            language='de',
            text='Europa'
        )

        with self.assertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field='name',
                language='de',
                text='Europa'
            )

        self.assertEqual(
            error.exception.args[0],
            ('UNIQUE constraint failed: ' +
             'translations_translation.content_type_id, ' +
             'translations_translation.object_id, ' +
             'translations_translation.field, ' +
             'translations_translation.language'),
        )


class TranslatableTest(TestCase):

0 Source : base.py
with GNU General Public License v2.0
from CastagnaIT

    def check_constraints(self, table_names=None):
        """Check rows in tables for invalid foreign key references

        Checks each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while
        constraint checks were off.

        Raises an IntegrityError on the first invalid foreign key reference
        encountered (if any) and provides detailed information about the
        invalid reference in the error message.

        Backends can override this method if they can more directly apply
        constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
        """
        ref_query = """
            SELECT REFERRING.`{0}`, REFERRING.`{1}` FROM `{2}` as REFERRING
            LEFT JOIN `{3}` as REFERRED
            ON (REFERRING.`{4}` = REFERRED.`{5}`)
            WHERE REFERRING.`{6}` IS NOT NULL AND REFERRED.`{7}` IS NULL"""
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = \
                self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor,
                                                             table_name)
            for column_name, referenced_table_name, referenced_column_name \
                    in key_columns:
                cursor.execute(ref_query.format(primary_key_column_name,
                                                column_name, table_name,
                                                referenced_table_name,
                                                column_name,
                                                referenced_column_name,
                                                column_name,
                                                referenced_column_name))
                for bad_row in cursor.fetchall():
                    msg = ("The row in table '{0}' with primary key '{1}' has "
                           "an invalid foreign key: {2}.{3} contains a value "
                           "'{4}' that does not have a corresponding value in "
                           "{5}.{6}.".format(table_name, bad_row[0],
                                             table_name, column_name,
                                             bad_row[1], referenced_table_name,
                                             referenced_column_name))
                    raise utils.IntegrityError(msg)

    def _rollback(self):

0 Source : base.py
with MIT License
from chunky2808

    def check_constraints(self, table_names=None):
        """
        Checks each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint
        checks were off.

        Raises an IntegrityError on the first invalid foreign key reference
        encountered (if any) and provides detailed information about the
        invalid reference in the error message.

        Backends can override this method if they can more directly apply
        constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
        """
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor, table_name)
            for column_name, referenced_table_name, referenced_column_name in key_columns:
                cursor.execute(
                    """
                    SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                    LEFT JOIN `%s` as REFERRED
                    ON (REFERRING.`%s` = REFERRED.`%s`)
                    WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
                    """ % (
                        primary_key_column_name, column_name, table_name,
                        referenced_table_name, column_name, referenced_column_name,
                        column_name, referenced_column_name,
                    )
                )
                for bad_row in cursor.fetchall():
                    raise utils.IntegrityError(
                        "The row in table '%s' with primary key '%s' has an invalid "
                        "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
                        % (
                            table_name, bad_row[0], table_name, column_name,
                            bad_row[1], referenced_table_name, referenced_column_name,
                        )
                    )

    def is_usable(self):

0 Source : base.py
with MIT License
from chunky2808

    def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.DatabaseError as e:
                # cx_Oracle raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
                raise

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends.
    def _savepoint_commit(self, sid):

0 Source : base.py
with MIT License
from chunky2808

    def check_constraints(self, table_names=None):
        """
        Checks each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint
        checks were off.

        Raises an IntegrityError on the first invalid foreign key reference
        encountered (if any) and provides detailed information about the
        invalid reference in the error message.

        Backends can override this method if they can more directly apply
        constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
        """
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor, table_name)
            for column_name, referenced_table_name, referenced_column_name in key_columns:
                cursor.execute(
                    """
                    SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                    LEFT JOIN `%s` as REFERRED
                    ON (REFERRING.`%s` = REFERRED.`%s`)
                    WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
                    """
                    % (
                        primary_key_column_name, column_name, table_name,
                        referenced_table_name, column_name, referenced_column_name,
                        column_name, referenced_column_name,
                    )
                )
                for bad_row in cursor.fetchall():
                    raise utils.IntegrityError(
                        "The row in table '%s' with primary key '%s' has an "
                        "invalid foreign key: %s.%s contains a value '%s' that "
                        "does not have a corresponding value in %s.%s." % (
                            table_name, bad_row[0], table_name, column_name,
                            bad_row[1], referenced_table_name, referenced_column_name,
                        )
                    )

    def is_usable(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_auth_user(self):
        """
        Fetch auth users and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        # Import all users, as also business accounts might have cards or subscriptions attached to them
        query = "SELECT * FROM auth_user WHERE id > 1"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map_auth_user = {}
        id_map_auth_user_teacher_profile = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            os_file = None
            if record.get('picture', None):
                os_file = os.path.join(self.os_media_root, record['picture'])

            try:
                account = m.Account(
                    is_active=not self._web2py_bool_to_python(record['trashed']), # We need to invert this
                    customer=self._web2py_bool_to_python(record['customer']),
                    instructor=self._web2py_bool_to_python(record['teacher']),
                    employee=self._web2py_bool_to_python(record['teacher']),
                    first_name=record['first_name'],
                    last_name=record['last_name'],
                    full_name=record['full_name'] or "",
                    email=record['email'],
                    username=record['email'],
                    gender=record['gender'] or "",
                    date_of_birth=record['date_of_birth'] or "",
                    address=record['address'] or "",
                    postcode=record['postcode'] or "",
                    city=record['city'] or "",
                    country=record['country'] or "",
                    phone=record['phone'] or "",
                    mobile=record['mobile'] or "",
                    emergency=record['emergency'] or "",
                    key_number=record['keynr'] or "",
                    organization_discovery=self.school_discovery_map.get(record['school_discovery_id'], None),
                    organization_language=self.school_languages_map.get(record['school_languages_id'], None),
                )
                account.save()

                # Try to import picture
                try:
                    with open(os_file, 'rb') as fh:
                        # Get the content of the file, we also need to close the content file
                        with ContentFile(fh.read()) as file_content:
                            # Set the media attribute of the article, but under an other path/filename
                            account.image.save(record['picture'], file_content)
                except FileNotFoundError:
                    logging.error("Could not locate auth_user picture: %s" % os_file)
                except TypeError:
                    pass

                # Create allauth email
                account.create_allauth_email()

                # Create instructor profile
                self._import_auth_user_create_instructor_profile(account, record)

                # Create account bank account record
                account.create_bank_account()

                id_map_auth_user[record['id']] = account

                records_imported += 1
            except django.db.utils.IntegrityError as e:
                logging.error("Import auth_user error for user id: %s %s : %s" % (
                    record['id'],
                    record['email'],
                    e
                ))

        log_message = "Import auth_user: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return {
            'id_map_auth_user': id_map_auth_user,
        }

    def _import_auth_user_business(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_classcards(self):
        """
        Fetch customer classcards and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * from customers_classcards"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_classpass = m.AccountClasspass(
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    organization_classpass=self.school_classcards_map.get(record['school_classcards_id']),
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    note=record['note'] or "",
                    classes_remaining=0
                )
                account_classpass.save()
                records_imported += 1
                id_map[record['id']] = account_classpass

            except django.db.utils.IntegrityError as e:
                logging.error("Import customer classcard error for user id: %s classcard id: %s : %s" % (
                    record['auth_customer_id'],
                    record['id'],
                    e
                ))

        log_message = "Import customer class cards: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_subscriptions(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_subscriptions(self):
        """
        Fetch customer subscriptins and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * from customers_subscriptions"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_subscription = m.AccountSubscription(
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    organization_subscription=self.school_subscriptions_map.get(record['school_subscriptions_id'], None),
                    finance_payment_method=self.payment_methods_map.get(record['payment_methods_id'], None),
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    note=record['note'] or "",
                    registration_fee_paid=self._web2py_bool_to_python(record['registrationfeepaid'])
                )
                account_subscription.save()
                records_imported += 1
                id_map[record['id']] = account_subscription

            except django.db.utils.IntegrityError as e:
                logging.error("Import customer subscription error for user id: %s subscription id: %s : %s" % (
                    record['auth_customer_id'],
                    record['id'],
                    e
                ))

        log_message = "Import customer subscriptions: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_subscriptions_alt_prices(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_subscriptions_alt_prices(self):
        """
        Fetch customer subscriptions alt prices and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM customers_subscriptions_alt_prices"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_subscription_alt_price = m.AccountSubscriptionAltPrice(
                    account_subscription=self.customers_subscriptions_map.get(record['customers_subscriptions_id'],
                                                                              None),
                    subscription_year=record['subscriptionyear'],
                    subscription_month=record['subscriptionmonth'],
                    amount=record['amount'],
                    description=record['description'] or "",
                    note=record['note'] or ""
                )
                account_subscription_alt_price.save()
                records_imported += 1

                id_map[record['id']] = account_subscription_alt_price

            except django.db.utils.IntegrityError as e:
                logging.error("Import customer subscription alt price error subscription alt price id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import customer subscriptions alt prices: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_subscriptions_blocks(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_subscriptions_blocks(self):
        """
        Fetch customer subscriptions blocks and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM customers_subscriptions_blocked"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_subscription_block = m.AccountSubscriptionBlock(
                    account_subscription=self.customers_subscriptions_map.get(record['customers_subscriptions_id'], None),
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    description=record['description'] or "",
                )
                account_subscription_block.save()
                records_imported += 1

                id_map[record['id']] = account_subscription_block
            except django.db.utils.IntegrityError as e:
                logging.error("Import customer subscription block error for subscription id: %s : %s: %s" % (
                    record['customers_subscriptions_id'],
                    record['id'],
                    e
                ))

        log_message = "Import customer subscriptions block: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_subscriptions_pauses(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_subscriptions_pauses(self):
        """
        Fetch customer subscriptions pauses and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM customers_subscriptions_paused"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_subscription_pause = m.AccountSubscriptionPause(
                    account_subscription=self.customers_subscriptions_map.get(record['customers_subscriptions_id'], None),
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    description=record['description'] or "",
                )
                account_subscription_pause.save()
                records_imported += 1

                id_map[record['id']] = account_subscription_pause
            except django.db.utils.IntegrityError as e:
                logging.error("Import customer subscription pause error for subscription id: %s : %s: %s" % (
                    record['customers_subscriptions_id'],
                    record['id'],
                    e
                ))

        log_message = "Import customer subscriptions pause: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_notes(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_notes(self):
        """
        Fetch customer notes and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * from customers_notes"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            note_type = "BACKOFFICE"
            if record['instructornote'] == "T":
                note_type = "INSTRUCTORS"

            try:
                account_note = m.AccountNote(
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    note_by=self.auth_user_map.get(record['auth_user_id'], None),
                    note_type=note_type,
                    note=record['note'] or "",
                    injury=self._web2py_bool_to_python(record['injury']),
                    processed=self._web2py_bool_to_python(record['processed']),
                )
                account_note.save()
                records_imported += 1

                id_map[record['id']] = account_note
            except django.db.utils.IntegrityError as e:
                logging.error("Import customer note error for user id: %s note id: %s : %s" % (
                    record['auth_customer_id'],
                    record['id'],
                    e
                ))

        log_message = "Import customers notes: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_documents(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_payment_mandates(self):
        """
        Fetch customers payment info mandates and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM customers_payment_info_mandates"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                content = ""
                if record['mandatetext']:
                    content = record['mandatetext'][:250]

                account_bank_account_mandate = m.AccountBankAccountMandate(
                    account_bank_account=self.customers_payment_info_map.get(record['customers_payment_info_id'], None),
                    reference=record['mandatereference'] or "",
                    content=content,
                    signature_date=record['mandatesignaturedate']
                )
                account_bank_account_mandate.save()
                records_imported += 1

                id_map[record['id']] = account_bank_account_mandate
            except django.db.utils.IntegrityError as e:
                logging.error("Import customer payment info mandate error for payment info id: %s note id: %s : %s" % (
                    record['customers_payment_info_id'],
                    record['id'],
                    e
                ))

        log_message = "Import customers payment info (bank accounts) mandates: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_classes(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_classes(self):
        """
        Fetch classes and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT cla.*, clm.* FROM classes cla LEFT JOIN classes_mail clm ON cla.id = clm.classes_id"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_item = m.ScheduleItem(
                    schedule_event=None,
                    schedule_item_type="CLASS",
                    frequency_type="WEEKLY",
                    frequency_interval=record['week_day'],
                    organization_location_room=self.school_locations_rooms_map.get(record['school_locations_id'], None),
                    organization_classtype=self.school_classtypes_map.get(record['school_classtypes_id'], None),
                    organization_level=self.school_levels_map.get(record['school_levels_id'], None),
                    spaces=record['maxstudents'],
                    walk_in_spaces=record['walkinspaces'],
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    time_start=str(record['starttime']),
                    time_end=str(record['endtime']),
                    display_public=self._web2py_bool_to_python(record['allowapi']),
                    info_mail_content=record['mailcontent'] or ""
                )
                schedule_item.save()
                records_imported += 1

                id_map[record['id']] = schedule_item
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import classes: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_classes_attendance(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_classes_attendance(self):
        """
        Fetch classes attendance and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM classes_attendance"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_item_attendance = m.ScheduleItemAttendance(
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    schedule_item=self.classes_map.get(record['classes_id'], None),
                    account_classpass=self.customers_classcards_map.get(record['customers_classcards_id'], None),
                    account_subscription=self.customers_subscriptions_map.get(record['customers_subscriptions_id'],
                                                                              None),
                    finance_invoice_item=None,
                    # Set to True when account has membership at time of check-in
                    attendance_type=self.map_attendance_types.get(record['attendancetype'], None),
                    date=record['classdate'],
                    online_booking=self._web2py_bool_to_python(record['online_booking']),
                    booking_status=self.map_booking_statuses.get(record['bookingstatus'])
                )
                schedule_item_attendance.save()
                records_imported += 1

                id_map[record['id']] = schedule_item_attendance
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class attendance: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import classes attendance: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_classes_otc(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_classes_otc(self):
        """
        Fetch classes and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM classes_otc"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                startime = None
                endtime = None
                if record['starttime']:
                    startime = str(record['starttime'])
                if record['endtime']:
                    endtime = str(record['endtime'])

                schedule_item_weekly_otc = m.ScheduleItemWeeklyOTC(
                    schedule_item=self.classes_map.get(record['classes_id'], None),
                    date=record['classdate'],
                    status=self.map_classes_otc_statuses.get(record['status'], ""),
                    description=record['description'] or '',
                    account=self.auth_user_map.get(record['auth_teacher_id'], None),
                    role=self.map_classes_instructor_roles.get(record['teacher_role'], ""),
                    account_2=self.auth_user_map.get(record['auth_teacher_id2'], None),
                    role_2=self.map_classes_instructor_roles.get(record['teacher_role2'], ""),
                    organization_location_room=self.school_locations_rooms_map.get(record['school_locations_id'], None),
                    organization_classtype=self.school_classtypes_map.get(record['school_classtypes_id'], None),
                    time_start=startime,
                    time_end=endtime,
                    spaces=record['maxstudents'] or None,
                    walk_in_spaces=record['walkinspaces'] or None,
                    info_mail_content=""
                )
                schedule_item_weekly_otc.save()
                records_imported += 1

                id_map[record['id']] = schedule_item_weekly_otc
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class otc id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import classes otc: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_classes_otc_mail(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_classes_school_classcards_groups(self):
        """
        Fetch classes school classcards groups and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM classes_school_classcards_groups"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                siocg = m.ScheduleItemOrganizationClasspassGroup(
                    schedule_item=self.classes_map.get(record['classes_id'], None),
                    organization_classpass_group=self.school_classcards_groups_map.get(
                        record['school_classcards_groups_id'], None),
                    shop_book=self._web2py_bool_to_python(record['shopbook']),
                    attend=self._web2py_bool_to_python(record['attend'])
                )
                siocg.save()
                records_imported += 1

                id_map[record['id']] = siocg
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class school classcards group id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import classes school classcards groups: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_classes_school_subscriptions_groups(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_classes_school_subscriptions_groups(self):
        """
        Fetch classes school classcards groups and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM classes_school_subscriptions_groups"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                siosg = m.ScheduleItemOrganizationSubscriptionGroup(
                    schedule_item=self.classes_map.get(record['classes_id'], None),
                    organization_subscription_group=self.school_subscriptions_groups_map.get(
                        record['school_subscriptions_groups_id'], None),
                    enroll=self._web2py_bool_to_python(record['enroll']),
                    shop_book=self._web2py_bool_to_python(record['shopbook']),
                    attend=self._web2py_bool_to_python(record['attend'])
                )
                siosg.save()
                records_imported += 1

                id_map[record['id']] = siosg
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class school subscriptions group id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import classes school subscriptions groups: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_classes_teachers(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_classes_teachers(self):
        """
        Fetch classes teachers and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM classes_teachers"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_item_account = m.ScheduleItemAccount(
                    schedule_item=self.classes_map.get(record['classes_id'], None),
                    account=self.auth_user_map.get(record['auth_teacher_id'], None),
                    role=self.map_classes_instructor_roles.get(record['teacher_role'], ""),
                    account_2=self.auth_user_map.get(record['auth_teacher_id2'], None),
                    role_2=self.map_classes_instructor_roles.get(record['teacher_role2'], ''),
                    date_start=record['startdate'],
                    date_end=record['enddate']
                )
                schedule_item_account.save()
                records_imported += 1

                id_map[record['id']] = schedule_item_account
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class teacher id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import classes teachers: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_shifts(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_shifts(self):
        """
        Fetch shifts and import them in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * from shifts"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_item = m.ScheduleItem(
                    schedule_event=None,
                    schedule_item_type="SHIFT",
                    frequency_type="WEEKLY",
                    frequency_interval=record['week_day'],
                    organization_location_room=self.school_locations_rooms_map.get(record['school_locations_id'], None),
                    organization_shift=self.school_shifts_map.get(record['school_shifts_id'], None),
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    time_start=str(record['starttime']),
                    time_end=str(record['endtime']),
                )
                schedule_item.save()
                records_imported += 1

                id_map[record['id']] = schedule_item
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for shift id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import shifts: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_shifts_otc(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_shifts_otc(self):
        """
        Fetch shifts otc and import them in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM shifts_otc"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                startime = None
                endtime = None
                if record['starttime']:
                    startime = str(record['starttime'])
                if record['endtime']:
                    endtime = str(record['endtime'])

                schedule_item_weekly_otc = m.ScheduleItemWeeklyOTC(
                    schedule_item=self.classes_map.get(record['shifts_id'], None),
                    date=record['shiftdate'],
                    status=self.map_classes_otc_statuses.get(record['status'], ""),
                    description=record['description'] or '',
                    account=self.auth_user_map.get(record['auth_employee_id'], None),
                    account_2=self.auth_user_map.get(record['auth_employee_id2'], None),
                    organization_location_room=self.school_locations_rooms_map.get(record['school_locations_id'], None),
                    organization_shift=self.school_shifts_map.get(record['school_shifts_id'], None),
                    time_start=startime,
                    time_end=endtime,
                )
                schedule_item_weekly_otc.save()
                records_imported += 1

                id_map[record['id']] = schedule_item_weekly_otc
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for class otc id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import shifts otc: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_shifs_staff(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_shifs_staff(self):
        """
        Fetch shifts staff and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM shifts_staff"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_item_account = m.ScheduleItemAccount(
                    schedule_item=self.shifts_map.get(record['shifts_id'], None),
                    account=self.auth_user_map.get(record['auth_employee_id'], None),
                    account_2=self.auth_user_map.get(record['auth_employee_id2'], None),
                    date_start=record['startdate'],
                    date_end=record['enddate']
                )
                schedule_item_account.save()
                records_imported += 1

                id_map[record['id']] = schedule_item_account
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for shift staff id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import shift staff: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_subscriptions_credits(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_subscriptions_credits(self):
        """
        Fetch customers subscriptions credits and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = "SELECT * FROM customers_subscriptions_credits"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_subscription_credit = m.AccountSubscriptionCredit(
                    account_subscription=self.customers_subscriptions_map.get(
                        record['customers_subscriptions_id'], None
                    ),
                    schedule_item_attendance=self.classes_attendance_map.get(
                        record['classes_attendance_id'], None
                    ),
                    mutation_type=record['mutationtype'].upper(),
                    mutation_amount=record['mutationamount'],
                    description=record['description'] or "",
                    subscription_year=record['subscriptionyear'],
                    subscription_month=record['subscriptionmonth']
                )
                account_subscription_credit.save()
                records_imported += 1

                id_map[record['id']] = account_subscription_credit
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for customers subscriptions credits id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import customers subscriptions credits: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_workshop_picture(self, schedule_event, os_picture_file_name, sort_order):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_workshops(self):
        """
        Fetch workshops and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = """
SELECT * FROM workshops w
LEFT JOIN workshops_mail wm ON wm.workshops_id = w.id
"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                tagline = ""
                if record['tagline']:
                    tagline = record['tagline'][:254]

                schedule_event = m.ScheduleEvent(
                    archived=self._web2py_bool_to_python(record['archived']),
                    display_public=self._web2py_bool_to_python(record['publicworkshop']),
                    display_shop=self._web2py_bool_to_python(record['publicworkshop']),
                    auto_send_info_mail=self._web2py_bool_to_python(record['autosendinfomail']),
                    organization_location=self.school_locations_map.get(record['school_locations_id']),
                    name=record['name'],
                    tagline=tagline,
                    preview=record['preview'] or "",
                    description=record['description'] or "",
                    organization_level=self.school_levels_map.get(record['school_levels_id']),
                    instructor=self.auth_user_map.get(record['auth_teacher_id']),
                    instructor_2=self.auth_user_map.get(record['auth_teacher_id2']),
                    date_start=record['startdate'],
                    date_end=record['enddate'],
                    time_start=str(record['starttime']) if record['starttime'] else None,
                    time_end=str(record['endtime']) if record['endtime'] else None,
                    info_mail_content=record['mailcontent'] or ""
                )
                schedule_event.save()
                records_imported += 1

                id_map[record['id']] = schedule_event

                # Import images
                if record.get('picture', None):
                    self._import_workshop_picture(schedule_event, record['picture'], 0)
                if record.get('picture_2', None):
                    self._import_workshop_picture(schedule_event, record['picture_2'], 1)
                if record.get('picture_3', None):
                    self._import_workshop_picture(schedule_event, record['picture_3'], 2)
                if record.get('picture_4', None):
                    self._import_workshop_picture(schedule_event, record['picture_4'], 3)
                if record.get('picture_5', None):
                    self._import_workshop_picture(schedule_event, record['picture_5'], 4)

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for workshop id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import workshops: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_workshops_activities(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_workshops_activities(self):
        """
        Fetch workshops activities and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM workshops_activities"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_item = m.ScheduleItem(
                    schedule_event=self.workshops_map.get(record['workshops_id']),
                    schedule_item_type='EVENT_ACTIVITY',
                    frequency_type='SPECIFIC',
                    frequency_interval=0,
                    organization_location_room=self.school_locations_rooms_map.get(record['school_locations_id']),
                    name=record['activity'],
                    spaces=record['spaces'],
                    date_start=record['activitydate'],
                    time_start=str(record['starttime']),
                    time_end=str(record['endtime']),
                    display_public=True,
                    account=self.auth_user_map.get(record['auth_teacher_id']),
                    account_2=self.auth_user_map.get(record['auth_teacher_id2'], None)
                )
                schedule_item.save()
                records_imported += 1

                id_map[record['id']] = schedule_item

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for workshop activity id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import workshops activities: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_workshops_products(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_workshops_products(self):
        """
        Fetch workshops products and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM workshops_products"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        helper = ScheduleEventTicketScheduleItemHelper()
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                schedule_event_ticket = m.ScheduleEventTicket(
                    schedule_event=self.workshops_map.get(record['workshops_id']),
                    full_event=self._web2py_bool_to_python(record['fullworkshop']),
                    deletable=self._web2py_bool_to_python(record['deletable']),
                    display_public=self._web2py_bool_to_python(record['publicproduct']),
                    name=record['name'],
                    description=record['description'] or "",
                    price=record['price'],
                    finance_tax_rate=self.tax_rates_map.get(record['tax_rates_id']),
                    finance_glaccount=self.accounting_glaccounts_map.get(record['accounting_glaccounts_id'], None),
                    finance_costcenter=self.accounting_costcenters_map.get(record['accounting_costcenters_id'], None)
                )
                schedule_event_ticket.save()
                # Add all schedule items for this event to this ticket
                helper.add_schedule_items_to_ticket(schedule_event_ticket)
                # Increase counter
                records_imported += 1

                id_map[record['id']] = schedule_event_ticket

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for workshop product id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import workshops products: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_workshops_products_activities(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_workshops_products_customers(self):
        """
        Fetch workshops products customers and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM workshops_products_customers"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        sales_dude = SalesDude()
        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                account_schedule_event_ticket = m.AccountScheduleEventTicket(
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    schedule_event_ticket=self.workshops_products_map.get(record['workshops_products_id'], None),
                    cancelled=self._web2py_bool_to_python(record['cancelled']),
                    payment_confirmation=self._web2py_bool_to_python(record['paymentconfirmation']),
                    info_mail_sent=self._web2py_bool_to_python(record['workshopinfo'])
                )
                account_schedule_event_ticket.save()
                # Add attendance items for customer
                sales_dude._sell_schedule_event_ticket_add_attendance(
                    account_schedule_event_ticket=account_schedule_event_ticket,
                    finance_invoice_item=None
                )

                # Increase counter
                records_imported += 1

                id_map[record['id']] = account_schedule_event_ticket

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for workshop product customer id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import workshops product customers: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_workshops_activities_customers(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_announcements(self):
        """
        Fetch announcements and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM announcements"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                date_end = datetime.date(2999, 12, 31)
                if record['enddate']:
                    date_end = record['enddate']

                organization_announcement = m.OrganizationAnnouncement(
                    display_public=self._web2py_bool_to_python(record['visible']),
                    display_shop=False,
                    display_backend=True,
                    title=record['title'],
                    content=record['note'],
                    date_start=record['startdate'],
                    date_end=date_end,
                    priority=record['priority']
                )
                organization_announcement.save()
                # Increase counter
                records_imported += 1

                id_map[record['id']] = organization_announcement

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for announcement id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import announcements: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_profile_announcements(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_profile_announcements(self):
        """
        Fetch customer profile announcements and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM customers_profile_announcements"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                priority = 200
                if record['sticky'] == 'T':
                    priority = 100

                date_end = datetime.date(2999, 12, 31)
                if record['enddate']:
                    date_end = record['enddate']

                organization_announcement = m.OrganizationAnnouncement(
                    display_public=self._web2py_bool_to_python(record['publicannouncement']),
                    display_shop=True,
                    display_backend=False,
                    title=record['title'],
                    content=record['announcement'],
                    date_start=record['startdate'],
                    date_end=date_end,
                    priority=priority
                )
                organization_announcement.save()
                # Increase counter
                records_imported += 1

                id_map[record['id']] = organization_announcement

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for customer profile announcement id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import customer profile announcements: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_invoices_groups(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_invoices_groups(self):
        """
        Fetch invoices groups and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        # Don't import default group
        query = "SELECT * FROM invoices_groups"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        # Add default group
        id_map[100] = m.FinanceInvoiceGroup.objects.get(id=100)

        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            if record['id'] == 100:
                print("Importing default group settings")

                finance_invoice_group = id_map[100]
                finance_invoice_group.archived = self._web2py_bool_to_python(record['archived'])
                finance_invoice_group.display_public = self._web2py_bool_to_python(record['publicgroup'])
                finance_invoice_group.name = record['name']
                finance_invoice_group.next_id = record['nextid']
                finance_invoice_group.due_after_days = record['duedays']
                finance_invoice_group.prefix = record['invoiceprefix'] or ""
                finance_invoice_group.prefix_year = self._web2py_bool_to_python(record['prefixyear'])
                finance_invoice_group.auto_reset_prefix_year = \
                    self._web2py_bool_to_python(record['autoresetprefixyear'])
                finance_invoice_group.terms = record['terms'] or ""
                finance_invoice_group.footer = record['footer'] or ""
                finance_invoice_group.code = record['journalid'] or ""
                finance_invoice_group.save()
                records_imported += 1

                logging.info("Imported default finance invoice group info")
            else:
                # Import non-default group
                try:
                    finance_invoice_group = m.FinanceInvoiceGroup(
                        archived=self._web2py_bool_to_python(record['archived']),
                        display_public=self._web2py_bool_to_python(record['publicgroup']),
                        name=record['name'],
                        next_id=record['nextid'],
                        due_after_days=record['duedays'],
                        prefix=record['invoiceprefix'] or "",
                        prefix_year=self._web2py_bool_to_python(record['prefixyear']),
                        auto_reset_prefix_year=self._web2py_bool_to_python(record['autoresetprefixyear']),
                        terms=record['terms'] or "",
                        footer=record['footer'] or "",
                        code=record['journalid'] or ""
                    )
                    finance_invoice_group.save()
                    records_imported += 1

                    id_map[record['id']] = finance_invoice_group
                except django.db.utils.IntegrityError as e:
                    logging.error("Import error for invoice group: %s: %s" % (
                        record['id'],
                        e
                    ))

        log_message = "Import invoice groups: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_invoices_groups_product_types(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_invoices_groups_product_types(self):
        """
        Fetch invoices groups prouct types and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        # Don't import default group
        query = "SELECT * FROM invoices_groups_product_types"
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                finance_invoice_group_default = m.FinanceInvoiceGroupDefault.objects.filter(
                    item_type=self.map_invoices_product_types.get(record['producttype'])
                ).first()
                finance_invoice_group_default.finance_invoice_group = self.invoices_groups_map.get(
                    record['invoices_groups_id'], 100
                )  # Set to default (100) if the group is not found
                finance_invoice_group_default.save()
                records_imported += 1

                id_map[record['id']] = finance_invoice_group_default
            except AttributeError as e:
                logging.error("Import error for invoice group default: %s: %s" % (
                    record['id'],
                    e
                ))
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for invoice group default: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import invoice group defaults: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_invoices(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_invoices(self):
        """
        Fetch invoices and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = """
SELECT * FROM invoices i
LEFT JOIN invoices_customers ic  ON ic.invoices_id = i.id
LEFT JOIN invoices_amounts ia ON ia.invoices_id = i.id
ORDER BY i.id
"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:

                try:
                    credit_invoice_for = id_map.get(record['credit_invoice_for'].id)
                except AttributeError:
                    credit_invoice_for = None

                summary = ""
                if record['description']:
                    summary = record['description'][:254]

                finance_invoice = m.FinanceInvoice(
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    finance_invoice_group=self.invoices_groups_map.get(record['invoices_groups_id'], None),
                    finance_payment_method=self.payment_methods_map.get(record['payment_methods_id'], None),
                    instructor_payment=self._web2py_bool_to_python(record['teacherpayment']),
                    employee_claim=self._web2py_bool_to_python(record['employeeclaim']),
                    status=self.map_invoices_statuses.get(record['status']),
                    summary=summary,
                    invoice_number=record['invoiceid'],
                    date_sent=record['datecreated'],
                    date_due=record['datedue'],
                    terms=record['terms'] or "",
                    footer=record['footer'] or "",
                    note=record['note'] or "",
                    subtotal=record['totalprice'],
                    tax=record['vat'],
                    total=record['totalpricevat'],
                    paid=record['paid'],
                    balance=record['balance'],
                    credit_invoice_for=credit_invoice_for
                )
                finance_invoice.save()

                finance_invoice.invoice_number = record['invoiceid']
                finance_invoice.save()
                records_imported += 1

                id_map[record['id']] = finance_invoice
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for finance invoice: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import finance invoices: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_invoices_items(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_invoices_items(self):
        """
        Fetch customers orders and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = """
SELECT * FROM invoices_items ii
LEFT JOIN invoices_items_workshops_products_customers iiwpc ON iiwpc.invoices_items_id = ii.id
LEFT JOIN invoices_items_classes_attendance iica ON iica.invoices_items_id = ii.id
LEFT JOIN invoices_items_customers_classcards iicc ON iicc.invoices_items_id = ii.id
LEFT JOIN invoices_items_customers_subscriptions iics ON iics.invoices_items_id = ii.id
LEFT JOIN invoices i ON ii.invoices_id = i.id
    """
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                finance_invoice_item = m.FinanceInvoiceItem(
                    finance_invoice=self.invoices_map.get(record['invoices_id'], None),
                    account_schedule_event_ticket=self.workshops_products_customers_map.get(
                        record['workshops_products_customers_id'], None
                    ),
                    account_classpass=self.customers_classcards_map.get(
                        record['customers_classcards_id'], None
                    ),
                    account_subscription=self.customers_subscriptions_map.get(
                        record['customers_subscriptions_id'], None
                    ),
                    subscription_year=record['subscriptionyear'],
                    subscription_month=record['subscriptionmonth'],
                    line_number=record['sorting'],
                    product_name=record['productname'],
                    description=record['description'],
                    quantity=record['quantity'],
                    price=record['price'],
                    finance_tax_rate=self.tax_rates_map.get(record['tax_rates_id']),
                    finance_glaccount=self.accounting_glaccounts_map.get(record['accounting_glaccounts_id'], None),
                    finance_costcenter=self.accounting_costcenters_map.get(record['accounting_costcenters_id'], None)
                )
                finance_invoice_item.save()

                # This invoice item was linked to a classes_attendance record. There is no 1:1 equivalent in
                # Costasiella as there are no prices for a class but passes are used.
                # We can link the invoice item to an attendance record though.
                if record['classes_attendance_id']:
                    schedule_item_attendance = self.classes_attendance_map.get(
                        record['classes_attendance_id'],
                        None
                    )
                    if schedule_item_attendance:
                        schedule_item_attendance.finance_invoice_item = finance_invoice_item
                        schedule_item_attendance.save()

                records_imported += 1

                id_map[record['id']] = finance_invoice_item
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for finance invoice item: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import finance invoices items: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_invoices_payments(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_invoices_payments(self):
        """
        Fetch invoice payments and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM invoices_payments"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                finance_invoice_payment = m.FinanceInvoicePayment(
                    finance_invoice=self.invoices_map.get(record['invoices_id'], None),
                    date=record['paymentdate'],
                    amount=record['amount'],
                    finance_payment_method=self.payment_methods_map.get(record['payment_methods_id'], None),
                    note=record['note'] or "",
                    online_payment_id=record['mollie_payment_id'],
                    online_refund_id=record['mollie_refund_id'],
                    online_chargeback_id=record['mollie_chargeback_id'],
                )
                finance_invoice_payment.save()
                # Increase counter
                records_imported += 1

                id_map[record['id']] = finance_invoice_payment

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for invoice payments id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import invoice payments: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_invoices_mollie_payment_ids(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_invoices_mollie_payment_ids(self):
        """
        Fetch records from invoices mollie payment ids and import it in Costasiella.
        :return: None
        """
        query = """SELECT * FROM invoices_mollie_payment_ids"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                integration_log_mollie = m.IntegrationLogMollie(
                     log_source='INVOICE_PAY',
                     mollie_payment_id=record['mollie_payment_id'],
                     recurring_type=record['recurringtype'].upper() if record['recurringtype'] else None,
                     webhook_url=record['webhookurl'],
                     finance_invoice=self.invoices_map.get(record['invoices_id'], None)
                )
                integration_log_mollie.save()
                # Increase counter
                records_imported += 1

                id_map[record['id']] = integration_log_mollie

            except django.db.utils.IntegrityError as e:
                logging.error("Import error for invoices mollie payment id: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import invoice mollie payments: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_orders(self):

0 Source : openstudio_import.py
with GNU General Public License v2.0
from costasiella

    def _import_customers_orders(self):
        """
        Fetch customers orders and import it in Costasiella.
        :param cursor: MySQL db cursor
        :return: None
        """
        query = """
SELECT * FROM customers_orders co
LEFT JOIN customers_orders_amounts coa ON coa.customers_orders_id = co.id
LEFT JOIN invoices_customers_orders ico ON ico.customers_orders_id = co.id
"""
        self.cursor.execute(query)
        records = self.cursor.fetchall()

        id_map = {}
        records_imported = 0
        for record in records:
            record = {k.lower(): v for k, v in record.items()}

            try:
                finance_order = m.FinanceOrder(
                    finance_invoice=self.invoices_map.get(record['invoices_id'], None),
                    account=self.auth_user_map.get(record['auth_customer_id'], None),
                    status=self.map_customers_orders_statuses.get(record['status'], None),
                    message=record['customernote'] or '',
                    subtotal=record['totalprice'] or 0,
                    tax=record['vat'] or 0,
                    total=record['totalpricevat'] or 0
                )
                finance_order.save()
                records_imported += 1

                id_map[record['id']] = finance_order
            except django.db.utils.IntegrityError as e:
                logging.error("Import error for finance order: %s: %s" % (
                    record['id'],
                    e
                ))

        log_message = "Import finance order id: "
        self.stdout.write(log_message + self.get_records_import_status_display(records_imported, len(records)))
        logging.info(log_message + self.get_records_import_status_display(records_imported, len(records), raw=True))

        return id_map

    def _import_customers_orders_items(self):

See More Examples