web.py 18.7 KB
Newer Older
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
1 2
# The COPYRIGHT file at the top level of this repository contains the full
# copyright notices and license terms.
3
from decimal import Decimal
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
4
import logging
5

Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
6 7
from woocommerce import API

8
from trytond.exceptions import UserError
9
from trytond.i18n import gettext, lazy_gettext
10
from trytond.model import Model, ModelSQL, Unique, fields
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
11 12 13 14
from trytond.pyson import Eval
from trytond.pool import PoolMeta, Pool
from trytond.tools import grouped_slice
from trytond.transaction import Transaction
15
from trytond.modules.product import round_price
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
16

17
from trytond.model.modelstorage import RequiredValidationError
18 19
from .exceptions import WooCommerceError, MissingParentsError

Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
20 21
logger = logging.getLogger(__name__)

Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

class ShopWooCommerceId(ModelSQL):
    "Web Shop WooCommerce ID"
    __name__ = 'web.shop.woocommerce_id'

    record = fields.Reference("Record", 'get_records', required=True)
    shop = fields.Many2One('web.shop', "Web Shop", required=True, select=True)
    woocommerce_id = fields.Integer("WooCommerce ID", required=True)

    @classmethod
    def __setup__(cls):
        super().__setup__()
        t = cls.__table__()
        cls._sql_constraints = [
            ('record_unique', Unique(t, t.record, t.shop),
                'web_shop_woocommerce.msg_id_record_unique'),
            ]

    @classmethod
    def get_records(cls):
        pool = Pool()
        Model = pool.get('ir.model')
        models = [klass.__name__ for _, klass in pool.iterobject()
            if issubclass(klass, ShopWooCommerceIdMixin)]
        models = Model.search([
                ('model', 'in', models),
                ])
        return [(m.model, m.name) for m in models]


class ShopWooCommerceIdMixin:

    woocommerce_id = fields.Function(
        fields.Integer(
            lazy_gettext('web_shop_woocommerce.msg_woocommerce_id')),
        'get_woocommerce_id',
58
        setter='set_woocommerce_id')
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
59 60 61 62 63 64 65

    @classmethod
    def get_woocommerce_id(cls, records, name):
        pool = Pool()
        WoocommerceID = pool.get('web.shop.woocommerce_id')
        result = {}.fromkeys(r.id for r in records)
        shop = Transaction().context.get('woocommerce_shop', -1)
66
        for sub_records in grouped_slice(records):
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
67 68
            for woo_id in WoocommerceID.search([
                        ('shop', '=', shop),
69
                        ('record', 'in', map(str, sub_records)),
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
70 71 72 73 74 75 76 77 78 79 80 81
                        ]):
                result[woo_id.record.id] = woo_id.woocommerce_id
        return result

    @classmethod
    def set_woocommerce_id(cls, records, name, value):
        pool = Pool()
        WooCommerceId = pool.get('web.shop.woocommerce_id')

        shop = Transaction().context.get('woocommerce_shop', -1)
        if shop < 0:
            return
82 83
        for sub_records in grouped_slice(records):
            sub_records = list(sub_records)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
84 85
            woo_ids = WooCommerceId.search([
                        ('shop', '=', shop),
86
                        ('record', '=', map(str, sub_records)),
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
87 88 89 90
                        ])
            if not woo_ids:
                woo_ids = [
                    WooCommerceId(record=r, shop=shop, woocommerce_id=value)
91
                    for r in sub_records]
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
92 93 94 95 96
                WooCommerceId.save(woo_ids)
            else:
                WooCommerceId.write(woo_ids, {'woocommerce_id': value})

    @classmethod
97 98 99 100 101 102 103 104 105 106
    def delete(cls, records):
        pool = Pool()
        WooCommerceId = pool.get('web.shop.woocommerce_id')
        for sub_records in grouped_slice(records):
            woo_ids = WooCommerceId.search([
                    ('record', 'in', [str(r) for r in sub_records]),
                    ])
            if woo_ids:
                WooCommerceId.delete(woo_ids)
        super().delete(records)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132


