这篇主要讲述如何二开增加自己的功能,我没有继承方式二开,习惯是不好的,直接改了原来的模块。

达到效果就这样,当在网站支付成功,会同步到ERP系统中。下面来讲述实现过程

建立文件 payment_notice.py

# -*- coding: utf-8 -*-

import logging
import xmlrpclib
from datetime import datetime, timedelta
import openerp.addons.decimal_precision as dp
from openerp import models, fields, api, _
from openerp.addons.connector.connector import ConnectorUnit
from openerp.addons.connector.exception import (NothingToDoJob,
                                                FailedJobError,
                                                IDMissingInBackend)
from openerp.addons.connector.queue.job import job

from openerp.addons.connector.unit.mapper import (mapping,
                                                  ImportMapper
                                                  )

from .unit.backend_adapter import (GenericAdapter,
                                   MAGENTO_DATETIME_FORMAT,
                                   )
from .unit.import_synchronizer import (DelayedBatchImporter,
                                       MagentoImporter,
                                       )
from .unit.mapper import normalize_datetime
from .backend import magento
from .connector import get_environment
from openerp.tools.float_utils import float_round

_logger = logging.getLogger(__name__)

class MagentoPaymentNotice(models.Model):
    _name = 'magento.payment.notice'
   
_inherit = 'magento.binding'
   
_description = 'Magento Payment Notice'
   
_inherits = {'payment.notice': 'openerp_id'}

    openerp_id = fields.Many2one(comodel_name='payment.notice',
                                 string='Payment Notice',
                                 required=True,
                                 ondelete='cascade')
    total_amount = fields.Float(
        string='Total amount',
        digits_compute=dp.get_precision('Account')
    )
    total_amount_tax = fields.Float(
        string='Total amount w. tax',
        digits_compute=dp.get_precision('Account')
    )
    magento_order_id = fields.Integer(string='Magento Order ID',
                                      help="'order_id' field in Magento")
    # when a sale order is modified, Magento creates a new one, cancels
    # the parent order and link the new one to the canceled parent
   
magento_parent_id = fields.Many2one(comodel_name='magento.sale.order',
                                        string='Parent Magento Order')
    storeview_id = fields.Many2one(comodel_name='magento.storeview',
                                   string='Magento Storeview')
    store_id = fields.Many2one(related='storeview_id.store_id',
                               string='Storeview',
                               readonly=True)

class PaymentNotice(models.Model):
    _inherit = 'payment.notice'

   
magento_bind_ids = fields.One2many(
        comodel_name='magento.payment.notice',
        inverse_name='openerp_id',
        string="Magento Bindings",
    )

@magento
class PaymentNoticeAdapter(GenericAdapter):
    _model_name = 'magento.payment.notice'
   
_magento_model = 'sales_order'
   
_admin_path = '{model}/view/order_id/{id}'

   
def _call(self, method, arguments):
        try:
            return super(PaymentNoticeAdapter, self)._call(method, arguments)
        except xmlrpclib.Fault as err:
            # this is the error in the Magento API
            # when the sales order does not exist
           
if err.faultCode == 100:
                raise IDMissingInBackend
            else:
                raise

    def
search(self, filters=None, from_date=None, to_date=None,
               magento_storeview_ids=None):
        """ Search records according to some criteria
        and returns a list of ids

       
:rtype: list
        """
       
if filters is None:
            filters = {}
        dt_fmt = MAGENTO_DATETIME_FORMAT
        if from_date is not None:
            filters.setdefault('created_at', {})
            filters['created_at']['from'] = from_date.strftime(dt_fmt)
        if to_date is not None:
            filters.setdefault('created_at', {})
            filters['created_at']['to'] = to_date.strftime(dt_fmt)
        if magento_storeview_ids is not None:
            filters['store_id'] = {'in': magento_storeview_ids}

        arguments = {'imported': False,
                     # 'limit': 200,
                    
'filters': filters,
                     }
        return super(PaymentNoticeAdapter, self).search(arguments)

    def read(self, id, attributes=None):
        """ Returns the information of a record

       
:rtype: dict
        """
       
record = self._call('%s.info' % self._magento_model,
                            [id, attributes])
        return record

@magento
class PaymentNoticeBatchImport(DelayedBatchImporter):
    _model_name = ['magento.payment.notice']

    def _import_record(self, record_id, description=None,**kwargs):
        """ Import the record directly """
       
return super(PaymentNoticeBatchImport, self)._import_record(
            record_id,description=description, max_retries=0, priority=5)

    def run(self, filters=None):
        """ Run the synchronization """
       
