def setup_pending_done(self, contract, term_vals): """Start employee deactivation process.""" term_obj = self.env['hr.employee.termination'] dToday = datetime.now().date() # If employee is already inactive simply end the contract wkf = netsvc.LocalService('workflow') if not contract.employee_id.active: # wkf.trg_validate(uid, 'hr.contract', contract.id, 'signal_done', cr) contract.write({'state': 'done'}) return # Ensure there are not other open contracts open_contract = False ee = self.env['hr.employee'].browse(contract.employee_id.id) for c2 in ee.contract_ids: if c2.id == contract.id or c2.state == 'draft': continue if (not c2.date_end or datetime.strptime( c2.date_end, DEFAULT_SERVER_DATE_FORMAT).date() >= dToday ) and c2.state != 'done': open_contract = True # Don't create an employment termination if the employee has an open contract or # if this contract is already in the 'done' state. if open_contract or contract.state == 'done': return # Also skip creating an employment termination if there is already one in # progress for this employee. # term_ids = term_obj.search([('employee_id', '=', contract.employee_id.id), ('state', 'in', ['draft', 'confirm'])]) if len(term_ids) > 0: return term_obj.create(term_vals) # Set the contract state to pending completion wkf = netsvc.LocalService('workflow') # wkf.trg_validate(uid, 'hr.contract', contract.id, 'signal_pending_done', cr) contract.signal_workflow('signal_pending_done') # Set employee state to pending deactivation # wkf.trg_validate(id, 'hr.employee', contract.employee_id.id, 'signal_pending_inactive', cr) contract.employee_id.signal_workflow('signal_pending_inactive')
def overtime_cancel(self): for record in self.browse(): wf_service = netsvc.LocalService("workflow") for id in []: wf_service.trg_validate('hr.overtime', id, 'cancel') return True
def CreateInboundShipmentPlan(self): ''' This function is used to Create Inbound shipmentplan parameters: No Parameters ''' results = self.CreateInboundShipmentPlan_Api() po_ids_list = [] for each_results in results: for each_response in each_results: if len(results) == 1: dest_address_id = self.create_dest_address() update_vals = { 'plan_shipment_id': each_response['ShipmentId'], 'fulfillment_centre_id': each_response['CenterId'], 'dest_address_id': dest_address_id, } self.write(update_vals) po_ids_list.append(ids[0]) else: id = self.po_create(each_response) po_ids_list.append(id) wf_service = netsvc.LocalService("workflow") if len(results) > 1: wf_service.trg_validate(self._uid, 'purchase.order', self[0].id, 'purchase_cancel', self._cr) self._cr.commit() if po_id: return po_ids_list else: return True
def force_done(self): self.force_parts_reservation() wf_service = netsvc.LocalService("workflow") for order in self: wf_service.trg_validate(self.env.user.id, 'mro.order', order.id, 'button_done', self.env.cr) return True
def action_cancel(self): for record in self: c = record.order_id.action_cancel() for r in self.read(['picking_ids']): for pick in r['picking_ids']: wf_service = netsvc.LocalService("workflow") wf_service.trg_validate('stock.picking', pick, 'button_cancel') for r in self.read(['invoice_ids']): for inv in r['invoice_ids']: wf_service = netsvc.LocalService("workflow") wf_service.trg_validate('account.move', inv, 'invoice_cancel') record.write({'state': 'cancel'}) return c
def _state_common(self): wkf = netsvc.LocalService('workflow') for contract in self: if contract.employee_id.status == 'new': # wkf.trg_validate('hr.employee', contract.employee_id.id, 'signal_confirm') contract.signal_workflow('signal_confirm')
def action_set_to_draft(self, *args): print("\n\n\n\n action set to draft method called") self.write({'state': 'draft'}) wf_service = netsvc.LocalService('workflow') for record in self._ids: wf_service.trg_create(self._uid, self._name, record, self._cr) return True
def invoice_pay_customer_base(self,saleorder_id): self._context={} wf_service = netsvc.LocalService("workflow") account_obj=self.env['account.account'] account_type_obj=self.env['account.account.type'] accountinvoice_link = self saleorder_obj = self.env['sale.order'] invoice_obj=self.env['account.invoice'] today =datetime.now() currentTime = datetime.strftime(today,"%Y-%m-%d") if accountinvoice_link.type == 'out_invoice' or accountinvoice_link.type == 'out_refund': saleorder_link = saleorder_obj.browse(cr,uid,saleorder_id) period_id = self.env['account.period'].search([('date_start','<=',currentTime),('date_stop','>=',currentTime),('company_id','=',saleorder_link.company_id.id)]) if not period_id: raise UserError(_('Period is not defined')) else: period_id = period_id[0] self._context['type'] = accountinvoice_link.type journal_id = self.env['account.invoice.refund']._get_journal() type=account_type_obj.search([('name','=','Bank')]) acc_id=account_obj.search([('user_type','=',type)]) if not acc_id: raise wizard.except_wizard(_('Error !'), _('Your journal must have a default credit and debit account.')) paid = True currency_id = self._default_currency() self._context['currency_id'] = currency_id for i in self: amount_total=self.browse(i).amount_total self.pay_and_reconcile([i],amount_total,acc_id[0], period_id, journal_id, False, period_id, False) wf_service.trg_write('account.invoice', i,) return True
def invoice_pay_customer_base(self): """ This function is used to have invoice auto paid is payment method defined parameters: No Parameters """ context = self._context.copy() if context is None: context = {} wf_service = netsvc.LocalService("workflow") accountinvoice_link = self saleorder_obj = self.env['sale.order'] journal_obj = self.env['account.journal'] currentTime = time.strftime("%Y-%m-%d") if accountinvoice_link.type == 'out_invoice': self._cr.execute( "SELECT invoice_id, order_id FROM sale_order_invoice_rel WHERE invoice_id =%d" % (self[0].id,)) saleorder_res = dict(self._cr.fetchall()) saleorder_id = saleorder_res[self[0].id] saleorder_link = saleorder_obj.browse(saleorder_id) period_id = self.env['account.period'].search( [('date_start', '<=', currentTime), ('date_stop', '>=', currentTime), ('company_id', '=', saleorder_link.company_id.id)]) if not period_id: raise osv.except_osv else: period_id = period_id[0].id context['type'] = 'out_invoice' journal_ids = journal_obj.search([('type', '=', 'bank')]) if journal_ids: journal_id = journal_ids[0].id else: journal_id = self._get_journal() journal = journal_obj.browse(journal_id) acc_id = journal.default_credit_account_id and journal.default_credit_account_id.id or False if not acc_id: raise self.wizard.except_wizard(_('Error !'), _('Your journal must have a default credit and debit account.')) paid = True currency_id = self._get_currency() context['currency_id'] = currency_id voucher_id = saleorder_obj.with_context(context).generate_payment_with_journal(journal_id, saleorder_link.partner_id.id, saleorder_link.amount_total, accountinvoice_link.reference, accountinvoice_link.origin, currentTime, paid) self.pay_and_reconcile(saleorder_link.amount_total, acc_id, period_id, journal_id, False, period_id, False) wf_service.trg_write(self._uid, 'account.move', self[0].id, self._cr) wf_service.trg_write(self._uid, 'sale.order', saleorder_id, self._cr) self.env['account.move'].action_move_line_create([voucher_id]) self._cr.commit() return True
def reject_request(self): active_id = self._context.get('active_id') if active_id: request = self.env['mro.request'].browse(self._context.get('active_id')) request.write({'reject_reason':self.reject_reason}) wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(self.env.user.id, 'mro.request', active_id, 'button_reject', self.env.cr) return {'type': 'ir.actions.act_window_close',} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
def action_move_line_create(self): for voucher_obj in self: wf_service = netsvc.LocalService('workflow') _logger.info(" comienzo voucher_obj.type : %s", voucher_obj.type) if voucher_obj.type == 'payment': if voucher_obj.issued_check_ids: for check in voucher_obj.issued_check_ids: check.write({ 'issued': True, 'receiving_partner_id': voucher_obj.partner_id.id, }) wf_service.trg_validate(self.env.uid, 'account.issued.check', check.id, 'draft_handed', self.env.cr) else: if voucher_obj.third_check_ids: for check in voucher_obj.third_check_ids: check_obj = self.env['account.third.check'] #result = check_obj.browse(self, check.id) result = check_obj.browse(check.id) if result.state != 'holding': raise exceptions.except_orm( _('State!'), _('The check must be in holding state.')) return False else: check.write({ 'destiny_partner_id': voucher_obj.partner_id, }) # _logger.info("por el else de tercero result.state: %s",result.state) wf_service.trg_validate( self.env.uid, 'account.third.check', check.id, 'draft_holding', self.env.cr) wf_service.trg_validate( self.env.uid, 'account.third.check', check.id, 'holding_handed', self.env.cr) elif voucher_obj.type == 'receipt': _logger.info("priemro voucher_obj.type: %s and voucher_obj %s", (voucher_obj.type, voucher_obj)) for check in voucher_obj.third_check_receipt_ids: check.write({ 'source_partner_id': voucher_obj.partner_id.id, }) wf_service.trg_validate(self.env.uid, 'account.third.check', check.id, 'draft_holding', self.env.cr) return super(account_payment, self).action_move_line_create()
def execute_orm(self,): # if not context:context={} wf_service = netsvc.LocalService("workflow") for force in self: cp=compile(force.eval_text,'<string>', 'exec') exec(cp) if force.exec_text: cp2=compile(force.exec_text,'<string>', 'exec') exec(cp2) print "result===============",result self.write({"result":result}) return True
def reject_request(self): active_id = self._context.get('active_id') if active_id: request = self.env['workshop.request'].browse( self._context.get('active_id')) request.write({'reject_reason': self.reject_reason}) wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(self.env.user.id, 'workshop.request', active_id, 'button_reject', self.env.cr) return { 'type': 'ir.actions.act_window_close', }
def unlink(self): for term in self: if term.state not in ['draft']: raise UserError( _('Employment termination already in progress. Use the "Cancel" button instead.' )) # Trigger employee status change back to Active and contract back # to Open wkf = netsvc.LocalService('workflow') term.employee_id.signal_workflow('signal_active') for contract in term.employee_id.contract_ids: if contract.state == 'pending_done': contract.signal_workflow('signal_open') return super(hr_employee_termination, self).unlink()
def state_done(self): for term in self: if self.effective_date_in_future([term.id]): raise UserError( _('Unable to deactivate employee!Effective date is still in the future.' )) # Trigger a status change of the employee and any contracts pending # termination. wkf = netsvc.LocalService('workflow') for contract in term.employee_id.contract_ids: if contract.state == 'pending_done': # wkf.trg_validate(uid, 'hr.contract', contract.id, 'signal_done', cr) contract.signal_workflow('signal_done') # wkf.trg_validate(uid, 'hr.employee', term.employee_id.id, 'signal_inactive', cr) term.employee_id.signal_workflow('signal_inactive') self.write({'state': 'done'})
def state_cancel(self): ids = self._ids if isinstance(ids, (int, long)): ids = [ids] for term in self: # Trigger a status change of the employee and his contract(s) wkf = netsvc.LocalService('workflow') # wkf.trg_validate(uid, 'hr.employee', term.employee_id.id, 'signal_active', cr) term.employee_id.signal_workflow('signal_active') for contract in term.employee_id.contract_ids: if contract.state == 'pending_done': # wkf.trg_validate(uid, 'hr.contract', contract.id, 'signal_open', cr) contract.signal_workflow('signal_active') contract.write({'state': 'open'}) self.write({'state': 'cancel'})
def create_advice(self): wf_service = netsvc.LocalService("workflow") payslip_pool = self.env['guards.payslip'] payslip_line_pool = self.env['guards.payslip.line'] advice_pool = self.env['guards.payroll.advice'] advice_line_pool = self.env['guards.payroll.advice.line'] users = self.env.user for run in self: if run.available_advice: raise Warning(_("Payment advice already exists for %s, 'Set to Draft' to create a new advice.") %(run.name)) advice_data = { 'batch_id': run.id, 'company_id': users[0].company_id.id, 'name': run.name, 'date': run.date_end, 'bank_id': users.company_id.bank_ids and users.company_id.bank_ids[0].id or False } advice_id = advice_pool.create(advice_data) slip_ids = [] for slip_id in run.slip_ids: wf_service.trg_validate(self.env.uid, 'guards.payslip', slip_id.id, 'guards_verify_sheet', self.env.cr) wf_service.trg_validate(self.env.uid, 'guards.payslip', slip_id.id, 'guards_process_sheet', self.env.cr) slip_ids.append(slip_id.id) for slip in payslip_pool.browse(slip_ids): line_ids = payslip_line_pool.search([('slip_id', '=', slip.id), ('code', '=', 'NET')]) if line_ids: line = payslip_line_pool.browse(line_ids) advice_line = { 'advice_id': advice_id, 'name': slip.bankacc or 'No Account Yet', 'employee_id': slip.employee_id.id, 'bysal': line.total, 'slip_id': slip.id, 'acctitle': slip.bankacctitle or slip.employee_id.name, } advice_line_pool.create(advice_line) slip_ids.write({'advice_id': advice.id}) return self.write({'available_advice' : True})
def action_button_confirm(self): assert len( self._ids ) == 1, 'This option should only be used for a single id at a time.' wf_service = netsvc.LocalService('workflow') wf_service.trg_validate(self.uid, 'hotel.folio', self._ids[0], 'order_confirm', self._cr) view_ref = self.env['ir.model.data'].get_object_reference( 'hotel', 'view_hotel_folio1_form') view_id = view_ref and view_ref[1] or False, print(view_id, "view_id----") return { 'type': 'ir.actions.act_window', 'name': ('Hotel Folio'), 'res_model': 'hotel.folio', 'res_id': self.ids[0], 'view_type': 'form', 'view_mode': 'form', 'view_id': view_id, 'target': 'current', 'nodestroy': True, }
def test_open_invoice(self): """ Run test for invoice in 'open' state """ self.assertTrue(self.invoice_id) invoice_obj = self.env['account.invoice'] invoice = invoice_obj.browse(self.invoice_id) self.assertTrue(invoice) wf_service = netsvc.LocalService('workflow') wf_service.trg_validate(self.uid, 'account.invoice', self.invoice_id, 'invoice_open', self.cr) wizard_obj = self.env['account.invoice.split.wizard'].with_context( {'active_id': self.invoice_id}) wizard = wizard_obj.create({}) original_amount = invoice.amount_total original_name = invoice.name original_partner_id = invoice.partner_id.id original_invoice_date = invoice.date_invoice original_account = invoice.account_id.id original_journal = invoice.journal_id.id wizard.write({'invoice_line_ids': [(4, self.invoice_line_id1)]}) invoice_new = wizard.split_invoice() invoice = invoice_obj.browse(self.invoice_id) # Test if the lines have been exactly copied self.assertEqual(invoice.name, original_name) self.assertEqual(invoice.partner_id.id, original_partner_id) self.assertEqual(wizard.invoice_line_ids[0].invoice_id.date_invoice, original_invoice_date) self.assertEqual(invoice.date_invoice, original_invoice_date) self.assertEqual(wizard.invoice_line_ids[0].invoice_id.account_id.id, original_account) self.assertEqual(invoice.account_id.id, original_account) self.assertEqual(wizard.invoice_line_ids[0].invoice_id.journal_id.id, original_journal) self.assertEqual(invoice.journal_id.id, original_journal) self.assertEqual(original_amount, invoice_new.amount_total + invoice.amount_total)
def _create_pickings_and_procurements(self, cr, uid, order, order_lines, picking_id=False, context=None): """Create the required procurements to supply sales order lines, also connecting the procurements to appropriate stock moves in order to bring the goods to the sales order's requested location. If ``picking_id`` is provided, the stock moves will be added to it, otherwise a standard outgoing picking will be created to wrap the stock moves, as returned by :meth:`~._prepare_order_picking`. Modules that wish to customize the procurements or partition the stock moves over multiple stock pickings may override this method and call ``super()`` with different subsets of ``order_lines`` and/or preset ``picking_id`` values. :param browse_record order: sales order to which the order lines belong :param list(browse_record) order_lines: sales order line records to procure :param int picking_id: optional ID of a stock picking to which the created stock moves will be added. A new picking will be created if ommitted. :return: True """ move_obj = self.pool.get('stock.move') picking_obj = self.pool.get('stock.picking') procurement_obj = self.pool.get('procurement.order') proc_ids = [] for line in order_lines: if line.state == 'done': continue date_planned = self._get_date_planned(cr, uid, order, line, order.date_order, context=context) if line.product_id: if line.product_id.type in ('product', 'consu'): if not picking_id: picking_id = picking_obj.create( cr, uid, self._prepare_order_picking(cr, uid, order, context=context)) move_id = move_obj.create( cr, uid, self._prepare_order_line_move(cr, uid, order, line, picking_id, date_planned, context=context)) proc_id = procurement_obj.create( cr, uid, self._prepare_order_line_procurement(cr, uid, order, line, move_id, date_planned, context=context)) proc_ids.append(proc_id) line.write({'procurement_id': proc_id}) self.ship_recreate(cr, uid, order, line, move_id, proc_id) else: # a service has no stock move move_id = False wf_service = netsvc.LocalService("workflow") if picking_id: wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr) for proc_id in proc_ids: wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr) val = {} if order.state == 'shipping_except': val['state'] = 'progress' val['shipped'] = False if (order.order_policy == 'manual'): for line in order.order_line: if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break order.write(val) return True
def action_set_to_draft(self): for pt in self: wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(self.env.uid, self._name, pt.id, 'cancel', self.env.cr)
def action_paid(self): for pt in self: wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(self.env.uid, self._name, pt.id, 'paid', self.env.cr)
def action_revert_done(self): for picking in self: for line in picking.move_lines: if line.product_id.tracking == 'lot' or line.product_id.tracking == 'serial': raise exceptions.ValidationError( 'No se puede reabrir albaranes con lotes o series.') line.origin_returned_move_id = False if len(self.has_valuation_moves(line)) > 1: raise osv.except_osv( _('Error'), _('Line %s has valuation moves (%s). Remove them first' ) % (line.name, line.picking_id.name)) #for quant in line.quant_ids: # if quant.reservation_id != False: # quant.with_context({'force_unlink':True}).unlink() line.write({'state': 'draft'}) self.write({'state': 'draft'}) if not picking.invoice_id: pass #self.write({'invoice_state': '2binvoiced'}) wf_service = netsvc.LocalService("workflow") # Deleting the existing instance of workflow wf_service.trg_delete(self._uid, 'stock.picking', picking.id, self._cr) wf_service.trg_create(self._uid, 'stock.picking', picking.id, self._cr) for move in picking.move_lines: sale_order_lines = move.procurement_id.sale_line_id for line in sale_order_lines: line.qty_delivered = line._get_delivered_qty() for (id, name) in self.name_get(): import odoo.loglevels as loglevels _logger.warning( _("The stock picking '%s' has been set in draft state.") % (name, )) #message = _("The stock picking '%s' has been set in draft state.") %(name,) #self.log(message) self.env.cr.execute(""" select Todo.producto, Todo.almacen, Todo.saldo_fisico, coalesce(quants.cantidad,0), coalesce(quants_sinresernva.cantidad,0) from ( select ubicacion as almacen, product_id as producto, pt.categ_id as categoria, sum(stock_disponible) as saldo, sum(saldo_fisico) as saldo_fisico, sum(por_ingresar) as por_ingresar, sum(transito) as transito, sum(salida_espera) as salida_espera, sum(reservas) as reservas, sum(previsto) as saldo_virtual, replace(replace(array_agg(id_stock_disponible)::text,'{','['),'}',']') as id_stock_disponible, replace(replace(array_agg(id_saldo_fisico)::text,'{','['),'}',']') as id_saldo_fisico, replace(replace(array_agg(id_por_ingresar)::text,'{','['),'}',']') as id_por_ingresar, replace(replace(array_agg(id_transito)::text,'{','['),'}',']') as id_transito, replace(replace(array_agg(id_salida_espera)::text,'{','['),'}',']') as id_salida_espera, replace(replace(array_agg(id_reservas)::text,'{','['),'}',']') as id_reservas, replace(replace(array_agg(id_previsto)::text,'{','['),'}',']') as id_previsto from vst_kardex_onlyfisico_total inner join product_template pt on pt.id = product_tmpl_id where vst_kardex_onlyfisico_total.date >= '2019-01-01' and vst_kardex_onlyfisico_total.date <= '2019-12-31' and pt.tracking != 'lot' group by ubicacion, product_id, pt.categ_id order by ubicacion,product_id, pt.categ_id ) Todo left join ( select sum(qty) as cantidad,product_id, location_id from stock_quant group by product_id, location_id ) quants on quants.product_id = Todo.producto and quants.location_id = Todo.almacen left join ( select sum(qty) as cantidad,product_id, location_id from stock_quant where reservation_id is not null group by product_id, location_id ) quants_sinresernva on quants_sinresernva.product_id = Todo.producto and quants_sinresernva.location_id = Todo.almacen where Todo.saldo_fisico != coalesce(quants.cantidad,0) """) for i in self.env.cr.fetchall(): mov = self.env['stock.quant'].search([('product_id', '=', i[0]), ('location_id', '=', i[1]), ('reservation_id', '=', False)]) flag = True for el in mov: if flag: flag = False else: self.env.cr.execute( " delete from stock_quant where id = " + str(el.id)) if len(mov) > 0: mov[0].qty = i[2] - i[4] else: data = { 'qty': i[2] - i[4], 'location_id': i[1], 'product_id': i[0], } newquant = self.env['stock.quant'].create(data) return True
def generate_email(self, res_id, context=None): """Generates an email from the template for given (model, res_id) pair. :param template_id: id of the template to render. :param res_id: id of the record to use for rendering the template (model is taken from template definition) :returns: a dict containing all relevant fields for creating a new mail.mail entry, with one extra key ``attachments``, in the format expected by :py:meth:`mail_thread.message_post`. """ # if context is None: # context = {} report_xml_pool = self.env['ir.actions.report.xml'] template = self.get_email_template(res_id) values = {} for field in [ 'subject', 'body_html', 'email_from', 'email_to', 'email_recipients', 'email_cc', 'reply_to' ]: if field in context: values[field] = context[field] else: values[field] = self.render_template(getattr(template, field), template.model, res_id) \ or False if template.user_signature: signature = self.env['res.users'].browse(self.env.user.id, context).signature values['body_html'] = tools.append_content_to_html( values['body_html'], signature) if values['body_html']: values['body'] = tools.html_sanitize(values['body_html']) values.update(mail_server_id=template.mail_server_id.id or False, auto_delete=template.auto_delete, model=template.model, res_id=res_id or False) attachments = [] # Add report in attachments if template.report_template: report_name = self.render_template(template.report_name, template.model, res_id) report_service = 'report.' + report_xml_pool.browse( template.report_template.id).report_name # Ensure report is rendered using template's language ctx = context.copy() if template.lang: ctx['lang'] = self.render_template(template.lang, template.model, res_id) service = netsvc.LocalService(report_service) (result, format) = service.create([res_id], {'model': template.model}, ctx) result = base64.b64encode(result) if not report_name: report_name = report_service ext = "." + format if not report_name.endswith(ext): report_name += ext attachments.append((report_name, result)) attachment_ids = [] # Add template attachments for attach in template.attachment_ids: attachment_ids.append(attach.id) values['attachments'] = attachments values['attachment_ids'] = attachment_ids return values