Пример #1
0
    def unit_for(self, connector_unit_class, model=None):
        """ According to the current
        :py:class:`~connector.connector.ConnectorEnvironment`,
        search and returns an instance of the
        :py:class:`~connector.connector.ConnectorUnit` for the current
        model and being a class or subclass of ``connector_unit_class``.

        If a different ``model`` is given, a new
        :py:class:`~connector.connector.ConnectorEnvironment`
        is built for this model.

        :param connector_unit_class: ``ConnectorUnit`` to search
                                     (class or subclass)
        :type connector_unit_class: :py:class:`connector.\
                                               connector.ConnectorUnit`
        :param model: to give if the ``ConnectorUnit`` is for another
                      model than the current one
        :type model: str
        """
        if model is None:
            env = self.connector_env
        else:
            env = ConnectorEnvironment(self.backend_record, self.session,
                                       model)
        return env.get_connector_unit(connector_unit_class)
Пример #2
0
 def get_map_file(self):
     self.mapping_file = False
     session = ConnectorSession.from_env(self.env)
     env = ConnectorEnvironment(self, session, 'prime.catalog.service')
     service = env.get_connector_unit(PrimeCatalogService)
     service.url = self.url
     service.token = self.token
     self.mapping_file = service.get_map_file()
def export_stock_quant_job(session, model_name, backend_id, quant_id=None):
    backend = backends(session, backend_id)
    env = ConnectorEnvironment(backend, session, 'prime.catalog.service')
    service = env.get_connector_unit(PrimeCatalogService)
    service.url = backend.url

    if quant_id:
        quants = session.env[model_name].browse(quant_id)
        for quant in quants:
            service.write_quant(quant)
Пример #4
0
 def revoke_token(self):
     self.ensure_one()
     session = ConnectorSession.from_env(self.env)
     env = ConnectorEnvironment(self, session, 'prime.catalog.service')
     service = env.get_connector_unit(PrimeCatalogService)
     service.url = self.url
     try:
         token = service.revoke_token(self.login, self.password)
     except NotImplementedError as err:
         raise UserError(str(err))
     self.write({'token': token})
Пример #5
0
def export_partner(session, model_name, record_id):
    """ Exporting a partner """
    _logger.info('exporting %s with id %d', model_name, record_id)
    binding = session.env[model_name].browse(record_id)
    if not binding.exists():
        return

    backend = binding.backend_id
    connector_env = ConnectorEnvironment(backend, session, model_name)
    exporter = connector_env.get_connector_unit(Exporter)
    exporter.run(binding.id)
Пример #6
0
 def get_mapper(cls, env, model):
     mapper = None
     backend_records = env[cls._name].search([])
     if backend_records:
         session = ConnectorSession(env.cr, env.uid)
         connector_env = ConnectorEnvironment(backend_records[0], session,
                                              model)
         try:
             mapper = connector_env.get_connector_unit(ImportMapperBase)
         except NoConnectorUnitError:
             pass
     return mapper
Пример #7
0
def export_product_job(session, model_name, backend_id, product_id):
    backend = backends(session, backend_id)
    env = ConnectorEnvironment(backend, session, 'prime.catalog.service')
    service = env.get_connector_unit(PrimeCatalogService)
    service.url = backend.url
    service.token = backend.token
    service.attrs_info = backend.get_attr_info()

    if product_id:
        product = session.env[model_name].browse(product_id)
        try:
            product_data = service.get_product_data(product)
            service.post_product(product_data)
        except ConnectionError:
            raise RetryableJobError('Failed Connect to Catalog!')
Пример #8
0
    def test_concurrent_import(self):
        connector_env = ConnectorEnvironment(self.backend, self.session,
                                             'magento.product.category')
        importer = ProductCategoryImporter(connector_env)
        with mock_api(magento_base_responses):
            importer.run(1)

        connector_env2 = ConnectorEnvironment(self.backend2,
                                              self.connector_session2,
                                              'magento.product.category')
        importer2 = ProductCategoryImporter(connector_env2)
        fields_path = ('openerp.addons.magentoerpconnect'
                       '.unit.import_synchronizer.fields')
        with mock.patch(fields_path):
            with self.assertRaises(RetryableJobError):
                importer2.run(1)
