Skip to content

Commit

Permalink
[IMP] : black, isort, prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
bizzappdev authored and dreispt committed Apr 27, 2024
1 parent efcc09b commit dc24ef1
Show file tree
Hide file tree
Showing 143 changed files with 30,379 additions and 26,836 deletions.
253 changes: 143 additions & 110 deletions connector_magento/components/backend_adapter.py

Large diffs are not rendered by default.

29 changes: 15 additions & 14 deletions connector_magento/components/binder.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,20 @@ class MagentoModelBinder(Component):
the Magento ID, the ID of the Magento Backend and the additional
fields belonging to the Magento instance.
"""
_name = 'magento.binder'
_inherit = ['base.binder', 'base.magento.connector']

_name = "magento.binder"
_inherit = ["base.binder", "base.magento.connector"]
_apply_on = [
'magento.website',
'magento.store',
'magento.storeview',
'magento.res.partner',
'magento.address',
'magento.res.partner.category',
'magento.product.category',
'magento.product.product',
'magento.stock.picking',
'magento.sale.order',
'magento.sale.order.line',
'magento.account.invoice',
"magento.website",
"magento.store",
"magento.storeview",
"magento.res.partner",
"magento.address",
"magento.res.partner.category",
"magento.product.category",
"magento.product.product",
"magento.stock.picking",
"magento.sale.order",
"magento.sale.order.line",
"magento.account.invoice",
]
6 changes: 3 additions & 3 deletions connector_magento/components/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ class BaseMagentoConnectorComponent(AbstractComponent):
All components of this connector should inherit from it.
"""

_name = 'base.magento.connector'
_inherit = 'base.connector'
_collection = 'magento.backend'
_name = "base.magento.connector"
_inherit = "base.connector"
_collection = "magento.backend"
10 changes: 6 additions & 4 deletions connector_magento/components/deleter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,21 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)

from odoo.tools.translate import _

from odoo.addons.component.core import AbstractComponent


class MagentoDeleter(AbstractComponent):
""" Base deleter for Magento """
_name = 'magento.exporter.deleter'
_inherit = 'base.deleter'
_usage = 'record.exporter.deleter'

_name = "magento.exporter.deleter"
_inherit = "base.deleter"
_usage = "record.exporter.deleter"

def run(self, external_id):
""" Run the synchronization, delete the record on Magento
:param external_id: identifier of the record to delete
"""
self.backend_adapter.delete(external_id)
return _('Record %s deleted on Magento') % (external_id,)
return _("Record %s deleted on Magento") % (external_id,)
112 changes: 61 additions & 51 deletions connector_magento/components/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

import logging

from contextlib import contextmanager
from datetime import datetime

import psycopg2

import odoo
from odoo import _

from odoo.addons.component.core import AbstractComponent
from odoo.addons.connector.exception import (IDMissingInBackend,
RetryableJobError)
from odoo.addons.connector.exception import IDMissingInBackend, RetryableJobError

from .backend_adapter import MAGENTO_DATETIME_FORMAT

_logger = logging.getLogger(__name__)
Expand All @@ -35,9 +35,9 @@
class MagentoBaseExporter(AbstractComponent):
""" Base exporter for Magento """

_name = 'magento.base.exporter'
_inherit = ['base.exporter', 'base.magento.connector']
_usage = 'record.exporter'
_name = "magento.base.exporter"
_inherit = ["base.exporter", "base.magento.connector"]
_usage = "record.exporter"

def __init__(self, working_context):
super(MagentoBaseExporter, self).__init__(working_context)
Expand All @@ -53,9 +53,9 @@ def _delay_import(self):
# force is True because the sync_date will be more recent
# so the import would be skipped
assert self.external_id
self.binding.with_delay().import_record(self.backend_record,
self.external_id,
force=True)
self.binding.with_delay().import_record(
self.backend_record, self.external_id, force=True
)

