<commit_before># -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
# Copyright (C) 2009  Renato Lima - Akretion, Gabriel C. Stabel                 #
#                                                                               #
#This program is free software: you can redistribute it and/or modify           #
#it under the terms of the GNU General Public License as published by           #
#the Free Software Foundation, either version 3 of the License, or              #
#(at your option) any later version.                                            #
#                                                                               #
#This program is distributed in the hope that it will be useful,                #
#but WITHOUT ANY WARRANTY; without even the implied warranty of                 #
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                  #
#GNU General Public License for more details.                                   #
#                                                                               #
#You should have received a copy of the GNU General Public License              #
#along with this program.  If not, see <http://www.gnu.org/licenses/>.          #
#################################################################################

from osv import osv, fields

##############################################################################
# Ordem de Compra Customizada
##############################################################################
class purchase_order(osv.osv):
    _inherit = 'purchase.order'
    _columns = {
        'fiscal_operation_category_id': fields.many2one('l10n_br_account.fiscal.operation.category', 'Categoria'),
        'fiscal_operation_id': fields.many2one('l10n_br_account.fiscal.operation', 'Operação Fiscal', domain="[('fiscal_operation_category_id','=',fiscal_operation_category_id)]" ),
    }

    def onchange_partner_id(self, cr, uid, ids, part, company_id=False, fiscal_operation_category_id=False):

        result = super(purchase_order, self ).onchange_partner_id(cr, uid, ids, part, company_id)

        if (not part or not company_id or not result['value']['partner_address_id'] or not fiscal_operation_category_id):
            result['value']['fiscal_position'] = False
            result['value']['fiscal_operation_id'] = False
            return result

        obj_company = self.pool.get('res.company').browse(cr, uid, [company_id])[0]

        company_addr = self.pool.get('res.partner').address_get(cr, uid, [obj_company.partner_id.id], ['default'])
        company_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [company_addr['default']])[0]

        from_country = company_addr_default.country_id.id
        from_state = company_addr_default.state_id.id

        obj_partner = self.pool.get('res.partner').browse(cr, uid, [part])[0]
        partner_fiscal_type = obj_partner.partner_fiscal_type_id.id

        if obj_partner.property_account_position:
            result['value']['fiscal_position'] = obj_partner.property_account_position
            result['value']['fiscal_operation_id'] = obj_partner.property_account_position.fiscal_operation_id.id
            result['value']['fiscal_operation_category_id'] = obj_partner.property_account_position.fiscal_operation_id.fiscal_operation_category_id.id
            return result

        partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [result['value']['partner_address_id']])[0]

        to_country = partner_addr_default.country_id.id
        to_state = partner_addr_default.state_id.id

        fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('partner_fiscal_type_id','=',partner_fiscal_type),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if fsc_pos_id:
            obj_fpo_rule = self.pool.get('account.fiscal.position.rule').browse(cr, uid, fsc_pos_id)[0]
            obj_fpo = self.pool.get('account.fiscal.position').browse(cr, uid, [obj_fpo_rule.fiscal_position_id.id])[0]
            obj_foperation = self.pool.get('l10n_br_account.fiscal.operation').browse(cr, uid, [obj_fpo.fiscal_operation_id.id])[0]
            result['value']['fiscal_position'] = obj_fpo.id
            result['value']['fiscal_operation_id'] = obj_foperation.id

        return result

    def onchange_partner_address_id(self, cr, uid, ids, partner_address_id, company_id=False, fiscal_operation_category_id=False):

        result = super(purchase_order, self ).onchange_partner_address_id(cr, uid, ids, partner_address_id, company_id)

        if not partner_address_id or not company_id:
            result['value']['fiscal_position'] = False
            result['value']['fiscal_operation_id'] = False
            return result

        obj_company = self.pool.get('res.company').browse(cr, uid, [company_id])[0]

        company_addr = self.pool.get('res.partner').address_get(cr, uid, [obj_company.partner_id.id], ['default'])
        company_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [company_addr['default']])[0]

        from_country = company_addr_default.country_id.id
        from_state = company_addr_default.state_id.id

        partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [partner_address_id])[0]

        to_country = partner_addr_default.country_id.id
        to_state = partner_addr_default.state_id.id

        obj_partner = self.pool.get('res.partner').browse(cr, uid, [partner_addr_default.partner_id.id])[0]
        partner_fiscal_type = obj_partner.partner_fiscal_type_id.id
        if obj_partner.property_account_position:
            result['value']['fiscal_position'] = obj_partner.property_account_position
            result['value']['fiscal_operation_id'] = obj_partner.property_account_position.fiscal_operation_id.id
            return result

        fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('partner_fiscal_type_id','=',partner_fiscal_type),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if fsc_pos_id:
            obj_fpo_rule = self.pool.get('account.fiscal.position.rule').browse(cr, uid, fsc_pos_id)[0]
            obj_fpo = self.pool.get('account.fiscal.position').browse(cr, uid, [obj_fpo_rule.fiscal_position_id.id])[0]
            obj_foperation = self.pool.get('l10n_br_account.fiscal.operation').browse(cr, uid, [obj_fpo.fiscal_operation_id.id])[0]
            result['value']['fiscal_position'] = obj_fpo.id
            result['value']['fiscal_operation_id'] = obj_foperation.id

        return result

    def onchange_fiscal_operation_category_id(self, cr, uid, ids, partner_address_id, company_id=False, fiscal_operation_category_id=False):

        result = {'value': {} }

        if not partner_address_id or not company_id or not fiscal_operation_category_id:
            result['value']['fiscal_position'] = False
            result['value']['fiscal_operation_id'] = False
            return result

        obj_company = self.pool.get('res.company').browse(cr, uid, [company_id])[0]

        company_addr = self.pool.get('res.partner').address_get(cr, uid, [obj_company.partner_id.id], ['default'])
        company_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [company_addr['default']])[0]

        from_country = company_addr_default.country_id.id
        from_state = company_addr_default.state_id.id

        partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [partner_address_id])[0]

        to_country = partner_addr_default.country_id.id
        to_state = partner_addr_default.state_id.id

        obj_partner = self.pool.get('res.partner').browse(cr, uid, [partner_addr_default.partner_id.id])[0]
        partner_fiscal_type = obj_partner.partner_fiscal_type_id.id
        if obj_partner.property_account_position:
            result['value']['fiscal_position'] = obj_partner.property_account_position
            result['value']['fiscal_operation_id'] = obj_partner.property_account_position.fiscal_operation_id.id
            return result

        fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('partner_fiscal_type_id','=',partner_fiscal_type),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if fsc_pos_id:
            obj_fpo_rule = self.pool.get('account.fiscal.position.rule').browse(cr, uid, fsc_pos_id)[0]
            obj_fpo = self.pool.get('account.fiscal.position').browse(cr, uid, [obj_fpo_rule.fiscal_position_id.id])[0]
            obj_foperation = self.pool.get('l10n_br_account.fiscal.operation').browse(cr, uid, [obj_fpo.fiscal_operation_id.id])[0]
            result['value']['fiscal_position'] = obj_fpo.id
            result['value']['fiscal_operation_id'] = obj_foperation.id

        return result

    def action_invoice_create(self, cr, uid, ids, *args):

        res = super(purchase_order, self).action_invoice_create(cr, uid, ids, *args)

        if not res:
            return res

        for order in self.browse(cr, uid, ids):
            #for invoice in order.invoice_id:
                if order.invoice_id.state in ('draft') and order.fiscal_operation_id:
                    #doc_serie_id = self.pool.get('l10n_br_account.document.serie').search(cr, uid,[('fiscal_document_id','=', order.fiscal_operation_id.fiscal_document_id.id),('active','=',True),('company_id','=',order.company_id.id)])
                    #if not doc_serie_id:
                    #    raise osv.except_osv(_('Nenhuma série de documento fiscal !'),_("Não existe nenhuma série de documento fiscal cadastrada para empresa:  '%s'") % (order.company_id.name,))
                    self.pool.get('account.invoice').write(cr, uid, order.invoice_id.id, {'fiscal_operation_category_id': order.fiscal_operation_category_id.id, 'fiscal_operation_id': order.fiscal_operation_id.id, 'cfop_id': order.fiscal_operation_id.cfop_id.id, 'fiscal_document_id': order.fiscal_operation_id.fiscal_document_id.id, 'fiscal_position': order.fiscal_position.id})
                    for inv_line in order.invoice_id.invoice_line:
                        self.pool.get('account.invoice.line').write(cr, uid, inv_line.id, {'cfop_id': order.fiscal_operation_id.cfop_id.id})

        return res

    def action_picking_create(self,cr, uid, ids, *args):

        picking_id = False

        for order in self.browse(cr, uid, ids):

            picking_id = super(purchase_order, self).action_picking_create(cr, uid, ids, *args)
            self.pool.get('stock.picking').write(cr, uid, picking_id, {'fiscal_operation_category_id': order.fiscal_operation_category_id.id, 'fiscal_operation_id': order.fiscal_operation_id.id, 'fiscal_position': order.fiscal_position.id})

        return picking_id