Пример #9
0
def delete_product_job(session, model_name, backend_id, product_id):
    backend = backends(session, backend_id)
    env = ConnectorEnvironment(backend, session, 'prime.catalog.service')
    service = env.get_connector_unit(PrimeCatalogService)
    service.url = backend.url
    service.token = backend.token

    if product_id:
        product_data = {
            'id': str(product_id),
            'delete': True,
        }
        try:
            service.post_product(product_data)
        except Exception:
            raise RetryableJobError('Failed Post Product')
Пример #10
0
 def _get_base_adapter(self):
     """
     Get an adapter to test the backend connection
     """
     self.ensure_one()
     session = ConnectorSession.from_env(self.env)
     environment = ConnectorEnvironment(self, session, None)
     return CmisAdapter(environment)
Пример #11
0
 def setUp(self):
     super(test_mapper_recordsets, self).setUp()
     self.session = ConnectorSession(self.cr, self.uid)
     self.backend = mock.Mock(wraps=Backend('x', version='y'),
                              name='backend')
     backend_record = mock.Mock()
     backend_record.get_backend.return_value = self.backend
     self.connector_env = ConnectorEnvironment(
         backend_record, self.session, 'res.partner')
Пример #12
0
    def test_create_environment_no_connector_env(self):
        session = mock.MagicMock(name="Session")
        backend_record = mock.Mock(name="BackendRecord")
        backend = mock.Mock(name="Backend")
        backend_record.get_backend.return_value = backend
        model = "res.user"

        connector_env = ConnectorEnvironment.create_environment(backend_record, session, model)

        self.assertEqual(type(connector_env), ConnectorEnvironment)
Пример #13
0
    def test_mapping_record_children_no_map_child(self):
        """ Map a record with children, using default MapChild """

        backend = Backend('backend', '42')

        @backend
        class LineMapper(ImportMapper):
            _model_name = 'res.currency.rate'
            direct = [('name', 'name')]

            @mapping
            def price(self, record):
                return {'rate': record['rate'] * 2}

            @only_create
            @mapping
            def discount(self, record):
                return {'test': .5}

        @backend
        class ObjectMapper(ImportMapper):
            _model_name = 'res.currency'

            direct = [('name', 'name')]

            children = [('lines', 'line_ids', 'res.currency.rate')]

        backend_record = mock.Mock()
        backend_record.get_backend.side_effect = lambda *a: backend
        env = ConnectorEnvironment(backend_record, self.session,
                                   'res.currency')

        record = {'name': 'SO1',
                  'lines': [{'name': '2013-11-07',
                             'rate': 10},
                            {'name': '2013-11-08',
                             'rate': 20}]}
        mapper = ObjectMapper(env)
        map_record = mapper.map_record(record)
        expected = {'name': 'SO1',
                    'line_ids': [(0, 0, {'name': '2013-11-07',
                                         'rate': 20}),
                                 (0, 0, {'name': '2013-11-08',
                                         'rate': 40})]
                    }
        self.assertEqual(map_record.values(), expected)
        expected = {'name': 'SO1',
                    'line_ids': [(0, 0, {'name': '2013-11-07',
                                         'rate': 20,
                                         'test': .5}),
                                 (0, 0, {'name': '2013-11-08',
                                         'rate': 40,
                                         'test': .5})]
                    }
        self.assertEqual(map_record.values(for_create=True), expected)
Пример #14
0
def get_environment(session, model_name, backend_id):
    """ Create an environment to work with.  """
    backend_record = session.env['wc.backend'].browse(backend_id)
    env = ConnectorEnvironment(backend_record, session, model_name)
    lang = backend_record.default_lang_id
    lang_code = lang.code if lang else 'en_US'
    if lang_code == session.context.get('lang'):
        return env
    else:
        with env.session.change_context(lang=lang_code):
            return env
Пример #15
0
    def test_create_environment_no_connector_env(self):
        session = mock.MagicMock(name='Session')
        backend_record = mock.Mock(name='BackendRecord')
        backend = mock.Mock(name='Backend')
        backend_record.get_backend.return_value = backend
        model = 'res.user'

        connector_env = ConnectorEnvironment.create_environment(
            backend_record, session, model)

        self.assertEqual(type(connector_env), ConnectorEnvironment)