if filters is None:
            filters = {}
        filters['status'] = {'in': ['complete', 'processing', 'challenged']}
        from_date = filters.pop('from_date', None)
        to_date = filters.pop('to_date', None)
        magento_storeview_ids = [filters.pop('magento_storeview_id')]
        record_ids = self.backend_adapter.search(
            filters,
            from_date=from_date,
            to_date=to_date,
            magento_storeview_ids=magento_storeview_ids)
        _logger.info('search for magento saleorders %s returned %s',
                     filters, record_ids)
        for record_id in record_ids:
            self._import_record(
                                record_id,
                                description='Import payment notice, Order# of website: %s' % self.backend_adapter.read(record_id).get('increment_id')
                                )

@magento
class PaymentNoticeImportRule(ConnectorUnit):
    _model_name = ['magento.payment.notice']

    def check(self, record):
        """ Check whether the current sale order should be imported
        or not. It will actually use the payment method configuration
        and see if the choosed rule is fullfilled.

       
:returns: True if the sale order should be imported
       
:rtype: boolean
        """
       
payment_method = record['payment']['method']
        method = self.env['payment.method'].search(
            [('magento_payment_code', '=', payment_method)],
            limit=1,
        )
        if not method:
            raise FailedJobError(
                "The configuration is missing for the Payment Method '%s'.\n\n"
                "Resolution:
\n"
                "- Go to "
                "'Sales > Configuration > Sales > Customer Payment Method
\n"
                "- Create a new Payment Method with name '%s'
\n"
                "-Eventually  link the Payment Method to an existing Workflow "
                "Process or create a new one."
% (payment_method,
                                                  payment_method))

@magento
class PaymentNoticeImportMapper(ImportMapper):
    _model_name = 'magento.payment.notice'

   
direct = [('increment_id', 'magento_id'),
              ('order_id', 'magento_order_id'),
              ('grand_total', 'total_amount'),
              ('tax_amount', 'total_amount_tax'),
              ('store_id', 'storeview_id'),
              ]

    @mapping
    def sale_order_site(self, record):
        sale_order_site = record['increment_id']
        return {'sale_order_site': sale_order_site}

    @mapping
    def amount(self, record):
        amount = record['grand_total']
        return {'amount': amount}

    @mapping
    def currency(self, record):
        record_currency = record['order_currency_code']
        currency = self.env['res.currency'].search(
            [['name', '=', record_currency]],
            limit=1,
        )
        assert currency, ("currency %s should exist because the import fails "
                        "in PaymentNoticeImporter._before_import when it is "
                        " missing"
% record['order_currency_code'])
        return {'currency_id': currency.id}

    @mapping
    def payment(self, record):
        record_method = record['payment']['method']
        method = self.env['payment.method'].search(
            [['magento_payment_code', '=', record_method]],
            limit=1,
        )

        assert method, ("method %s should exist because the import fails "
                        "in PaymentNoticeImporter._before_import when it is "
                        " missing"
% record['payment']['method'])
        return {'payment_method_id': method.id}

    @mapping
    def description(self, record):
        order_date = normalize_datetime('created_at')(self, record, '')
        dd=datetime.strptime(order_date, '%Y-%m-%d %H:%M:%S')
        order_date_f=dd.strftime('%m/%d/%Y')
        record_currency = record['order_currency_code']
        billing_address = record['billing_address']
        billing_name = billing_address['firstname']+' ' + billing_address['lastname']
        paypal_id = record['payment']['last_trans_id'] and record['payment']['last_trans_id'] or ''
       
prec = self.env['decimal.precision'].precision_get('Account')
        amount = str(float_round(float(record['grand_total']), prec))
        payment_method = record['payment']['method']
        if payment_method == 'paypal_standard' or payment_method =='paypal_express' :
            description = order_date_f+' '+billing_name +' '+ record_currency+' '+amount+ ' ID: '+ paypal_id
        else:
            description = order_date_f + ' ' + billing_name + ' ' + record_currency + ' ' + amount
        return {'description': description}

    @mapping
    def backend_id(self, record):
        return {'backend_id': self.backend_record.id}

@magento
class PaymentNoticeImporter(MagentoImporter):
    _model_name = ['magento.payment.notice']

    _base_mapper = PaymentNoticeImportMapper

    def _must_skip(self):
        if self.binder.to_openerp(self.magento_id):
            return _('Already imported')

    def _before_import(self):
        rules = self.unit_for(PaymentNoticeImportRule)
        rules.check(self.magento_record)

    def _get_storeview(self, record):
        """ Return the tax inclusion setting for the appropriate storeview """
       