class Shop(metaclass=PoolMeta):
    __name__ = 'web.shop'

    woocommerce_url = fields.Char(
        "WooCommerce URL",
        states={
            'required': Eval('type') == 'woocommerce',
            'invisible': Eval('type') != 'woocommerce',
            },
        depends=['type'])
    woocommerce_consumer_key = fields.Char(
        "WooCommerce Consumer Key",
        states={
            'required': Eval('type') == 'woocommerce',
            'invisible': Eval('type') != 'woocommerce',
            },
        depends=['type'])
    woocommerce_consumer_secret = fields.Char(
        "WooCommerce Consumer Secret",
        states={
            'required': Eval('type') == 'woocommerce',
            'invisible': Eval('type') != 'woocommerce',
            },
        depends=['type'])
133
    price_list = fields.Many2One('product.price_list', "Price List")
134 135 136 137 138
    shipping_product = fields.Many2One('product.product', "Shipping Product",
        domain=[
            ('salable', '=', True),
            ('type', '=', 'service'),
            ])
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152

    @classmethod
    def __setup__(cls):
        super().__setup__()
        cls.type.selection.append(('woocommerce', "WooCommerce"))

    @classmethod
    def view_attributes(cls):
        return super().view_attributes() + [
            ('//page[@id="woocommerce"]', 'states', {
                    'invisible': Eval('type') != 'woocommerce',
                    }),
            ]

153 154 155 156 157 158 159 160
    def get_context(self):
        context = super().get_context()
        if self.type == 'woocommerce':
            context['woocommerce_shop'] = self.id
        if self.price_list:
            context['price_list'] = self.price_list.id
        return context

Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    @property
    def to_sync(self):
        result = super().to_sync
        if self.type == 'woocommerce':
            result = True
        return result

    @property
    def woocommerce_api_parameters(self):
        return {
            'url': self.woocommerce_url,
            'consumer_key': self.woocommerce_consumer_key,
            'consumer_secret': self.woocommerce_consumer_secret,
            'timeout': 30,
            }

    def get_woocommerce_api(self):
        return API(**self.woocommerce_api_parameters)

    @classmethod
    def woocommerce_response(cls, request):
182 183 184 185 186 187
        try:
            response = request.json()
        except Exception:
            raise WooCommerceError(
                gettext('web_shop_woocommerce.msg_sincronization_error',
                    response=request.text))
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
188
        if 'message' in response:
189 190 191
            raise WooCommerceError(
                gettext('web_shop_woocommerce.msg_sincronization_error',
                    response=response['message']))
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
192 193
        return response

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    def woocommerce_tryton_record(self, model, woocommerce_id):
        "Return the tryton record of a giveen woocommerce id"
        pool = Pool()
        WooCommerceID = pool.get('web.shop.woocommerce_id')

        if issubclass(model, Model):
            model = model.__name__
        # TODO: Cache?
        table = WooCommerceID.__table__()
        query = table.select(table.id,
            where=(table.record.like(model + '%%')
                & (table.shop == self.id)
                & (table.woocommerce_id == woocommerce_id)))
        records = WooCommerceID.search([('id', 'in', query)], limit=1)
        if records:
            return records[0].record
        return None

212 213
    def woocommerce_compare_values(self, Model, woo_values, values):
        to_update = {}
214 215
        if not woo_values:
            return to_update
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        for key, value in values.items():
            # Do not compare empty categories
            if value == []:
                continue
            woo_value = woo_values.get(key)
            if (isinstance(woo_value, list)
                    and woo_value
                    and isinstance(woo_value[0], dict)
                    and isinstance(value[0], dict)
                    and 'id' in woo_value[0]):
                if 'id' in value[0]:
                    # Use only ids to relation fields
                    woo_value = [{'id': w['id']} for w in woo_value]
                else:
                    # Only compare keys set on Tryton
                    tryton_keys = value[0].keys()
                    woo_value = [dict((k, v)
                            for k, v in x.items()
                            if k in tryton_keys
                            ) for x in woo_value]
            if woo_value != value:
                to_update[key] = value
        return to_update

Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
240 241 242 243 244 245
    def woocommerce_sync_records(self, Model, records, endpoint):
        wcapi = self.get_woocommerce_api()
        to_update = {}
        latter = []

        while records:
246 247 248 249 250 251 252
            for record in records:
                entity = record.get_woocommerce_entity()
                if entity is None:
                    latter.append(record)
                    continue
                woo_id = record.woocommerce_id
                if not woo_id:
253 254 255 256 257 258 259 260
                    try:
                        response = self.woocommerce_response(
                            wcapi.post(endpoint, entity))
                        record.woocommerce_id = response['id']
                    except WooCommerceError:
                        logger.exception(
                            "Error updating record %d", record.id)
                        continue