def unwrap_binding(session, job, id_pos=2, binder_class=EasypostBinder):
    """ Open a form view with the unwrapped record.
    For instance, for a job on a ``magento.product.product``,
    it will open a ``product.product`` form view with the unwrapped
    record.
    :param id_pos: position of the binding ID in the args
    :param binder_class: base class to search for the binder
    """
    binding_model = job.args[0]
    # shift one to the left because session is not in job.args
    binding_id = job.args[id_pos - 1]
    action = {
        'name': _('Related Record'),
        'type': 'ir.actions.act_window',
        'view_type': 'form',
        'view_mode': 'form',
    }
    # try to get an unwrapped record
    binding = session.env[binding_model].browse(binding_id)
    if not binding.exists():
        # it has been deleted
        return None
    env = ConnectorEnvironment(binding.backend_id, session, binding_model)
    binder = env.get_connector_unit(binder_class)
    try:
        model = binder.unwrap_model()
        record_id = binder.unwrap_binding(binding_id)
    except ValueError:
        # the binding record will be displayed
        action.update({
            'res_model': binding_model,
            'res_id': binding_id,
        })
    else:
        # the unwrapped record will be displayed
        action.update({
            'res_model': model,
            'res_id': record_id,
        })
    return action
Пример #17
0
 def catalog_api_load_mapping(self):
     self.ensure_one()
     session = ConnectorSession.from_env(self.env)
     env = ConnectorEnvironment(self, session, 'prime.catalog.service')
     service = env.get_connector_unit(PrimeCatalogService)
     service.url = self.url
     service.token = self.token
     esa = self.env['external.service.attribute']
     mapping = service.get_mapping()
     clear_fields = {
         key: value
         for key, value in mapping.items() if isinstance(value, dict)
     }
     for code, data in clear_fields.items():
         field = {
             'backend_id': self.id,
             'parent_id': False,
             'code': code,
             'type_id': data['type'],
             'additional_info': json_dumps(data)
         }
         esa.get_or_create(field)
Пример #18
0
def get_environment(session, binding_model_name, backend_id):
    """ Create an environment to work with. """
    backend_record = session.env['getresponse.backend'].browse(backend_id)

    # Get a connector environment for the given model
    con_env = ConnectorEnvironment(backend_record, session, binding_model_name)

    # Change the language based on the backend setting and return the env
    backend_lang = backend_record.default_lang_id
    lang_code = backend_lang.code if backend_lang and backend_lang.code else 'de_DE'
    if lang_code == session.context.get('lang'):
        return con_env
    else:
        _logger.warning(
            "Changing lang code for getresponse connector env to %s" %
            lang_code)
        with con_env.session.change_context(lang=lang_code):
            return con_env
    def setUp(self):
        super(TestDefaultBinder, self).setUp()

        class PartnerBinder(Binder):
            "we use already existing fields for the binding"
            _model_name = 'res.partner'
            _external_field = 'ref'
            _sync_date_field = 'date'
            _backend_field = 'color'
            _openerp_field = 'id'

        self.session = ConnectorSession(self.cr, self.uid)
        self.backend = Backend('dummy', version='1.0')
        backend_record = mock.Mock()
        backend_record.id = 1
        backend_record.get_backend.return_value = self.backend
        self.connector_env = ConnectorEnvironment(
            backend_record, self.session, 'res.partner')
        self.partner_binder = PartnerBinder(self.connector_env)
Пример #20
0
def get_environment(session, model_name, backend_id):
    """ Create an environment to work with. """
    backend_record = session.env['locomotive.backend'].browse(backend_id)
    return ConnectorEnvironment(backend_record, session, model_name)
Пример #21
0
 def get_environment(self, model_name, session=None):
     self.ensure_one()
     if not session:
         session = ConnectorSession.from_env(self.env)
     return ConnectorEnvironment(self, session, model_name)