storeview_binder = self.binder_for('magento.storeview')
        # we find storeview_id in store_id!
        # (http://www.magentocommerce.com/bug-tracking/issue?issue=15886)
       
return storeview_binder.to_openerp(record['store_id'], browse=True)

    def _get_magento_data(self):
        """ Return the raw Magento data for ``self.magento_id`` """
       
record = super(PaymentNoticeImporter, self)._get_magento_data()
        # sometimes we don't have website_id...
        # we fix the record!
       
if not record.get('website_id'):
            storeview = self._get_storeview(record)
            # deduce it from the storeview
           
record['website_id'] = storeview.store_id.website_id.magento_id
        return record

    def _create_data(self, map_record, **kwargs):
        storeview = self._get_storeview(map_record.source)
        return super(PaymentNoticeImporter, self)._create_data(
            map_record,
            storeview=storeview,
            **kwargs)

    def _update_data(self, map_record, **kwargs):
        storeview = self._get_storeview(map_record.source)
        return super(PaymentNoticeImporter, self)._update_data(
            map_record,
            storeview=storeview,
            **kwargs)

PaymentNoticeImporter = PaymentNoticeImporter  # deprecated

@job(default_channel='root.magento')
def payment_notice_import_batch(session, model_name, backend_id, filters=None):
    """ Prepare a batch import of sale order(payment notice) from Magento """
   
if filters is None:
        filters = {}
    assert 'magento_storeview_id' in filters, ('Missing information about '
                                               'Magento Storeview'
)
    env = get_environment(session, model_name, backend_id)
    importer = env.get_connector_unit(PaymentNoticeBatchImport)
    importer.run(filters)

在 __init__.py

在 unit/binder 下加入

在magento_model.py 加入

在_name = 'magento.storeview' 类中
@api.multi

def import_payment_notices(self):

    session = ConnectorSession(self.env.cr, self.env.uid,

                               context=self.env.context)

    import_start_time = datetime.now()

    for storeview in self:

        if storeview.no_payment_notice_sync:

            _logger.debug("The storeview '%s' is active in Magento "

                          "but is configured not to import the "

                          "payment notices"
, storeview.name)

            continue

       
backend_id = storeview.backend_id.id

        if storeview.import_payment_notices_from_date:

            from_string = fields.Datetime.from_string

            from_date = from_string(storeview.import_payment_notices_from_date)

        else:

            from_date = None

        payment_notice_import_batch.delay(

            session,

            'magento.payment.notice',

            backend_id,

            {'magento_storeview_id': storeview.magento_id,

             'from_date': from_date,

             'to_date': import_start_time},

            priority=1,

        )  # executed as soon as possible



   
next_time = import_start_time - timedelta(seconds=IMPORT_DELTA_BUFFER)

    next_time = fields.Datetime.to_string(next_time)

    self.write({'import_payment_notices_from_date': next_time})

    return True
 在_name = 'magento.backend'

中

import_payment_notices_from_date = fields.Datetime(

    string='Import payment notices from date',

    help='do not consider non-imported payment notice before this date. '

         'Leave empty to import all payment notice of sale orders'
,

)
@api.multi

def import_payment_notices(self):

    """ Import sale orders from all store views """

   
storeview_obj = self.env['magento.storeview']

    storeviews = storeview_obj.search([('backend_id', 'in', self.ids)])

    storeviews.import_payment_notices()

    return True
@api.model

def _scheduler_import_payment_notices(self, domain=None):

    self._magento_backend('import_payment_notices', domain=domain)
 
在magentoerpconnect_data.xml 中加入
<record forcecreate="True" id="ir_cron_import_payment_notices" model="ir.cron">

    <field name="name">Magento - Import Payment Notices</field>

    <field eval="False" name="active"/>

    <field name="user_id" ref="base.user_root"/>

    <field name="interval_number">1</field>

    <field name="interval_type">days</field>

    <field name="numbercall">-1</field>

    <field eval="False" name="doall"/>

    <field eval="'magento.backend'" name="model"/>

    <field eval="'_scheduler_import_payment_notices'" name="function"/>

    <field eval="'()'" name="args"/>

</record>
 

剩下来,就是界面的设定

这样就完成了。