261 262 263 264
                else:
                    to_update[woo_id] = entity
            Model.save(records)
            Transaction().commit()
265
            if latter and len(records) == len(latter):
266 267 268
                raise MissingParentsError(
                    gettext('web_shop_woocommerce.msg_missing_parents_error',
                        records=','.join([x.rec_name for x in latter])))
269
            logger.info("Created new records %d/%d", len(records), len(latter))
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
270 271 272
            records = latter
            latter = []

273 274
        logger.info("Getting existing records info")
        woo_values = {}
275
        for sub_ids in grouped_slice(list(to_update.keys()), 100):
276 277
            params = {
                'include': ','.join(map(str, sub_ids)),
278
                'per_page': 100,
279 280 281 282 283 284 285
                }
            response = self.woocommerce_response(
                wcapi.get(endpoint, params=params))
            for woo_record in response:
                woo_values[woo_record['id']] = woo_record

        logger.info("Comparing and updating values")
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
286
        for woo_id, values in to_update.items():
287
            to_update = self.woocommerce_compare_values(
288
                Model, woo_values.get(woo_id), values)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
289
            if to_update:
290 291 292 293 294 295
                try:
                    self.woocommerce_response(
                        wcapi.post('%s/%d' % (endpoint, woo_id), to_update))
                except WooCommerceError:
                    logger.exception(
                        "Error updating record %d", woo_id)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
296 297 298 299 300 301

    @classmethod
    def woocommerce_update_products(cls, shops=None):
        pool = Pool()
        Product = pool.get('product.product')
        Category = pool.get('product.category')
302

Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
303 304 305 306 307 308
        if shops is None:
            shops = cls.search([
                    ('type', '=', 'woocommerce'),
                    ])
        cls.lock(shops)
        for shop in shops:
309
            with Transaction().set_context(**shop.get_context()):
310
                logger.info("Syncronizing categories for %s", shop.rec_name)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
311 312 313 314
                shop.woocommerce_sync_records(
                    Category,
                    shop.get_categories(),
                    'products/categories')
315
                logger.info("Syncronizing products for %s", shop.rec_name)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
316 317 318 319 320 321
                products, _, _ = shop.get_products()
                shop.woocommerce_sync_records(
                    Product,
                    products,
                    'products')

322 323 324 325
                logger.info("Removing products for %s", shop.rec_name)
                wcapi = shop.get_woocommerce_api()
                # Rebrowse to get proper context
                for removed in Product.browse(shop.products_removed):
326 327
                    if not removed.woocommerce_id:
                        continue
328 329 330 331 332
                    shop.woocommerce_response(
                        wcapi.post('products/%d' % (removed.woocommerce_id),
                            removed.woocommerce_disable_data(shop)))
                shop.products_removed = []
                # TODO: Manage category removal
333 334
                # shop.categories_removed = []
                logger.info("Finised syncronization for %s", shop.rec_name)
Sergi Almacellas Abellana's avatar
Sergi Almacellas Abellana committed
335 336

        cls.save(shops)
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

    def woocommerce_orders_params(self, page):
        return {
            'status': 'on-hold',
            'page': page,
            }

    def woocommerce_customer(self, order):
        pool = Pool()
        Party = pool.get('party.party')
        customer_id = order.get('customer_id', 0)
        email = order.get('billing', {}).get('email', '')
        if customer_id != 0:
            party = self.woocommerce_tryton_record(Party, customer_id)
            if party:
                return party
        elif email:
            parties = Party.search([
                    ('contact_mechanisms', 'where', [
                            ('type', '=', 'email'),
                            ('value', '=', email),
                            ]),
                    ], limit=1)
            if parties:
                return parties[0]
        return Party.create_from_woocommerce(self, order)

    def woocommerce_sale(self, order):
        pool = Pool()
        Sale = pool.get('sale.sale')