Пример #22
0
    def test_mapping_record_children_filters(self):
        """ Map a record with children, using defined MapChild """

        backend = Backend('backend', '42')

        @backend
        class LineMapper(ImportMapper):
            _model_name = 'res.currency.rate'
            direct = [('name', 'name')]

            @mapping
            def price(self, record):
                return {'rate': record['rate'] * 2}

        @backend
        class SaleLineImportMapChild(ImportMapChild):
            _model_name = 'res.currency.rate'

            def format_items(self, items_values):
                return [('ABC', values) for values in items_values]

            def skip_item(self, map_record):
                '''Filter by the values before the mapping'''
                record = map_record.source
                return (record['rate'] > 35)

            def skip_add_item(self, item_values):
                '''Filter by the values after the mapping'''
                return (item_values['rate'] < 30)

        @backend
        class ObjectMapper(ImportMapper):
            _model_name = 'res.currency'

            direct = [('name', 'name')]

            children = [('lines', 'line_ids', 'res.currency.rate')]

        backend_record = mock.Mock()
        backend_record.get_backend.side_effect = lambda *a: backend
        env = ConnectorEnvironment(backend_record, self.session,
                                   'res.currency')

        record = {'name': 'SO1',
                  'lines': [{'name': '2013-11-07',
                             'rate': 10},
                            {'name': '2013-11-08',
                             'rate': 20},
                            {'name': '2013-11-09',
                             'rate': 30},
                            {'name': '2013-11-10',
                             'rate': 40}]
                  }
        mapper = ObjectMapper(env)
        map_record = mapper.map_record(record)
        expected = {'name': 'SO1',
                    'line_ids': [('ABC', {'name': '2013-11-08',
                                          'rate': 40}),
                                 ('ABC', {'name': '2013-11-09',
                                          'rate': 60})]
                    }
        self.assertEqual(map_record.values(), expected)
Пример #23
0
    def test_play_onchange(self):
        """ Play the onchange ConnectorUnit on a sales order """
        product_model = self.env['product.product']
        partner_model = self.env['res.partner']
        tax_model = self.env['account.tax']

        backend_record = mock.Mock()
        env = ConnectorEnvironment(backend_record, self.session, 'sale.order')

        partner = partner_model.create({
            'name': 'seb',
            'zip': '69100',
            'city': 'Villeurbanne'
        })
        partner_invoice = partner_model.create({
            'name': 'Guewen',
            'zip': '1015',
            'city': 'Lausanne',
            'type': 'invoice',
            'parent_id': partner.id
        })
        tax = tax_model.create({'name': 'My Tax', 'amount': 1.0})
        product = product_model.create({
            'default_code': 'MyCode',
            'name': 'My Product',
            'weight': 15,
            'taxes_id': [(6, 0, [tax.id])]
        })
        payment_mode_xmlid = 'account_payment_mode.payment_mode_inbound_ct2'
        payment_mode = self.env.ref(payment_mode_xmlid)

        order_vals = {
            'name':
            'mag_10000001',
            'partner_id':
            partner.id,
            'payment_mode_id':
            payment_mode.id,
            'order_line': [
                (0, 0, {
                    'product_id': product.id,
                    'price_unit': 20,
                    'name': 'My Real Name',
                    'product_uom_qty': 1,
                    'sequence': 1,
                }),
            ],
            # fake field for the lines coming from a backend
            'backend_order_line': [
                (0, 0, {
                    'product_id': product.id,
                    'price_unit': 10,
                    'name': 'Line 2',
                    'product_uom_qty': 2,
                    'sequence': 2,
                }),
            ],
        }

        extra_lines = order_vals['backend_order_line']

        onchange = SaleOrderOnChange(env)
        order = onchange.play(order_vals, extra_lines)

        self.assertEqual(order['partner_invoice_id'], partner_invoice.id)
        self.assertEqual(len(order['order_line']), 1)
        line = order['order_line'][0][2]
        self.assertEqual(line['name'], 'My Real Name')
        self.assertEqual(line['product_uom'], product.uom_id.id)
        self.assertEqual(line['tax_id'], [(5, ), (4, tax.id)])
        line = order['backend_order_line'][0][2]
        self.assertEqual(line['name'], 'Line 2')
        self.assertEqual(line['product_uom'], product.uom_id.id)
        self.assertEqual(line['tax_id'], [(5, ), (4, tax.id)])