def _should_import(self):
""" Before the export, compare the update date
Expand All @@ -69,14 +69,12 @@ def _should_import(self):
sync = self.binding.sync_date
if not sync:
return True
record = self.backend_adapter.read(self.external_id,
attributes=['updated_at'])
if not record['updated_at']:
record = self.backend_adapter.read(self.external_id, attributes=["updated_at"])
if not record["updated_at"]:
# in rare case it can be empty, in doubt, import it
return True
sync_date = odoo.fields.Datetime.from_string(sync)
magento_date = datetime.strptime(record['updated_at'],
MAGENTO_DATETIME_FORMAT)
magento_date = datetime.strptime(record["updated_at"], MAGENTO_DATETIME_FORMAT)
return sync_date < magento_date

def run(self, binding, *args, **kwargs):
Expand All @@ -102,7 +100,7 @@ def run(self, binding, *args, **kwargs):
# exports (due to dependencies) and one of them fails.
# The commit will also release the lock acquired on the binding
# record
if not odoo.tools.config['test_enable']:
if not odoo.tools.config["test_enable"]:
# pylint: disable=invalid-commit
self.env.cr.commit() # noqa

Expand All @@ -121,8 +119,8 @@ def _after_export(self):
class MagentoExporter(AbstractComponent):
""" A common flow for the exports to Magento """

_name = 'magento.exporter'
_inherit = 'magento.base.exporter'
_name = "magento.exporter"
_inherit = "magento.base.exporter"

def __init__(self, working_context):
super(MagentoExporter, self).__init__(working_context)
Expand All @@ -144,19 +142,21 @@ def _lock(self):
on the binding record it has to export.
"""
sql = ("SELECT id FROM %s WHERE ID = %%s FOR UPDATE NOWAIT" %
self.model._table)
sql = "SELECT id FROM %s WHERE ID = %%s FOR UPDATE NOWAIT" % self.model._table
try:
self.env.cr.execute(sql, (self.binding.id, ),
log_exceptions=False)
self.env.cr.execute(sql, (self.binding.id,), log_exceptions=False)
except psycopg2.OperationalError:
_logger.info('A concurrent job is already exporting the same '
'record (%s with id %s). Job delayed later.',
self.model._name, self.binding.id)
_logger.info(
"A concurrent job is already exporting the same "
"record (%s with id %s). Job delayed later.",
self.model._name,
self.binding.id,
)
raise RetryableJobError(
'A concurrent job is already exporting the same record '
'(%s with id %s). The job will be retried later.' %
(self.model._name, self.binding.id))
"A concurrent job is already exporting the same record "
"(%s with id %s). The job will be retried later."
% (self.model._name, self.binding.id)
)

def _has_to_skip(self):
""" Return True if the export can be skipped """
Expand Down Expand Up @@ -187,17 +187,22 @@ def _retry_unique_violation(self):
except psycopg2.IntegrityError as err:
if err.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION:
raise RetryableJobError(
'A database error caused the failure of the job:\n'
'%s\n\n'
'Likely due to 2 concurrent jobs wanting to create '
'the same record. The job will be retried later.' % err)
"A database error caused the failure of the job:\n"
"%s\n\n"
"Likely due to 2 concurrent jobs wanting to create "
"the same record. The job will be retried later." % err
)
else:
raise

def _export_dependency(self, relation, binding_model,
component_usage='record.exporter',
binding_field='magento_bind_ids',
binding_extra_vals=None):
def _export_dependency(
self,
relation,
binding_model,
component_usage="record.exporter",
binding_field="magento_bind_ids",
binding_extra_vals=None,
):
"""
Export a dependency. The exporter class is a subclass of
``MagentoExporter``. If a more precise class need to be defined,
Expand Down Expand Up @@ -242,38 +247,44 @@ def _export_dependency(self, relation, binding_model,
wrap = relation._name != binding_model

if wrap and hasattr(relation, binding_field):
domain = [('odoo_id', '=', relation.id),
('backend_id', '=', self.backend_record.id)]
domain = [
("odoo_id", "=", relation.id),
("backend_id", "=", self.backend_record.id),
]
binding = self.env[binding_model].search(domain)
if binding:
assert len(binding) == 1, (
'only 1 binding for a backend is '
'supported in _export_dependency')
"only 1 binding for a backend is " "supported in _export_dependency"
)
# we are working with a unwrapped record (e.g.
# product.category) and the binding does not exist yet.
# Example: I created a product.product and its binding
# magento.product.product and we are exporting it, but we need to
# create the binding for the product.category on which it
# depends.
else:
bind_values = {'backend_id': self.backend_record.id,
'odoo_id': relation.id}
bind_values = {
"backend_id": self.backend_record.id,
"odoo_id": relation.id,
}
if binding_extra_vals:
bind_values.update(binding_extra_vals)
# If 2 jobs create it at the same time, retry
# one later. A unique constraint (backend_id,
# odoo_id) should exist on the binding model
with self._retry_unique_violation():
binding = (self.env[binding_model]
.with_context(connector_no_export=True)
.sudo()
.create(bind_values))
binding = (
self.env[binding_model]
.with_context(connector_no_export=True)
.sudo()
.create(bind_values)
)
# Eager commit to avoid having 2 jobs
# exporting at the same time. The constraint
# will pop if an other job already created
# the same binding. It will be caught and
# raise a RetryableJobError.
if not odoo.tools.config['test_enable']:
if not odoo.tools.config["test_enable"]:
# pylint: disable=invalid-commit
self.env.cr.commit() # noqa
else:
Expand All @@ -283,8 +294,7 @@ def _export_dependency(self, relation, binding_model,
binding = relation

if not rel_binder.to_external(binding):
exporter = self.component(usage=component_usage,
model_name=binding_model)
exporter = self.component(usage=component_usage, model_name=binding_model)
exporter.run(binding)

def _export_dependencies(self):
Expand Down Expand Up @@ -361,11 +371,11 @@ def _run(self, fields=None):
if self.external_id:
record = self._update_data(map_record, fields=fields)
if not record:
return _('Nothing to export.')
return _("Nothing to export.")
self._update(record)
else:
record = self._create_data(map_record, fields=fields)
if not record:
return _('Nothing to export.')
return _("Nothing to export.")
self.external_id = self._create(record)
return _('Record exported with ID %s on Magento.') % self.external_id
return _("Record exported with ID %s on Magento.") % self.external_id
Loading

0 comments on commit dc24ef1

Please sign in to comment.