(51) magento集成增加到款通知的更多相关文章

  1. magento currency magento头部增加币种切换选择

    magento currency magento头部增加币种切换选择 默认magento 货币选择切换是显示在左边 有时候我们需要让其显示在头部 Step 1. Create a new file a ...

  2. 如何在magento后台增加一个自定义订单状态

    magento后台订单状态(order status)只有Pending.Processing.On Hold.Closed.Canceled.Pending Payment 等等,如何在magent ...

  3. jenkins 集成钉钉机器人通知

    公司使用钉钉做为公司内部的通讯工具,所以想通过Jenkins发布完成以后通过钉钉来通知大家,研究发现钉钉提供机器人,所以我把机器人集成进来通知相关人员. 1.创建通知人群组,添加机器人(钉钉默认自带了 ...

  4. (九十七)集成JPush实现远程通知和推送的发送

    上节介绍了通过直接和APNS交互实现推送的方法,较为繁琐,最为重要的是发送推送需要特定的服务端,通过JPush,不仅可以简化客户端的接收,还可以通过控制台或者API实现通知的发送. 首先注册JPush ...

  5. (50)与magento集成

    我对接的是 odoo8 和 magento1.9.x 准备工作: l  服务器 装上mangento 组件 : $  pip install magento 装上 requests 组件:$ pip ...

  6. APICloud首款全功能集成开发工具重磅发布,彰显云端一体理念

    近日,APICloud重磅推出首款云端一体的全功能集成开发工具--APICloud Studio 2.为了更深入了解这款开发工具的特性及优势,APICloud CTO 邹达针对几个核心问题做出了解答. ...

  7. 持续集成 TeamCity 的配置与使用

    环境:实现自动编译与自动化测试,发布到远程服务器,环境 VS2015 +WIN2008R2 什么是TeamCity TeamCity是由Jetbrains开发的一款功能强大的持续集成(Continue ...

  8. 10款无需编程的App DIY开发工具

    10款无需编程的App DIY开发工具 你有一个很棒的创意但不会编程怎么办?外包.合伙开发还是从零学编程?这里提供另外一种方式--使用无需编程的App  DIY开发工具.DIY开发工具不仅节省了开发时 ...

  9. 使用TeamCity对项目进行可持续集成管理

    使用TeamCity对项目进行可持续集成管理 一.可持续集成管理   持续集成,CI:即Continuous integration. 可持续集成的概念是基于团队(小组)协作开发而提出来的,为了提高团 ...

随机推荐

  1. luogu p1003

    P1003 题意 经过多个矩形(1e3)覆盖后后某个坐标属于那个矩形(仅仅是一次询问) 大水题,直接的做法,从后向前处理矩形是否覆盖查询的点,若覆盖,则是该矩形编号 题解 int get_num(){ ...

  2. POJ 1743 [USACO5.1] Musical Theme (后缀数组+二分)

    洛谷P2743传送门 题目大意:给你一个序列,求其中最长的一对相似等长子串 一对合法的相似子串被定义为: 1.任意一个子串长度都大于等于5 2.不能有重叠部分 3.其中一个子串可以在全部+/-某个值后 ...

  3. 首页 > 所有书 > 操作系统 > Linux >

    http://book.51cto.com/col/1213/list_1213_8.htm linux一些经典教材

  4. VUE:路由

    VUE:路由 一.说明 1)官方提供的用来实现SPA的vue插件 2)github:https://github.com/vuejs/vue-router 3)中文文档:http://router.v ...

  5. tp 在Nginx上各种404

    对于ThinkPHP的URL访问路劲如:http://域名/index.php/Index/BlogTest/read,原先的Nginx的是不支持的pathinfo路劲的,导致你在thinkPHP5上 ...

  6. HDU 4253 Two Famous Companies

    Two Famous Companies Time Limit: 15000ms Memory Limit: 32768KB This problem will be judged on HDU. O ...

  7. HDU 4310 Contest 2

    贪心,注意排序条件. #include <iostream> #include <cstdio> #include <algorithm> using namesp ...

  8. PC端 java 开发蓝牙所遇到的问题

    由于项目的原因.要在电脑上开发一个通过蓝牙传送数据的client.我採用的是JAVA,JSME开发. client:去搜素蓝牙信号,然后找到对应的蓝牙信号进行连接. 服务端:client须要进行连接的 ...

  9. Android LaunchMode案例篇

    首先感谢小伙伴的关注.然后祝愿广大的情侣们节日快乐! 在开发中有时会遇到这种场景,用户点击注冊.第一步,第二步,完毕注冊跳转到登录界面,不须要用户一步一步的返回到登录界面.这是怎么实现的呢? 案例:有 ...

  10. Baby_Step,Gaint_Step(分析具体解释+模板)

    下面是总结自他人博客资料.以及本人自己的学习经验. [Baby_Step,Gaint_Step定义] 高次同余方程. BL == N (mod P) 求解最小的L.因为数据范围非常大,暴力不行 这里用 ...