367
        Address = pool.get('party.address')
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
        Currency = pool.get('currency.currency')

        sale = Sale()
        sale.company = self.company
        sale.web_shop = self
        sale.web_id = order['id']
        sale.reference = order['number']
        currencies = Currency.search([
                ('code', '=', order['currency'])
                ], limit=1)
        if not currencies:
            currencies = Currency.search([
                    ('symbol', '=', order['currency_symbol'])
                    ], limit=1)
        if not currencies:
            raise UserError('missing currency')
        sale.currency, = currencies
        sale.party = self.woocommerce_customer(order)
        sale.on_change_party()
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
        if not sale.invoice_address.woocommerce_equal(
                self, order['billing']):
            for address in sale.party.addresses:
                if address.woocommerce_equal(self, order['billing']):
                    sale.invoice_address = address
                    break
            else:
                invoice_address = Address.create_from_woocommerce(
                    self, order['billing'])
                invoice_address.party = sale.party
                invoice_address.save()
                sale.invoice_address = invoice_address
        if not sale.shipment_address.woocommerce_equal(
                self, order['shipping']):
            for address in sale.party.addresses:
                if address.woocommerce_equal(self, order['shipping']):
                    sale.shipment_address = address
                    break
            else:
                shipment_address = Address.create_from_woocommerce(
                    self, order['shipping'])
                shipment_address.party = sale.party
                shipment_address.save()
                sale.shipment_address = shipment_address
        sale.comment = order.get('customer_note')

413 414 415 416 417
        lines = []
        for item in order['line_items']:
            line = self.woocommerce_sale_line(order, item, sale)
            if line:
                lines.append(line)
418 419 420 421 422
        if order.get('shipping_lines'):
            for item in order['shipping_lines']:
                line = self.woocommerce_shipping_line(order, item, sale)
                if line:
                    lines.append(line)
423 424 425 426 427 428 429 430 431 432 433 434 435
        sale.lines = lines
        return sale

    def woocommerce_sale_line(self, order, item, sale):
        pool = Pool()
        Product = pool.get('product.product')
        Line = pool.get('sale.line')

        line = Line()
        line.type = 'line'
        line.sale = sale
        line.product = self.woocommerce_tryton_record(
            Product, item['product_id'])
436 437
        if not line.product:
            line.description = item['name']
438 439 440 441 442
        line.quantity = item['quantity']
        line.on_change_product()
        line.unit_price = round_price(Decimal(str(item['price'])))
        return line

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    def woocommerce_shipping_line(self, order, item, sale):
        pool = Pool()
        Line = pool.get('sale.line')

        if not self.shipping_product:
            raise RequiredValidationError(
                gettext('web_shop_woocommerce'
                    '.msg_missing_shipping_product',
                    shop=self.rec_name))

        line = Line()
        line.type = 'line'
        line.sale = sale
        line.product = self.shipping_product
        line.description = item['method_title']
        line.quantity = 1.0
        line.on_change_product()
        line.unit_price = round_price(Decimal(str(item['total'])))
        return line

463 464 465 466 467 468 469 470 471 472 473
    @classmethod
    def woocommerce_download_orders(cls, shops=None):
        pool = Pool()
        Sale = pool.get('sale.sale')

        if shops is None:
            shops = cls.search([
                    ('type', '=', 'woocommerce'),
                    ])
        cls.lock(shops)
        for shop in shops:
474
            sales = []
475
            with Transaction().set_context(**shop.get_context()):
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
                wcapi = shop.get_woocommerce_api()
                page = 1
                orders = shop.woocommerce_response(
                    wcapi.get(
                        'orders',
                        params=shop.woocommerce_orders_params(page)))
                while orders:
                    for order in orders:
                        sale = shop.woocommerce_sale(order)
                        if sale:
                            sales.append(sale)
                    page += 1
                    orders = shop.woocommerce_response(
                        wcapi.get(
                            'orders',
                            params=shop.woocommerce_orders_params(page)))
492
                Sale.save(sales)
493 494
                Sale.quote(sales)
                Sale.confirm(sales)
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
                shop.update_woocommerce_status(sales, 'processing')

    def update_woocommerce_status(self, sales, status):
        wcapi = self.get_woocommerce_api()
        for sale in sales:
            self.woocommerce_response(
                wcapi.post(
                    'orders/%s' % sale.web_id,
                    data={'status': status}))


class Sale(metaclass=PoolMeta):
    __name__ = 'sale.sale'

    @property
    def woocommerce_completed(self):
        return self.shipment_state == 'sent'

    @classmethod
    def process(cls, sales):
        to_check = []
        for sale in sales:
            if (sale.web_shop
                    and sale.web_shop.type == 'woocommerce'
                    and not sale.woocommerce_completed):
                to_check.append(sale)
        super().process(sales)
        for sale in to_check:
            if sale.woocommerce_completed:
                sale.web_shop.update_woocommerce_status([sale], 'completed')