purchase_order()
<commit_msg>corrigida a busca nas account.fiscal.position.rule para buscar regras que não tenha tipo fiscal, pois existe operações que podem ser tanto para contribuinte quanto para não contribuinte<commit_after># -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
# Copyright (C) 2009  Renato Lima - Akretion, Gabriel C. Stabel                 #
#                                                                               #
#This program is free software: you can redistribute it and/or modify           #
#it under the terms of the GNU General Public License as published by           #
#the Free Software Foundation, either version 3 of the License, or              #
#(at your option) any later version.                                            #
#                                                                               #
#This program is distributed in the hope that it will be useful,                #
#but WITHOUT ANY WARRANTY; without even the implied warranty of                 #
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                  #
#GNU General Public License for more details.                                   #
#                                                                               #
#You should have received a copy of the GNU General Public License              #
#along with this program.  If not, see <http://www.gnu.org/licenses/>.          #
#################################################################################

from osv import osv, fields

##############################################################################
# Ordem de Compra Customizada
##############################################################################
class purchase_order(osv.osv):
    _inherit = 'purchase.order'
    _columns = {
        'fiscal_operation_category_id': fields.many2one('l10n_br_account.fiscal.operation.category', 'Categoria'),
        'fiscal_operation_id': fields.many2one('l10n_br_account.fiscal.operation', 'Operação Fiscal', domain="[('fiscal_operation_category_id','=',fiscal_operation_category_id)]" ),
    }

    def onchange_partner_id(self, cr, uid, ids, part, company_id=False, fiscal_operation_category_id=False):

        result = super(purchase_order, self ).onchange_partner_id(cr, uid, ids, part, company_id)

        if (not part or not company_id or not result['value']['partner_address_id'] or not fiscal_operation_category_id):
            result['value']['fiscal_position'] = False
            result['value']['fiscal_operation_id'] = False
            return result

        obj_company = self.pool.get('res.company').browse(cr, uid, [company_id])[0]

        company_addr = self.pool.get('res.partner').address_get(cr, uid, [obj_company.partner_id.id], ['default'])
        company_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [company_addr['default']])[0]

        from_country = company_addr_default.country_id.id
        from_state = company_addr_default.state_id.id

        obj_partner = self.pool.get('res.partner').browse(cr, uid, [part])[0]
        partner_fiscal_type = obj_partner.partner_fiscal_type_id.id

        if obj_partner.property_account_position:
            result['value']['fiscal_position'] = obj_partner.property_account_position
            result['value']['fiscal_operation_id'] = obj_partner.property_account_position.fiscal_operation_id.id
            result['value']['fiscal_operation_category_id'] = obj_partner.property_account_position.fiscal_operation_id.fiscal_operation_category_id.id
            return result

        partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [result['value']['partner_address_id']])[0]

        to_country = partner_addr_default.country_id.id
        to_state = partner_addr_default.state_id.id

        fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('partner_fiscal_type_id','=',partner_fiscal_type),('fiscal_operation_category_id','=',fiscal_operation_category_id)])
        if not fsc_pos_id:
            fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if fsc_pos_id:
            obj_fpo_rule = self.pool.get('account.fiscal.position.rule').browse(cr, uid, fsc_pos_id)[0]
            obj_fpo = self.pool.get('account.fiscal.position').browse(cr, uid, [obj_fpo_rule.fiscal_position_id.id])[0]
            obj_foperation = self.pool.get('l10n_br_account.fiscal.operation').browse(cr, uid, [obj_fpo.fiscal_operation_id.id])[0]
            result['value']['fiscal_position'] = obj_fpo.id
            result['value']['fiscal_operation_id'] = obj_foperation.id

        return result

    def onchange_partner_address_id(self, cr, uid, ids, partner_address_id, company_id=False, fiscal_operation_category_id=False):

        result = super(purchase_order, self ).onchange_partner_address_id(cr, uid, ids, partner_address_id, company_id)

        if not partner_address_id or not company_id:
            result['value']['fiscal_position'] = False
            result['value']['fiscal_operation_id'] = False
            return result

        obj_company = self.pool.get('res.company').browse(cr, uid, [company_id])[0]

        company_addr = self.pool.get('res.partner').address_get(cr, uid, [obj_company.partner_id.id], ['default'])
        company_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [company_addr['default']])[0]

        from_country = company_addr_default.country_id.id
        from_state = company_addr_default.state_id.id

        partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [partner_address_id])[0]

        to_country = partner_addr_default.country_id.id
        to_state = partner_addr_default.state_id.id

        obj_partner = self.pool.get('res.partner').browse(cr, uid, [partner_addr_default.partner_id.id])[0]
        partner_fiscal_type = obj_partner.partner_fiscal_type_id.id
        if obj_partner.property_account_position:
            result['value']['fiscal_position'] = obj_partner.property_account_position
            result['value']['fiscal_operation_id'] = obj_partner.property_account_position.fiscal_operation_id.id
            return result

        fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('partner_fiscal_type_id','=',partner_fiscal_type),('fiscal_operation_category_id','=',fiscal_operation_category_id)])
        if not fsc_pos_id:
            fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if fsc_pos_id:
            obj_fpo_rule = self.pool.get('account.fiscal.position.rule').browse(cr, uid, fsc_pos_id)[0]
            obj_fpo = self.pool.get('account.fiscal.position').browse(cr, uid, [obj_fpo_rule.fiscal_position_id.id])[0]
            obj_foperation = self.pool.get('l10n_br_account.fiscal.operation').browse(cr, uid, [obj_fpo.fiscal_operation_id.id])[0]
            result['value']['fiscal_position'] = obj_fpo.id
            result['value']['fiscal_operation_id'] = obj_foperation.id

        return result

    def onchange_fiscal_operation_category_id(self, cr, uid, ids, partner_address_id, company_id=False, fiscal_operation_category_id=False):

        result = {'value': {} }

        if not partner_address_id or not company_id or not fiscal_operation_category_id:
            result['value']['fiscal_position'] = False
            result['value']['fiscal_operation_id'] = False
            return result

        obj_company = self.pool.get('res.company').browse(cr, uid, [company_id])[0]

        company_addr = self.pool.get('res.partner').address_get(cr, uid, [obj_company.partner_id.id], ['default'])
        company_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [company_addr['default']])[0]

        from_country = company_addr_default.country_id.id
        from_state = company_addr_default.state_id.id

        partner_addr_default = self.pool.get('res.partner.address').browse(cr, uid, [partner_address_id])[0]

        to_country = partner_addr_default.country_id.id
        to_state = partner_addr_default.state_id.id

        obj_partner = self.pool.get('res.partner').browse(cr, uid, [partner_addr_default.partner_id.id])[0]
        partner_fiscal_type = obj_partner.partner_fiscal_type_id.id
        if obj_partner.property_account_position:
            result['value']['fiscal_position'] = obj_partner.property_account_position
            result['value']['fiscal_operation_id'] = obj_partner.property_account_position.fiscal_operation_id.id
            return result

        fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('partner_fiscal_type_id','=',partner_fiscal_type),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if not fsc_pos_id:
            fsc_pos_id = self.pool.get('account.fiscal.position.rule').search(cr, uid, [('company_id','=',company_id), ('from_country','=',from_country),('from_state','=',from_state),('to_country','=',to_country),('to_state','=',to_state),('use_purchase','=',True),('fiscal_operation_category_id','=',fiscal_operation_category_id)])

        if fsc_pos_id:
            obj_fpo_rule = self.pool.get('account.fiscal.position.rule').browse(cr, uid, fsc_pos_id)[0]
            obj_fpo = self.pool.get('account.fiscal.position').browse(cr, uid, [obj_fpo_rule.fiscal_position_id.id])[0]
            obj_foperation = self.pool.get('l10n_br_account.fiscal.operation').browse(cr, uid, [obj_fpo.fiscal_operation_id.id])[0]
            result['value']['fiscal_position'] = obj_fpo.id
            result['value']['fiscal_operation_id'] = obj_foperation.id

        return result

    def action_invoice_create(self, cr, uid, ids, *args):

        res = super(purchase_order, self).action_invoice_create(cr, uid, ids, *args)

        if not res:
            return res

        for order in self.browse(cr, uid, ids):
            #for invoice in order.invoice_id:
                if order.invoice_id.state in ('draft') and order.fiscal_operation_id:
                    #doc_serie_id = self.pool.get('l10n_br_account.document.serie').search(cr, uid,[('fiscal_document_id','=', order.fiscal_operation_id.fiscal_document_id.id),('active','=',True),('company_id','=',order.company_id.id)])
                    #if not doc_serie_id:
                    #    raise osv.except_osv(_('Nenhuma série de documento fiscal !'),_("Não existe nenhuma série de documento fiscal cadastrada para empresa:  '%s'") % (order.company_id.name,))
                    self.pool.get('account.invoice').write(cr, uid, order.invoice_id.id, {'fiscal_operation_category_id': order.fiscal_operation_category_id.id, 'fiscal_operation_id': order.fiscal_operation_id.id, 'cfop_id': order.fiscal_operation_id.cfop_id.id, 'fiscal_document_id': order.fiscal_operation_id.fiscal_document_id.id, 'fiscal_position': order.fiscal_position.id})
                    for inv_line in order.invoice_id.invoice_line:
                        self.pool.get('account.invoice.line').write(cr, uid, inv_line.id, {'cfop_id': order.fiscal_operation_id.cfop_id.id})

        return res

    def action_picking_create(self,cr, uid, ids, *args):

        picking_id = False

        for order in self.browse(cr, uid, ids):

            picking_id = super(purchase_order, self).action_picking_create(cr, uid, ids, *args)
            self.pool.get('stock.picking').write(cr, uid, picking_id, {'fiscal_operation_category_id': order.fiscal_operation_category_id.id, 'fiscal_operation_id': order.fiscal_operation_id.id, 'fiscal_position': order.fiscal_position.id})

        return picking_id

purchase_order()
<|endoftext|>


<commit_before># Copyright 2004-2011 Luis Manuel Angueira Blanco - Pexego
# Copyright 2013-2019 Ignacio Ibeas - Acysos S.L. (http://acysos.com)
# Copyright 2015 Ainara Galdona <agaldona@avanzosc.com>
# Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2018 Juan Vicente Pascual <jvpascual@puntsistemes.es>
# Copyright 2019 Tecnativa - Carlos Dauden
# Copyright 2013-2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl

{
    "name": "AEAT Base",
    "summary": "Modulo base para declaraciones de la AEAT",
    "version": "14.0.1.5.0",
    "author": "Pexego, "
    "Acysos S.L., "
    "AvanzOSC, "
    "Tecnativa, "
    "Odoo Community Association (OCA)",
    "license": "AGPL-3",
    "website": "https://github.com/OCA/l10n-spain",
    "category": "Accounting & Finance",
    "development_status": "Mature",
    "depends": ["l10n_es", "account_tax_balance"],
    "external_dependencies": {"python": ["unidecode", "cryptography"]},
    "data": [
        "security/aeat_security.xml",
        "security/ir.model.access.csv",
        "data/aeat_partner.xml",
        "data/ir_config_parameter.xml",
        "data/aeat_tax_agency_data.xml",
        "wizard/export_to_boe_wizard.xml",
        "wizard/compare_boe_file_views.xml",
        "wizard/aeat_certificate_password_view.xml",
        "views/aeat_menuitem.xml",
        "views/aeat_report_view.xml",
        "views/aeat_tax_agency_view.xml",
        "views/aeat_tax_line_view.xml",
        "views/aeat_export_configuration_view.xml",
        "views/aeat_tax_code_mapping_view.xml",
        "views/account_move_line_view.xml",
        "views/res_company_view.xml",
        "views/res_partner_view.xml",
        "views/aeat_certificate_view.xml",
    ],
    "installable": True,
    "maintainers": ["pedrobaeza"],
}
<commit_msg>l10n_es_aeat 14.0.2.0.0<commit_after># Copyright 2004-2011 Luis Manuel Angueira Blanco - Pexego
# Copyright 2013-2019 Ignacio Ibeas - Acysos S.L. (http://acysos.com)
# Copyright 2015 Ainara Galdona <agaldona@avanzosc.com>
# Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2018 Juan Vicente Pascual <jvpascual@puntsistemes.es>
# Copyright 2019 Tecnativa - Carlos Dauden
# Copyright 2013-2021 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl

{
    "name": "AEAT Base",
    "summary": "Modulo base para declaraciones de la AEAT",
    "version": "14.0.2.0.0",
    "author": "Pexego, "
    "Acysos S.L., "
    "AvanzOSC, "
    "Tecnativa, "
    "Odoo Community Association (OCA)",
    "license": "AGPL-3",
    "website": "https://github.com/OCA/l10n-spain",
    "category": "Accounting & Finance",
    "development_status": "Mature",
    "depends": ["l10n_es", "account_tax_balance"],
    "external_dependencies": {"python": ["unidecode", "cryptography"]},
    "data": [
        "security/aeat_security.xml",
        "security/ir.model.access.csv",
        "data/aeat_partner.xml",
        "data/ir_config_parameter.xml",
        "data/aeat_tax_agency_data.xml",
        "wizard/export_to_boe_wizard.xml",
        "wizard/compare_boe_file_views.xml",
        "wizard/aeat_certificate_password_view.xml",
        "views/aeat_menuitem.xml",
        "views/aeat_report_view.xml",
        "views/aeat_tax_agency_view.xml",
        "views/aeat_tax_line_view.xml",
        "views/aeat_export_configuration_view.xml",
        "views/aeat_tax_code_mapping_view.xml",
        "views/account_move_line_view.xml",
        "views/res_company_view.xml",
        "views/res_partner_view.xml",
        "views/aeat_certificate_view.xml",
    ],
    "installable": True,
    "maintainers": ["pedrobaeza"],
}
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011 Numérigraphe SARL.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

{
    'name': 'French company identity numbers SIRET/SIREN/NIC',
    'version': '1.0',
    "category": 'Accounting',
    'description': """
This module lets users keep track of the companies' unique
identification numbers from the official SIRENE registry in France:
SIRET, SIREN and NIC.  These numbers identify each company and their
subsidiaries, and are often required for administrative tasks.

At the top of the Partner form, users will be able to enter the SIREN
and NIC numbers, and the SIRET number will be calculated
automatically.  The last digits of the SIREN and NIC are control keys:
OpenERP will check their validity when partners are recorded.
""",
    'author' : u'Numérigraphe SARL',
    'depends': [],
    'data': ['partner_view.xml',
             ],
    'installable': True,
    'active': False,
}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>[FIX] add missing dependency on base module<commit_after># -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011 Numérigraphe SARL.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

{
    'name': 'French company identity numbers SIRET/SIREN/NIC',
    'version': '1.0',
    "category": 'Accounting',
    'description': """
This module lets users keep track of the companies' unique
identification numbers from the official SIRENE registry in France:
SIRET, SIREN and NIC.  These numbers identify each company and their
subsidiaries, and are often required for administrative tasks.

At the top of the Partner form, users will be able to enter the SIREN
and NIC numbers, and the SIRET number will be calculated
automatically.  The last digits of the SIREN and NIC are control keys:
OpenERP will check their validity when partners are recorded.
""",
    'author' : u'Numérigraphe SARL',
    'depends': ['base'],
    'data': ['partner_view.xml',
             ],
    'installable': True,
    'active': False,
}

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>


<commit_before># Copyright 2015 Lockheed Martin Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re
import struct
import hashlib
import binascii
import logging
import pefile
from datetime import datetime
from laikaboss.objectmodel import (ModuleObject,
                                   ExternalVars,
                                   QuitScanException,
                                   GlobalScanTimeoutError,
                                   GlobalModuleTimeoutError)
from laikaboss.si_module import SI_MODULE

IMAGE_MAGIC_LOOKUP = {0x10b: '32_BIT',
                      0x20b: '64_BIT',
                      0x107: 'ROM_IMAGE', }

class META_PE(SI_MODULE):
    def __init__(self):
        self.module_name = "META_PE"

    def _run(self, scanObject, result, depth, args):
        moduleResult = []
        imports = {}
        sections = {}
        exports = []

        try:
            pe = pefile.PE(data=scanObject.buffer)
            dump_dict = pe.dump_dict()

            # Parse sections
            for section in dump_dict.get('PE Sections', []):
                secName = section.get('Name', {}).get('Value', '').strip('\0')
                ptr = section.get('PointerToRawData', {}).get('Value')
                virtAddress = section.get('VirtualAddress', {}).get('Value')
                virtSize = section.get('Misc_VirtualSize', {}).get('Value')
                size = section.get('SizeOfRawData', {}).get('Value')
                secData = pe.get_data(ptr, size)
                secInfo = {
                    'Virtual Address': '0x%08X' % virtAddress,
                    'Virtual Size': virtSize,
                    'Raw Size': size,
                    'MD5': section.get('MD5', ''),
                    'SHA1': section.get('SHA1', ''),
                    'SHA256': section.get('SHA256', ''),
                    'Entropy': section.get('Entropy', ''),
                    'Section Characteristics': section.get('Flags', []),
                    'Structure': section.get('Structure', ''),
                }
                if secInfo['MD5'] != scanObject.objectHash:
                    moduleResult.append(ModuleObject(
                        buffer=secData,
                        externalVars=ExternalVars(filename=secName)))
                sections[secName] = secInfo
            sections['Total'] = pe.FILE_HEADER.NumberOfSections
            scanObject.addMetadata(self.module_name, 'Sections', sections)

            # Parse imports and exports
            try:
                for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
                    exports.append(exp.name)
                scanObject.addMetadata(self.module_name, 'Exports', exports)
            except (QuitScanException,
                    GlobalScanTimeoutError,
                    GlobalModuleTimeoutError):
                raise
            except:
                logging.debug('No export entries')

            for imp_symbol in dump_dict['Imported symbols']:
                for imp in imp_symbol:
                    if imp.get('DLL'):
                        dll = imp.get('DLL')
                        imports.setdefault(dll, [])
                        # Imports can be identified by ordinal or name
                        if imp.get('Ordinal'):
                            ordinal = imp.get('Ordinal')
                            imports[dll].append(ordinal)
                        if imp.get('Name'):
                            name = imp.get('Name')
                            imports[dll].append(name)
            scanObject.addMetadata(self.module_name, 'Imports', imports)

            # Parse resources
            try:
                for resource in pe.DIRECTORY_ENTRY_RESOURCE.entries:
                    res_type = pefile.RESOURCE_TYPE.get(resource.id, 'Unknown')
                    for entry in resource.directory.entries:
                        for e_entry in entry.directory.entries:
                            sublang = pefile.get_sublang_name_for_lang(
                                e_entry.data.lang,
                                e_entry.data.sublang,
                            )
                            offset = e_entry.data.struct.OffsetToData
                            size = e_entry.data.struct.Size
                            r_data = pe.get_data(offset, size)
                            language = pefile.LANG.get(
                                e_entry.data.lang, 'Unknown')
                            data = {
                                'Type': res_type,
                                'Id': e_entry.id,
                                'Name': e_entry.data.struct.name,
                                'Offset': offset,
                                'Size': size,
                                'SHA256': hashlib.sha256(r_data).hexdigest(),
                                'SHA1': hashlib.sha1(r_data).hexdigest(),
                                'MD5': hashlib.md5(r_data).hexdigest(),
                                'Language': language,
                                'Sub Language': sublang,
                            }
                            scanObject.addMetadata(
                                self.module_name, 'Resources', data)
            except (QuitScanException,
                    GlobalScanTimeoutError,
                    GlobalModuleTimeoutError):
                raise
            except:
                logging.debug('No resources')

            # Gather miscellaneous stuff
            try:
                scanObject.addMetadata(self.module_name,
                                       'Imphash', pe.get_imphash())
            except:
                logging.debug('Unable to identify imphash')

            imgChars = dump_dict.get('Flags', [])
            scanObject.addMetadata(
                self.module_name, 'Image Characteristics', imgChars)
            # Make a pretty date format
            date = datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp)
            isoDate = date.isoformat()
            scanObject.addMetadata(self.module_name, 'Date', isoDate)
            scanObject.addMetadata(
                self.module_name, 'Timestamp', pe.FILE_HEADER.TimeDateStamp)

            machine = pe.FILE_HEADER.Machine
            machineData = {
                'Id': machine,
                'Type': pefile.MACHINE_TYPE.get(machine)
            }
            scanObject.addMetadata(
                self.module_name, 'Machine Type', machineData)

            # Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680339%28v=vs.85%29.aspx
            scanObject.addMetadata(
                self.module_name,
                'Image Magic',
                IMAGE_MAGIC_LOOKUP.get(pe.OPTIONAL_HEADER.Magic, 'Unknown'))

            dllChars = dump_dict.get('DllCharacteristics', [])
            scanObject.addMetadata(
                self.module_name, 'DLL Characteristics', dllChars)

            subsystem = pe.OPTIONAL_HEADER.Subsystem
            subName = pefile.SUBSYSTEM_TYPE.get(subsystem)
            scanObject.addMetadata(self.module_name, 'Subsystem', subName)

            # Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms648009%28v=vs.85%29.aspx

            scanObject.addMetadata(
                self.module_name,
                'Stack Reserve Size',
                pe.OPTIONAL_HEADER.SizeOfStackReserve)
            scanObject.addMetadata(
                self.module_name,
                'Stack Commit Size',
                pe.OPTIONAL_HEADER.SizeOfStackCommit)
            scanObject.addMetadata(
                self.module_name,
                'Heap Reserve Size',
                pe.OPTIONAL_HEADER.SizeOfHeapReserve)
            scanObject.addMetadata(
                self.module_name,
                'Heap Commit Size',
                pe.OPTIONAL_HEADER.SizeOfHeapCommit)
            scanObject.addMetadata(
                self.module_name,
                'EntryPoint',
                hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint))
            scanObject.addMetadata(
                self.module_name,
                'ImageBase',
                hex(pe.OPTIONAL_HEADER.ImageBase))

            # Parse RSDS & Rich
            scanObject.addMetadata(
                self.module_name, 'RSDS', self.parseRSDS(scanObject))
            scanObject.addMetadata(
                self.module_name, 'Rich Header', self.parseRich(pe))

        except pefile.PEFormatError:
            logging.debug("Invalid PE format")
        return moduleResult

    @staticmethod
    def parseRSDS(scanObject):
        """
        Parses out RSDS pdb information

        00000000  52 53 44 53 b4 bc 76 74  d2 9f 6a 49 b5 6c 74 7c  |RSDS..vt..jI.lt||
        00000010  1d 41 bb a5 05 00 00 00  44 3a 5c 4d 69 63 72 6f  |.A......D:\Micro|
        00000020  73 6f 66 74 20 56 69 73  75 61 6c 20 53 74 75 64  |soft Visual Stud|
        00000030  69 6f 5c 66 69 6c 65 73  5c 43 23 5c 7a 63 67 2e  |io\files\C#\zcg.|
        00000040  43 68 6f 70 70 65 72 53  72 65 76 65 72 46 6f 72  |ChopperSreverFor|
        00000050  43 73 68 61 72 70 5c 6f  62 6a 5c 52 65 6c 65 61  |Csharp\obj\Relea|
        00000060  73 65 5c 53 79 73 74 65  6d 2e 57 65 62 53 65 72  |se\System.WebSer|
        00000070  76 69 63 65 73 2e 70 64  62 00 00 00 04 55 00 00  |vices.pdb....U..|

        +0h   dword        "RSDS" signature
        +4h   GUID         16-byte Globally Unique Identifier
        +14h  dword        "age"
        +18h  byte string  zero terminated UTF8 path and file name

        http://www.godevtool.com/Other/pdb.htm
        """

        result = {}
        rsds = re.compile('RSDS.{24,1024}\.pdb')
        x = rsds.findall(scanObject.buffer)

        if x and x[-1]:
            match = x[-1]
            result["guid"] = "%s-%s-%s-%s" % (binascii.hexlify(match[4:8]),
                                              binascii.hexlify(match[8:10]),
                                              binascii.hexlify(match[10:12]),
                                              binascii.hexlify(match[12:20]))
            result["age"] = struct.unpack('<L', match[20:24])[0]
            result["pdb"] = match[24:]

        return result

    def parseRich(self, pe):
        """
        Parses out Rich header information using pefile.
        """
        result = {}
        data = []
        if pe.RICH_HEADER:
            for x in range(0, len(pe.RICH_HEADER.values), 2):
                value = pe.RICH_HEADER.values[x] >> 16
                version = pe.RICH_HEADER.values[x] & 0xffff
                count = pe.RICH_HEADER.values[x + 1]
                data.append({
                    'Id': value,
                    'Version': version,
                    'Count': count,
                })

            result['Rich Header Values'] = data
            result['Checksum'] = pe.RICH_HEADER.checksum
            result['Hashes'] = self.richHeaderHashes(pe)

        return result

    @staticmethod
    def richHeaderHashes(pe):
        """
        Returns hashes of the Rich PE header
        """
        rich_data = pe.get_data(0x80, 0x80)
        data = list(struct.unpack('<32I', rich_data))
        checksum = data[1]
        rich_end = data.index(0x68636952)
        md5 = hashlib.md5()
        sha1 = hashlib.sha1()
        sha256 = hashlib.sha256()
        for i in range(rich_end):
            md5.update(struct.pack('<I', (data[i] ^ checksum)))
            sha1.update(struct.pack('<I', (data[i] ^ checksum)))
            sha256.update(struct.pack('<I', (data[i] ^ checksum)))
        data = {
            'MD5': md5.hexdigest(),
            'SHA1': sha1.hexdigest(),
            'SHA256': sha256.hexdigest(),
        }
        return data
<commit_msg>dict formatting<commit_after># Copyright 2015 Lockheed Martin Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re
import struct
import hashlib
import binascii
import logging
import pefile
from datetime import datetime
from laikaboss.objectmodel import (ModuleObject,
                                   ExternalVars,
                                   QuitScanException,
                                   GlobalScanTimeoutError,
                                   GlobalModuleTimeoutError)
from laikaboss.si_module import SI_MODULE

IMAGE_MAGIC_LOOKUP = {
    0x10b: '32_BIT',
    0x20b: '64_BIT',
    0x107: 'ROM_IMAGE',
}

class META_PE(SI_MODULE):
    def __init__(self):
        self.module_name = "META_PE"

    def _run(self, scanObject, result, depth, args):
        moduleResult = []
        imports = {}
        sections = {}
        exports = []

        try:
            pe = pefile.PE(data=scanObject.buffer)
            dump_dict = pe.dump_dict()

            # Parse sections
            for section in dump_dict.get('PE Sections', []):
                secName = section.get('Name', {}).get('Value', '').strip('\0')
                ptr = section.get('PointerToRawData', {}).get('Value')
                virtAddress = section.get('VirtualAddress', {}).get('Value')
                virtSize = section.get('Misc_VirtualSize', {}).get('Value')
                size = section.get('SizeOfRawData', {}).get('Value')
                secData = pe.get_data(ptr, size)
                secInfo = {
                    'Virtual Address': '0x%08X' % virtAddress,
                    'Virtual Size': virtSize,
                    'Raw Size': size,
                    'MD5': section.get('MD5', ''),
                    'SHA1': section.get('SHA1', ''),
                    'SHA256': section.get('SHA256', ''),
                    'Entropy': section.get('Entropy', ''),
                    'Section Characteristics': section.get('Flags', []),
                    'Structure': section.get('Structure', ''),
                }
                if secInfo['MD5'] != scanObject.objectHash:
                    moduleResult.append(ModuleObject(
                        buffer=secData,
                        externalVars=ExternalVars(filename=secName)))
                sections[secName] = secInfo
            sections['Total'] = pe.FILE_HEADER.NumberOfSections
            scanObject.addMetadata(self.module_name, 'Sections', sections)

            # Parse imports and exports
            try:
                for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
                    exports.append(exp.name)
                scanObject.addMetadata(self.module_name, 'Exports', exports)
            except (QuitScanException,
                    GlobalScanTimeoutError,
                    GlobalModuleTimeoutError):
                raise
            except:
                logging.debug('No export entries')

            for imp_symbol in dump_dict['Imported symbols']:
                for imp in imp_symbol:
                    if imp.get('DLL'):
                        dll = imp.get('DLL')
                        imports.setdefault(dll, [])
                        # Imports can be identified by ordinal or name
                        if imp.get('Ordinal'):
                            ordinal = imp.get('Ordinal')
                            imports[dll].append(ordinal)
                        if imp.get('Name'):
                            name = imp.get('Name')
                            imports[dll].append(name)
            scanObject.addMetadata(self.module_name, 'Imports', imports)

            # Parse resources
            try:
                for resource in pe.DIRECTORY_ENTRY_RESOURCE.entries:
                    res_type = pefile.RESOURCE_TYPE.get(resource.id, 'Unknown')
                    for entry in resource.directory.entries:
                        for e_entry in entry.directory.entries:
                            sublang = pefile.get_sublang_name_for_lang(
                                e_entry.data.lang,
                                e_entry.data.sublang,
                            )
                            offset = e_entry.data.struct.OffsetToData
                            size = e_entry.data.struct.Size
                            r_data = pe.get_data(offset, size)
                            language = pefile.LANG.get(
                                e_entry.data.lang, 'Unknown')
                            data = {
                                'Type': res_type,
                                'Id': e_entry.id,
                                'Name': e_entry.data.struct.name,
                                'Offset': offset,
                                'Size': size,
                                'SHA256': hashlib.sha256(r_data).hexdigest(),
                                'SHA1': hashlib.sha1(r_data).hexdigest(),
                                'MD5': hashlib.md5(r_data).hexdigest(),
                                'Language': language,
                                'Sub Language': sublang,
                            }
                            scanObject.addMetadata(
                                self.module_name, 'Resources', data)
            except (QuitScanException,
                    GlobalScanTimeoutError,
                    GlobalModuleTimeoutError):
                raise
            except:
                logging.debug('No resources')

            # Gather miscellaneous stuff
            try:
                scanObject.addMetadata(self.module_name,
                                       'Imphash', pe.get_imphash())
            except:
                logging.debug('Unable to identify imphash')

            imgChars = dump_dict.get('Flags', [])
            scanObject.addMetadata(
                self.module_name, 'Image Characteristics', imgChars)
            # Make a pretty date format
            date = datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp)
            isoDate = date.isoformat()
            scanObject.addMetadata(self.module_name, 'Date', isoDate)
            scanObject.addMetadata(
                self.module_name, 'Timestamp', pe.FILE_HEADER.TimeDateStamp)

            machine = pe.FILE_HEADER.Machine
            machineData = {
                'Id': machine,
                'Type': pefile.MACHINE_TYPE.get(machine)
            }
            scanObject.addMetadata(
                self.module_name, 'Machine Type', machineData)

            # Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680339%28v=vs.85%29.aspx
            scanObject.addMetadata(
                self.module_name,
                'Image Magic',
                IMAGE_MAGIC_LOOKUP.get(pe.OPTIONAL_HEADER.Magic, 'Unknown'))

            dllChars = dump_dict.get('DllCharacteristics', [])
            scanObject.addMetadata(
                self.module_name, 'DLL Characteristics', dllChars)

            subsystem = pe.OPTIONAL_HEADER.Subsystem
            subName = pefile.SUBSYSTEM_TYPE.get(subsystem)
            scanObject.addMetadata(self.module_name, 'Subsystem', subName)

            # Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms648009%28v=vs.85%29.aspx

            scanObject.addMetadata(
                self.module_name,
                'Stack Reserve Size',
                pe.OPTIONAL_HEADER.SizeOfStackReserve)
            scanObject.addMetadata(
                self.module_name,
                'Stack Commit Size',
                pe.OPTIONAL_HEADER.SizeOfStackCommit)
            scanObject.addMetadata(
                self.module_name,
                'Heap Reserve Size',
                pe.OPTIONAL_HEADER.SizeOfHeapReserve)
            scanObject.addMetadata(
                self.module_name,
                'Heap Commit Size',
                pe.OPTIONAL_HEADER.SizeOfHeapCommit)
            scanObject.addMetadata(
                self.module_name,
                'EntryPoint',
                hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint))
            scanObject.addMetadata(
                self.module_name,
                'ImageBase',
                hex(pe.OPTIONAL_HEADER.ImageBase))

            # Parse RSDS & Rich
            scanObject.addMetadata(
                self.module_name, 'RSDS', self.parseRSDS(scanObject))
            scanObject.addMetadata(
                self.module_name, 'Rich Header', self.parseRich(pe))

        except pefile.PEFormatError:
            logging.debug("Invalid PE format")
        return moduleResult

    @staticmethod
    def parseRSDS(scanObject):
        """
        Parses out RSDS pdb information

        00000000  52 53 44 53 b4 bc 76 74  d2 9f 6a 49 b5 6c 74 7c  |RSDS..vt..jI.lt||
        00000010  1d 41 bb a5 05 00 00 00  44 3a 5c 4d 69 63 72 6f  |.A......D:\Micro|
        00000020  73 6f 66 74 20 56 69 73  75 61 6c 20 53 74 75 64  |soft Visual Stud|
        00000030  69 6f 5c 66 69 6c 65 73  5c 43 23 5c 7a 63 67 2e  |io\files\C#\zcg.|
        00000040  43 68 6f 70 70 65 72 53  72 65 76 65 72 46 6f 72  |ChopperSreverFor|
        00000050  43 73 68 61 72 70 5c 6f  62 6a 5c 52 65 6c 65 61  |Csharp\obj\Relea|
        00000060  73 65 5c 53 79 73 74 65  6d 2e 57 65 62 53 65 72  |se\System.WebSer|
        00000070  76 69 63 65 73 2e 70 64  62 00 00 00 04 55 00 00  |vices.pdb....U..|

        +0h   dword        "RSDS" signature
        +4h   GUID         16-byte Globally Unique Identifier
        +14h  dword        "age"
        +18h  byte string  zero terminated UTF8 path and file name

        http://www.godevtool.com/Other/pdb.htm
        """

        result = {}
        rsds = re.compile('RSDS.{24,1024}\.pdb')
        x = rsds.findall(scanObject.buffer)

        if x and x[-1]:
            match = x[-1]
            result["guid"] = "%s-%s-%s-%s" % (binascii.hexlify(match[4:8]),
                                              binascii.hexlify(match[8:10]),
                                              binascii.hexlify(match[10:12]),
                                              binascii.hexlify(match[12:20]))
            result["age"] = struct.unpack('<L', match[20:24])[0]
            result["pdb"] = match[24:]

        return result

    def parseRich(self, pe):
        """
        Parses out Rich header information using pefile.
        """
        result = {}
        data = []
        if pe.RICH_HEADER:
            for x in range(0, len(pe.RICH_HEADER.values), 2):
                value = pe.RICH_HEADER.values[x] >> 16
                version = pe.RICH_HEADER.values[x] & 0xffff
                count = pe.RICH_HEADER.values[x + 1]
                data.append({
                    'Id': value,
                    'Version': version,
                    'Count': count,
                })

            result['Rich Header Values'] = data
            result['Checksum'] = pe.RICH_HEADER.checksum
            result['Hashes'] = self.richHeaderHashes(pe)

        return result

    @staticmethod
    def richHeaderHashes(pe):
        """
        Returns hashes of the Rich PE header
        """
        rich_data = pe.get_data(0x80, 0x80)
        data = list(struct.unpack('<32I', rich_data))
        checksum = data[1]
        rich_end = data.index(0x68636952)
        md5 = hashlib.md5()
        sha1 = hashlib.sha1()
        sha256 = hashlib.sha256()
        for i in range(rich_end):
            md5.update(struct.pack('<I', (data[i] ^ checksum)))
            sha1.update(struct.pack('<I', (data[i] ^ checksum)))
            sha256.update(struct.pack('<I', (data[i] ^ checksum)))
        data = {
            'MD5': md5.hexdigest(),
            'SHA1': sha1.hexdigest(),
            'SHA256': sha256.hexdigest(),
        }
        return data
<|endoftext|>


<commit_before>"""
WSGI config for biosys project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
from __future__ import absolute_import, unicode_literals, print_function, division

import confy
from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling
import os

confy.read_environment_file('.env')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "biosys.settings")
application = Cling(MediaCling(get_wsgi_application()))
<commit_msg>Rearrange import order<commit_after>"""
WSGI config for biosys project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
from __future__ import absolute_import, unicode_literals, print_function, division

import os
import confy
from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling

confy.read_environment_file('.env')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "biosys.settings")
application = Cling(MediaCling(get_wsgi_application()))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#     This file is part of partner_academic_title,
#     an Odoo module.
#
#     Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#     partner_academic_title is free software:
#     you can redistribute it and/or modify it under the terms of the GNU
#     Affero General Public License as published by the Free Software
#     Foundation,either version 3 of the License, or (at your option) any
#     later version.
#
#     partner_academic_title is distributed
#     in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
#     even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with partner_academic_title.
#     If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import models, fields

class PartnerAcademicTitle(models.Model):
    _name = 'partner.academic.title'

    name = fields.Char(required=True)
    sequence = fields.Integer(required=True,
                              help="""defines the order to display titles""")
    active = fields.Boolean(default=True)
<commit_msg>Add translate=True on academic title name<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#     This file is part of partner_academic_title,
#     an Odoo module.
#
#     Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#     partner_academic_title is free software:
#     you can redistribute it and/or modify it under the terms of the GNU
#     Affero General Public License as published by the Free Software
#     Foundation,either version 3 of the License, or (at your option) any
#     later version.
#
#     partner_academic_title is distributed
#     in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
#     even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with partner_academic_title.
#     If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import models, fields

class PartnerAcademicTitle(models.Model):
    _name = 'partner.academic.title'

    name = fields.Char(required=True, translate=True)
    sequence = fields.Integer(required=True,
                              help="""defines the order to display titles""")
    active = fields.Boolean(default=True)
<|endoftext|>


<commit_before>#!/usr/bin/python
#
# Copyright 2013 Greg Neagle
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""See docstring for MSOffice2011UpdateInfoProvider class"""

import plistlib
import urllib2

from distutils.version import LooseVersion
from operator import itemgetter

from autopkglib import Processor, ProcessorError

__all__ = ["MSOffice2011UpdateInfoProvider"]

# Some interesting URLs:

# Office 2011
# http://www.microsoft.com/mac/autoupdate/0409MSOf14.xml

# Microsoft Auto Update 2
# http://www.microsoft.com/mac/autoupdate/0409MSau02.xml

# Microsoft Error Reporting 2
# http://www.microsoft.com/mac/autoupdate/0409Merp2.xml

# See http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx
# for a table of "Culture Codes"
CULTURE_CODE = "0409"
BASE_URL = "http://www.microsoft.com/mac/autoupdate/%sMSOf14.xml"
MUNKI_UPDATE_NAME = "Office2011_update"

class MSOffice2011UpdateInfoProvider(Processor):
    """Provides a download URL for an Office 2011 update."""
    description = __doc__

    input_variables = {
        "culture_code": {
            "required": False,
            "description": (
                "See "
                "http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx"
                " for a table of CultureCodes Defaults to 0409, which "
                "corresponds to en-US (English - United States)"),
        },
        "base_url": {
            "required": False,
            "description": (
                "Default is %s. If this is given, culture_code is ignored."
                % (BASE_URL % CULTURE_CODE)),
        },
        "version": {
            "required": False,
            "description": "Update version number. Defaults to latest.",
        },
        "munki_update_name": {
            "required": False,
            "description": (
                "Name for the update in Munki repo. Defaults to '%s'"
                % MUNKI_UPDATE_NAME),
        },
    }
    output_variables = {
        "url": {
            "description": "URL to the latest Office 2011 update.",
        },
        "pkg_name": {
            "description": "Name of the package within the disk image.",
        },
        "additional_pkginfo": {
            "description":
                "Some pkginfo fields extracted from the Microsoft metadata.",
        },
    }

    def sanity_check_expected_triggers(self, item):
        """Raises an exeception if the Trigger Condition or
        Triggers for an update don't match what we expect.
        Protects us if these change in the future."""
        #pylint: disable=no-self-use
        if not item.get("Trigger Condition") == ["and", "MCP"]:
            raise ProcessorError(
                "Unexpected Trigger Condition in item %s: %s"
                % (item["Title"], item["Trigger Condition"]))
        if not "MCP" in item.get("Triggers", {}):
            raise ProcessorError(
                "Missing expected MCP Trigger in item %s" % item["Title"])

    def get_requires_from_update(self, item):
        """Attempts to determine what earlier updates are
        required by this update"""

        def compare_versions(this, that):
            """Internal comparison function for use with sorting"""
            return cmp(LooseVersion(this), LooseVersion(that))

        self.sanity_check_expected_triggers(item)
        munki_update_name = self.env.get("munki_update_name", MUNKI_UPDATE_NAME)
        mcp_versions = item.get(
            "Triggers", {}).get("MCP", {}).get("Versions", [])
        if not mcp_versions:
            return None
        # Versions array is already sorted in current 0409MSOf14.xml,
        # may be no need to sort; but we should just to be safe...
        mcp_versions.sort(compare_versions)
        if mcp_versions[0] == "14.0.0":
            # works with original Office release, so no requires array
            return None
        return ["%s-%s" % (munki_update_name, mcp_versions[0])]

    def get_installs_item_from_update(self, item):
        """Attempts to parse the Triggers to create an installs item"""
        self.sanity_check_expected_triggers(item)
        triggers = item.get("Triggers", {})
        paths = [triggers[key].get("File") for key in triggers.keys()]
        if "Office/MicrosoftComponentPlugin.framework" in paths:
            # use MicrosoftComponentPlugin.framework as installs item
            installs_item = {
                "CFBundleShortVersionString": self.get_version(item),
                "CFBundleVersion": self.get_version(item),
                "path": ("/Applications/Microsoft Office 2011/"
                         "Office/MicrosoftComponentPlugin.framework"),
                "type": "bundle",
                "version_comparison_key": "CFBundleShortVersionString"
            }
            return [installs_item]
        return None

    def get_version(self, item):
        """Extracts the version of the update item."""
        # currently relies on the item having a title in the format
        # "Office 2011 x.y.z Update"
        #pylint: disable=no-self-use
        title_start = "Office 2011 "
        title_end = " Update"
        title = item.get("Title", "")
        version_str = title.replace(title_start, "").replace(title_end, "")
        return version_str

    def value_to_os_version_string(self, value):
        """Converts a value to an OS X version number"""
        #pylint: disable=no-self-use
        if isinstance(value, int):
            version_str = hex(value)[2:]
        elif isinstance(value, basestring):
            if value.startswith('0x'):
                version_str = value[2:]
        # OS versions are encoded as hex:
        # 4184 = 0x1058 = 10.5.8
        # not sure how 10.4.11 would be encoded;
        # guessing 0x104B ?
        major = 0
        minor = 0
        patch = 0
        try:
            if len(version_str) == 1:
                major = int(version_str[0])
            if len(version_str) > 1:
                major = int(version_str[0:2])
            if len(version_str) > 2:
                minor = int(version_str[2], 16)
            if len(version_str) > 3:
                patch = int(version_str[3], 16)
        except ValueError:
            raise ProcessorError("Unexpected value in version: %s" % value)
        return "%s.%s.%s" % (major, minor, patch)

    def get_mso2011update_info(self):
        """Gets info about an Office 2011 update from MS metadata."""
        if "base_url" in self.env:
            base_url = self.env["base_url"]
        else:
            culture_code = self.env.get("culture_code", CULTURE_CODE)
            base_url = BASE_URL % culture_code
        version_str = self.env.get("version")
        if not version_str:
            version_str = "latest"
        # Get metadata URL
        try:
            fref = urllib2.urlopen(base_url)
            data = fref.read()
            fref.close()
        except BaseException as err:
            raise ProcessorError("Can't download %s: %s" % (base_url, err))

        metadata = plistlib.readPlistFromString(data)
        if version_str == "latest":
            # Office 2011 update metadata is a list of dicts.
            # we need to sort by date.
            sorted_metadata = sorted(metadata, key=itemgetter('Date'))
            # choose the last item, which should be most recent.
            item = sorted_metadata[-1]
        else:
            # we've been told to find a specific version. Unfortunately, the
            # Office2011 update metadata items don't have a version attibute.
            # The version is only in text in the update's Title. So we look for
            # that...
            # Titles are in the format "Office 2011 x.y.z Update"
            padded_version_str = " " + version_str + " "
            matched_items = [item for item in metadata
                             if padded_version_str in item["Title"]]
            if len(matched_items) != 1:
                raise ProcessorError(
                    "Could not find version %s in update metadata. "
                    "Updates that are available: %s"
                    % (version_str, ", ".join(["'%s'" % item["Title"]
                                               for item in metadata])))
            item = matched_items[0]

        self.env["url"] = item["Location"]
        self.env["pkg_name"] = item["Payload"]
        self.output("Found URL %s" % self.env["url"])
        self.output("Got update: '%s'" % item["Title"])
        # now extract useful info from the rest of the metadata that could
        # be used in a pkginfo
        pkginfo = {}
        pkginfo["description"] = "%s" % item["Short Description"]
        pkginfo["display_name"] = item["Title"]
        max_os = self.value_to_os_version_string(item['Max OS'])
        min_os = self.value_to_os_version_string(item['Min OS'])
        if max_os != "0.0.0":
            pkginfo["maximum_os_version"] = max_os
        if min_os != "0.0.0":
            pkginfo["minimum_os_version"] = min_os
        installs_items = self.get_installs_item_from_update(item)
        if installs_items:
            pkginfo["installs"] = installs_items
        requires = self.get_requires_from_update(item)
        if requires:
            pkginfo["requires"] = requires
            self.output(
                "Update requires previous update version %s"
                % requires[0].split("-")[1])

        pkginfo['name'] = self.env.get("munki_update_name", MUNKI_UPDATE_NAME)
        self.env["additional_pkginfo"] = pkginfo
        self.output("Additional pkginfo: %s" % self.env["additional_pkginfo"])

    def main(self):
        """Get information about an update"""
        self.get_mso2011update_info()

if __name__ == "__main__":
    PROCESSOR = MSOffice2011UpdateInfoProvider()
    PROCESSOR.execute_shell()
<commit_msg>Use a sample MAU User-Agent for feed request<commit_after>#!/usr/bin/python
#
# Copyright 2013 Greg Neagle
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""See docstring for MSOffice2011UpdateInfoProvider class"""

import plistlib
import urllib2

from distutils.version import LooseVersion
from operator import itemgetter

from autopkglib import Processor, ProcessorError

__all__ = ["MSOffice2011UpdateInfoProvider"]

# Some interesting URLs:

# Office 2011
# http://www.microsoft.com/mac/autoupdate/0409MSOf14.xml

# Microsoft Auto Update 2
# http://www.microsoft.com/mac/autoupdate/0409MSau02.xml

# Microsoft Error Reporting 2
# http://www.microsoft.com/mac/autoupdate/0409Merp2.xml

# See http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx
# for a table of "Culture Codes"
CULTURE_CODE = "0409"
BASE_URL = "http://www.microsoft.com/mac/autoupdate/%sMSOf14.xml"
MUNKI_UPDATE_NAME = "Office2011_update"

class MSOffice2011UpdateInfoProvider(Processor):
    """Provides a download URL for an Office 2011 update."""
    description = __doc__

    input_variables = {
        "culture_code": {
            "required": False,
            "description": (
                "See "
                "http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx"
                " for a table of CultureCodes Defaults to 0409, which "
                "corresponds to en-US (English - United States)"),
        },
        "base_url": {
            "required": False,
            "description": (
                "Default is %s. If this is given, culture_code is ignored."
                % (BASE_URL % CULTURE_CODE)),
        },
        "version": {
            "required": False,
            "description": "Update version number. Defaults to latest.",
        },
        "munki_update_name": {
            "required": False,
            "description": (
                "Name for the update in Munki repo. Defaults to '%s'"
                % MUNKI_UPDATE_NAME),
        },
    }
    output_variables = {
        "url": {
            "description": "URL to the latest Office 2011 update.",
        },
        "pkg_name": {
            "description": "Name of the package within the disk image.",
        },
        "additional_pkginfo": {
            "description":
                "Some pkginfo fields extracted from the Microsoft metadata.",
        },
    }

    def sanity_check_expected_triggers(self, item):
        """Raises an exeception if the Trigger Condition or
        Triggers for an update don't match what we expect.
        Protects us if these change in the future."""
        #pylint: disable=no-self-use
        if not item.get("Trigger Condition") == ["and", "MCP"]:
            raise ProcessorError(
                "Unexpected Trigger Condition in item %s: %s"
                % (item["Title"], item["Trigger Condition"]))
        if not "MCP" in item.get("Triggers", {}):
            raise ProcessorError(
                "Missing expected MCP Trigger in item %s" % item["Title"])

    def get_requires_from_update(self, item):
        """Attempts to determine what earlier updates are
        required by this update"""

        def compare_versions(this, that):
            """Internal comparison function for use with sorting"""
            return cmp(LooseVersion(this), LooseVersion(that))

        self.sanity_check_expected_triggers(item)
        munki_update_name = self.env.get("munki_update_name", MUNKI_UPDATE_NAME)
        mcp_versions = item.get(
            "Triggers", {}).get("MCP", {}).get("Versions", [])
        if not mcp_versions:
            return None
        # Versions array is already sorted in current 0409MSOf14.xml,
        # may be no need to sort; but we should just to be safe...
        mcp_versions.sort(compare_versions)
        if mcp_versions[0] == "14.0.0":
            # works with original Office release, so no requires array
            return None
        return ["%s-%s" % (munki_update_name, mcp_versions[0])]

    def get_installs_item_from_update(self, item):
        """Attempts to parse the Triggers to create an installs item"""
        self.sanity_check_expected_triggers(item)
        triggers = item.get("Triggers", {})
        paths = [triggers[key].get("File") for key in triggers.keys()]
        if "Office/MicrosoftComponentPlugin.framework" in paths:
            # use MicrosoftComponentPlugin.framework as installs item
            installs_item = {
                "CFBundleShortVersionString": self.get_version(item),
                "CFBundleVersion": self.get_version(item),
                "path": ("/Applications/Microsoft Office 2011/"
                         "Office/MicrosoftComponentPlugin.framework"),
                "type": "bundle",
                "version_comparison_key": "CFBundleShortVersionString"
            }
            return [installs_item]
        return None

    def get_version(self, item):
        """Extracts the version of the update item."""
        # currently relies on the item having a title in the format
        # "Office 2011 x.y.z Update"
        #pylint: disable=no-self-use
        title_start = "Office 2011 "
        title_end = " Update"
        title = item.get("Title", "")
        version_str = title.replace(title_start, "").replace(title_end, "")
        return version_str

    def value_to_os_version_string(self, value):
        """Converts a value to an OS X version number"""
        #pylint: disable=no-self-use
        if isinstance(value, int):
            version_str = hex(value)[2:]
        elif isinstance(value, basestring):
            if value.startswith('0x'):
                version_str = value[2:]
        # OS versions are encoded as hex:
        # 4184 = 0x1058 = 10.5.8
        # not sure how 10.4.11 would be encoded;
        # guessing 0x104B ?
        major = 0
        minor = 0
        patch = 0
        try:
            if len(version_str) == 1:
                major = int(version_str[0])
            if len(version_str) > 1:
                major = int(version_str[0:2])
            if len(version_str) > 2:
                minor = int(version_str[2], 16)
            if len(version_str) > 3:
                patch = int(version_str[3], 16)
        except ValueError:
            raise ProcessorError("Unexpected value in version: %s" % value)
        return "%s.%s.%s" % (major, minor, patch)

    def get_mso2011update_info(self):
        """Gets info about an Office 2011 update from MS metadata."""
        if "base_url" in self.env:
            base_url = self.env["base_url"]
        else:
            culture_code = self.env.get("culture_code", CULTURE_CODE)
            base_url = BASE_URL % culture_code
        version_str = self.env.get("version")
        if not version_str:
            version_str = "latest"
        # Get metadata URL
        req = urllib2.Request(base_url)
        # Add the MAU User-Agent, since MAU feed server seems to explicitly block
        # a User-Agent of 'Python-urllib/2.7' - even a blank User-Agent string
        # passes.
        req.add_header("User-Agent",
            "Microsoft%20AutoUpdate/3.0.2 CFNetwork/720.2.4 Darwin/14.1.0 (x86_64)")
        try:
            fref = urllib2.urlopen(req)
            data = fref.read()
            fref.close()
        except BaseException as err:
            raise ProcessorError("Can't download %s: %s" % (base_url, err))

        metadata = plistlib.readPlistFromString(data)
        if version_str == "latest":
            # Office 2011 update metadata is a list of dicts.
            # we need to sort by date.
            sorted_metadata = sorted(metadata, key=itemgetter('Date'))
            # choose the last item, which should be most recent.
            item = sorted_metadata[-1]
        else:
            # we've been told to find a specific version. Unfortunately, the
            # Office2011 update metadata items don't have a version attibute.
            # The version is only in text in the update's Title. So we look for
            # that...
            # Titles are in the format "Office 2011 x.y.z Update"
            padded_version_str = " " + version_str + " "
            matched_items = [item for item in metadata
                             if padded_version_str in item["Title"]]
            if len(matched_items) != 1:
                raise ProcessorError(
                    "Could not find version %s in update metadata. "
                    "Updates that are available: %s"
                    % (version_str, ", ".join(["'%s'" % item["Title"]
                                               for item in metadata])))
            item = matched_items[0]

        self.env["url"] = item["Location"]
        self.env["pkg_name"] = item["Payload"]
        self.output("Found URL %s" % self.env["url"])
        self.output("Got update: '%s'" % item["Title"])
        # now extract useful info from the rest of the metadata that could
        # be used in a pkginfo
        pkginfo = {}
        pkginfo["description"] = "%s" % item["Short Description"]
        pkginfo["display_name"] = item["Title"]
        max_os = self.value_to_os_version_string(item['Max OS'])
        min_os = self.value_to_os_version_string(item['Min OS'])
        if max_os != "0.0.0":
            pkginfo["maximum_os_version"] = max_os
        if min_os != "0.0.0":
            pkginfo["minimum_os_version"] = min_os
        installs_items = self.get_installs_item_from_update(item)
        if installs_items:
            pkginfo["installs"] = installs_items
        requires = self.get_requires_from_update(item)
        if requires:
            pkginfo["requires"] = requires
            self.output(
                "Update requires previous update version %s"
                % requires[0].split("-")[1])

        pkginfo['name'] = self.env.get("munki_update_name", MUNKI_UPDATE_NAME)
        self.env["additional_pkginfo"] = pkginfo
        self.output("Additional pkginfo: %s" % self.env["additional_pkginfo"])

    def main(self):
        """Get information about an update"""
        self.get_mso2011update_info()

if __name__ == "__main__":
    PROCESSOR = MSOffice2011UpdateInfoProvider()
    PROCESSOR.execute_shell()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from sqlalchemy import Column, types

from ..extensions import db

class Revenue(db.Model):

    __tablename__ = 'revenue'

    id = Column(db.Integer, primary_key=True)
    code = Column(db.String(), nullable=False)
    description = Column(db.String(), nullable=False)
    date = Column(db.Date())
    monthly_predicted = Column(db.DECIMAL(19,2))
    monthly_outcome = Column(db.DECIMAL(19,2))
    economical_category = Column(db.Integer)
    economical_subcategory = Column(db.Integer)
    source = Column(db.Integer)
    rubric = Column(db.Integer)
    paragraph = Column(db.Integer)
    subparagraph = Column(db.Integer)
<commit_msg>Change Revenu model column types for 'code' column and 'description' for MySQL<commit_after># -*- coding: utf-8 -*-

from sqlalchemy import Column, types

from ..extensions import db

class Revenue(db.Model):

    __tablename__ = 'revenue'

    id = Column(db.Integer, primary_key=True)
    code = Column(db.String(30), nullable=False)
    description = Column(db.Text(), nullable=False)
    date = Column(db.Date())
    monthly_predicted = Column(db.DECIMAL(19,2))
    monthly_outcome = Column(db.DECIMAL(19,2))
    economical_category = Column(db.Integer)
    economical_subcategory = Column(db.Integer)
    source = Column(db.Integer)
    rubric = Column(db.Integer)
    paragraph = Column(db.Integer)
    subparagraph = Column(db.Integer)
<|endoftext|>


<commit_before>import json

from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext as _

from linaro_django_jsonfield.models import JSONField

class DeviceType(models.Model):
    """
    A class of device, for example a pandaboard or a snowball.
    """

    name = models.SlugField(unique=True)

    def __unicode__(self):
        return self.name

    # We will probably hang uboot command and such off here...

class Device(models.Model):
    """
    A device that we can run tests on.
    """

    #OFFLINE = 0
    #IDLE = 1
    #RUNNING = 2
    #
    #STATUS_CHOICES = (
    #    (OFFLINE, 'Offline'),
    #    (IDLE, 'Idle'),
    #    (RUNNING, 'Running'),
    #)

    hostname = models.CharField(
        verbose_name = _(u"Hostname"),
        max_length = 200,
        primary_key = True,
    )

    device_type = models.ForeignKey(
        DeviceType, verbose_name=_(u"Device type"))

    #status = models.IntegerField(
    #    choices = STATUS_CHOICES,
    #    default = IDLE,
    #    verbose_name = _(u"Device status"),
    #    editable = False
    #)

    def __unicode__(self):
        return self.hostname

    #@classmethod
    #def find_devices_by_type(cls, device_type):
    #    return device_type.device_set.all()

class TestJob(models.Model):
    """
    A test job is a test process that will be run on a Device.
    """

    SUBMITTED = 0
    RUNNING = 1
    COMPLETE = 2
    INCOMPLETE = 3
    CANCELED = 4

    STATUS_CHOICES = (
        (SUBMITTED, 'Submitted'),
        (RUNNING, 'Running'),
        (COMPLETE, 'Complete'),
        (INCOMPLETE, 'Incomplete'),
        (CANCELED, 'Canceled'),
    )

    submitter = models.ForeignKey(
        User,
        verbose_name = _(u"Submitter"),
    )

    #description = models.CharField(
    #    verbose_name = _(u"Description"),
    #    max_length = 200
    #)

    target = models.ForeignKey(Device, null=True)
    device_type = models.ForeignKey(DeviceType)

    #priority = models.IntegerField(
    #    verbose_name = _(u"Priority"),
    #    default=0)
    submit_time = models.DateTimeField(
        verbose_name = _(u"Submit time"),
        auto_now = False,
        auto_now_add = True
    )
    #start_time = models.DateTimeField(
    #    verbose_name = _(u"Start time"),
    #    auto_now = False,
    #    auto_now_add = False,
    #    null = True,
    #    blank = True,
    #    editable = False
    #)
    #end_time = models.DateTimeField(
    #    verbose_name = _(u"End time"),
    #    auto_now = False,
    #    auto_now_add = False,
    #    null = True,
    #    blank = True,
    #    editable = False
    #)
    status = models.IntegerField(
        choices = STATUS_CHOICES,
        default = SUBMITTED,
        verbose_name = _(u"Status"),
        editable = False
    )
    definition = JSONField(
        editable = False,
    )

    #def __unicode__(self):
    #    return self.description

    @classmethod
    def from_json_and_user(cls, json_data, user):
        job_data = json.loads(json_data)
        if 'target' in job_data:
            target = Device.objects.get(hostname=job_data['target'])
            device_type = target.device_type
        else:
            target = None
            device_type = DeviceType.objects.get(name=job_data['device_type'])
        job = TestJob(
            definition=json_data, submitter=user, device_type=device_type,
            target=target)
        job.save()
        return job
<commit_msg>make the DeviceType.name primary<commit_after>import json

from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext as _

from linaro_django_jsonfield.models import JSONField

class DeviceType(models.Model):
    """
    A class of device, for example a pandaboard or a snowball.
    """

    name = models.SlugField(primary_key=True)

    def __unicode__(self):
        return self.name

    # We will probably hang uboot command and such off here...

class Device(models.Model):
    """
    A device that we can run tests on.
    """

    #OFFLINE = 0
    #IDLE = 1
    #RUNNING = 2
    #
    #STATUS_CHOICES = (
    #    (OFFLINE, 'Offline'),
    #    (IDLE, 'Idle'),
    #    (RUNNING, 'Running'),
    #)

    hostname = models.CharField(
        verbose_name = _(u"Hostname"),
        max_length = 200,
        primary_key = True,
    )

    device_type = models.ForeignKey(
        DeviceType, verbose_name=_(u"Device type"))

    #status = models.IntegerField(
    #    choices = STATUS_CHOICES,
    #    default = IDLE,
    #    verbose_name = _(u"Device status"),
    #    editable = False
    #)

    def __unicode__(self):
        return self.hostname

    #@classmethod
    #def find_devices_by_type(cls, device_type):
    #    return device_type.device_set.all()

class TestJob(models.Model):
    """
    A test job is a test process that will be run on a Device.
    """

    SUBMITTED = 0
    RUNNING = 1
    COMPLETE = 2
    INCOMPLETE = 3
    CANCELED = 4

    STATUS_CHOICES = (
        (SUBMITTED, 'Submitted'),
        (RUNNING, 'Running'),
        (COMPLETE, 'Complete'),
        (INCOMPLETE, 'Incomplete'),
        (CANCELED, 'Canceled'),
    )

    submitter = models.ForeignKey(
        User,
        verbose_name = _(u"Submitter"),
    )

    #description = models.CharField(
    #    verbose_name = _(u"Description"),
    #    max_length = 200
    #)

    target = models.ForeignKey(Device, null=True)
    device_type = models.ForeignKey(DeviceType)

    #priority = models.IntegerField(
    #    verbose_name = _(u"Priority"),
    #    default=0)
    submit_time = models.DateTimeField(
        verbose_name = _(u"Submit time"),
        auto_now = False,
        auto_now_add = True
    )
    #start_time = models.DateTimeField(
    #    verbose_name = _(u"Start time"),
    #    auto_now = False,
    #    auto_now_add = False,
    #    null = True,
    #    blank = True,
    #    editable = False
    #)
    #end_time = models.DateTimeField(
    #    verbose_name = _(u"End time"),
    #    auto_now = False,
    #    auto_now_add = False,
    #    null = True,
    #    blank = True,
    #    editable = False
    #)
    status = models.IntegerField(
        choices = STATUS_CHOICES,
        default = SUBMITTED,
        verbose_name = _(u"Status"),
        editable = False
    )
    definition = JSONField(
        editable = False,
    )

    #def __unicode__(self):
    #    return self.description

    @classmethod
    def from_json_and_user(cls, json_data, user):
        job_data = json.loads(json_data)
        if 'target' in job_data:
            target = Device.objects.get(hostname=job_data['target'])
            device_type = target.device_type
        else:
            target = None
            device_type = DeviceType.objects.get(name=job_data['device_type'])
        job = TestJob(
            definition=json_data, submitter=user, device_type=device_type,
            target=target)
        job.save()
        return job
<|endoftext|>