def add_dynamic_fields(self, res, dynamic_fields, wiz):
        """ Create the configuration view using the dynamically generated
            fields in fields_get()
        """
        try:
            # Search for view container hook and add dynamic view and fields
            xml_view = etree.fromstring(res['arch'])
            xml_static_form = xml_view.xpath("//group[@name='static_form']")[0]
            xml_dynamic_form = etree.Element('group',
                                             colspan='3',
                                             name='dynamic_form')
            xml_parent = xml_static_form.getparent()
            xml_parent.insert(
                xml_parent.index(xml_static_form) + 1, xml_dynamic_form)
            xml_dynamic_form = xml_view.xpath(
                "//group[@name='dynamic_form']")[0]
        except Exception:
            raise Warning(
                _('There was a problem rendering the view '
                  '(dynamic_form not found)'))

        # Get all dynamic fields inserted via fields_get method
        attr_lines = wiz.product_tmpl_id.attribute_line_ids.sorted()

        # Loop over the dynamic fields and add them to the view one by one
        for attr_line in attr_lines:

            attribute_id = attr_line.attribute_id.id
            field_name = self.field_prefix + str(attribute_id)
            custom_field = self.custom_field_prefix + str(attribute_id)

            # Check if the attribute line has been added to the db fields
            if field_name not in dynamic_fields:
                continue

            config_steps = wiz.product_tmpl_id.config_step_line_ids.filtered(
                lambda x: attr_line in x.attribute_line_ids)

            # attrs property for dynamic fields
            attrs = {'readonly': ['|'], 'required': [], 'invisible': ['|']}

            if config_steps:
                cfg_step_ids = [str(id) for id in config_steps.ids]
                attrs['invisible'].append(('state', 'not in', cfg_step_ids))
                attrs['readonly'].append(('state', 'not in', cfg_step_ids))

                # If attribute is required make it so only in the proper step
                if attr_line.required:
                    attrs['required'].append(('state', 'in', cfg_step_ids))

            if attr_line.custom:
                pass
                # TODO: Implement restrictions for ranges

            config_lines = wiz.product_tmpl_id.config_line_ids
            dependencies = config_lines.filtered(
                lambda cl: cl.attribute_line_id == attr_line)

            # If an attribute field depends on another field from the same
            # configuration step then we must use attrs to enable/disable the
            # required and readonly depending on the value entered in the
            # dependee

            if attr_line.value_ids <= dependencies.mapped('value_ids'):
                attr_depends = {}
                domain_lines = dependencies.mapped('domain_id.domain_line_ids')
                for domain_line in domain_lines:
                    attr_id = domain_line.attribute_id.id
                    attr_field = self.field_prefix + str(attr_id)
                    attr_lines = wiz.product_tmpl_id.attribute_line_ids
                    # If the fields it depends on are not in the config step
                    if config_steps and str(attr_line.id) != wiz.state:
                        continue
                    if attr_field not in attr_depends:
                        attr_depends[attr_field] = set()
                    if domain_line.condition == 'in':
                        attr_depends[attr_field] |= set(
                            domain_line.value_ids.ids)
                    elif domain_line.condition == 'not in':
                        val_ids = attr_lines.filtered(
                            lambda l: l.attribute_id.id == attr_id).value_ids
                        val_ids = val_ids - domain_line.value_ids
                        attr_depends[attr_field] |= set(val_ids.ids)

                for dependee_field, val_ids in attr_depends.items():
                    if not val_ids:
                        continue
                    attrs['readonly'].append(
                        (dependee_field, 'not in', list(val_ids)))
                    attrs['required'].append(
                        (dependee_field, 'in', list(val_ids)))

            # Create the new field in the view
            node = etree.Element(
                "field",
                name=field_name,
                on_change="onchange_attribute_value(%s, context)" % field_name,
                default_focus="1" if attr_line == attr_lines[0] else "0",
                attrs=str(attrs),
                context="{'show_attribute': False}",
                options=str({
                    'no_create': True,
                    'no_create_edit': True,
                    'no_open': True
                }))

            if attr_line.required and not config_steps:
                node.attrib['required'] = '1'

            field_type = dynamic_fields[field_name].get('type')
            if field_type == 'many2many':
                node.attrib['widget'] = 'many2many_tags'

            # Apply the modifiers (attrs) on the newly inserted field in the
            # arch and add it to the view
            orm.setup_modifiers(node)
            xml_dynamic_form.append(node)

            if attr_line.custom and custom_field in dynamic_fields:
                widget = ''
                custom_ext_id = 'product_configurator.custom_attribute_value'
                custom_option_id = self.env.ref(custom_ext_id).id

                if field_type == 'many2many':
                    field_val = [(6, False, [custom_option_id])]
                else:
                    field_val = custom_option_id

                attrs['readonly'] += [(field_name, '!=', field_val)]
                attrs['invisible'] += [(field_name, '!=', field_val)]
                attrs['required'] += [(field_name, '=', field_val)]

                if config_steps:
                    attrs['required'] += [('state', 'in', cfg_step_ids)]

                # TODO: Add a field2widget mapper
                if attr_line.attribute_id.custom_type == 'color':
                    widget = 'color'
                node = etree.Element("field",
                                     name=custom_field,
                                     attrs=str(attrs),
                                     widget=widget)
                orm.setup_modifiers(node)
                xml_dynamic_form.append(node)

        return xml_view
Ejemplo n.º 2
0
 def validate_dates(self):
     if self.rent_end_date < self.rent_start_date:
         raise Warning("Please select the valid end date.")
Ejemplo n.º 3
0
 def file_not_found(fname):
     raise Warning(
         _('''Error while reading file %s.
         Maybe it was removed or permission is changed.
         Please refresh the list.''' % fname))
Ejemplo n.º 4
0
    def get_result(self):
        data = self.read()[0]

        start_date = data.get('date_start', False)
        end_date = data.get('date_end', False)
        if start_date and end_date and end_date < start_date:
            raise Warning(_("End date should be greater than start date!"))
        res_user = self.env["res.users"].browse(self._uid)

        # Create Inventory Export report in Excel file.
        workbook = xlwt.Workbook()
        worksheet = workbook.add_sheet('Sheet 1')
        font = xlwt.Font()
        font.bold = True
        header = xlwt.easyxf('font: bold 1, height 280')
        # start_date = datetime.strptime(str(context.get("date_from")), DEFAULT_SERVER_DATE_FORMAT)
        # start_date_formate = start_date.strftime('%d/%m/%Y')
        # end_date = datetime.strptime(str(context.get("date_to")), DEFAULT_SERVER_DATE_FORMAT)
        # end_date_formate = end_date.strftime('%d/%m/%Y')
        # start_date_to_end_date = tools.ustr(start_date_formate) + ' To ' + tools.ustr(end_date_formate)

        style = xlwt.easyxf('align: wrap yes')
        worksheet.row(0).height = 500
        worksheet.row(1).height = 500
        for x in range(0, 41):
            worksheet.col(x).width = 6000
        borders = xlwt.Borders()
        borders.top = xlwt.Borders.MEDIUM
        borders.bottom = xlwt.Borders.MEDIUM
        border_style = xlwt.XFStyle()  # Create Style
        border_style.borders = borders
        border_style1 = xlwt.easyxf('font: bold 1')
        border_style1.borders = borders
        style = xlwt.easyxf('align: wrap yes', style)

        ids_location = []
        ids_categ = []
        ids_product = []
        where_end_date_awal = " sm.date is null "
        where_start_date = " 1=1 "
        if start_date:
            where_start_date = " sm.date + interval '7 hour' >= '%s 00:00:00' " % start_date
            where_end_date_awal = " sm.date + interval '7 hour' < '%s 00:00:00' " % start_date
        where_end_date = " 1=1 "
        if end_date:
            where_end_date = " sm.date + interval '7 hour' <= '%s 23:59:59'" % end_date
        where_end_date_opn = " 1=1 "
        if end_date:
            where_end_date_opn = " si.date::text LIKE '%s%s'" % (end_date, "%")

        where_location = " 1=1 "
        if ids_location:
            where_location = """(sm.location_id in %s 
            or sm.location_dest_id in %s)""" % (str(
                tuple(ids_location)).replace(
                    ',)', ')'), str(tuple(ids_location)).replace(',)', ')'))
        where_location_opn = " sil.location_id = 12 "

        where_categ = " 1=1 "
        if ids_categ:
            where_categ = "pt.categ_id in %s" % str(tuple(ids_categ)).replace(
                ',)', ')')
        where_product = " 1=1 "
        if ids_product:
            where_product = "pp.id in %s" % str(tuple(ids_product)).replace(
                ',)', ')')
        query = """
                SELECT 	pp.id as prod_id, 
				pt.default_code as prod_code, 
				pt.name as prod_name,
				pu.name as uom,
				sum(coalesce(awal.qty,0)) as saldo_awal, 
                sum(coalesce(saldo_masuk.qty,0)) as masuk, 
                sum(coalesce(saldo_keluar.qty,0)) as keluar,
                sum(coalesce(prod_adj.qty,0)) as adjusment,
                sum(coalesce(opn.qty,0)) as opname
                    
                from product_product pp
                    left join
                        (
                            select sm.product_id, 
                            sum(case when sl.name = 'Scrap' and dl.name != 'Scrap'
                                then sm.product_qty*-1 
                            when sl.name != 'Scrap' and dl.name = 'Scrap'
                                then sm.product_qty else 0 end) as qty
                            
                            from stock_move sm
                            left join stock_location sl on sl.id = sm.location_id
                            left join stock_location dl on dl.id = sm.location_dest_id
                            left join product_product pp on pp.id=sm.product_id
                            left join product_template pt on pt.id=pp.product_tmpl_id
                            left join uom_uom pu on pu.id= sm.product_uom
                            where """ + where_end_date_awal + """ and """ + where_location + """ 
                            and sm.state = 'done'
                            group by sm.product_id
                        ) awal on awal.product_id=pp.id
                        
                    left join 
                        (
                            select sm.product_id, 
                            sum(sm.product_qty) as qty 
                            from stock_move sm
                            left join stock_location sl on sl.id = sm.location_id
                            left join stock_location dl on dl.id = sm.location_dest_id
                            left join product_product pp on pp.id=sm.product_id
                            left join product_template pt on pt.id=pp.product_tmpl_id
                            left join uom_uom pu on pu.id= sm.product_uom
                            where sl.name != 'Scrap' and dl.name = 'Scrap' and sm.state = 'done' and sm.inventory_id is null
                            and """ + where_start_date + """ and """ + where_end_date + """ and """ + where_location + """  
                            group by sm.product_id
                        ) saldo_masuk on saldo_masuk.product_id=pp.id
                        
                    left join 
                        (
                            select sm.product_id, sum(sm.product_qty) as qty 
                            from stock_move sm 
                            left join stock_location sl on sl.id = sm.location_id 
                            left join stock_location dl on dl.id = sm.location_dest_id
                            left join product_product pp on pp.id=sm.product_id
                            left join product_template pt on pt.id=pp.product_tmpl_id	
                            left join uom_uom pu on pu.id= sm.product_uom 
                            where sl.name = 'Scrap' and dl.name != 'Scrap' and sm.state = 'done' and sm.inventory_id is null
                            and """ + where_start_date + """ and """ + where_end_date + """ and """ + where_location + """
                            group by sm.product_id
                        ) saldo_keluar on saldo_keluar.product_id=pp.id
                
                    left join
                        (
                            select sm.product_id, 
                            sum(case when sl.name = 'Scrap' and dl.name != 'Scrap' and inventory_id is not null
                                then sm.product_qty*-1 
                            when sl.name != 'Scrap' and dl.name = 'Scrap' and inventory_id is not null
                                then sm.product_qty else 0 end ) as qty
                            
                            from stock_move sm
                            left join stock_location sl on sl.id = sm.location_id
                            left join stock_location dl on dl.id = sm.location_dest_id
                            left join product_product pp on pp.id=sm.product_id
                            left join product_template pt on pt.id=pp.product_tmpl_id
                            left join uom_uom pu on pu.id= sm.product_uom
                            where """ + where_start_date + """ and """ + where_end_date + """ and """ + where_location + """ and sm.state = 'done'
                            group by sm.product_id
                        ) prod_adj on prod_adj.product_id=pp.id

                    left join
                        (
                            select sil.product_id,
                            sum(sil.product_qty) as qty
                            
                            from stock_inventory_line sil
                            INNER JOIN stock_inventory si on sil.inventory_id = si.id
                            INNER JOIN stock_location sl on sl.id = sil.location_id
                            left join product_product pp on pp.id=si.product_id
                            left join product_template pt on pt.id=pp.product_tmpl_id
                            left join uom_uom pu on pu.id= sil.product_uom_id
                            where """ + where_end_date_opn + """ and """ + where_location_opn + """ and si.state = 'done'
                            group by sil.product_id
                        ) opn on opn.product_id=pp.id
                
                
                LEFT JOIN product_template pt on pt.id=pp.product_tmpl_id
                LEFT JOIN uom_uom pu on pt.uom_id=pu.id
                LEFT JOIN product_category pc on pt.categ_id=pc.id
                where """ + where_categ + """ and """ + where_product + """ and pc.report_type = 'bahan_baku'
                    and (coalesce(awal.qty,0) != 0 
                    or coalesce(saldo_masuk.qty,0) != 0 
                    or coalesce(saldo_keluar.qty,0) != 0) 
                    
                group by pt.default_code, pt.name, pp.id , pu.name 
                    order by pt.name asc
            """
        list_data = []
        company = self.env.user.company_id.name
        start_date_format = start_date.strftime('%d/%m/%Y')
        end_date_format = end_date.strftime('%d/%m/%Y')

        self._cr.execute(query)
        vals = self._cr.fetchall()

        no = 1
        for val in vals:
            saldo_akhir = float(val[4]) + float(val[5]) - \
                float(val[6]) + float(val[7])
            selisih = saldo_akhir - float(val[8])
            list_data.append({
                'no': val[0],
                'kode_barang': val[1],
                'nama_barang': val[2],
                'satuan': val[3],
                'saldo_awal': val[4],
                'pemasukan': val[5],
                'pengeluaran': val[6],
                'penyesuaian': val[7],
                'saldo_akhir': saldo_akhir,
                'stock_opname': val[8],
                'selisih': selisih,
                'keterangan': ""
            })
            no += 1
        hasil = list_data
        return hasil
Ejemplo n.º 5
0
    def create_move(self):
        #         period_obj = self.env['account.period']
        move_obj = self.env['account.move']
        move_line_obj = self.env['account.move.line']
        currency_obj = self.env['res.currency']

        ctx = dict(self._context or {})

        created_move_ids = []
        for line in self:
            if line.state == 'paid':
                raise Warning(_('Accounting Moves already created.'))
            if not line.journal_id:
                raise Warning(_('Please specify journal.'))
            if not line.employee_account:
                raise Warning(_('Please specify employee account.'))

#             period_ids = period_obj.find(line.date)
            company_currency = line.company_id.currency_id
            current_currency = line.currency_id
            flag = True
            if not current_currency:
                flag = False

            ctx.update({'date': line.date})
            if flag and current_currency != company_currency:
                amount_currency = company_currency.compute(
                    line.amount, current_currency)
            else:
                amount_currency = False

            res = company_currency.compute(line.amount, current_currency)
            ctx.update({'date': line.date})
            amount = current_currency.compute(line.amount, company_currency)
            if line.journal_id.type == 'purchase':
                sign = 1
            else:
                sign = -1
            asset_name = line.name
            reference = line.name
            move_vals = {
                #                'name': asset_name,
                'date': line.date,
                'ref': reference,
                #                 'period_id': period_ids and period_ids.id or False,
                'journal_id': line.journal_id.id,
            }
            move_id = move_obj.create(move_vals)
            journal_id = line.journal_id.id
            #            partner_id = line.asset_id.partner_id.id
            if not line.journal_id.default_credit_account_id:
                raise Warning(_('Please specify account on journal.'))
            address_id = line.employee_id.address_home_id or False
            if not address_id:
                raise Warning(
                    _('There is no home address defined for employee: %s ') %
                    (_(line.employee_id.name)))
            partner_id = address_id and address_id.id or False
            if not partner_id:
                raise Warning(
                    _('There is no partner defined for employee : %s ') %
                    (_(line.employee_id.name)))
            t = 0.0
            t1 = 0.0  # sat
            mline = self.env['account.move.line'].browse()  #[]  # mon

            cr_line = []
            dr_line = []

            for l in line.line_ids:  # exp lines entry for debits
                t += l.total_amount
                amount1 = current_currency.compute(l.total_amount,
                                                   company_currency)
                t1 += amount1
                sign = amount1 - 0 < 0 and -1 or 1
                #                 move_line_obj.create({
                #                     'name': asset_name,
                #                     'ref': reference,
                #                     'move_id': move_id.id,
                #                     'account_id': l.account_id.id,
                #                     'credit': 0.0,
                #                     'debit': amount1,
                # #                     'period_id': period_ids and period_ids.id or False,
                #                     'journal_id': journal_id,
                #                     'partner_id': partner_id,
                #                     'currency_id': company_currency.id <> current_currency.id and  current_currency.id or False,
                #                     'amount_currency': flag and company_currency.id <> current_currency.id and sign * l.total_amount or 0.0,
                #                     'analytic_account_id': l.analytic_account and l.analytic_account.id or False,
                #                     'date': line.date,
                #                 })
                dr_line.append((
                    0,
                    0,
                    {
                        'name':
                        asset_name,
                        'ref':
                        reference,
                        'move_id':
                        move_id.id,
                        'account_id':
                        l.account_id.id,
                        'credit':
                        0.0,
                        'debit':
                        amount1,
                        #                     'period_id': period_ids and period_ids.id or False,
                        'journal_id':
                        journal_id,
                        'partner_id':
                        partner_id,
                        'currency_id':
                        company_currency.id != current_currency.id
                        and current_currency.id or False,
                        'amount_currency':
                        flag and company_currency.id != current_currency.id
                        and sign * l.total_amount or 0.0,
                        'analytic_account_id':
                        l.analytic_account and l.analytic_account.id or False,
                        'date':
                        line.date,
                    }))

            # emp credit entry below
            sign = 0.0 - t1 < 0 and -1 or 1
            #             g = move_line_obj.create({  # mon
            #                 'name': asset_name,
            #                 'ref': reference,
            #                 'move_id': move_id.id,
            #                 'account_id': line.employee_account.id,
            #                 'debit': 0.0,
            #                 'credit': t1,
            # #                 'period_id': period_ids and period_ids.id or False,
            #                 'journal_id': journal_id,
            #                 'partner_id': partner_id,
            #                 'currency_id': company_currency.id <> current_currency.id and current_currency.id or False,
            #                 'amount_currency': flag and company_currency.id <> current_currency.id and sign * t or 0.0,
            #                 'date': line.date,
            #             })
            cr_line.append((0, 0, {  # mon
                'name': asset_name,
                'ref': reference,
                'move_id': move_id.id,
                'account_id': line.employee_account.id,
                'debit': 0.0,
                'credit': t1,
                #                 'period_id': period_ids and period_ids.id or False,
                'journal_id': journal_id,
                'partner_id': partner_id,
                'currency_id': company_currency.id != current_currency.id and current_currency.id or False,
                'amount_currency': flag and company_currency.id != current_currency.id and sign * t or 0.0,
                'date': line.date,
            }))
            final_list = cr_line + dr_line
            move_id.write({'line_ids': final_list})

            g = move_id.line_ids

            mline += g  # mon
            #            self.write(cr, uid, line.id, {'move_id': move_id}, context=context)
            created_move_ids.append(move_id)
            line.write({'move_id1': move_id.id})
            line.employee_id.write(
                {'balance': line.employee_id.balance - amount})
            myline = self.env['account.move.line'].browse()  # mon
            for x in line.rec_line_ids:  # sat
                if x.allocate_amount > 0.0:
                    if x.ret_id and x.ret_id.move_id1:  # mon
                        for j in x.ret_id.move_id1.line_ids:  # mon
                            #                             if j.account_id.type == 'receivable':  # mon#todoprobuse
                            if j.account_id.reconcile:  # mon
                                myline += j  # mon
                    if current_currency != company_currency:
                        p = company_currency.compute(x.allocate_amount,
                                                     current_currency)
#                        p = currency_obj.compute(current_currency, company_currency, x.allocate_amount)
                    else:
                        p = x.allocate_amount

                    y = x.ret_id.ret_amount + p
                    z = self.env['cash.advance'].browse(x.ret_id.id)
                    x.ret_id.write({'ret_amount': y})
                    x.ret_id.write({})  # like store={}
                    if y == x.ret_id.amount_total:
                        x.ret_id.write({'state': 'rem'})


#         if mline:  # mon
#             mline += myline
#             mline.reconcile_partial('manual')  # mon #todoprobuse
        line.write({'state': 'paid'})
        return True
Ejemplo n.º 6
0
    def to_json(self):
        if not self.company_id.archivo_cer:
            raise UserError(_('Archivo .cer path is missing.'))
        if not self.company_id.archivo_key:
            raise UserError(_('Archivo .key path is missing.'))
        archivo_cer = self.company_id.archivo_cer
        archivo_key = self.company_id.archivo_key
        self.monedap = self.currency_id.name
        if self.currency_id.name == 'MXN':
            self.tipocambiop = '1'
        else:
            self.tipocambiop = self.currency_id.with_context(
                date=self.payment_date).rate

        timezone = self._context.get('tz')
        if not timezone:
            timezone = self.env.user.partner_id.tz or 'America/Mexico_City'
        #timezone = tools.ustr(timezone).encode('utf-8')

        if not self.fecha_pago:
            raise Warning(
                "Falta configurar fecha de pago en la sección de CFDI del documento."
            )
        else:
            local = pytz.timezone(timezone)
            naive_from = self.fecha_pago
            local_dt_from = naive_from.replace(
                tzinfo=pytz.UTC).astimezone(local)
            date_from = local_dt_from.strftime("%Y-%m-%d %H:%M:%S")
        self.add_resitual_amounts()

        #corregir hora
        local2 = pytz.timezone(timezone)
        naive_from2 = datetime.now()
        local_dt_from2 = naive_from2.replace(
            tzinfo=pytz.UTC).astimezone(local2)
        date_payment = local_dt_from2.strftime("%Y-%m-%d %H:%M:%S")

        if self.docto_relacionados != '[]':
            request_params = {
                'company': {
                    'rfc': self.company_id.rfc,
                    'api_key': self.company_id.proveedor_timbrado,
                    'modo_prueba': self.company_id.modo_prueba,
                    'regimen_fiscal': self.company_id.regimen_fiscal,
                    'postalcode': self.company_id.zip,
                    'nombre_fiscal': self.company_id.nombre_fiscal,
                    'telefono_sms': self.company_id.telefono_sms,
                },
                'customer': {
                    'name': self.partner_id.name,
                    'rfc': self.partner_id.rfc,
                    'uso_cfdi': 'P01',
                },
                'invoice': {
                    'tipo_comprobante':
                    self.tipo_comprobante,
                    'folio_complemento':
                    self.name.replace('CUST.IN', '').replace('/', ''),
                    'serie_complemento':
                    self.company_id.serie_complemento,
                    'fecha_factura':
                    date_payment,
                },
                'concept': {
                    'claveprodserv': '84111506',
                    'calveunidad': 'ACT',
                    'cantidad': 1,
                    'descripcion': 'Pago',
                },
                'payment': {
                    'moneda':
                    self.monedap,
                    'tipocambio':
                    self.tipocambiop,
                    'forma_pago':
                    self.forma_pago,
                    'numero_operacion':
                    self.numero_operacion,
                    'banco_emisor':
                    self.banco_emisor,
                    'cuenta_emisor':
                    self.cuenta_emisor and self.cuenta_emisor.acc_number or '',
                    'rfc_banco_emisor':
                    self.rfc_banco_emisor,
                    'banco_receptor':
                    self.banco_receptor,
                    'cuenta_beneficiario':
                    self.cuenta_beneficiario,
                    'rfc_banco_receptor':
                    self.rfc_banco_receptor,
                    'fecha_pago':
                    date_from,
                    'monto_factura':
                    self.amount
                },
                'docto_relacionado': json.loads(self.docto_relacionados),
                'adicional': {
                    'tipo_relacion': self.tipo_relacion,
                    'uuid_relacionado': self.uuid_relacionado,
                    'confirmacion': self.confirmacion,
                },
                'certificados': {
                    'archivo_cer': archivo_cer.decode("utf-8"),
                    'archivo_key': archivo_key.decode("utf-8"),
                    'contrasena': self.company_id.contrasena,
                },
                'version': {
                    'cfdi': '3.3',
                    'sistema': 'odoo11',
                    'version': '6',
                },
            }
        else:
            raise Warning(
                "No tiene ninguna factura ligada al documento de pago, debe al menos tener una factura ligada. \n Desde la factura crea el pago para que se asocie la factura al pago."
            )
        return request_params
Ejemplo n.º 7
0
    def payment_process(self):
        sum = 0
        remainder = 0
        print(self._ids, "ids", self._context,
              "context-------------------------------------------",
              self.browse(self._ids))
        if self._context.get('active_model') == 'hotel.folio':
            for obj in self:
                print('==============obj===========', obj.reservation_id)
                folio_obj = self.env['hotel.folio'].search([
                    ('reservation_id', '=', obj.reservation_id.id)
                ])
                print('===============folio obj=========', folio_obj)
                if folio_obj:
                    folio_id = folio_obj[0]
#                     if folio_id.amount_total < folio_id.total_advance + obj.amt:
#                         raise Warning("Advance Amount Should not be greater than Total Amount.")
                if not obj.deposit_recv_acc:
                    raise Warning("Account is not set for Deposit account.")
                if not obj.journal_id.default_account_id:
                    raise Warning("Account is not set for selected journal.")
                name = ''
                seq_obj = self.env['ir.sequence']
                if obj.journal_id.secure_sequence_id:
                    name = seq_obj.get_id(obj.journal_id.secure_sequence_id.id)
                print("folio_idfolio_id", folio_id)
                # move_id = self.env['account.move'].create({
                #     'journal_id': obj.journal_id.id,
                #     'partner_id':folio_id.partner_id.id,
                #     'name': name ,
                #     'move_type': 'in_receipt',
                #     'ref': obj.reservation_id.name,
                # })
                payment_id = self.env['account.payment'].create({
                    'journal_id':
                    obj.journal_id.id,
                    'partner_id':
                    folio_id.partner_id.id,
                    'payment_type':
                    'inbound',
                    'partner_type':
                    'customer',
                    'amount':
                    obj.amt,
                })
                payment_id.move_id.ref = obj.reservation_id.name
                payment_id.action_post()
                print("paymnttttttttttttttttttttttttt", payment_id)

                # move_line1 = {
                #
                #     'name': name ,
                #     'move_id': move_id,
                #     'account_id': obj.deposit_recv_acc.id,
                #     'debit': 0.0,
                #     'credit': obj.amt,
                #     'ref': obj.reservation_id.name,
                #     'journal_id': obj.journal_id.id,
                #     'partner_id': obj.reservation_id.partner_id.id,
                #     'date': obj.payment_date
                # }
                # print("move_line1====================================================", move_line1)
                # move_line2 = {
                #     'name': name ,
                #     'move_id': move_id,
                #     'account_id': obj.journal_id.default_account_id.id,
                #     'debit': obj.amt,
                #     'credit': 0.0,
                #     'ref': obj.reservation_id.name,
                #     'journal_id': obj.journal_id.id,
                #     'partner_id': obj.reservation_id.partner_id.id,
                #     'date': obj.payment_date
                # }
                #
                # move_id.write(
                #     {'line_ids': [(0, 0, move_line1), (0, 0, move_line2)]})
                # move_id.post()

                if folio_id:
                    self._cr.execute(
                        'insert into sale_account_move_rel(sale_id,move_id) values (%s,%s)',
                        (folio_id.order_id.id, payment_id.move_id.id))
                    result = folio_id
                    print(
                        "result====================================================",
                        result)
                    sum = result.total_advance + obj.amt
                    remainder = folio_id.amount_total - sum
                    print(
                        "remainder========================================================",
                        remainder)
                    self.env['hotel.folio'].write({'total_advance': sum})
                    sale = self.env['sale.order'].search([
                        ('id', '=', folio_id.order_id.id)
                    ])
                    if sale:
                        rr = self.env['sale.order'].write(
                            {'remaining_amt': remainder})
                    sum = 0
                    remainder = 0
        else:
            for obj in self:
                if not obj.deposit_recv_acc:
                    raise Warning("Account is not set for Deposit account.")
                if not obj.journal_id.default_account_id:
                    raise Warning("Account is not set for selected journal.")
                name = ''
                seq_obj = self.env['ir.sequence']
                if obj.journal_id.secure_sequence_id:
                    print("nameeee", name)
                    name = seq_obj.get_id(obj.journal_id.secure_sequence_id.id)
                    print("nameeee", name)
                move_id = self.env['account.move'].create({
                    'journal_id':
                    obj.journal_id.id,
                    'name':
                    name or obj.id,
                    'ref':
                    obj.reservation_id.name,
                })
                move_line1 = {
                    'name': name or obj.id,
                    'move_id': move_id,
                    'account_id': obj.deposit_recv_acc.id,
                    'debit': 0.0,
                    'credit': obj.amt,
                    'ref': obj.reservation_id.name,
                    'journal_id': obj.journal_id.id,
                    'partner_id': obj.reservation_id.partner_id.id,
                    'date': obj.payment_date
                }
                print(
                    "move_line1====================================================",
                    move_line1)
                move_line2 = {
                    'name': name or obj.id,
                    'move_id': move_id,
                    'account_id': obj.journal_id.default_account_id.id,
                    'debit': obj.amt,
                    'credit': 0.0,
                    'ref': obj.reservation_id.name,
                    'journal_id': obj.journal_id.id,
                    'partner_id': obj.reservation_id.partner_id.id,
                    'date': obj.payment_date
                }

                move_id.write(
                    {'line_ids': [(0, 0, move_line1), (0, 0, move_line2)]})
                move_id.post()
                self._cr.execute(
                    'insert into reservation_account_move_rel(reservation_id,move_id) values (%s,%s)',
                    (obj.reservation_id.id, move_id.id))
                result = obj.reservation_id
                sum = result.total_advance + obj.amt
                remainder = result.total_cost1 - sum
                result.total_advance = sum
                #                 sale = self.env['sale.order'].search([('id', '=', folio_id.order_id.id)])
                #                 if sale:
                #                     rr = self.env['sale.order'].write({'remaining_amt': remainder})
                sum = 0
                remainder = 0
#             if  self.reservation_id.total_cost1 > 0:
#                 adv_payment = self.reservation_id.total_advance + self.amt
#                 remainder = self.reservation_id.total_cost1 - adv_payment
#                 self.reservation_id.write({'total_advance': adv_payment, 'remaining_amt':remainder})
        return {'type': 'ir.actions.act_window_close'}
Ejemplo n.º 8
0
    def request_stock(self):
        stock_obj = self.env['stock.picking']
        move_obj = self.env['stock.move']
        for rec in self:
            if not rec.location.id:
                raise Warning(
                    _('Select Source location under the picking details.'))

            if not rec.custom_picking_type_id.id:
                raise Warning(
                    _('Select Picking type under the picking details.'))

            if not rec.desti_loca_id:
                raise Warning(
                    _('Select Destination location under the picking details.')
                )
            vals = {
                'partner_id':
                rec.request_emp.address_home_id.id,
                'date':
                fields.Date.today(),
                'location_id':
                rec.location.id,
                'location_dest_id':
                rec.desti_loca_id and rec.desti_loca_id.id
                or rec.request_emp.desti_loca_id.id
                or rec.request_emp.department_id.desti_loca_id.id,
                'picking_type_id':
                rec.custom_picking_type_id.id,  # internal_obj.id,
                'note':
                rec.reason,
                'inter_requi_id':
                rec.id,
                'origin':
                rec.name,
            }
            stock_id = stock_obj.create(vals)
            for line in rec.requisition_line_ids:
                vals1 = {
                    'product_id':
                    line.product_id.id,
                    'product_uom_qty':
                    line.qty,
                    'product_uom':
                    line.uom.id,
                    'location_id':
                    rec.location.id,
                    'location_dest_id':
                    rec.desti_loca_id and rec.desti_loca_id.id
                    or rec.request_emp.desti_loca_id.id
                    or rec.request_emp.department_id.desti_loca_id.id,
                    'name':
                    line.product_id.name,
                    'picking_id':
                    stock_id.id,
                }
                move_obj.create(vals1)
            vals3 = {
                'delivery_picking_id': stock_id.id,
            }
            rec.write(vals3)
            rec.state = 'stock'
            self.delivery_picking_id.action_confirm()
Ejemplo n.º 9
0
 def _get_default_location(self):
     obj = self.env['bt.asset.location'].search([('default','=',True)])
     if not obj:
         raise Warning(_("Please create asset location first"))
     loc = obj[0]
     return loc 
Ejemplo n.º 10
0
 def fun_amount_total(self):
     if self.amount_total > self.maximum_amount_due - self.total_amount_due:
         raise Warning((
             "Sorry this customer has exceeded the specified limit, please check with the manager "
                       ))
Ejemplo n.º 11
0
    def analytic_resource_plan_copy_version_open_window(self):
        new_line_plan_ids = []
        analytic_obj = self.env['account.analytic.account']
        line_plan_obj = self.env['analytic.resource.plan.line']

        data = self[0]
        record_ids = self._context and self._context.get(
            'active_ids', False
        )
        active_model = self._context and self._context.get(
            'active_model', False
        )
        assert active_model == (
            'account.analytic.account',
            'Bad context propagation'
        )
        record = analytic_obj.browse(record_ids)
        include_child = (
            data.include_child if data and
            data.include_child else False
        )
        source_version = (
            data.source_version_id if data and
            data.source_version_id else False
        )
        dest_version = (
            data.dest_version_id if data and
            data.dest_version_id else False
        )
        if dest_version.default_plan:
            raise Warning(_('''It is prohibited to copy to the default
                planning version.'''))

        if source_version == dest_version:
            raise Warning(_('''Choose different source and destination
                planning versions.'''))
        if include_child:
            account_ids = record.get_child_accounts().keys()
        else:
            account_ids = record_ids

        line_plans = line_plan_obj.search(
            [
                ('account_id', 'in', account_ids),
                ('version_id', '=', source_version.id)
            ]
        )
        new_line_plan_rec = line_plan_obj
        for line_plan in line_plans:
            new_line_plan = line_plan.copy()
            new_line_plan_rec += new_line_plan
            new_line_plan_ids.append(new_line_plan.id)
        if new_line_plan_rec:
            new_line_plan_rec.write({'version_id': dest_version[0]})
        return {
            'domain': "[('id','in', [" + ','.join(
                map(str, new_line_plan_ids)
            ) + "])]",
            'name': _('Resource Plan Lines'),
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'analytic.resource.plan.line',
            'view_id': False,
            'context': False,
            'type': 'ir.actions.act_window'
        }
Ejemplo n.º 12
0
    def make_purchase(self, values):
        purchase_obj = self.env['purchase.order']
        if self.sequence_opt == "custom":
            pur_search = purchase_obj.search([
                ('name', '=', values.get('purchase_no')),
            ])
        else:
            pur_search = purchase_obj.search([
                ('purchase_name', '=', values.get('purchase_no')),
            ])

        if pur_search:
            if pur_search.partner_id.name == values.get('vendor'):
                if pur_search.currency_id.name == values.get('currency'):
                    self.make_purchase_line(values, pur_search)
                    return pur_search
                else:
                    raise Warning(
                        _('Currency is different for "%s" .\n Please define same.'
                          ) % values.get('currency'))
            else:
                raise Warning(
                    _('Customer name is different for "%s" .\n Please define same.'
                      ) % values.get('vendor'))
        else:
            if values.get('seq_opt') == 'system':
                name = self.env['ir.sequence'].next_by_code('purchase.order')
            elif values.get('seq_opt') == 'custom':
                name = values.get('purchase_no')
            partner_id = self.find_partner(values.get('vendor'))
            currency_id = self.find_currency(values.get('currency'))
            if values.get('date'):
                pur_date = self.make_purchase_date(values.get('date'))
            else:
                pur_date = datetime.today()

            if partner_id.property_account_receivable_id:
                account_id = partner_id.property_account_payable_id
            else:
                account_search = self.env['ir.property'].search([
                    ('name', '=', 'property_account_expense_categ_id')
                ])
                account_id = account_search.value_reference
                account_id = account_id.split(",")[1]
                account_id = self.env['account.account'].browse(account_id)
            pur_id = purchase_obj.create({
                'partner_id':
                partner_id.id,
                'currency_id':
                currency_id.id,
                'name':
                name,
                'date_order':
                pur_date,
                'custom_seq':
                True if values.get('seq_opt') == 'custom' else False,
                'system_seq':
                True if values.get('seq_opt') == 'system' else False,
                'purchase_name':
                values.get('purchase_no')
            })
        self.make_purchase_line(values, pur_id)
        return pur_id
Ejemplo n.º 13
0
    def make_purchase_line(self, values, pur_id):
        product_obj = self.env['product.product']
        account = False
        purchase_line_obj = self.env['purchase.order.line']
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        if self.import_prod_option == 'barcode':
            product_search = product_obj.search([('barcode', '=',
                                                  values['product'])])
        elif self.import_prod_option == 'code':
            product_search = product_obj.search([('default_code', '=',
                                                  values['product'])])
        else:
            product_search = product_obj.search([('name', '=',
                                                  values['product'])])

        product_uom = self.env['uom.uom'].search([('name', '=',
                                                   values.get('uom'))])
        if product_uom.id == False:
            raise Warning(
                _(' "%s" Product UOM category is not available.') %
                values.get('uom'))

        if product_search:
            product_id = product_search
        else:
            if self.import_prod_option == 'name':
                product_id = product_obj.create({
                    'name':
                    values.get('product'),
                    'lst_price':
                    float(values.get('price')),
                    'uom_id':
                    product_uom.id,
                    'uom_po_id':
                    product_uom.id
                })
            else:
                raise Warning(
                    _('%s product is not found" .\n If you want to create product then first select Import Product By Name option .'
                      ) % values.get('product'))

        if pur_id.state == 'draft':
            po_order_lines = purchase_line_obj.create({
                'order_id':
                pur_id.id,
                'product_id':
                product_id.id,
                'name':
                values.get('description'),
                'date_planned':
                current_time,
                'product_qty':
                values.get('quantity'),
                'product_uom':
                product_uom.id,
                'price_unit':
                values.get('price')
            })
        elif pur_id.state == 'sent':
            po_order_lines = purchase_line_obj.create({
                'order_id':
                pur_id.id,
                'product_id':
                product_id.id,
                'name':
                values.get('description'),
                'date_planned':
                current_time,
                'product_qty':
                values.get('quantity'),
                'product_uom':
                product_uom.id,
                'price_unit':
                values.get('price')
            })
        elif pur_id.state != 'sent' or pur_id.state != 'draft':
            raise Warning(
                _('We cannot import data in validated or confirmed order.'))

        tax_ids = []
        if values.get('tax'):
            if ';' in values.get('tax'):
                tax_names = values.get('tax').split(';')
                for name in tax_names:
                    tax = self.env['account.tax'].search([('name', '=', name),
                                                          ('type_tax_use', '=',
                                                           'purchase')])
                    if not tax:
                        raise Warning(_('"%s" Tax not in your system') % name)
                    tax_ids.append(tax.id)

            elif ',' in values.get('tax'):
                tax_names = values.get('tax').split(',')
                for name in tax_names:
                    tax = self.env['account.tax'].search([('name', '=', name),
                                                          ('type_tax_use', '=',
                                                           'purchase')])
                    if not tax:
                        raise Warning(_('"%s" Tax not in your system') % name)
                    tax_ids.append(tax.id)
            else:
                tax_names = values.get('tax').split(',')
                for name in tax_names:
                    tax = self.env['account.tax'].search([('name', '=', name),
                                                          ('type_tax_use', '=',
                                                           'purchase')])
                    if not tax:
                        raise Warning(_('"%s" Tax not in your system') % name)
                    tax_ids.append(tax.id)

        if tax_ids:
            po_order_lines.write({'taxes_id': ([(6, 0, tax_ids)])})

        return True
    def write(self, vals):
        """Prevent database storage of dynamic fields and instead write values
        to database persistent value_ids field"""

        # Get current database value_ids (current configuration)

        custom_ext_id = 'product_configurator.custom_attribute_value'
        custom_val = self.env.ref(custom_ext_id)

        attr_val_dict = {}
        custom_val_dict = {}

        for attr_line in self.product_tmpl_id.attribute_line_ids:
            attr_id = attr_line.attribute_id.id
            field_name = self.field_prefix + str(attr_id)
            custom_field_name = self.custom_field_prefix + str(attr_id)

            if field_name not in vals and custom_field_name not in vals:
                continue

            # Add attribute values from the client except custom attribute
            # If a custom value is being written, but field name is not in
            #   the write dictionary, then it must be a custom value!
            if vals.get(field_name, custom_val.id) != custom_val.id:
                if attr_line.multi and isinstance(vals[field_name], list):
                    if not vals[field_name]:
                        field_val = None
                    else:
                        field_val = vals[field_name][0][2]
                elif not attr_line.multi and isinstance(vals[field_name], int):
                    field_val = vals[field_name]
                else:
                    raise Warning(
                        _('An error occursed while parsing value for '
                          'attribute %s' % attr_line.attribute_id.name))
                attr_val_dict.update({attr_id: field_val})
                # Ensure there is no custom value stored if we have switched
                # from custom value to selected attribute value.
                if attr_line.custom:
                    custom_val_dict.update({attr_id: False})
            elif attr_line.custom:
                val = vals.get(custom_field_name, False)
                if attr_line.attribute_id.custom_type == 'binary':
                    # TODO: Add widget that enables multiple file uploads
                    val = [{
                        'name': 'custom',
                        'datas': vals[custom_field_name]
                    }]
                custom_val_dict.update({attr_id: val})
                # Ensure there is no standard value stored if we have switched
                # from selected value to custom value.
                attr_val_dict.update({attr_id: False})

            # Remove dynamic field from value list to prevent error
            if field_name in vals:
                del vals[field_name]
            if custom_field_name in vals:
                del vals[custom_field_name]

        self.config_session.update_config(attr_val_dict, custom_val_dict)
        res = super(ProductConfigurator, self).write(vals)
        return res
Ejemplo n.º 15
0
    def imoport_file(self):

        # -----------------------------
        if self.import_option == 'csv':

            keys = ['code', 'name', 'user_type_id']

            try:
                csv_data = base64.b64decode(self.File_slect)
                data_file = io.StringIO(csv_data.decode("utf-8"))
                data_file.seek(0)
                file_reader = []
                values = {}
                csv_reader = csv.reader(data_file, delimiter=',')
                file_reader.extend(csv_reader)

            except:

                raise Warning(_("Invalid file!"))

            for i in range(len(file_reader)):
                field = list(map(str, file_reader[i]))
                values = dict(zip(keys, field))
                if values:
                    if i == 0:
                        continue
                    else:
                        values.update({
                            'code': field[0],
                            'name': field[1],
                            'user': field[2],
                            'tax': field[3],
                            'tag': field[4],
                            # 'group': field[5],
                            'currency': field[5],
                            'reconcile': field[6],
                            'deprecat': field[7],
                        })
                        res = self.create_chart_accounts(values)

# ---------------------------------------
        elif self.import_option == 'xls':
            try:
                fp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
                fp.write(binascii.a2b_base64(self.File_slect))
                fp.seek(0)
                values = {}
                workbook = xlrd.open_workbook(fp.name)
                sheet = workbook.sheet_by_index(0)

            except:
                raise Warning(_("Invalid file!"))

            for row_no in range(sheet.nrows):
                val = {}
                if row_no <= 0:
                    fields = map(lambda row: row.value.encode('utf-8'),
                                 sheet.row(row_no))
                else:

                    line = list(
                        map(
                            lambda row: isinstance(row.value, bytes) and row.
                            value.encode('utf-8') or str(row.value),
                            sheet.row(row_no)))

                    values.update({
                        'code': line[0],
                        'name': line[1],
                        'user': line[2],
                        'tax': line[3],
                        'tag': line[4],
                        # 'group': line[5],
                        'currency': line[5],
                        'reconcile': line[6],
                        'deprecat': line[7],
                    })

                    res = self.create_chart_accounts(values)
# ------------------------------------------------------------
        else:
            raise Warning(_("Please select any one from xls or csv formate!"))

        return res
Ejemplo n.º 16
0
    def importar_productos(self):
        res = False
        if self.import_option == 'csv':
            keys = [
                'f_alta_ped', 'SAZON', 'Consec.', 'Code_B', 'Producto',
                'cant_Ped', 'unidad', 'Surtido', 'cant_surt', 'Tipo'
            ]
            try:
                csv_data = base64.b64decode(self.sale_order_file)
                data_file = io.StringIO(csv_data.decode("utf-8"))
                data_file.seek(0)
                file_reader = []
                csv_reader = csv.reader(data_file, delimiter=',')
                file_reader.extend(csv_reader)

            except Exception:
                raise Warning(_("Selecciona un archivo válido"))

            values = {}
            for i in range(len(file_reader)):
                field = list(map(str, file_reader[i]))
                values = dict(zip(keys, field))
                if values:
                    if i < 3:
                        continue
                    else:
                        if field[0] == "" or not field:
                            print("row_ no break", i)
                            return res
                        values.update({
                            'product': field[3].split('.')[0],
                            'name': field[4],
                            'quantity': field[5],
                            'uom': field[6],
                            'row': i
                        })
                        print(values)
                        res = self.create_order_line(values)
        else:
            try:
                fp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
                fp.write(binascii.a2b_base64(self.sale_order_file))
                fp.seek(0)
                values = {}
                workbook = xlrd.open_workbook(fp.name)
                sheet = workbook.sheet_by_name('PRODUCTOS SURTIDOS')
            except Exception:
                raise Warning(_("Selecciona un archivo válido"))

            for row_no in range(sheet.nrows):
                val = {}
                print("numero", sheet.nrows)
                if row_no <= 0:
                    fields = map(lambda row: row.value.encode('utf-8'),
                                 sheet.row(row_no))
                else:
                    row_no = row_no + 2
                    line = list(
                        map(
                            lambda row: isinstance(row.value, bytes) and row.
                            value.encode('utf-8') or str(row.value),
                            sheet.row(row_no)))
                    if line[0] == "":
                        print("row_ no break", row_no)
                        return res
                    values.update({
                        'product': line[3].split('.')[0],
                        'name': line[4],
                        'quantity': line[5],
                        'uom': line[6],
                        'row': row_no
                    })
                    res = self.create_order_line(values)
        return res
Ejemplo n.º 17
0
 def create(self, vals):
     if 'qty' in vals:
         print("---------------------------------", vals['qty'])
         if vals['qty'] <= 0.0:
             raise Warning('Product Quntity should not be 0 ')
     return super(product_product_line, self).create(vals)
Ejemplo n.º 18
0
 def _find_vendor(self,name):
     partner_search = self.env['res.partner'].search([('name','=',name)])
     if not partner_search:
         raise Warning (_("%s Vendor Not Found") % name)
     return partner_search.id
Ejemplo n.º 19
0
    def complete_payment(self):
        for p in self:
            if p.folio_fiscal:
                p.write({'estado_pago': 'pago_correcto'})
                return True

            values = p.to_json()
            if self.company_id.proveedor_timbrado == 'multifactura':
                url = '%s' % ('http://facturacion.itadmin.com.mx/api/payment')
            elif self.company_id.proveedor_timbrado == 'multifactura2':
                url = '%s' % ('http://facturacion2.itadmin.com.mx/api/payment')
            elif self.company_id.proveedor_timbrado == 'multifactura3':
                url = '%s' % ('http://facturacion3.itadmin.com.mx/api/payment')
            elif self.company_id.proveedor_timbrado == 'gecoerp':
                if self.company_id.modo_prueba:
                    #url = '%s' % ('https://ws.gecoerp.com/itadmin/pruebas/payment/?handler=OdooHandler33')
                    url = '%s' % (
                        'https://itadmin.gecoerp.com/payment2/?handler=OdooHandler33'
                    )
                else:
                    url = '%s' % (
                        'https://itadmin.gecoerp.com/payment2/?handler=OdooHandler33'
                    )
            try:
                response = requests.post(
                    url,
                    auth=None,
                    verify=False,
                    data=json.dumps(values),
                    headers={"Content-type": "application/json"})
            except Exception as e:
                error = str(e)
                if "Name or service not known" in error or "Failed to establish a new connection" in error:
                    raise Warning(
                        "Servidor fuera de servicio, favor de intentar mas tarde"
                    )
                else:
                    raise Warning(error)

            #print 'Response: ', response.status_code
            json_response = response.json()
            xml_file_link = False
            estado_pago = json_response['estado_pago']
            if estado_pago == 'problemas_pago':
                raise UserError(_(json_response['problemas_message']))
            # Receive and stroe XML
            if json_response.get('pago_xml'):
                xml_file_link = p.company_id.factura_dir + '/' + p.name.replace(
                    '/', '_') + '.xml'
                xml_file = open(xml_file_link, 'w')
                xml_payment = base64.b64decode(json_response['pago_xml'])
                xml_file.write(xml_payment.decode("utf-8"))
                xml_file.close()
                p._set_data_from_xml(xml_payment)

                xml_file_name = p.name.replace('/', '_') + '.xml'
                self.env['ir.attachment'].sudo().create({
                    'name':
                    xml_file_name,
                    'datas':
                    json_response['pago_xml'],
                    'datas_fname':
                    xml_file_name,
                    'res_model':
                    self._name,
                    'res_id':
                    p.id,
                    'type':
                    'binary'
                })
                report = self.env['ir.actions.report']._get_report_from_name(
                    'cdfi_invoice.report_payment')
                report_data = report.render_qweb_pdf([p.id])[0]
                pdf_file_name = p.name.replace('/', '_') + '.pdf'
                self.env['ir.attachment'].sudo().create({
                    'name':
                    pdf_file_name,
                    'datas':
                    base64.b64encode(report_data),
                    'datas_fname':
                    pdf_file_name,
                    'res_model':
                    self._name,
                    'res_id':
                    p.id,
                    'type':
                    'binary'
                })

            p.write({
                'estado_pago': estado_pago,
                'xml_payment_link': xml_file_link
            })
            p.message_post(body="CFDI emitido")
Ejemplo n.º 20
0
    def import_xls_file(self):
        self.ensure_one()
        if not self.import_file:
            raise Warning("Please select the file first.")
        p, ext = os.path.splitext(self.file_name)
        if ext[1:] not in ['xls', 'xlsx']:
            raise Warning(
                _("Unsupported file format \"{}\", import only supports XLS, XLSX"
                  ).format(self.file_name))

        ctx = self._context.copy()
        active_id = ctx.get('active_id')
        active_model = ctx.get('active_model')
        if not ctx.get('active_id') or not active_model:
            return

        # guess mimetype from file content
        options = {
            u'datetime_format': u'',
            u'date_format': u'',
            u'keep_matches': False,
            u'encoding': u'utf-8',
            u'fields': [],
            u'quoting': u'"',
            u'headers': True,
            u'separator': u',',
            u'float_thousand_separator': u',',
            u'float_decimal_separator': u'.',
            u'advanced': False
        }
        import_file = base64.b64decode(self.import_file)
        mimetype = guess_mimetype(import_file)
        (file_extension, handler,
         req) = FILE_TYPE_DICT.get(mimetype, (None, None, None))

        result = []
        if handler:
            result = getattr(self, '_read_' + file_extension)(options,
                                                              import_file)
        if not result and self.file_name:
            p, ext = os.path.splitext(self.file_name)
            if ext in EXTENSIONS:
                result = getattr(self, '_read_' + ext[1:])(options,
                                                           import_file)
        if not result and req:
            raise Warning(
                _("Unable to load \"{extension}\" file: requires Python module \"{modname}\""
                  ).format(extension=file_extension, modname=req))
        employee_obj = self.env['hr.employee']
        employee_not_found = []
        #payslip_obj = self.env['hr.payslip']
        #field_list = payslip_obj._fields.keys()
        #default_payslip_vals = payslip_obj.default_get(field_list)
        payslip_batch = self.env[active_model].browse(active_id)
        worked_days_lines_by_payslip = {}
        other_inputs = self._context.get('other_inputs')
        for row in result:
            emp_code = row[0]
            if not emp_code:
                continue
            employee = employee_obj.search([('no_empleado', '=', emp_code)],
                                           limit=1)
            if not employee:
                employee_not_found.append(emp_code)
                continue

            payslips = payslip_batch.slip_ids.filtered(
                lambda x: x.employee_id.id == employee.id)
            if not payslips:
                continue

            description = row[1]
            code = row[2]
            vals = {}
            if other_inputs:
                vals['amount'] = row[3]
            else:
                vals.update({
                    'number_of_days': row[3],
                    'number_of_hours': row[4]
                })

            for payslip in payslips:
                contract_id = payslip.contract_id and payslip.contract_id.id
                if not contract_id:
                    contract_ids = payslip.get_contract(
                        payslip.employee_id, payslip.date_from,
                        payslip.date_to)
                    contract_id = contract_ids and contract_ids[0] or False
                if not contract_id:
                    contract_id = self.contract_id.id

                if payslip not in worked_days_lines_by_payslip:
                    worked_days_lines_by_payslip[payslip] = []
                if other_inputs:
                    worked_lines = payslip.input_line_ids.filtered(
                        lambda x: x.code == code)
                else:
                    worked_lines = payslip.worked_days_line_ids.filtered(
                        lambda x: x.code == code)

                if worked_lines:
                    worked_days_lines_by_payslip[payslip] += [
                        (1, l.id, vals) for l in worked_lines
                    ]
                    #worked_lines.write({'number_of_days':no_of_days, 'number_of_hours' : no_of_hours})
                else:
                    if not contract_id:
                        raise Warning(
                            "Please select Contract. No valid contract found for employee %s."
                            % (payslip.employee_id.name))
                    vals.update({
                        'name': description,
                        'code': code,
                        'contract_id': contract_id
                    })
                    worked_days_lines_by_payslip[payslip].append((0, 0, vals))

        for payslip, worked_day_lines in worked_days_lines_by_payslip.items():
            if not worked_day_lines:
                continue
            if other_inputs:
                vls = {'input_line_ids': worked_day_lines}
            else:
                vls = {'worked_days_line_ids': worked_day_lines}
            payslip.write(vls)

        return True
Ejemplo n.º 21
0
    def action_check(self):
        #TODO IF you are changing this method then pls change
        # action_check_auto_allocate method
        for record in self:
            if not record.team:
                raise Warning(_('Please add the Service and team for the booking and then validate.'))
            start_date = fields.Datetime.from_string(record.start_date)
            end_date = fields.Datetime.from_string(record.end_date)

            # try:
            #    book_setting = self.env.ref('booking_service_V2.setting_data')
            # except Exception as e:
            #    raise ValidationError(_('Please define Pre and Post Booking Time in Settings.'))
            book_setting = self.env['booking.settings'].search([], order='id desc', limit=1)
            if not book_setting:
                raise ValidationError(_("Please define booking settings."))

            if not book_setting.pre_booking_time:
                raise ValidationError(_('Please define Pre Booking Time in Settings.'))

            if not book_setting.post_booking_time:
                raise ValidationError(_('Please define Post Booking Time in Settings.'))

            pre_book_time = int(book_setting.pre_booking_time)
            post_book_time = int(book_setting.post_booking_time)

            booking_start = (start_date - datetime.timedelta(minutes=post_book_time)).strftime('%Y-%m-%d %H:%M:%S')
            booking_end = (end_date + datetime.timedelta(minutes=pre_book_time)).strftime('%Y-%m-%d %H:%M:%S')

            # Prepare serial numbers
            #commented due to once team manage only one team
            # serial_numbers = record.equipment_ids.mapped(lambda r: r.lot_id)
            serial_numbers = self.env['stock.production.lot'].search([('product_id', '=', self.vehicle_new_id.id)], limit=1)
            # Prepare partners
            partners = self.get_partners(record)
            # Search conflict partners
            partner_names = []
            events = self.env['calendar.event'].search([
                ('partner_ids', 'in', partners.ids),
                ('start', '<=', booking_end), ('stop', '>=', booking_start),
                ('active', '=', True),
            ])
            for event in events:
                for partner in event.partner_ids:
                    if partner.id in partners.ids:
                        if partner.name not in partner_names:
                            partner_names.append(partner.name)

            # Search conflict equipments
            equipment_names = []
            events = self.env['calendar.event'].search([
                ('serial_numbers_ids', 'in', serial_numbers.ids),
                ('start', '<=', booking_end), ('stop', '>=', booking_start),
                ('active', '=', True),
            ])
            for event in events:
                for equipment in event.serial_numbers_ids:
                    if equipment.id in serial_numbers.ids:
                        if equipment.name not in equipment_names:
                            equipment_names.append(equipment.name)

            # Show validation message
            if len(partner_names) > 0 or len(equipment_names) > 0:
                validation_message = ''
                if len(partner_names) > 0:
                    validation_message += 'Employee: %s ' %(', '.join(partner_names), )
                    if len(equipment_names) > 0:
                        validation_message += 'and/or '

                if len(equipment_names) > 0:
                    validation_message += 'Serial Number: %s ' %(', '.join(equipment_names),)
                raise ValidationError(validation_message + ' has an event on that day and time')
            else:
                raise ValidationError('Everyone is available for the booking')
Ejemplo n.º 22
0
    def generate_bank_statement(self):
        """
        Use : Using this method user can able to create bank statement.
        Added by : Deval Jagad
        Added on : 05/06/2020
        Task ID : 164126
        :return: True
        """
        bank_statement_obj = self.env['account.bank.statement']
        partner_obj = self.env['res.partner']
        bank_statement_line_obj = self.env['account.bank.statement.line']
        payout_logline_obj = self.env['shopify.payout.logline.ept']
        account_invoice_obj = self.env['account.move']
        journal = self.instance_id.shopify_settlement_report_journal_id
        if not journal:
            message_body = "You have not configured Payout report Journal in " \
                           "Instance.\nPlease configured it from Setting"
            if self._context.get('is_cron'):
                self.message_post(body=_(message_body))
                self.is_skip_from_cron = True
                return False
            else:
                raise Warning(_(message_body))

        currency_id = journal.currency_id.id or self.instance_id.shopify_company_id.currency_id.id or False
        if currency_id != self.currency_id.id:
            message_body = "Report currency and Currency in Instance Journal are different.\nMake sure Report currency and Instance Journal currency must be same."
            self.message_post(body=_(message_body))

        bank_statement_exist = bank_statement_obj.search([('shopify_payout_ref', '=', self.payout_reference_id)], limit=1)

        if bank_statement_exist:
            self.write({'statement_id': bank_statement_exist.id})
            self.is_skip_from_cron = False
            return True

        name = '{0}_{1}'.format(self.instance_id.name, self.payout_reference_id)
        vals = {
            'shopify_payout_ref': self.payout_reference_id,
            'journal_id': journal.id,
            'name': name,
            'accounting_date': self.payout_date,
	        'date' : self.payout_date,
        }
        bank_statement_id = bank_statement_obj.create(vals)
        for transaction in self.payout_transaction_ids:
            order_id = transaction.order_id
            if transaction.transaction_type in ['charge', 'refund'] and not order_id:
                message = "Transaction line is skip due to order {0} is not found in odoo.".format(
                    transaction.source_order_id)
                payout_logline_obj.create({'message': message,
                                           'instance_id': self.instance_id.id,
                                           'payout_transaction_ref': transaction.transaction_id,
                                           'payout_id': self.id})
                transaction.is_remaining_statement = True
                continue
            partner = partner_obj._find_accounting_partner(order_id.partner_id)
            invoice_ids = account_invoice_obj
            account_id = False
            if transaction.transaction_type == 'charge':
                invoice_ids = order_id.invoice_ids.filtered(lambda l: l.state == 'posted' and l.type == 'out_invoice' and l.amount_total == transaction.amount)
                if not invoice_ids:
                    message = "Invoice is not created for order %s in odoo" % (order_id.name or transaction.source_order_id)
                    payout_logline_obj.create({'message': message,
                                               'is_skipped': True,
                                               'instance_id': self.instance_id.id,
                                               'payout_transaction_ref': transaction.transaction_id,
                                               'payout_id': self.id})
                    transaction.is_remaining_statement = True
                    continue
            if transaction.transaction_type == 'refund':
                invoice_ids = order_id.invoice_ids.filtered(lambda l: l.state == 'posted' and l.type == 'out_refund' and l.amount_total == -(transaction.amount))
                if not invoice_ids:
                    message = "In shopify payout there is refund, but Refund is not created for order %s in odoo" % (order_id.name or transaction.source_order_id)
                    payout_logline_obj.create({'message': message,
                                               'is_skipped': True,
                                               'instance_id': self.instance_id.id,
                                               'payout_transaction_ref': transaction.transaction_id,
                                               'payout_id': self.id})
                    transaction.is_remaining_statement = True
                    continue

            payment_reference = False
            if transaction.transaction_type not in ['charge', 'refund']:
                shopify_account_config_id = self.instance_id.transaction_line_ids.filtered(lambda l:
                                                                                           l.transaction_type ==
                                                                                           transaction.transaction_type)
                account_id = shopify_account_config_id and shopify_account_config_id.account_id
            if transaction.transaction_type == 'charge':
                payment_reference = self.env['account.payment'].search([('invoice_ids', 'in',invoice_ids.ids),
                                                                        ('amount', '=', transaction.amount),
                                                                        ('payment_type', '=','inbound')], limit=1)
            if transaction.transaction_type == 'refund':
                payment_reference = self.env['account.payment'].search([('invoice_ids', 'in',invoice_ids.ids),
                                                                        ('amount', '=',-(transaction.amount)),
                                                                        ('payment_type', '=','outbound')], limit=1)
            if payment_reference:
                reference = payment_reference.name
                payment_aml_rec = payment_reference.mapped('move_line_ids').filtered(lambda line: line.account_internal_type == "liquidity")
                if self.check_reconciled_transactions(transaction, payment_aml_rec):
                    continue
            else:
                reference = invoice_ids.name or ''

            if transaction.amount:
                bank_line_vals = {
                    'name': order_id.name or transaction.transaction_type,
                    'ref': reference or '',
                    'date': self.payout_date,
                    'partner_id': partner and partner.id,
                    'amount': transaction.amount,
                    'statement_id': bank_statement_id.id,
                    'shopify_order_ids': [(6, 0, order_id.ids)],
                    'shopify_transaction_id': transaction.transaction_id,
                    'shopify_transaction_type': transaction.transaction_type,
                }
                if account_id:
                    bank_line_vals.update({'account_ept_id': account_id.id})
                bank_statement_line_obj.create(bank_line_vals)

        if self.check_process_statement():
            state = 'generated'
        else:
            state = 'partially_generated'

        if bank_statement_id:
            self.write({'statement_id': bank_statement_id.id, 'state': state})
        if self.reconciliation_log_ids:
            self.env['shopify.payout.logline.ept'].create_payout_schedule_activity(self.reconciliation_log_ids)
        self.is_skip_from_cron = False
        return True
Ejemplo n.º 23
0
 def check_expr_date(self):
     for each in self:
         exp_date = each.expiry_date
         if exp_date < date.today():
             raise Warning('Your Document Is Already Expired.')
Ejemplo n.º 24
0
    def get_payout_report(self, start_date, end_date, instance):
        """
        Use : Using this method get Payout records as per date given.
        Added by : Deval Jagad (02/06/2020)
        Task ID : 164126
        :param start_date:From Date(year-month-day)
        :param end_date: To Date(year-month-day)
        :param instance: Browsable shopify instance.
        :return: True
        """
        shopify_payout_report_line_obj = self.env['shopify.payout.report.line.ept']
        log_book_obj = self.env['common.log.book.ept']
        log_line_obj = self.env['common.log.lines.ept']
        log_book_id = False
        if not instance.shopify_api_url:
            raise Warning(_("Shopify API URL is blank!"))

        shop = instance.shopify_host.split("//")
        headers = {"Accept": "application/json",
                   "Content-Type": "application/json; charset=utf-8"}
        params = {"status": 'paid', "date_min": start_date, "date_max": end_date, "limit": 250}
        try:
            shopify_api_url = instance.shopify_api_url + 'payouts.json'
            payout_ids = []
            if len(shop) == 2:
                url = "{0}//{1}:{2}@{3}/{4}".format(shop[0], instance.shopify_api_key, instance.shopify_password,shop[1], shopify_api_url)
            else:
                url = "https://{0}:{1}@{2}/{3}".format(instance.shopify_api_key, instance.shopify_password,shop[0],shopify_api_url)
            response = requests.get(url, params=params, headers=headers)
            payout_response = response.json()
            payout_ids = payout_ids + payout_response.get('payouts', [])
        except Exception as error:
            message = "Something is wrong while import the payout records : {0}".format(error)
            if not log_book_id:
                model = "shopify.payout.report.ept"
                model_id = self.env["common.log.lines.ept"].get_model_id(model)
                log_book_id = log_book_obj.create({'type': 'import',
                                                   'module': 'shopify_ept',
                                                   'shopify_instance_id': instance.id,
                                                   'model_id':model_id and model_id.id,
                                                   'create_date':datetime.now(),
                                                   'active': True})
            log_line_obj.create({'log_line_id':log_book_id,
                                 'message':message,
                                 'model_id':model_id and model_id.id or False,
                                 })
            return False

        for payout in payout_ids:
            _logger.info("Payout ID %s ", payout.get('id'))
            payout_id = self.search([('instance_id', '=', instance.id),
                                     ('payout_reference_id', '=', payout.get('id'))])
            if payout_id:
                continue
            payout_vals = self.prepare_payout_vals(payout, instance)
            payout_id = self.create(payout_vals)

            if not payout_id:
                continue
            # Get Payout Transaction data and Create record.
            transaction_ids = self.get_payout_transactions_data(payout_id, instance)
            for transaction in transaction_ids:
                _logger.info("Transaction ID %s ", transaction.get('id'))
                transaction_vals = self.prepare_transaction_vals(transaction, payout_id,
                                                                 instance)
                shopify_payout_report_line_obj.create(transaction_vals)
            # Create fees line
            fees_amount = float(payout.get('summary').get('charges_fee_amount', 0.0)) + float(
                    payout.get('summary').get('refunds_fee_amount', 0.0)) + float(
                    payout.get('summary').get('adjustments_fee_amount', 0.0))
            shopify_payout_report_line_obj.create({
                'payout_id': payout_id.id or False,
                'transaction_id': '',
                'source_order_id': '',
                'transaction_type': 'fees',
                'order_id': '',
                'amount': -fees_amount,
                'fee': 0.0,
                'net_amount': fees_amount,
            })
        instance.write({'payout_last_import_date': datetime.now()})
        return True
Ejemplo n.º 25
0
 def _check_config_step(self):
     cfg_step_lines = self.product_tmpl_id.config_step_line_ids
     cfg_steps = cfg_step_lines.filtered(
         lambda l: l != self).mapped('config_step_id')
     if self.config_step_id in cfg_steps:
         raise Warning(_('Cannot have a configuration step defined twice.'))
Ejemplo n.º 26
0
    def _prepare_invoice(self):
        """
        Prepare the dict of values to create the new invoice . This method may be
        overridden to implement custom invoice generation (making sure to call super() to establish
        a clean extension chain).
        """
        self.ensure_one()

        #find Applicant as a invoice related
        partner = self.commission_user_id
        #applicant = self.applicant_ids.search([('applicant_based_on_invoice','=',True)],limit=1)
        #         if not partner.property_product_pricelist:
        #             raise Warning(_('Please set pricelist.'))
        #
        #         domain = [
        #             ('type', '=', 'purchase'),
        #             ('company_id', '=', self.company_id.id),]
        #         journal_id = self.env['account.journal'].search(domain, limit=1)
        #         if not journal_id:
        #             raise UserError(_('Please configure an accounting sale journal for this company.'))

        if not partner.property_product_pricelist:
            raise Warning(
                _('Please set Pricelist on Vendor Form For: %s!' %
                  (partner.name)))

        if not partner.property_account_payable_id:  # fix for take purchase pricelist
            raise Warning(
                _('Please set Payable Account on Vendor Form For: %s!' %
                  (partner.name)))

        ctx = self._context.copy()
        ctx.update({'type': 'in_invoice', 'company_id': self.company_id.id})
        #        journal_id = self.env['account.invoice'].with_context(
        #            ctx
        #        )._default_journal()
        journal_id = self.env['account.move'].with_context(
            ctx)._get_default_journal()
        if not journal_id:
            raise Warning(
                _('Please configure purchase journal for company: %s' %
                  (self.company_id.name)))

        partner_payment_term = False
        if partner.property_supplier_payment_term_id:
            partner_payment_term = partner.property_supplier_payment_term_id.id

        invoice_vals = {
            'ref': self.name or '',
            #            'origin': self.name,
            'invoice_origin': self.name,
            'type': 'in_invoice',
            #            'account_id': partner.property_account_payable_id.id,
            'partner_id': partner.id,
            'journal_id': journal_id.id,
            'currency_id': partner.property_product_pricelist.currency_id.id,
            #            'comment': partner.name,
            'narration': partner.name,
            #            'payment_term_id': partner_payment_term,#partner.property_payment_term_id.id,
            'invoice_payment_term_id': partner_payment_term,
            'fiscal_position_id': partner.property_account_position_id.id,
            'company_id': self.company_id.id,
            'user_id': self.env.user.id,
            'sale_commission_id': self.id,
        }
        return invoice_vals
Ejemplo n.º 27
0
    def action_invoice_create(self):
        for each in self:
            rent_date = self.rent_start_date
            if each.cost_frequency != 'no' and rent_date < date.today():
                rental_days = (date.today() - rent_date).days
                if each.cost_frequency == 'weekly':
                    rental_days = int(rental_days / 7)
                if each.cost_frequency == 'monthly':
                    rental_days = int(rental_days / 30)
                for each1 in range(0, rental_days + 1):
                    if rent_date > datetime.strptime(each.rent_end_date,
                                                     "%Y-%m-%d").date():
                        break
                    each.fleet_scheduler1(rent_date)
                    if each.cost_frequency == 'daily':
                        rent_date = rent_date + timedelta(days=1)
                    if each.cost_frequency == 'weekly':
                        rent_date = rent_date + timedelta(days=7)
                    if each.cost_frequency == 'monthly':
                        rent_date = rent_date + timedelta(days=30)

        if self.first_payment != 0:
            self.first_invoice_created = True
            inv_obj = self.env['account.move']
            inv_line_obj = self.env['account.move.line']
            supplier = self.customer_id
            inv_data = {
                # 'name': supplier.name,
                'ref': supplier.name,
                'move_type': 'out_invoice',
                # 'account_id': supplier.property_account_payable_id.id,
                'partner_id': supplier.id,
                'currency_id': self.account_type.company_id.currency_id.id,
                'journal_id': self.journal_type.id,
                'invoice_origin': self.name,
                'company_id': self.account_type.company_id.id,
                'invoice_date_due': self.rent_end_date,
            }
            inv_id = inv_obj.create(inv_data)
            print(inv_id, 'hi')
            self.first_payment_inv = inv_id.id
            product_id = self.env['product.product'].search([
                ("name", "=", "Fleet Rental Service")
            ])
            if product_id.property_account_income_id.id:
                income_account = product_id.property_account_income_id.id
            elif product_id.categ_id.property_account_income_categ_id.id:
                income_account = product_id.categ_id.property_account_income_categ_id.id
            else:
                raise UserError(
                    _('Please define income account for this product: "%s" (id:%d).'
                      ) % (product_id.name, product_id.id))

            if inv_id:
                list_value = [(0, 0, {
                    'name': self.vehicle_id.name,
                    'price_unit': self.first_payment,
                    'quantity': 1.0,
                    'account_id': income_account,
                    'product_id': product_id.id,
                    'move_id': inv_id.id,
                })]
                inv_id.write({'invoice_line_ids': list_value})
            mail_content = _(
                '<h3>First Payment Received!</h3><br/>Hi %s, <br/> This is to notify that your first payment has '
                'been received. <br/><br/>'
                'Please find the details below:<br/><br/>'
                '<table><tr><td>Invoice Number<td/><td> %s<td/><tr/>'
                '<tr><td>Date<td/><td> %s <td/><tr/><tr><td>Amount <td/><td> %s<td/><tr/><table/>'
            ) % (self.customer_id.name, inv_id.payment_reference,
                 inv_id.invoice_date, inv_id.amount_total)
            main_content = {
                'subject':
                _('Payment Received: %s') % inv_id.payment_reference,
                'author_id': self.env.user.partner_id.id,
                'body_html': mail_content,
                'email_to': self.customer_id.email,
            }
            self.env['mail.mail'].create(main_content).send()
            imd = self.env['ir.model.data']
            action = imd.xmlid_to_object(
                'account.action_move_out_invoice_type')
            result = {
                'name': action.name,
                'type': 'ir.actions.act_window',
                'views': [[False, 'form']],
                'target': 'current',
                'res_id': inv_id.id,
                'res_model': 'account.move',
            }
            return result

        else:
            raise Warning("Please enter advance amount to make first payment")
Ejemplo n.º 28
0
    def create_chart_accounts(self, values):

        if values.get("code") == "":
            raise Warning(_('Code field cannot be empty.'))

        if values.get("name") == "":
            raise Warning(_('Name field cannot be empty.'))

        if values.get("user") == "":
            raise Warning(_('Type field cannot be empty.'))

        if values.get("code"):
            s = str(values.get("code"))
            code_no = s.rstrip('0').rstrip('.') if '.' in s else s

        account_obj = self.env['account.account']
        account_search = account_obj.search([('code', '=', values.get('code'))
                                             ])

        is_reconcile = False
        is_deprecated = False

        if values.get("reconcile") == 'TRUE' or values.get("reconcile") == "1":
            is_reconcile = True

        if values.get("deprecat") == 'TRUE' or values.get("deprecat") == "1":
            is_deprecated = True

        user_id = self.find_user_type(values.get('user'))
        currency_get = self.find_currency(values.get('currency'))

        # --------tax-
        tax_ids = []
        if values.get('tax'):
            if ';' in values.get('tax'):
                tax_names = values.get('tax').split(';')
                for name in tax_names:
                    tax = self.env['account.tax'].search([('name', '=', name)])
                    if not tax:
                        raise Warning(_('%s Tax not in your system') % name)
                    for t in tax:
                        tax_ids.append(t)

            elif ',' in values.get('tax'):
                tax_names = values.get('tax').split(',')
                for name in tax_names:
                    tax = self.env['account.tax'].search([('name', '=', name)])
                    if not tax:
                        raise Warning(_('%s Tax not in your system') % name)
                    for t in tax:
                        tax_ids.append(t)
            else:
                tax_names = values.get('tax').split(',')
                tax = self.env['account.tax'].search([('name', '=', tax_names)
                                                      ])
                if not tax:
                    raise Warning(_('"%s" Tax not in your system') % tax_names)
                tax_ids.append(tax)

# ------------tags
        tag_ids = []
        if values.get('tag'):
            if ';' in values.get('tag'):
                tag_names = values.get('tag').split(';')
                for name in tag_names:
                    tag = self.env['account.account.tag'].search([('name', '=',
                                                                   name)])
                    if not tag:
                        raise Warning(_('"%s" Tag not in your system') % name)
                    tag_ids.append(tag)

            elif ',' in values.get('tag'):
                tag_names = values.get('tag').split(',')
                for name in tag_names:
                    tag = self.env['account.account.tag'].search([('name', '=',
                                                                   name)])
                    if not tag:
                        raise Warning(_('"%s" Tag not in your system') % name)
                    tag_ids.append(tag)
            else:
                tag_names = values.get('tag').split(',')
                tag = self.env['account.account.tag'].search([('name', '=',
                                                               tag_names)])
                if not tag:
                    raise Warning(_('"%s" Tag not in your system') % tag_names)
                tag_ids.append(tag)

        abc = {
            'code': code_no,
            'name': values.get('name'),
            'user_type_id': user_id.id,
            'tax_ids':
            [(6, 0, [y.id for y in tax_ids])] if values.get('tax') else False,
            'tag_ids':
            [(6, 0, [x.id for x in tag_ids])] if values.get('tag') else False,
            'currency_id': currency_get or False,
            'reconcile': is_reconcile,
            'deprecated': is_deprecated,
        }
        chart_id = account_obj.create(abc)

        return chart_id
Ejemplo n.º 29
0
    def get_result(self):
        data = self.read()[0]

        start_date = data.get('date_start', False)
        end_date = data.get('date_end', False)
        if start_date and end_date and end_date < start_date:
            raise Warning(_("End date should be greater than start date!"))
        res_user = self.env["res.users"].browse(self._uid)
        export = data.get('export_report', False)

        # Create Inventory Export report in Excel file.
        workbook = xlwt.Workbook()
        worksheet = workbook.add_sheet('Sheet 1')
        font = xlwt.Font()
        font.bold = True
        header = xlwt.easyxf('font: bold 1, height 280')
        # start_date = datetime.strptime(str(context.get("date_from")), DEFAULT_SERVER_DATE_FORMAT)
        # start_date_formate = start_date.strftime('%d/%m/%Y')
        # end_date = datetime.strptime(str(context.get("date_to")), DEFAULT_SERVER_DATE_FORMAT)
        # end_date_formate = end_date.strftime('%d/%m/%Y')
        # start_date_to_end_date = tools.ustr(start_date_formate) + ' To ' + tools.ustr(end_date_formate)

        style = xlwt.easyxf('align: wrap yes')
        worksheet.row(0).height = 500
        worksheet.row(1).height = 500
        for x in range(0, 41):
            worksheet.col(x).width = 6000
        borders = xlwt.Borders()
        borders.top = xlwt.Borders.MEDIUM
        borders.bottom = xlwt.Borders.MEDIUM
        border_style = xlwt.XFStyle()  # Create Style
        border_style.borders = borders
        border_style1 = xlwt.easyxf('font: bold 1')
        border_style1.borders = borders
        style = xlwt.easyxf('align: wrap yes', style)

        ids_location = []
        ids_categ = []
        ids_product = []
        where_end_date_awal = " sm.date is null "
        where_start_date = " 1=1 "
        if start_date:
            where_start_date = " sm.date + interval '7 hour' >= '%s 00:00:00' " % start_date
            where_end_date_awal = " sm.date + interval '7 hour' < '%s 00:00:00' " % start_date
        where_end_date = " 1=1 "
        if end_date:
            where_end_date = " sm.date + interval '7 hour' <= '%s 23:59:59'" % end_date
        where_location = " 1=1 "
        if ids_location:
            where_location = """(sm.location_id in %s 
            or sm.location_dest_id in %s)""" % (str(
                tuple(ids_location)).replace(
                    ',)', ')'), str(tuple(ids_location)).replace(',)', ')'))
        where_categ = " 1=1 "
        if ids_categ:
            where_categ = "pt.categ_id in %s" % str(tuple(ids_categ)).replace(
                ',)', ')')
        where_product = " 1=1 "
        if ids_product:
            where_product = "pp.id in %s" % str(tuple(ids_product)).replace(
                ',)', ')')

        where_export = "AND sp.jenis_dokumen NOT IN ('', 'Non BC')"
        if export == "AND sp.jenis_dokumen = 'BC 2.5'":
            where_export = "BC 2.5"
        elif export == "AND sp.jenis_dokumen = 'BC 2.6.1'":
            where_export = "BC 2.6.1"
        elif export == "BC 2.7":
            where_export = "AND sp.jenis_dokumen = 'BC 2.7'"
        elif export == "BC 3.0":
            where_export = "AND sp.jenis_dokumen = 'BC 3.0'"
        elif export == "BC 3.3":
            where_export = "AND sp.jenis_dokumen = 'BC 3.3'"
        elif export == "BC 4.1":
            where_export = "AND sp.jenis_dokumen = 'BC 4.1'"

        query = """
                SELECT 
                    sp.jenis_dokumen, sp.no_dokumen AS no_dokumen_pabean, sp.tanggal_dokumen AS tanggal_dokumen_pabean, sp.name AS no_dokumen, 
                    sp.date_done AS tanggal_dokumen, rp.name AS nama_mitra, pp.default_code AS kode_barang, pt.name AS nama_barang, uu.name, 
                    SUM(sm.product_uom_qty) AS product_uom_qty, SUM(sm.subtotal_price) AS nilai_barang, spt.code AS status_type, rc.symbol,
                    sp.no_aju 
                FROM stock_move sm 
                INNER JOIN stock_picking sp ON sm.picking_id=sp.id 
                LEFT JOIN res_partner rp ON sp.partner_id=rp.id
                LEFT JOIN product_product pp ON pp.id=sm.product_id
                LEFT JOIN uom_uom uu ON uu.id=sm.product_uom
                LEFT JOIN product_template pt ON pt.id=pp.product_tmpl_id
                LEFT JOIN stock_picking_type spt ON spt.id=sm.picking_type_id
                LEFT JOIN sale_order_line sol ON sol.id=sm.sale_line_id
                LEFT JOIN res_currency rc ON rc.id = sp.currency_id
                WHERE sm.state = 'done' 
                AND (sm.location_id = '29' AND sm.location_dest_id != '29')
                AND """ + where_start_date + """ 
                AND """ + where_end_date + """                  
                """ + where_export + """
                GROUP BY sp.jenis_dokumen, sp.no_dokumen AS no_dokumen_pabean, sp.tanggal_dokumen AS tanggal_dokumen_pabean, sp.name AS no_dokumen, 
                    sp.date_done AS tanggal_dokumen, rp.name AS nama_mitra, pp.default_code AS kode_barang, pt.name AS nama_barang, uu.name, 
                    spt.code AS status_type, rc.symbol, sp.no_aju
                ORDER BY sp.tanggal_dokumen ASC, sp.no_dokumen ASC 
            """
        list_data = []
        company = self.env.user.company_id.name
        start_date_format = start_date.strftime('%d/%m/%Y')
        end_date_format = end_date.strftime('%d/%m/%Y')

        self._cr.execute(query)
        vals = self._cr.fetchall()

        no = 1
        for val in vals:
            list_data.append({
                'jenis_dokumen': val[0],
                'nomor_pabean': val[1],
                'tanggal_pabean': val[2],
                'nomor_penerimaan_barang': val[3],
                'tanggal_penerimaan_barang': val[4],
                'pemasok_pengirim': val[5],
                'kode_barang': val[6],
                'nama_barang': val[7],
                'satuan': val[8],
                'jumlah': val[9],
                'nilai_barang': val[10],
                'currency': val[12],
                'no_aju': val[13]
            })
            no += 1
        hasil = list_data
        return hasil
Ejemplo n.º 30
0
    def shipa_delivery_send_shipping(self, pickings):
        for picking in pickings:
            if self.prod_environment:
                url = self.shipa_prod_url + "?apikey=" + self.shipa_api_key

            else:
                url = self.shipa_test_url + "?apikey=" + self.shipa_api_key

            shipper_address = picking.company_id
            recipient_address = picking.partner_id

            request_body = []
            cod_amount = 0.0

            shipa_payment_method = self.shipa_payment_method
            # if (pickings.sale_id.payment_gateway_id and pickings.sale_id.payment_gateway_id.code in ["cod", "COD"]) or (
            #         pickings.sale_id.eg_magento_payment_method_id and pickings.sale_id.eg_magento_payment_method_id.code in [
            #     "cod", "COD"]):
            if (pickings.sale_id.eg_magento_payment_method_id
                    and pickings.sale_id.eg_magento_payment_method_id.code
                    in ["cod", "COD"]):
                if not pickings.invoice_id.residual and self.env.user.has_group(
                        'eg_send_to_shipper.send_to_shipper_restriction'):
                    raise ValidationError(
                        "Shipment Can not be created with 0 COD amount!!!")
                shipa_payment_method = "CashOnDelivery"
                cod_amount = pickings.invoice_id.residual

            final_city = ""
            for t in recipient_address.city.split():
                result = regex.sub(u'[^\p{Latin}]', u'', t)
                if final_city:
                    final_city = final_city + " " + result
                else:
                    final_city = result
            final_city = final_city.strip()
            if not final_city:
                raise ValidationError(
                    "Recipient City is missing or No english Character")

            mobile_number = recipient_address.mobile or recipient_address.phone
            if not mobile_number:
                if pickings.partner_id.parent_id:
                    mobile_number = pickings.partner_id.parent_id.mobile or pickings.partner_id.parent_id.phone
                else:
                    raise ValidationError(
                        'There is no Mobile or Phone number in shipping address!'
                    )
            if mobile_number:
                # mobile_number.replace("+","") #Sahil Navadiya remove this & added below line
                mobile_number = mobile_number.split(
                    '+',
                    1)[-1]  # remove all characters before '+' including '+'

            else:
                raise ValidationError(
                    'There is no Mobile or Phone number in shipping address!')

            address_one = recipient_address.street or ""
            address_two = recipient_address.street2 or ""
            address_three = recipient_address.city or ""
            address_four = recipient_address.zip or ""

            body = {
                "id": "{}-{}".format(picking.name, str(uuid.uuid4())),
                "amount": cod_amount,
                "paymentMethod": "%s" % shipa_payment_method,
                "description": picking.origin,
                "typeDelivery": "%s" % self.shipa_type_delivery,
                "sender": {
                    "email": shipper_address.email,
                    "phone": shipper_address.phone,
                    "address": shipper_address.street,
                    "name": shipper_address.name
                },
                "recipient": {
                    "name":
                    recipient_address.name,
                    "phone":
                    mobile_number.replace(" ", ""),
                    "address":
                    ','.join(
                        filter(VALID_STRING, [
                            address_one, address_two, address_three,
                            address_four
                        ])),
                    "city":
                    final_city
                }
                # "goodsValue": cod_amount
            }
            request_body.append(body)

            payload = json.dumps(request_body)
            headers = {
                "Accept": "application/json",
                'Content-Type': "application/json"
            }
            try:
                _logger.info(
                    "Shipa Delivery Request Data : {}".format(payload))
                response_body = requests.request("POST",
                                                 url,
                                                 data=payload,
                                                 headers=headers)
                if response_body.status_code == 200:
                    results = response_body.json()
                    _logger.info(
                        "Shipa Delivery Rate Response Data : {}".format(
                            results))
                    final_tracking_no = []
                    for result in results:
                        tracking_no = result.get("deliveryInfo").get(
                            "reference")
                        final_tracking_no.append(tracking_no)
                    self.get_shipa_label(final_tracking_no, picking)
                    return [{
                        'exact_price': 0.0,
                        'tracking_number': ','.join(final_tracking_no)
                    }]
                else:
                    raise Warning("%s" % response_body.text)
            except Exception as e:
                raise Warning(e)