Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions om_connector_base/__manifest__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
'name': 'Connector Base',
'version': '1.0',
'version': '1.1',
'author': 'Odoo Mates',
'category': 'Sales',
'summary': 'Job queue, retries, external ID mappings and webhook helpers for shop and marketplace connectors',
Expand All @@ -9,7 +9,7 @@
'maintainer': 'Odoo Mates',
'support': 'odoomates@gmail.com',
'license': 'LGPL-3',
'depends': ['mail', 'sale_management'],
'depends': ['mail', 'sale_management', 'sale_stock'],
'data': [
'security/om_connector_groups.xml',
'security/ir.model.access.csv',
Expand Down
2 changes: 2 additions & 0 deletions om_connector_base/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
from . import om_connector_backend_mixin
from . import om_connector_binding_mixin
from . import om_connector_order_workflow
from . import res_partner
from . import sale_order
68 changes: 68 additions & 0 deletions om_connector_base/models/om_connector_backend_mixin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import float_round


class OmConnectorBackendMixin(models.AbstractModel):
Expand Down Expand Up @@ -39,6 +41,72 @@ def _connector_enqueue_once(self, method_name, payload=None, **kwargs):
def _connector_job_failed(self, job):
""" Called when ``job`` of this connection fails for good. """

# ------------------------------------------------------------------
# Orders: pricelist and taxes (the connection has a ``company_id``)
# ------------------------------------------------------------------

def _connector_pricelist(self, currency_code, label):
""" A pricelist in the currency ``currency_code`` of an order, when it is not the currency of
the company (found, or created as "<label> <currency>"). """
self.ensure_one()
if not currency_code or currency_code == self.company_id.currency_id.name:
return self.env['product.pricelist']
currency = self.env['res.currency'].with_context(active_test=False).search([('name', '=', currency_code)],
limit=1)
if not currency:
raise UserError(_("Unknown currency %(currency)s.", currency=currency_code))
if not currency.active:
currency.sudo().active = True
Pricelist = self.env['product.pricelist'].sudo()
return Pricelist.search([('currency_id', '=', currency.id), ('company_id', 'in', [False, self.company_id.id])],
limit=1) or Pricelist.create({
'name': f"{label} {currency.name}",
'currency_id': currency.id, 'company_id': self.company_id.id})

def _connector_taxes(self, rates, included, account=None):
""" The Odoo sale taxes of ``rates``, found or created.

:param rates: ``[(percent, title)]``, e.g. ``[(10.0, 'State Tax')]``
:param included: the prices of the order include the taxes
:param account: the tax account of the taxes created, else the one of the company """
self.ensure_one()
Tax = self.env['account.tax'].sudo().with_company(self.company_id)
taxes = Tax.browse()
for percent, title in rates or []:
rate = float_round(float(percent or 0.0), precision_digits=4)
if not rate:
continue
candidates = Tax.search([
('company_id', '=', self.company_id.id), ('type_tax_use', '=', 'sale'),
('amount_type', '=', 'percent'), ('amount', '=', rate),
])
tax = candidates.filtered(lambda t: t.price_include == included)[:1]
if not tax:
tax = Tax.create({
'name': f"{title or _('Tax')} {rate:g}%" + (_(" (included)") if included else ''),
'amount': rate,
'amount_type': 'percent',
'type_tax_use': 'sale',
'price_include_override': 'tax_included' if included else 'tax_excluded',
'company_id': self.company_id.id,
'country_id': self.company_id.account_fiscal_country_id.id,
})
if account:
(tax.invoice_repartition_line_ids | tax.refund_repartition_line_ids).filtered(
lambda l: l.repartition_type == 'tax').account_id = account
taxes |= tax
return taxes

def _connector_activity(self, summary, note, once=True):
""" An activity for the responsible of the connection (``responsible_id``, else its creator);
with ``once``, not while one with this summary is open. """
self.ensure_one()
if once and self.activity_ids.filtered(lambda a: a.summary == summary):
return
responsible = self.responsible_id if 'responsible_id' in self._fields else self.env['res.users']
self.activity_schedule('mail.mail_activity_data_todo', summary=summary, note=note,
user_id=(responsible or self.create_uid or self.env.user).id)

def _connector_job_domain(self):
return [('backend_model', '=', self._name), ('backend_id', 'in', self.ids)]

Expand Down
3 changes: 2 additions & 1 deletion om_connector_base/models/om_connector_binding_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ def _connector_find(self, backend, external_ids):
@api.model
def _connector_bind(self, backend, external_id, record, vals=None):
""" Link ``external_id`` to ``record`` for ``backend``, creating or updating the binding. """
binding = self._connector_find(backend, external_id)
# an archived binding too: the external ID is unique per backend
binding = self.with_context(active_test=False)._connector_find(backend, external_id)
values = {self._connector_record_field: record.id, 'sync_date': fields.Datetime.now(), **(vals or {})}
if binding:
binding.write(values)
Expand Down
81 changes: 81 additions & 0 deletions om_connector_base/models/res_partner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from odoo import api, models


class ResPartner(models.Model):
""" Contacts and addresses of the customers of a shop or a marketplace.

The connectors give an address as a dict with the keys ``name``, ``company``, ``street``,
``street2``, ``city``, ``zip``, ``state_code``, ``country_code``, ``phone`` and ``email``
(all optional), whatever the format of their own API. """
_inherit = 'res.partner'

@api.model
def _connector_address_vals(self, address):
""" The address fields of a contact for ``address``. """
if not address:
return {}
country = self.env['res.country'].search([('code', '=ilike', address['country_code'])], limit=1) \
if address.get('country_code') else self.env['res.country']
state = self.env['res.country.state']
if country and address.get('state_code'):
state = state.search([('country_id', '=', country.id), ('code', '=ilike', address['state_code'])], limit=1)
return {
'street': address.get('street') or False,
'street2': address.get('street2') or False,
'city': address.get('city') or False,
'zip': address.get('zip') or False,
'country_id': country.id,
'state_id': state.id,
}

@api.model
def _connector_find_or_create(self, company, email, name, address=None, phone=None):
""" The contact of a customer: the one with this email (a company or a person without a
parent), else a new one with ``address``. """
email = (email or '').strip()
partner = self.browse()
if email:
partner = self.search([
('email', '=ilike', email), ('parent_id', '=', False),
('company_id', 'in', [False, company.id]),
], limit=1)
if partner:
return partner
return self.create({
'name': name or email or '?',
'email': email or False,
'phone': phone or (address or {}).get('phone') or False,
**self._connector_address_vals(address),
})

def _connector_fill_blanks(self, vals):
""" Fill the empty fields of this contact with ``vals``; never replace what is set. """
self.ensure_one()
self.write({key: value for key, value in vals.items() if value and not self[key]})

def _connector_address(self, address_type, address):
""" The ``address_type`` address (invoice, delivery) of this contact for ``address``:
itself when it is the same, else one of its own addresses of this type, found or created.
Never the address of another contact. """
self.ensure_one()
if not address:
return self
vals = self._connector_address_vals(address)
name = address.get('name') or self.name

def same(record):
return all((record[key].id if hasattr(record[key], 'id') else record[key] or False) == value
for key, value in vals.items())

if same(self) and name == self.name:
return self
child = self.child_ids.filtered(lambda c: c.type == address_type and c.name == name and same(c))[:1]
if child:
return child
return self.create({
'parent_id': self.id,
'type': address_type,
'name': name,
'phone': address.get('phone') or False,
**vals,
})
141 changes: 141 additions & 0 deletions om_connector_base/models/sale_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
from odoo import _, api, fields, models
from odoo.tools import float_round


class SaleOrder(models.Model):
""" Helpers shared by the connectors for the orders they import. """
_inherit = 'sale.order'

@api.model
def _connector_discount(self, amount, discount_amount):
""" The discount percentage of ``discount_amount`` on ``amount``. """
if not amount or not discount_amount:
return 0.0
return float_round(discount_amount / amount * 100.0, precision_digits=6)

def _connector_check_total(self, total, source):
""" A note on the order when its total is not ``total``, the total of the shop: the order is
kept, the user checks it (a rounding, a tax set up differently). """
self.ensure_one()
if self.currency_id.compare_amounts(self.amount_total, total) != 0:
self.message_post(body=_(
"The total of this order in Odoo (%(odoo)s) is not the total in %(shop)s (%(total)s): check its "
"taxes and discounts.",
odoo=self.currency_id.format(self.amount_total), shop=source, total=self.currency_id.format(total)))

def _connector_deliver(self, context=None):
""" The order was shipped by the shop before it reached Odoo: its open deliveries are done.
``context``: added to the validation, e.g. to tell the connector not to ship it again.
Gives the pickings validated. """
self.ensure_one()
pickings = self.picking_ids.filtered(lambda p: p.state not in ('done', 'cancel')
and p.picking_type_code == 'outgoing')
if not pickings:
return pickings
for move in pickings.move_ids.filtered(lambda m: m.state not in ('done', 'cancel')):
move.quantity = move.product_uom_qty
move.picked = True
pickings.with_context(skip_backorder=True, skip_sanity_check=True, **(context or {}))._action_done()
return pickings

def _connector_credit_note(self, lines, total, ref, *, shipping=0.0, shipping_product=None,
adjustment_product=None, narration=False, extra_vals=None):
""" A posted credit note for a refund of the shop, on the posted invoice of the order.

:param lines: ``[(sale order line, quantity)]``: the refunded products; only what was invoiced
is credited on its line, the rest goes in the adjustment
:param total: the amount refunded by the shop
:param shipping: the refunded shipping, on ``shipping_product``, taxed as the delivery line
:param adjustment_product: what the shop refunded besides the lines and the shipping
:param extra_vals: other values of the credit note (the refund ID of the connector…)
Gives the credit note, or an empty recordset when the order has no posted invoice. """
self.ensure_one()
invoice = self.invoice_ids.filtered(lambda m: m.move_type == 'out_invoice' and m.state == 'posted')[:1]
if not invoice or not total:
return self.env['account.move']
line_vals = []
for sale_line, quantity in lines:
quantity = min(quantity, sale_line.qty_invoiced)
if quantity <= 0:
continue
line_vals.append({
'product_id': sale_line.product_id.id,
'name': sale_line.name,
'quantity': quantity,
'price_unit': sale_line.price_unit,
'discount': sale_line.discount,
'tax_ids': [fields.Command.set(sale_line.tax_id.ids)],
'sale_line_ids': [fields.Command.link(sale_line.id)],
})
if shipping and shipping_product:
delivery = self.order_line.filtered('is_delivery')[:1]
line_vals.append({
'product_id': shipping_product.id,
'name': _("Shipping refund"),
'quantity': 1,
'price_unit': shipping,
'tax_ids': [fields.Command.set(delivery.tax_id.ids)] if delivery else [fields.Command.clear()],
'sale_line_ids': [fields.Command.link(delivery.id)] if delivery else [],
})
credit_note = self.env['account.move'].with_company(self.company_id).create({
'move_type': 'out_refund',
'partner_id': self.partner_invoice_id.id,
'invoice_origin': self.name,
'ref': ref,
'reversed_entry_id': invoice.id,
'currency_id': self.currency_id.id,
'journal_id': invoice.journal_id.id,
'narration': narration,
'invoice_line_ids': [fields.Command.create(vals) for vals in line_vals],
**(extra_vals or {}),
})
difference = self.currency_id.round(total - credit_note.amount_total)
if not self.currency_id.is_zero(difference) and adjustment_product:
credit_note.invoice_line_ids = [fields.Command.create({
'product_id': adjustment_product.id,
'name': _("Refund adjustment"),
'quantity': 1,
'price_unit': difference,
'tax_ids': [fields.Command.clear()],
})]
credit_note.action_post()
return credit_note

def _connector_return(self, quantities, validate=False, context=None):
""" Return to stock the products of the order shipped by its first done delivery.

:param quantities: ``{sale order line: quantity}`` to return
:param validate: validate the return at once
:param context: added to the validation
Gives the return, or None when there is nothing to return. """
self.ensure_one()
quantities = {line: qty for line, qty in quantities.items() if qty > 0}
picking = self.picking_ids.filtered(lambda p: p.state == 'done' and p.picking_type_code == 'outgoing')[:1]
if not quantities or not picking:
return None
wizard = self.env['stock.return.picking'].create({'picking_id': picking.id})
left = dict(quantities)
for return_line in wizard.product_return_moves:
origin = return_line.move_id
wanted = min(left.get(origin.sale_line_id, 0.0), origin.quantity)
return_line.quantity = max(wanted, 0.0)
if wanted > 0:
left[origin.sale_line_id] -= wanted
if not any(line.quantity > 0 for line in wizard.product_return_moves):
return None
returned = wizard._create_return()
if validate:
for move in returned.move_ids:
move.quantity = move.product_uom_qty
move.picked = True
returned.with_context(skip_backorder=True, **(context or {}))._action_done()
return returned

@api.model
def _connector_tags(self, names):
""" The sales tags named ``names``, found or created. """
Tag = self.env['crm.tag']
tags = Tag.browse()
for name in {n.strip() for n in names or [] if n and n.strip()}:
tags |= Tag.search([('name', '=', name)], limit=1) or Tag.create({'name': name})
return tags
Binary file modified om_connector_base/static/description/banner.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading