def view_init(self, cr, uid, fields_list, context=None): """ Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view with new columns. """ res = super(AccountBalanceCommonWizard, self).view_init(cr, uid, fields_list, context=context) for index in range(self.COMPARISON_LEVEL): # create columns for each comparison page self._columns.update({ "comp%s_filter" % (index,): fields.selection(self.COMPARE_SELECTION, string="Compare By", required=True), "comp%s_fiscalyear_id" % (index,): fields.many2one('account.fiscalyear', 'Fiscal year'), "comp%s_period_from" % (index,): fields.many2one('account.period', 'Start period'), "comp%s_period_to" % (index,): fields.many2one('account.period', 'End period'), "comp%s_date_from" % (index,): fields.date("Start Date"), "comp%s_date_to" % (index,): fields.date("End Date"), }) return res
def _update_analytic_line_columns(self, cr, ids=None, context=None): super(AnalyticAxis, self)._update_analytic_line_columns(cr, ids, context) context = context or {} if isinstance(ids, (int, long)): ids = [ids] if not ids: ids = self.search(cr, 1, [], context={'active_test': False}) line_obj = self.pool.get('crossovered.budget.lines') for axis in self.browse(cr, 1, ids, context): if (not axis.active or context.get('unlink_axis') or not axis.is_budget_axis) and axis.column_label in line_obj._columns: del line_obj._columns[axis.column_label] if axis.field_ids: for field in axis.field_ids: column = '%s_%s' % (axis.column_label, field.id) if column in line_obj._columns: del line_obj._columns[column] elif axis.active and axis.is_budget_axis: line_obj._columns[axis.column_label] = fields.many2one(axis.model, axis.name, domain=axis.domain and eval(axis.domain) or [], required=axis.required) if axis.field_ids: for field in axis.field_ids: column = '%s_%s' % (axis.column_label, field.id) line_obj._columns[column] = fields.related(axis.column_label, field.name, type=field.ttype, relation=field.relation, store={ # To store and to avoid the field re-computation 'crossovered.budget.lines': (lambda self, cr, uid, ids, context=None: [], None, 10), }) line_obj._auto_init(cr, context) return True
def __new__(cls, *args, **kwargs): # A new column is automatically added if it does not exist: # menu_id, which correspond to the menu attached to this item. if 'menu_id' not in cls._columns: cls._columns['menu_id'] = fields.many2one('ir.ui.menu') defaults = { '_menu_icon' : 'STOCK_OPEN', '_menu_parent' : None, '_menu_name' : 'name', '_menu_view_type' : 'form', '_menu_view_mode' : 'form,tree', '_menu_res_model' : None, '_menu_context' : '{}', '_menu_help' : None, '_menu_domain' : None, '_menu_target' : 'current', '_menu_groups' : None, } for variable in defaults: if not hasattr(cls, variable): setattr(cls, variable, defaults[variable]) return super(AttachMenu, cls).__new__(cls, *args, **kwargs)
def action_compute(self, cr, uid, ids, properties=None, context=None): """ Computes bills of material of a product. @param properties: List containing dictionaries of properties. @return: No. of products. """ if properties is None: properties = [] results = [] bom_obj = self.pool.get('mrp.bom') uom_obj = self.pool.get('product.uom') prod_line_obj = self.pool.get('mrp.production.product.line') workcenter_line_obj = self.pool.get('mrp.production.workcenter.line') for production in self.browse(cr, uid, ids): cr.execute('delete from mrp_production_product_line where production_id=%s', (production.id,)) cr.execute('delete from mrp_production_workcenter_line where production_id=%s', (production.id,)) bom_point = production.bom_id bom_id = production.bom_id.id if not bom_point: bom_id = bom_obj._bom_find(cr, uid, production.product_id.id, production.product_uom.id, properties) if bom_id: bom_point = bom_obj.browse(cr, uid, bom_id) routing_id = bom_point.routing_id.id or False self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id}) if not bom_id: raise osv.except_osv(_('Error!'), _("Cannot find a bill of material for this product.")) factor = uom_obj._compute_qty(cr, uid, production.product_uom.id, production.product_qty, bom_point.product_uom.id) res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, properties, routing_id=production.routing_id.id) results = res[0] results2 = res[1] for line in results: line['production_id'] = production.id prod_line_obj.create(cr, uid, line) for line in results2: line['production_id'] = production.id workcenter_line_obj.create(cr, uid, line) return len(results) _columns = { 'pallet_stack_id': fields.many2one('pallet.stack.layout','Pallet Stack'), #TODO Filter to ids returned by product.product.pallet_stack_layers for the product 'num_layers': fields.many2one('pallet.stack.layers', 'Number of layers') #TODO Filter to ids returned by field above, and pre-enter default number of layers as a default. 'num_pallets': fields.integer('Quantity of pallets') }
def _check_amount(self, cr, uid, ids, context=None): for obj in self.browse(cr, uid, ids, context=context): if obj.voucher_id: if not (abs(obj.amount) == obj.voucher_id.amount): return False return True _constraints = [(_check_amount, 'The amount of the voucher must be the same amount as the one on the statement line', ['amount']),] _columns = { 'amount_reconciled': fields.function(_amount_reconciled,string='Amount reconciled', method=True, type='float'), 'voucher_id': fields.many2one('account.voucher', 'Payment'), }
def _update_analytic_line_columns(self, cr, ids=None, context=None): context = context or {} if isinstance(ids, (int, long)): ids = [ids] if not ids: ids = self.search(cr, 1, [], context={'active_test': False}) line_obj = self.pool.get('account.analytic.line') non_unicity_fields = line_obj._non_unicity_fields[:] for axis in self.browse(cr, 1, ids, context): if (not axis.active or context.get('unlink_axis')) and axis.column_label in line_obj._columns: del line_obj._columns[axis.column_label] if axis.field_ids: for field in axis.field_ids: column = '%s_%s' % (axis.column_label, field.id) if column in line_obj._columns: del line_obj._columns[column] elif axis.active: # To be compatible with smile_analytic_forecasting if hasattr(line_obj, '_non_unicity_fields'): if axis.is_unicity_field and axis.column_label in line_obj._non_unicity_fields: line_obj._non_unicity_fields.remove(axis.column_label) elif not axis.is_unicity_field and axis.column_label not in line_obj._non_unicity_fields: line_obj._non_unicity_fields.append(axis.column_label) ### line_obj._columns[axis.column_label] = fields.many2one(axis.model, axis.name, domain=axis.domain and eval(axis.domain) or [], required=axis.required, ondelete=axis.ondelete) if axis.field_ids: for field in axis.field_ids: column = '%s_%s' % (axis.column_label, field.id) line_obj._columns[column] = fields.related(axis.column_label, field.name, type=field.ttype, relation=field.relation, store={ # To store and to avoid the field re-computation 'account.analytic.line': (lambda self, cr, uid, ids, context=None: [], None, 10), }) line_obj._auto_init(cr, context) # To be compatible with smile_analytic_forecasting if hasattr(line_obj, '_non_unicity_fields'): if line_obj._non_unicity_fields != non_unicity_fields: cr.execute("SELECT count(0) FROM pg_class WHERE relname = 'account_analytic_line_multi_columns_index'") exists = cr.fetchone() if exists[0]: cr.execute('DROP INDEX account_analytic_line_multi_columns_index') cr.execute('CREATE INDEX account_analytic_line_multi_columns_index ' 'ON account_analytic_line (%s)' % ', '.join(line_obj._get_unicity_fields())) ### return True
from lxml import etree class res_company(osv.Model): """override company to add currency update""" def button_refresh_currency(self, cr, uid, ids, context=None): """Refresh the currency ! For all the company now""" service_id = None if 'service_id' not in context: raise osv.except_osv(_('Warning!'), _('You must choose bank for currency rate update. Also, that bank must have defined update service.')) else: service_id = context['service_id'] currency_updater_obj = self.pool.get('res.currency.rate.update') try: currency_updater_obj.run_currency_update(cr, uid, service_id, None, None, called_from='company', context=context) except Exception, e: return False return True _inherit = "res.company" _columns = { # activate the currency update 'update_service_id': fields.many2one(obj='res.currency.rate.update.service', string='Currency update service'), 'service_currency_to_update': fields.related('update_service_id', 'currency_to_update', type="many2many", relation='res.currency', string='currency to update with this service', readonly=True), }
cr.execute("SAVEPOINT update_entity_last_activity") cr.execute('select id from sync_server_entity_activity where entity_id=%s for update nowait', (entity.id,), log_exceptions=False) cr.execute('update sync_server_entity_activity set datetime=%s, activity=%s where entity_id=%s', (now, activity, entity.id)) except psycopg2.OperationalError, e: if not wait and e.pgcode == '55P03': # can't acquire lock: ok the show must go on cr.execute("ROLLBACK TO update_entity_last_activity") logging.getLogger('sync.server').info("Can't acquire lock to set last_activity") return raise _columns = { 'name':fields.char('Instance Name', size=64, required=True, select=True), 'identifier':fields.char('Identifier', size=64, readonly=True, select=True), 'hardware_id' : fields.char('Hardware Identifier', size=128, select=True), 'parent_id':fields.many2one('sync.server.entity', 'Parent Instance', ondelete='cascade'), 'group_ids':fields.many2many('sync.server.entity_group', 'sync_entity_group_rel', 'entity_id', 'group_id', string="Groups"), 'state' : fields.selection([('pending', 'Pending'), ('validated', 'Validated'), ('invalidated', 'Invalidated'), ('updated', 'Updated')], 'State'), 'email':fields.char('Contact Email', size=512), 'user_id': fields.many2one('res.users', 'User', ondelete='restrict', required=True), #just in case, since the many2one exist it has no cost in database 'children_ids' : fields.one2many('sync.server.entity', 'parent_id', 'Children Instances'), 'update_token' : fields.char('Update security token', size=256), 'activity' : fields.function(_get_activity, type='char', string="Activity", method=True, multi="_get_act"), 'last_dateactivity': fields.function(_get_activity, type='datetime', string="Date of last activity", method=True, multi="_get_act"), #'last_activity' : fields.datetime("Date of last activity", readonly=True), 'parent_left' : fields.integer("Left Parent", select=1), 'parent_right' : fields.integer("Right Parent", select=1),
'product_id': fields.many2one('product.product', 'Pallet Product'), } _defaults = { 'active': lambda *a, 1, } _sql_constraints = [('name_uniq', 'unique(name)', 'Pallet names must be unique!')] pallet_types() class pallet_stack_layout(osv.osv): _name = 'pallet.stack.layout' _columns = { 'name': fields.char('Description', size=128, required=True), 'active': fields.boolean('Active'), 'program': fields.integer('Program Number', help='If this is stacked on a palletiser, this is the palletiser program number'), 'pallet_type_id': fields.many2one('pallet.types','Pallet Type', ondelete='set null'), 'layout_diagram': fields.binary('Layout diagram', filters='*.bmp,*.jpg,*.gif') 'slipsheeted': fields.boolean('Slipsheeted', help='If product is stacked onto slipsheets, this box should be ticked.'), 'layer_qty': fields.integer('Packages per layer'), 'layer_height': fields.integer('Height per layer (mm)'), 'layer_ids': fields.one2many('pallet_stack_layers', 'layout_id','Layer options'), } _defaults = { 'active': lambda *a, 1, } pallet_stack_layout() class pallet_stack_layers(osv.osv): _name = 'pallet.stack.layers' #TODO This needs to calculate sum height of each layer and add the pallet height to come up with an overall height. #def _calc_total_height(self, cr, uid, ids, field_name, arg, context=None)
# invisible field to filter payment order lines by payment type "payment_type_name": fields.function( _payment_type_name_get, method=True, type="char", size=64, string="Payment type name" ), # The field name is necessary to add attachement documents to payment orders "name": fields.function(_name_get, method=True, type="char", size=64, string="Name"), "create_account_moves": fields.selection( [("bank-statement", "Bank Statement"), ("direct-payment", "Direct Payment")], "Create Account Moves", required=True, states={"done": [("readonly", True)]}, help='Indicates when account moves should be created for order payment lines. "Bank Statement" ' 'will wait until user introduces those payments in bank a bank statement. "Direct Payment" ' "will mark all payment lines as payied once the order is done.", ), "period_id": fields.many2one("account.period", "Period", states={"done": [("readonly", True)]}), } _defaults = { "type": _get_type, "reference": _get_reference, "create_account_moves": lambda *a: "bank-statement", "period_id": _get_period, } def unlink(self, cr, uid, ids, context=None): pay_orders = self.read(cr, uid, ids, ["state"], context=context) unlink_ids = [] for t in pay_orders: if t["state"] in ("draft", "cancel"): unlink_ids.append(t["id"]) else:
class purchase_advance_payment_inv(osv.osv_memory): _name = "purchase.advance.payment.inv" _description = "Sales Advance Payment Invoice" _columns = { #'account_id':fields.many2one('account.account', 'Account', required=True, ), 'amount': fields.float('Down Payment Amount', digits_compute=dp.get_precision('Account'), required=True), 'name': fields.char('Down Payment Description', size=64, required=True), 'journal_id': fields.many2one('account.journal', 'Payment Method', required=True), } def create_payment(self, cr, uid, ids, context=None): obj_dp = self.pool.get('downpayment') obj_dp_line = self.pool.get('downpayment.line') list_inv = [] lines = [] obj_purchase = self.pool.get('purchase.order') obj_voc_lines = self.pool.get('account.voucher.line') voc_obj = self.pool.get('account.voucher') if context is None: context = {} for purchase_adv_obj in self.browse(cr, uid, ids, context=context): for purchase in obj_purchase.browse(cr, uid, context.get('active_ids', []), context=context): dp_account_id = purchase.company_id.downpayment_account_id.id if not dp_account_id: raise osv.except_osv( _('Error !'), _('Please define a Downpayment Account !')) dp_cr = purchase.downpayment_id if not dp_cr: for purchase_adv_obj in self.browse(cr, uid, ids, context=context): for purchase in obj_purchase.browse(cr, uid, context.get( 'active_ids', []), context=context): print "Amount----------***>>", purchase_adv_obj.amount dp_desc = purchase_adv_obj.name amount = purchase_adv_obj.amount journal_id = purchase_adv_obj.journal_id.id purchase_id = context.get('active_ids', [])[0] currency_id = purchase.pricelist_id.currency_id.id company_id = purchase.company_id.id print "purchase_id-------------->>", purchase_id #obj_purchase.write(cr, uid, context.get('active_ids', []), {'dp': True}) vals_line = { 'name': dp_desc, #'dp_id' : fields.many2one('downpayment', 'ID'), 'amount': amount, 'account_id': dp_account_id, 'purchase_id': purchase_id, } lines.append((0, 0, vals_line)) vals = { 'name': '/', 'dp_line': lines, 'journal_id': journal_id, 'ref': dp_desc, 'date': time.strftime('%Y-%m-%d'), 'currency_id': currency_id, 'company_id': company_id, #'used' : fields.boolean('Used'), 'partner_id': purchase.partner_id.id, } dp_id = obj_dp.create(cr, uid, vals) obj_purchase.write(cr, uid, context.get('active_ids', []), { 'dp': True, 'downpayment_id': dp_id }) elif dp_cr: for purchase_adv_obj in self.browse(cr, uid, ids, context=context): for purchase in obj_purchase.browse(cr, uid, context.get( 'active_ids', []), context=context): dp_desc = purchase_adv_obj.name amount = purchase_adv_obj.amount journal_id = purchase_adv_obj.journal_id.id purchase_id = context.get('active_ids', [])[0] vals_line = { 'name': dp_desc, #'dp_id' : fields.many2one('downpayment', 'ID'), 'amount': amount, 'account_id': dp_account_id, 'purchase_id': purchase_id, 'dp_id': dp_cr.id, } lines.append((0, 0, vals_line)) obj_dp_line.create(cr, uid, vals_line) return { 'name': 'Downpayment Notification', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'downpayment.notification', 'type': 'ir.actions.act_window', 'target': 'new', 'context': context }
#This program is distributed in the hope that it will be useful, # #but WITHOUT ANY WARRANTY; without even the implied warranty of # #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # #GNU Affero General Public License for more details. # # # #You should have received a copy of the GNU Affero General Public License # #along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################# import time from osv import osv, fields import decimal_precision as dp FISCAL_RULE_COLUMNS = { 'partner_fiscal_type_id': fields.many2one('l10n_br_account.partner.fiscal.type', 'Tipo Fiscal do Parceiro'), 'fiscal_operation_category_id': fields.many2one('l10n_br_account.fiscal.operation.category', 'Categoria', requeried=True), 'fiscal_type': fields.selection([('1', 'Simples Nacional'), ('2', 'Simples Nacional – excesso de sublimite de receita bruta'), ('3', 'Regime Normal')], 'Regime Tributário', required=True), 'revenue_start': fields.float('Faturamento Inicial', digits_compute=dp.get_precision('Account'), help="Faixa inicial de faturamento bruto"), 'revenue_end': fields.float('Faturamento Final', digits_compute=dp.get_precision('Account'), help="Faixa inicial de faturamento bruto"),} FISCAL_RULE_DEFAULTS = { 'fiscal_type': '3',
class account_move_reversal(osv.osv_memory): _name = "account.move.reverse" _description = "Create reversal of account moves" _columns = { 'date': fields.date( 'Reversal Date', required=True, help= "Enter the date of the reversal account entries. By default, OpenERP proposes the first day of the next period." ), 'period_id': fields.many2one('account.period', 'Reversal Period', help="If empty, take the period of the date."), 'journal_id': fields.many2one( 'account.journal', 'Reversal Journal', help= 'If empty, uses the journal of the journal entry to be reversed.'), 'move_prefix': fields.char( 'Entries Ref. Prefix', size=32, help= "Prefix that will be added to the 'Ref' of the journal entry to be reversed to create the 'Ref' of the reversal journal entry (no space added after the prefix)." ), 'move_line_prefix': fields.char( 'Items Name Prefix', size=32, help= "Prefix that will be added to the name of the journal item to be reversed to create the name of the reversal journal item (a space is added after the prefix)." ), } def _next_period_first_date(self, cr, uid, context=None): if context is None: context = {} period_obj = self.pool.get('account.period') current_period_id = period_obj.find(cr, uid, context=context)[0] current_period = period_obj.browse(cr, uid, current_period_id, context=context) next_period_id = period_obj.next(cr, uid, current_period, 1, context=context) next_period = period_obj.browse(cr, uid, next_period_id, context=context) return next_period.date_start _defaults = { 'date': _next_period_first_date, 'move_line_prefix': lambda *a: 'REV -', } def action_reverse(self, cr, uid, ids, context=None): if context is None: context = {} form = self.read(cr, uid, ids, context=context)[0] action = {'type': 'ir.actions.act_window_close'} if context.get('active_ids', False): mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') move_obj = self.pool.get('account.move') move_ids = context['active_ids'] period_id = form.get('period_id', False) and form['period_id'][0] or False journal_id = form.get('journal_id', False) and form['journal_id'][0] or False reversed_move_ids = move_obj.create_reversals( cr, uid, move_ids, form['date'], reversal_period_id=period_id, reversal_journal_id=journal_id, move_prefix=form['move_prefix'], move_line_prefix=form['move_line_prefix'], context=context) action_ref = mod_obj.get_object_reference( cr, uid, 'account', 'action_move_journal_line') action_id = action_ref and action_ref[1] or False action = act_obj.read(cr, uid, [action_id], context=context)[0] action['domain'] = str([('id', 'in', reversed_move_ids)]) action['name'] = _('Reversal Entries') action['context'] = unicode({'search_default_to_be_reversed': 0}) return action
class multi_company_default(osv.osv): """ Manage multi company default value """ _name = 'multi_company.default' _description = 'Default multi company' _order = 'company_id,sequence,id' _columns = { 'sequence': fields.integer('Sequence'), 'name': fields.char('Name', size=256, required=True, help='Name it to easily find a record'), 'company_id': fields.many2one('res.company', 'Main Company', required=True, help='Company where the user is connected'), 'company_dest_id': fields.many2one('res.company', 'Default Company', required=True, help='Company to store the current record'), 'object_id': fields.many2one('ir.model', 'Object', required=True, help='Object affected by this rule'), 'expression': fields.char( 'Expression', size=256, required=True, help= 'Expression, must be True to match\nuse context.get or user (browse)' ), 'field_id': fields.many2one('ir.model.fields', 'Field', help='Select field property'), } _defaults = { 'expression': 'True', 'sequence': 100, } def copy(self, cr, uid, id, default=None, context=None): """ Add (copy) in the name when duplicate record """ if not context: context = {} if not default: default = {} company = self.browse(cr, uid, id, context=context) default = default.copy() default['name'] = company.name + _(' (copy)') return super(multi_company_default, self).copy(cr, uid, id, default, context=context)
class crm_lead(orm.Model): """ CRM Lead Case """ _inherit = "crm.lead" _columns = { 'legal_name': fields.char(u'Razão Social', size=128, help="nome utilizado em " "documentos fiscais"), 'cnpj_cpf': fields.char('CNPJ/CPF', size=18), 'inscr_est': fields.char('Inscr. Estadual/RG', size=16), 'inscr_mun': fields.char('Inscr. Municipal', size=18), 'suframa': fields.char('Suframa', size=18), 'l10n_br_city_id': fields.many2one( 'l10n_br_base.city', 'Municipio', domain="[('state_id','=',state_id)]"), 'district': fields.char('Bairro', size=32), 'number': fields.char('Número', size=10) } def _check_cnpj_cpf(self, cr, uid, ids): for partner in self.browse(cr, uid, ids): if not partner.cnpj_cpf: continue if partner.partner_name: if not fiscal.validate_cnpj(partner.cnpj_cpf): return False elif not fiscal.validate_cpf(partner.cnpj_cpf): return False return True def _check_ie(self, cr, uid, ids): """Checks if company register number in field insc_est is valid, this method call others methods because this validation is State wise :Return: True or False. :Parameters: - 'cr': Database cursor. - 'uid': Current user’s ID for security checks. - 'ids': List of partner objects IDs. """ for partner in self.browse(cr, uid, ids): if not partner.inscr_est \ or partner.inscr_est == 'ISENTO' \ or not partner.partner_name: continue uf = partner.state_id and \ partner.state_id.code.lower() or '' try: mod = __import__( 'tools.fiscal', globals(), locals(), 'fiscal') validate = getattr(mod, 'validate_ie_%s' % uf) if not validate(partner.inscr_est): return False except AttributeError: if not fiscal.validate_ie_param(uf, partner.inscr_est): return False return True _constraints = [ (_check_cnpj_cpf, u'CNPJ/CPF invalido!', ['cnpj_cpf']), (_check_ie, u'Inscrição Estadual inválida!', ['inscr_est']) ] def onchange_mask_cnpj_cpf(self, cr, uid, ids, partner_name, cnpj_cpf): result = {'value': {}} if cnpj_cpf: val = re.sub('[^0-9]', '', cnpj_cpf) if partner_name and len(val) == 14: cnpj_cpf = "%s.%s.%s/%s-%s"\ % (val[0:2], val[2:5], val[5:8], val[8:12], val[12:14]) elif not partner_name and len(val) == 11: cnpj_cpf = "%s.%s.%s-%s"\ % (val[0:3], val[3:6], val[6:9], val[9:11]) result['value'].update({'cnpj_cpf': cnpj_cpf}) return result def onchange_mask_zip(self, cr, uid, ids, code_zip): result = {'value': {'zip': False}} if not code_zip: return result val = re.sub('[^0-9]', '', code_zip) if len(val) == 8: code_zip = "%s-%s" % (val[0:5], val[5:8]) result['value']['zip'] = code_zip return result def on_change_partner(self, cr, uid, ids, partner_id, context=None): result = super(crm_lead, self).on_change_partner( cr, uid, ids, partner_id, context) if partner_id: partner = self.pool.get('res.partner').browse( cr, uid, partner_id, context=context) result['value']['legal_name'] = partner.legal_name result['value']['cnpj_cpf'] = partner.cnpj_cpf result['value']['inscr_est'] = partner.inscr_est result['value']['suframa'] = partner.suframa result['value']['number'] = partner.number result['value']['district'] = partner.district result['value']['l10n_br_city_id'] = partner.l10n_br_city_id.id return result def _create_lead_partner(self, cr, uid, lead, context=None): partner_id = super(crm_lead, self)._create_lead_partner( cr, uid, lead, context) self.pool.get('res.partner').write(cr, uid, [partner_id], { 'legal_name': lead.legal_name, 'cnpj_cpf': lead.cnpj_cpf, 'inscr_est': lead.inscr_est, 'inscr_mun': lead.inscr_mun, 'suframa': lead.suframa, 'number': lead.number, 'district': lead.district, 'l10n_br_city_id': lead.l10n_br_city_id.id }) return partner_id
class account_balance_full_report(osv.osv_memory): _name = "account.balance.full.report" _description = "Print Full account balance" _columns = { 'company_id': fields.many2one('res.company', 'Company', required=True), 'account_list': fields.many2many('account.account', 'account_balance_account_list_rel', 'acc_balance_id','account_id','Root accounts', required=True), 'state': fields.selection([ ('bydate','By Date'), ('byperiod','By Period'), ('all', 'By Date and Period'), ('none','No Filter')],'Date/Period Filter'), 'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscal year', help='Keep empty to use all open fiscal years to compute the balance'), 'periods': fields.many2many('account.period','account_balance_account_period_rel','acc_balance_id','account_period_id','Periods', help='All periods in the fiscal year if empty'), 'display_account': fields.selection([ ('bal_all','All'), ('bal_solde', 'With balance'), ('bal_mouvement','With movements')], 'Display accounts'), 'display_account_level': fields.integer('Up to level', help= 'Display accounts up to this level (0 to show all)'), 'date_from': fields.date('Start date'), 'date_to': fields.date('End date') } def default_get(self, cr, uid, fields, context=None): if context is None: context = {} res = {} result = [] if context and context.get('active_model') == 'account.account': list_ids = context.get('active_ids',[]) if list_ids: res['account_list'] = [(6,0,list_ids)] res['state'] = 'none' res['display_account_level'] = 0 res['date_from'] = time.strftime('%Y-01-01') res['date_to'] = time.strftime('%Y-%m-%d') res['company_id'] = self.pool.get('res.users').browse(cr, uid, uid, context).company_id.id res['fiscalyear'] = self.pool.get('account.fiscalyear').find(cr, uid) return res def _check_state(self, cr, uid, ids, context=None): if ids: current_obj = self.browse(cr, uid, ids[0], context=context) if current_obj.state and current_obj.state == 'bydate': self._check_date(cr, uid, ids, context=context) return True def _check_date(self, cr, uid, ids, context=None): if ids: current_obj = self.browse(cr, uid, ids[0], context=context) res = self.pool.get('account.fiscalyear').search(cr, uid, [('date_start', '<=', current_obj.date_from),('date_stop', '>=', current_obj.date_from)]) if res: acc_fy = self.pool.get('account.fiscalyear').browse(cr, uid, res[0], context=context) if current_obj.date_to > acc_fy.date_stop or current_obj.date_to < acc_fy.date_start: raise osv.except_osv(_('UserError'),_('Date to must be set between %s and %s') % (acc_fy.date_start,acc_fy.date_stop)) else: return True else: raise osv.except_osv(_('UserError'),_('Date not in a defined fiscal year')) def print_report(self, cr, uid, ids, context=None): """prints report""" if context is None: context = {} data = self.read(cr, uid, ids)[0] datas = { 'ids': context.get('active_ids',[]), 'model': 'account.balance.full.report', 'form': data } self._check_state(cr, uid, ids, context=context) return { 'type': 'ir.actions.report.xml', 'report_name': 'account.balance.full.report.wzd', 'datas': datas }
class res_company(osv.osv): _name = "res.company" _description = 'Companies' _order = 'name' def _get_address_data(self, cr, uid, ids, field_names, arg, context=None): """ Read the 'address' functional fields. """ result = {} part_obj = self.pool.get('res.partner') for company in self.browse(cr, uid, ids, context=context): result[company.id] = {}.fromkeys(field_names, False) if company.partner_id: address_data = part_obj.address_get(cr, openerp.SUPERUSER_ID, [company.partner_id.id], adr_pref=['default']) if address_data['default']: address = part_obj.read(cr, openerp.SUPERUSER_ID, address_data['default'], field_names, context=context) for field in field_names: result[company.id][field] = address[field] or False return result def _set_address_data(self, cr, uid, company_id, name, value, arg, context=None): """ Write the 'address' functional fields. """ company = self.browse(cr, uid, company_id, context=context) if company.partner_id: part_obj = self.pool.get('res.partner') address_data = part_obj.address_get(cr, uid, [company.partner_id.id], adr_pref=['default']) address = address_data['default'] if address: part_obj.write(cr, uid, [address], {name: value or False}) else: part_obj.create(cr, uid, { name: value or False, 'parent_id': company.partner_id.id }, context=context) return True _columns = { 'name': fields.related('partner_id', 'name', string='Company Name', size=128, required=True, store=True, type='char'), 'parent_id': fields.many2one('res.company', 'Parent Company', select=True), 'child_ids': fields.one2many('res.company', 'parent_id', 'Child Companies'), 'partner_id': fields.many2one('res.partner', 'Partner', required=True), 'rml_header': fields.text('RML Header', required=True), 'rml_header1': fields.char( 'Company Slogan', size=200, help= "Appears by default on the top right corner of your printed documents (report header)." ), 'rml_header2': fields.text('RML Internal Header', required=True), 'rml_header3': fields.text('RML Internal Header for Landscape Reports', required=True), 'rml_footer': fields.text( 'Report Footer', help="Footer text displayed at the bottom of all reports."), 'rml_footer_readonly': fields.related('rml_footer', type='text', string='Report Footer', readonly=True), 'custom_footer': fields.boolean( 'Custom Footer', help= "Check this to define the report footer manually. Otherwise it will be filled in automatically." ), 'logo': fields.related('partner_id', 'image', string="Logo", type="binary"), 'currency_id': fields.many2one('res.currency', 'Currency', required=True), 'currency_ids': fields.one2many('res.currency', 'company_id', 'Currency'), 'user_ids': fields.many2many('res.users', 'res_company_users_rel', 'cid', 'user_id', 'Accepted Users'), 'account_no': fields.char('Account No.', size=64), 'street': fields.function(_get_address_data, fnct_inv=_set_address_data, size=128, type='char', string="Street", multi='address'), 'street2': fields.function(_get_address_data, fnct_inv=_set_address_data, size=128, type='char', string="Street2", multi='address'), 'zip': fields.function(_get_address_data, fnct_inv=_set_address_data, size=24, type='char', string="Zip", multi='address'), 'city': fields.function(_get_address_data, fnct_inv=_set_address_data, size=24, type='char', string="City", multi='address'), 'state_id': fields.function(_get_address_data, fnct_inv=_set_address_data, type='many2one', domain="[('country_id', '=', country_id)]", relation='res.country.state', string="Fed. State", multi='address'), 'bank_ids': fields.one2many('res.partner.bank', 'company_id', 'Bank Accounts', help='Bank accounts related to this company'), 'country_id': fields.function(_get_address_data, fnct_inv=_set_address_data, type='many2one', relation='res.country', string="Country", multi='address'), 'email': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Email", multi='address'), 'phone': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Phone", multi='address'), 'fax': fields.function(_get_address_data, fnct_inv=_set_address_data, size=64, type='char', string="Fax", multi='address'), 'website': fields.related('partner_id', 'website', string="Website", type="char", size=64), 'vat': fields.related('partner_id', 'vat', string="Tax ID", type="char", size=32), 'company_registry': fields.char('Company Registry', size=64), 'paper_format': fields.selection([('a4', 'A4'), ('us_letter', 'US Letter')], "Paper Format", required=True), } _sql_constraints = [('name_uniq', 'unique (name)', 'The company name must be unique !')] def onchange_footer(self, cr, uid, ids, custom_footer, phone, fax, email, website, vat, company_registry, bank_ids, context=None): if custom_footer: return {} # first line (notice that missing elements are filtered out before the join) res = ' | '.join( filter(bool, [ phone and '%s: %s' % (_('Phone'), phone), fax and '%s: %s' % (_('Fax'), fax), email and '%s: %s' % (_('Email'), email), website and '%s: %s' % (_('Website'), website), vat and '%s: %s' % (_('TIN'), vat), company_registry and '%s: %s' % (_('Reg'), company_registry), ])) # second line: bank accounts res_partner_bank = self.pool.get('res.partner.bank') account_data = self.resolve_2many_commands(cr, uid, 'bank_ids', bank_ids, context=context) account_names = res_partner_bank._prepare_name_get(cr, uid, account_data, context=context) if account_names: title = _('Bank Accounts') if len(account_names) > 1 else _( 'Bank Account') res += '\n%s: %s' % (title, ', '.join( name for id, name in account_names)) return {'value': {'rml_footer': res, 'rml_footer_readonly': res}} def on_change_country(self, cr, uid, ids, country_id, context=None): currency_id = self._get_euro(cr, uid, context=context) if country_id: currency_id = self.pool.get('res.country').browse( cr, uid, country_id, context=context).currency_id.id return {'value': {'currency_id': currency_id}} def _search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None): if context is None: context = {} if context.get('user_preference'): # We browse as superuser. Otherwise, the user would be able to # select only the currently visible companies (according to rules, # which are probably to allow to see the child companies) even if # she belongs to some other companies. user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context) cmp_ids = list( set([user.company_id.id] + [cmp.id for cmp in user.company_ids])) return cmp_ids return super(res_company, self)._search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count, access_rights_uid=access_rights_uid) def _company_default_get(self, cr, uid, object=False, field=False, context=None): """ Check if the object for this company have a default value """ if not context: context = {} proxy = self.pool.get('multi_company.default') args = [ ('object_id.model', '=', object), ('field_id', '=', field), ] ids = proxy.search(cr, uid, args, context=context) user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context) for rule in proxy.browse(cr, uid, ids, context): if eval(rule.expression, {'context': context, 'user': user}): return rule.company_dest_id.id return user.company_id.id @tools.ormcache() def _get_company_children(self, cr, uid=None, company=None): if not company: return [] ids = self.search(cr, uid, [('parent_id', 'child_of', [company])]) return ids def _get_partner_hierarchy(self, cr, uid, company_id, context=None): if company_id: parent_id = self.browse(cr, uid, company_id)['parent_id'] if parent_id: return self._get_partner_hierarchy(cr, uid, parent_id.id, context) else: return self._get_partner_descendance(cr, uid, company_id, [], context) return [] def _get_partner_descendance(self, cr, uid, company_id, descendance, context=None): descendance.append(self.browse(cr, uid, company_id).partner_id.id) for child_id in self._get_company_children(cr, uid, company_id): if child_id != company_id: descendance = self._get_partner_descendance( cr, uid, child_id, descendance) return descendance # # This function restart the cache on the _get_company_children method # def cache_restart(self, cr): self._get_company_children.clear_cache(self) def create(self, cr, uid, vals, context=None): if not vals.get('name', False) or vals.get('partner_id', False): self.cache_restart(cr) return super(res_company, self).create(cr, uid, vals, context=context) obj_partner = self.pool.get('res.partner') partner_id = obj_partner.create(cr, uid, { 'name': vals['name'], 'is_company': True, 'image': vals.get('logo', False) }, context=context) vals.update({'partner_id': partner_id}) self.cache_restart(cr) company_id = super(res_company, self).create(cr, uid, vals, context=context) obj_partner.write(cr, uid, partner_id, {'company_id': company_id}, context=context) return company_id def write(self, cr, uid, ids, values, context=None): self.cache_restart(cr) return super(res_company, self).write(cr, uid, ids, values, context=context) def _get_euro(self, cr, uid, context=None): rate_obj = self.pool.get('res.currency.rate') rate_id = rate_obj.search(cr, uid, [('rate', '=', 1)], context=context) return rate_id and rate_obj.browse( cr, uid, rate_id[0], context=context).currency_id.id or False def _get_logo(self, cr, uid, ids): return open( os.path.join(tools.config['root_path'], 'addons', 'base', 'res', 'res_company_logo.png'), 'rb').read().encode('base64') _header = """ <header> <pageTemplate> <frame id="first" x1="28.0" y1="28.0" width="%s" height="%s"/> <pageGraphics> <fill color="black"/> <stroke color="black"/> <setFont name="DejaVu Sans" size="8"/> <drawString x="%s" y="%s"> [[ formatLang(time.strftime("%%Y-%%m-%%d"), date=True) ]] [[ time.strftime("%%H:%%M") ]]</drawString> <setFont name="DejaVu Sans Bold" size="10"/> <drawCentredString x="%s" y="%s">[[ company.partner_id.name ]]</drawCentredString> <stroke color="#000000"/> <lines>%s</lines> </pageGraphics> </pageTemplate> </header>""" _header2 = _header % (539, 772, "1.0cm", "28.3cm", "11.1cm", "28.3cm", "1.0cm 28.1cm 20.1cm 28.1cm") _header3 = _header % (786, 525, 25, 555, 440, 555, "25 550 818 550") def _get_header(self, cr, uid, ids): try: header_file = tools.file_open( os.path.join('base', 'report', 'corporate_rml_header.rml')) try: return header_file.read() finally: header_file.close() except: return self._header_a4 _header_main = """ <header> <pageTemplate> <frame id="first" x1="1.3cm" y1="3.0cm" height="%s" width="19.0cm"/> <stylesheet> <paraStyle name="main_footer" fontName="DejaVu Sans" fontSize="8.0" alignment="CENTER"/> <paraStyle name="main_header" fontName="DejaVu Sans" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> </stylesheet> <pageGraphics> <!-- You Logo - Change X,Y,Width and Height --> <image x="1.3cm" y="%s" height="40.0" >[[ company.logo or removeParentNode('image') ]]</image> <setFont name="DejaVu Sans" size="8"/> <fill color="black"/> <stroke color="black"/> <!-- page header --> <lines>1.3cm %s 20cm %s</lines> <drawRightString x="20cm" y="%s">[[ company.rml_header1 ]]</drawRightString> <drawString x="1.3cm" y="%s">[[ company.partner_id.name ]]</drawString> <place x="1.3cm" y="%s" height="1.55cm" width="15.0cm"> <para style="main_header">[[ display_address(company.partner_id) or '' ]]</para> </place> <drawString x="1.3cm" y="%s">Phone:</drawString> <drawRightString x="7cm" y="%s">[[ company.partner_id.phone or '' ]]</drawRightString> <drawString x="1.3cm" y="%s">Mail:</drawString> <drawRightString x="7cm" y="%s">[[ company.partner_id.email or '' ]]</drawRightString> <lines>1.3cm %s 7cm %s</lines> <!-- left margin --> <rotate degrees="90"/> <fill color="grey"/> <drawString x="2.65cm" y="-0.4cm">produced by OpenERP.com</drawString> <fill color="black"/> <rotate degrees="-90"/> <!--page bottom--> <lines>1.2cm 2.65cm 19.9cm 2.65cm</lines> <place x="1.3cm" y="0cm" height="2.55cm" width="19.0cm"> <para style="main_footer">[[ company.rml_footer ]]</para> <para style="main_footer">Contact : [[ user.name ]] - Page: <pageNumber/></para> </place> </pageGraphics> </pageTemplate> </header>""" _header_a4 = _header_main % ( '23.0cm', '27.6cm', '27.7cm', '27.7cm', '27.8cm', '27.4cm', '25.8cm', '26.0cm', '26.0cm', '25.6cm', '25.6cm', '25.5cm', '25.5cm') _header_letter = _header_main % ( '21.3cm', '25.9cm', '26.0cm', '26.0cm', '26.1cm', '25.5cm', '25.1cm', '24.3cm', '24.3cm', '23.9cm', '23.9cm', '23.8cm', '23.8cm') def onchange_paper_format(self, cr, uid, ids, paper_format, context=None): if paper_format == 'us_letter': return {'value': {'rml_header': self._header_letter}} return {'value': {'rml_header': self._header_a4}} _defaults = { 'currency_id': _get_euro, 'paper_format': 'a4', 'rml_header': _get_header, 'rml_header2': _header2, 'rml_header3': _header3, 'logo': _get_logo } _constraints = [ (osv.osv._check_recursion, 'Error! You can not create recursive companies.', ['parent_id']) ]
class crm_phonecall_report(osv.osv): """ Phone calls by user and section """ _name = "crm.phonecall.report" _description = "Phone calls by user and section" _auto = False _columns = { 'name': fields.char('Year', size=64, required=False, readonly=True), 'user_id':fields.many2one('res.users', 'User', readonly=True), 'section_id':fields.many2one('crm.case.section', 'Section', readonly=True), 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), 'nbr': fields.integer('# of Cases', readonly=True), 'state': fields.selection(AVAILABLE_STATES, 'Status', size=16, readonly=True), 'month':fields.selection([('01', 'January'), ('02', 'February'), \ ('03', 'March'), ('04', 'April'),\ ('05', 'May'), ('06', 'June'), \ ('07', 'July'), ('08', 'August'),\ ('09', 'September'), ('10', 'October'),\ ('11', 'November'), ('12', 'December')], 'Month', readonly=True), 'create_date': fields.datetime('Create Date', readonly=True, select=True), 'day': fields.char('Day', size=128, readonly=True), 'delay_close': fields.float('Delay to close', digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to close the case"), 'duration': fields.float('Duration', digits=(16,2),readonly=True, group_operator="avg"), 'delay_open': fields.float('Delay to open',digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to open the case"), 'categ_id': fields.many2one('crm.case.categ', 'Category', \ domain="[('section_id','=',section_id),\ ('object_id.model', '=', 'crm.phonecall')]" ), 'partner_id': fields.many2one('res.partner', 'Partner' , readonly=True), 'company_id': fields.many2one('res.company', 'Company', readonly=True), 'opening_date': fields.date('Opening Date', readonly=True, select=True), 'creation_date': fields.date('Creation Date', readonly=True, select=True), 'date_closed': fields.date('Close Date', readonly=True, select=True), } def init(self, cr): """ Phone Calls By User And Section @param cr: the current row, from the database cursor, """ tools.drop_view_if_exists(cr, 'crm_phonecall_report') cr.execute(""" create or replace view crm_phonecall_report as ( select id, to_char(c.date, 'YYYY') as name, to_char(c.date, 'MM') as month, to_char(c.date, 'YYYY-MM-DD') as day, to_char(c.create_date, 'YYYY-MM-DD') as creation_date, to_char(c.date_open, 'YYYY-MM-DD') as opening_date, to_char(c.date_closed, 'YYYY-mm-dd') as date_closed, c.state, c.user_id, c.section_id, c.categ_id, c.partner_id, c.duration, c.company_id, c.priority, 1 as nbr, date_trunc('day',c.create_date) as create_date, extract('epoch' from (c.date_closed-c.create_date))/(3600*24) as delay_close, extract('epoch' from (c.date_open-c.create_date))/(3600*24) as delay_open from crm_phonecall c )""")
class order_requisition_delivery_line(osv.osv): def _get_qty_available(self, cr, uid, ids, field_name, args, context={}): res = {} for item in self.browse(cr, uid, ids, context=context): move = self.pool.get('purchase.order.line').search( cr, uid, [('line_pb_general_id', '=', item.id)]) hasil = 0 for data in self.pool.get('purchase.order.line').browse( cr, uid, move): hasil += data.received_items - data.supplied_items res[item.id] = hasil return res _name = 'order.requisition.delivery.line' _columns = { 'name': fields.many2one('product.product', "Product", required=False, select=True), 'order_requisition_delivery_id': fields.many2one('order.requisition.delivery', 'Order Requisition Delivery', required=False, ondelete='cascade', change_default=True), 'purchase_requisition_id': fields.many2one('pembelian.barang', 'PB No', required=False, ondelete='cascade', select=True, domain=[('state', '=', 'purchase')]), 'purchase_requisition_line_id': fields.many2one('detail.pb', 'Detail PB', required=False, ondelete='cascade', select=True), 'product_id': fields.related('purchase_requisition_line_id', 'name', type='many2one', relation='product.product', string='Item PB'), 'desc': fields.text('Description', required=False), 'move_id': fields.many2one('stock.move', 'Stock Move', required=False, ondelete='cascade'), 'qty_delivery': fields.float('Qty To Send', required=False, readonly=False), 'qty': fields.float('Qty Items', required=False, readonly=False), 'received_items_po': fields.float(string="Received Items", readonly=False), 'uom_id': fields.many2one('product.uom', 'UOM', required=False), 'qty_available': fields.function(_get_qty_available, string="Qty Available", type="float", store=True), 'picked_po': fields.one2many('order.requisition.delivery.line.po', 'order_requisition_delivery_line_id', 'Picking PO'), 'notes': fields.text('Notes'), 'state': fields.selection([ ('draft', 'Draft'), ('confirmed', 'Confirmed'), ('approved', 'Approved'), ('done', 'Done'), ], 'State'), } _defaults = { 'state': 'draft', } def cek_qty_delivery(self, cr, uid, ids, qty_available, qty_delivery, product_id, context=None): res = {} line = [] if qty_delivery > qty_available: warning = { "title": ("Warning"), "message": ("Product Item Delivery Tidak Mencukupi") } return {'warning': warning, 'value': {'qty_delivery': 0}} else: cek = self.pool.get('purchase.order.line').search( cr, uid, [('line_pb_general_id', '=', product_id)]) data = self.pool.get('purchase.order.line').browse(cr, uid, cek) cek_available = qty_delivery for x in data: if x.qty_available_to_pick == cek_available: qty = cek_available if cek_available > 0: line.append({ 'po_id': x.order_id.id, 'po_line_id': x.id, 'po_line_product_id': x.product_id.id, 'po_line_description': x.name, 'po_line_qty': x.product_qty, 'po_line_received_items': x.received_items, 'po_line_available_to_pick': x.qty_available_to_pick, 'qty': qty, 'uom_id': x.product_uom.id }) cek_available -= cek_available elif x.qty_available_to_pick < cek_available: if x.qty_available_to_pick > 0: qty = x.qty_available_to_pick if cek_available > 0: line.append({ 'po_id': x.order_id.id, 'po_line_id': x.id, 'po_line_product_id': x.product_id.id, 'po_line_description': x.name, 'po_line_qty': x.product_qty, 'po_line_received_items': x.received_items, 'po_line_available_to_pick': x.qty_available_to_pick, 'qty': qty, 'uom_id': x.product_uom.id }) cek_available -= x.qty_available_to_pick elif x.qty_available_to_pick > cek_available: qty = cek_available if cek_available > 0: line.append({ 'po_id': x.order_id.id, 'po_line_id': x.id, 'po_line_product_id': x.product_id.id, 'po_line_description': x.name, 'po_line_qty': x.product_qty, 'po_line_received_items': x.received_items, 'po_line_available_to_pick': x.qty_available_to_pick, 'qty': qty, 'uom_id': x.product_uom.id }) cek_available -= cek_available else: qty = 0 res['picked_po'] = line return {'value': res} def cek_detail_pb(self, cr, uid, ids, purchase_requisition_id, context=None): cek = self.pool.get('detail.pb').search( cr, uid, [('detail_pb_id', '=', purchase_requisition_id)]) hasil = self.pool.get('detail.pb').browse(cr, uid, cek) if hasil: # Cek Detail PB yang Prosesd Item lebih dari 0 (Sudah di Proses di PO) product = [ x.name.id for x in hasil if x.jumlah_diminta <> x.delivery_items ] res = {'domain': {'product_id': [('id', 'in', tuple(product))]}} else: res = { 'warning': { 'title': 'Informasi', 'message': 'Items PB Belum ada yang di terima' } } return res def cek_item_pb(self, cr, uid, ids, product_id, purchase_requisition_id, context=None): print '=====', product_id if product_id: res = {} line = [] # item_pb=self.pool.get('detail.pb').search(cr,uid,[('id','=',product_id)]) item_pb = self.pool.get('detail.pb').search( cr, uid, [('name', '=', product_id), ('detail_pb_id', '=', purchase_requisition_id)]) item = self.pool.get('detail.pb').browse(cr, uid, item_pb)[0] cek = self.pool.get('purchase.order.line').search( cr, uid, [('line_pb_general_id', '=', item.id)]) data = self.pool.get('purchase.order.line').browse(cr, uid, cek) qty_available = 0 for x in data: if x.qty_available_to_pick > 0: line.append({ 'po_id': x.order_id.id, 'po_line_id': x.id, 'po_line_product_id': x.product_id.id, 'po_line_description': x.name, 'po_line_qty': x.product_qty, 'po_line_received_items': x.received_items, 'po_line_available_to_pick': x.qty_available_to_pick, 'qty': 0, 'uom_id': x.product_uom.id }) qty_available += x.qty_available_to_pick res['picked_po'] = line res['desc'] = item.name.name res['uom_id'] = item.satuan.id res['qty_delivery'] = 0 res['qty_available'] = qty_available res['purchase_requisition_line_id'] = item.id return {'value': res} def onchange_product(self, cr, uid, ids, productID, context=None): cek = self.pool.get('purchase.order.line').search( cr, uid, [('product_id', '=', productID), ('state', '=', 'confirmed')]) hasil = self.pool.get('purchase.order.line').browse(cr, uid, cek) for x in hasil: if x.received_items > 0: product = [x.id] else: product = [] return {'domain': {'po_line_id': [('id', 'in', tuple(product))]}} def onchange_po_line(self, cr, uid, ids, poLine, context=None): data = self.pool.get('purchase.order.line').browse(cr, uid, poLine) cek = self.pool.get('order.requisition.delivery.line').search( cr, uid, [('purchase_requisition_line_id', '=', data.line_pb_general_id.id), ('state', '=', 'done')]) hasil = self.pool.get('order.requisition.delivery.line').browse( cr, uid, cek) nilai = 0 for x in hasil: nilai += x.qty_delivery return { 'value': { 'po_id': data.order_id.id, 'purchase_requisition_line_id': data.line_pb_general_id.id, 'desc': data.name, 'qty_delivery': data.received_items - nilai, 'qty': data.product_qty, 'uom_id': data.product_uom.id, 'received_items_po': data.received_items - nilai, } } def onchange_delivery(self, cr, uid, ids, qty1, qty2, context=None): if qty1 > qty2: warning = { "title": ("Warning"), "message": ("Product Item Delivery Tidak Mencukupi") } return {'warning': warning, 'value': {'qty_delivery': 0}} else: return False
class order_requisition_delivery(osv.osv): def _get_pr_names(self, cr, uid, ids, field_name, args, context={}): res = {} for item in self.browse(cr, uid, ids, context=context): move = self.pool.get('order.requisition.delivery.line').search( cr, uid, [('order_requisition_delivery_id', '=', item.id)]) line = [ data.purchase_requisition_id.name[:5] for data in self.pool.get( 'order.requisition.delivery.line').browse(cr, uid, move) ] hasil = '' for x in set(line): hasil += x + ', ' res[item.id] = hasil return res _name = 'order.requisition.delivery' _columns = { 'name': fields.char('Refference', required=True, readonly=False, size=64, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'source_location': fields.many2one('stock.location', "Source Location", required=True, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'destination_location_id': fields.many2one('stock.location', "Destination Location", required=True, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'date': fields.date('Date', required=True, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'pr_names': fields.function(_get_pr_names, string="PR Names", type="char", store=False, readonly=False, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'notes': fields.text('Date', required=False, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'lines': fields.one2many('order.requisition.delivery.line', 'order_requisition_delivery_id', 'Lines', readonly=False, states={ 'confirmed': [('readonly', True)], 'approved': [('readonly', True)], 'done': [('readonly', True)] }), 'state': fields.selection([ ('draft', 'Draft'), ('confirmed', 'Wait For Approve'), ('approved', 'Ready To Transfer'), ('done', 'Received'), ], 'State'), 'picking_id': fields.many2one('stock.picking', "Stock Picking", required=False, readonly=True), 'prepare_by': fields.many2one('res.users', string="Prepare", ondelete="CASCADE", onupdate='CASCADE', readonly=True), 'confirmed_by': fields.many2one('res.users', string="Confirmed", ondelete="CASCADE", onupdate='CASCADE', readonly=True), 'approved_by': fields.many2one('res.users', string="Approved", ondelete="CASCADE", onupdate='CASCADE', readonly=True), 'received_by': fields.many2one('res.users', string="Received", ondelete="CASCADE", onupdate='CASCADE', readonly=True), } _inherit = ['mail.thread'] _track = { 'note': {}, 'state': { 'sbm_order_requisition_delivery.ord_pack_confirm': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'confirmed', 'sbm_order_requisition_delivery.ord_pack_approved': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'approved', 'sbm_order_requisition_delivery.ord_pack_done': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'done', 'sbm_order_requisition_delivery.ord_pack_draft': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'draft', }, } _defaults = { 'name': '/', 'state': 'draft', 'date': time.strftime('%Y-%m-%d'), } def create(self, cr, uid, vals, context={}): vals['name'] = self.pool.get('ir.sequence').get( cr, uid, 'order.requisition.delivery') offer_id = super(order_requisition_delivery, self).create(cr, uid, vals, context=context) order = self.browse(cr, uid, offer_id, context=context) or [] lines = self.pool.get('order.requisition.delivery.line').search( cr, uid, [('order_requisition_delivery_id', '=', order.id)]) for x in self.pool.get('order.requisition.delivery.line').browse( cr, uid, lines): if x.qty_delivery == 0: raise osv.except_osv(('Warning !!!'), ('Qty To Send Can Not "0"')) return offer_id def def_confirmed(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, { 'state': 'confirmed', 'confirmed_by': uid }) def def_approved(self, cr, uid, ids, context=None): val = self.browse(cr, uid, ids)[0] return self.write(cr, uid, ids, { 'state': 'approved', 'approved_by': uid }) def def_validate(self, cr, uid, ids, context=None): val = self.browse(cr, uid, ids)[0] if val.source_location.id == val.destination_location_id.id: raise osv.except_osv( _('Warning!'), _('Tujuan dan Sumber Pengiriman,\n Tidak Boleh sama')) else: stock_picking = self.pool.get("stock.picking") stock_move = self.pool.get('stock.move') picking_type = 'out' seq_obj_name = 'stock.picking.' + picking_type picking = stock_picking.create( cr, uid, { 'name': self.pool.get('ir.sequence').get( cr, uid, seq_obj_name), 'origin': val.name, 'state': 'done' }) for line in val.lines: move_id = stock_move.create( cr, uid, { 'name': self.pool.get('ir.sequence').get( cr, uid, seq_obj_name), 'product_id': line.product_id.id, 'product_qty': line.qty_delivery, 'product_uom': line.uom_id.id, 'location_id': val.source_location.id, 'location_dest_id': val.destination_location_id.id, 'picking_id': picking, 'state': 'done' }, context=context) self.pool.get('order.requisition.delivery.line').write( cr, uid, line.id, {'state': 'done'}, context=context) self.pool.get('order.requisition.delivery').write( cr, uid, ids, {'state': 'done'}, context=context) return self.write(cr, uid, ids, { 'state': 'done', 'picking_id': picking, 'received_by': uid }) def def_draft(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'draft'})
""" unity = self.get(category_id__name='Duration', _object='product.uom') if not unity: _logger.warning("It seems that there isn't a reference unity in the 'Duration' UoM category. " "Please check that the category exists, and there's a refernce unity.") return unity.id if unity else False _name = 'product.product' _inherit = 'product.product' _columns = { 'can_be_rent' : fields.boolean('Can be rented', help='Enable this if you want to rent this product.'), 'rent_price' : fields.float('Rent price', help= 'The price is expressed for the duration unity defined in the company configuration.'), 'rent_price_unity' : fields.many2one('product.uom', 'Rent Price Unity', domain=[('category_id.name', '=', 'Duration')], help='Rent duration unity in which the price is defined.'), } _defaults = { 'can_be_rent' : True, 'rent_price' : 0, 'rent_price_unity' : default_price_unity, } _constraints = [(check_rent_price, _('The Rent price must be a positive value or 0 for free service or product.'), ['rent_price']),] Product()
class report_mrp_planning(osv.osv_memory): _name = 'report.mrp.planning' _columns = { 'workcenter_id': fields.many2one('mrp.workcenter', 'Nguồn Lưc Tham Gia', required=True), 'from_date': fields.datetime('Từ Ngày(Giờ)', required=True), 'to_date': fields.datetime('Đến Ngày(Giờ)', required=True), 'congdoan_id': fields.many2one('mrp.congdoan', 'Công Đoạn', required=True), 'congdoan': fields.selection([('thoi', 'Thổi'), ('chia', 'Chia'), ('ghep', 'Ghép'), ('in', 'In'), ('tui', 'Làm túi')], 'Công đoạn'), } _defaults = { 'from_date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), 'to_date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), } def onchange_condgoan(self, cr, uid, ids, workcenter_id, context=None): if not workcenter_id: return workcenter_obj = self.pool.get('mrp.workcenter').browse( cr, uid, workcenter_id) return {'value': {'congdoan': workcenter_obj.type}} def onchange_workcenter(self, cr, uid, ids, congdoan_id, workcenter_id, context=None): domain = {} congdoan_obj = self.pool.get('mrp.congdoan').browse( cr, uid, congdoan_id) if congdoan_obj.type == 'in': workcenter_ids = self.pool.get('mrp.workcenter').search( cr, uid, [('type', '=', 'in')]) if workcenter_ids: domain.update({'workcenter_id': [('id', '=', workcenter_ids)]}) if congdoan_obj.type in ('ghep', 'ghep2', 'ghep3', 'ghep4'): workcenter_ids = self.pool.get('mrp.workcenter').search( cr, uid, [('type', '=', 'ghep')]) if workcenter_ids: domain.update({'workcenter_id': [('id', '=', workcenter_ids)]}) if congdoan_obj.type == 'chia': workcenter_ids = self.pool.get('mrp.workcenter').search( cr, uid, [('type', '=', 'chia')]) if workcenter_ids: domain.update({'workcenter_id': [('id', '=', workcenter_ids)]}) if congdoan_obj.type == 'tui': workcenter_ids = self.pool.get('mrp.workcenter').search( cr, uid, [('type', '=', 'tui')]) if workcenter_ids: domain.update({'workcenter_id': [('id', '=', workcenter_ids)]}) if congdoan_obj.type == 'thoi': workcenter_ids = self.pool.get('mrp.workcenter').search( cr, uid, [('type', '=', 'thoi')]) if workcenter_ids: domain.update({'workcenter_id': [('id', '=', workcenter_ids)]}) return {'domain': domain} def print_inphieu(self, cr, uid, ids, context=None): datas = {'ids': context.get('active_ids', [])} datas['model'] = 'report.mrp.planning' datas['form'] = self.read(cr, uid, ids)[0] congdoan = datas['form'] and datas['form']['congdoan'] if congdoan and congdoan == 'thoi': report_name = 'trapaco_report_khsx_cd_thoi' if congdoan and congdoan == 'chia': report_name = 'trapaco_report_khsx_cd_chia' if congdoan and congdoan == 'in': report_name = 'trapaco_report_khsx_cd_in' if congdoan and congdoan == 'ghep': report_name = 'trapaco_report_khsx_cd_ghep' if congdoan and congdoan == 'tui': report_name = 'trapaco_report_khsx_cd_tui' return { 'type': 'ir.actions.report.xml', 'report_name': report_name, 'datas': datas }
'type': fields.selection([ ('payable','Payable'), ('receivable','Receivable'), ],'Type', readonly=True, select=True), # invisible field to filter payment order lines by payment type 'payment_type_name': fields.function(_payment_type_name_get, method=True, type="char", size=64, string="Payment type name"), # The field name is necessary to add attachement documents to payment orders 'name': fields.function(_name_get, method=True, type="char", size=64, string="Name"), 'create_account_moves': fields.selection([('bank-statement','Bank Statement'),('direct-payment','Direct Payment')], 'Create Account Moves', required=True, states={'done':[('readonly',True)]}, help='Indicates when account moves should be created for order payment lines. "Bank Statement" '\ 'will wait until user introduces those payments in bank a bank statement. "Direct Payment" '\ 'will mark all payment lines as payied once the order is done.'), 'period_id': fields.many2one('account.period', 'Period', states={'done':[('readonly',True)]}), } _defaults = { 'type': _get_type, 'reference': _get_reference, 'create_account_moves': lambda *a: 'bank-statement', 'period_id': _get_period, } def cancel_from_done(self, cr, uid, ids, context=None): if context is None: context = {} #Search for account_moves remove = [] for move in self.browse(cr,uid,ids,context):
class account_cash_statement(osv.osv): _inherit = 'account.bank.statement' _columns = { 'pos_session_id': fields.many2one('pos.session'), }
size=250), 'pem_subject':fields.char( ' Subject', size=200,), 'pem_body_text':fields.text( 'Standard Body (Text)'), 'pem_body_html':fields.text( 'Body (Text-Web Client Only)'), 'pem_attachments_ids':fields.many2many( 'ir.attachment', 'mail_attachments_rel', 'mail_id', 'att_id', 'Attachments'), 'pem_account_id' :fields.many2one( 'poweremail.core_accounts', 'User account', required=True), 'pem_user':fields.related( 'pem_account_id', 'user', type="many2one", relation="res.users", string="User"), 'server_ref':fields.integer( 'Server Reference of mail', help="Applicable for inward items only."), 'pem_recd':fields.char('Received at', size=50), 'mail_type':fields.selection([ ('multipart/mixed', 'Has Attachments'), ('multipart/alternative',
class via_form_templates(osv.osv): _name = 'via.form.templates' _description = 'Generic Template holder to be used for rendering Forms' def _get_output(self, cr, uid, context=None): _selections = [('pdf', 'PDF'), ('html', 'HTML')] return _selections def _get_engines(self, cr, uid, context=None): _selections = [('mako', 'Mako')] return _selections def _get_internal_name(self, cr, uid, ids, field, arg=None, context={}): res = {} for _obj in self.browse(cr, uid, ids, context=context): _internal_name = _obj.name _internal_name = re.sub(r'\s', r'_', _internal_name.strip().lower()) res[_obj.id] = _internal_name return res _columns = { 'name': fields.char('Name', size=64, readonly=False, required=True, select=True), 'internal_name': fields.function(_get_internal_name, method=True, string='Internal Name', type='char', size=64), 'model_id': fields.many2one( 'ir.model', 'Model', required=True, select=True, help="Model/object that the template is used to render."), 'model': fields.related('model_id', 'model', string='Object', type='char', size=64), 'active': fields.boolean('Active'), 'multi': fields.boolean( 'Allow Multi-Document', help="Whether this form can be printed for multiple documents."), 'tags': fields.text( 'Tags', select=True, help= "Free text that can be used to search/filter templates to use. Space will indicate separate tags." ), 'company_id': fields.many2one( 'res.company', 'Company', select=True, help="Specific company to which this template belongs to."), 'act_report_id': fields.many2one('ir.actions.report.xml', 'Report', readonly=True, help="External ID of the Report"), 'old_act_report_id': fields.many2one('ir.actions.report.xml', 'Report', readonly=True, help="Old External ID of the Report"), 'webkit_header': fields.property('ir.header_webkit', type='many2one', relation='ir.header_webkit', string='WebKit Header', help="The header linked to the report", method=True, view_load=True), 'engine': fields.selection(_get_engines, 'Engine', select=True, required=True, help="Engine used to render the template."), 'report_output': fields.selection(_get_output, 'Output', required=True), 'template': fields.text('Template'), } _defaults = { 'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse( cr, uid, uid, c).company_id.id, 'active': lambda *a: False, 'multi': lambda *a: False, 'engine': lambda *a: 'mako', 'report_output': lambda *a: 'pdf', 'old_act_report_id': lambda *a: False, } _sql_constraints = [ ('name_uniq', 'unique (name)', 'Name must be unique!'), ] def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): _active_set = False for _crit in args: _active_set = _active_set or (_crit[0] == 'active') if _active_set: break if not _active_set: args.extend([('active', '=', True)]) return super(via_form_templates, self).search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count) def copy(self, cr, uid, id, default={}, context=None): _obj = self.browse(cr, uid, id, context=context) if not default: default = {} default = default.copy() default['name'] = (_obj.name or '') + '(copy)' return super(via_form_templates, self).copy(cr, uid, id, default=default, context=context) def populate_values(self, cr, uid, vals, context=None): _vals = vals.copy() return _vals def create(self, cr, uid, vals, context=None): _vals = self.populate_values(cr, uid, vals, context=context) vals.update(_vals) return super(via_form_templates, self).create(cr, uid, vals, context=context) def write(self, cr, uid, ids, vals, context=None): _vals = self.populate_values(cr, uid, vals, context=context) vals.update(_vals) return super(via_form_templates, self).write(cr, uid, ids, vals, context=context) def activate(self, cr, uid, ids, context=None): _report_obj = self.pool.get('ir.actions.report.xml') _xml_obj = self.pool.get('ir.model.data') _rpt_vals = { 'report_type': 'webkit', 'auto': False, 'header': False, 'report_file': False, 'report_rml': False, } for _rpt in self.browse(cr, uid, ids, context=context): _vals = _rpt_vals.copy() _vals.update({ 'name': _rpt.name, 'report_name': _rpt.internal_name, 'model': _rpt.model, 'multi': not _rpt.multi, 'webkit_header': _rpt.webkit_header, 'report_webkit_data': _rpt.template, 'webkit_debug': bool(_rpt.report_output == 'html'), }) # Check if the report has old related report, if so, update that if _rpt.old_act_report_id: _rpt.old_act_report_id.write(_vals, context=context) _report_id = _rpt.old_act_report_id.id else: _report_id = _report_obj.create( cr, uid, _vals, context=context) or False if not _report_id: raise osv.except_osv( _('Error'), _("Report Action creation failed for Report %s!") % (_rpt.name)) _rpt.write({ 'active': True, 'act_report_id': _report_id }, context=context) # Register the report _iar = _report_obj.browse(cr, uid, _report_id, context=context) register_report(_iar.report_name, _iar.model, _iar.report_rml, parser=via_form_template_mako_parser, force_parser=True) return True def deactivate(self, cr, uid, ids, context=None): _ir_obj = self.pool.get('ir.model.data') for _rpt in self.browse(cr, uid, ids, context=context): # Update the ir_act_report_xml record so that it will not be processed by way of changing the report_type # Multi is set to false so that it wouldn't show in the right-side pane if _rpt.act_report_id: _rpt.act_report_id.write( { 'report_type': 'inactive', 'multi': False }, context=context) _rpt.write( { 'active': False, 'act_report_id': False, 'old_act_report_id': _rpt.act_report_id.id }, context=context) return True
class hr_action_reason_rule(osv.osv): _name = "hr.aa.action_reason_rule" _description = "Action Reason Rule" _columns = { 'name': fields.char("Name", size=64, required=True), 'active': fields.boolean('Active'), 'seq': fields.integer('Priority', required=True, help='Low values have' ' more priority'), 'rule': fields.text("Rule", required=True, help=_rule_help), 'action': fields.many2one('hr.action.reason', 'Action Reason', select=True), } _defaults = { 'rule': lambda *a: 'lambda a: False', 'seq': lambda *a: 10, } _sql_constraints = [('rule_name', 'UNIQUE (name)', 'The name of the rule must be unique')] _order = 'seq desc' def compute(self, cr, uid, ids, att_ids, context=None): """ Compute rules in to an attendance list """ att_pool = self.pool.get('hr.attendance') con_pool = self.pool.get('hr.contract') hol_pool = self.pool.get('hr.holidays') att_ids = att_pool.search(cr, uid, [('id', 'in', att_ids)], order='name asc') # TODO: Compile rules before iterate over attendances for att in att_pool.browse(cr, uid, att_ids, context=context): # # Define classes and functions: date, datetime, timedelta, time, dt, d # _r_globals = { 'date': tu.date, 'datetime': tu.datetime, 'timedelta': tu.timedelta, 'time': tu.time, 'total_hours': tu.total_hours, 'total_seconds': tu.total_seconds, 'dt': tu.dt, 'd': tu.d, } logger.notifyChannel( 'hr.aa.action_reason_rule', netsvc.LOG_DEBUG, 'Attendance to check %s (%s) with turn %s - %s' % (att.name, att.action, att.turn_start, att.turn_end)) action = False for rule in [ r for r in self.browse(cr, uid, ids) if r.action.action_type == att.action ]: code = rule.rule.strip() logger.notifyChannel('hr.aa.action_reason_rule', netsvc.LOG_DEBUG, 'Compiling (%s) %s' % (rule.name, code)) f = eval(code, _r_globals) A = Interface(cr, uid, self.pool, att.id, att._table_name) v = f(A) logger.notifyChannel('hr.aa.action_reason_rule', netsvc.LOG_DEBUG, 'Evaluating %s=%s' % (rule.name, v)) if att.action == rule.action.action_type and v: action = rule.action if action: logger.notifyChannel('hr.aa.action_reason_rule', netsvc.LOG_DEBUG, 'Selection %s' % action.name) att_pool.write(cr, uid, att.id, {'action_desc': action.id})
class product_percent_struct_costs(osv.osv_memory): """ Auxiliar object to associate percentually costs to products """ def onchange_product_id(self, cr, uid, ids, prev_fyear_id, prev_period_id, product_id): """ Gets total sales for this product, fiscal year and period """ res = {} total_sales = 0.0 sales_facade = self.pool.get('sale.order') fiscalyear = self.pool.get('account.fiscalyear').browse( cr, uid, prev_fyear_id) if not prev_period_id: from_date = fiscalyear.date_start to_date = fiscalyear.date_stop else: period = self.pool.get('account.period').browse( cr, uid, prev_period_id) from_date = period.date_start to_date = period.date_stop period_sales = sales_facade.browse( cr, uid, sales_facade.search(cr, uid, [('state', 'not in', ['draft', 'cancel']), ('date_order', '<=', to_date), ('date_order', '>=', from_date)])) for sale in period_sales: for line in sale.order_line: if line.product_id: if line.product_id.id == product_id: total_sales += line.product_uom_qty res['total_sales'] = total_sales res['forecasted_sales'] = total_sales return {'value': res} def onchange_total_sales(self, cr, uid, ids, total_sales): """ Refresh forecasted values according total sales """ res = {} if total_sales: res['forecasted_sales'] = total_sales else: res['forecasted_sales'] = 0.0 return {'value': res} _name = 'product.percent.struct.costs' _description = 'Structural products cost' _columns = { 'product_id': fields.many2one('product.product', 'Product', required=True), 'total_sales': fields.float('Sold Units', digits_compute=dp.get_precision('Account'), required=True), 'forecasted_sales': fields.float('Forecasted Sold Units', digits_compute=dp.get_precision('Account')), 'wizard_id': fields.many2one('structural.costs.impact.wizard', 'Wizard'), } _defaults = { 'wizard_id': lambda self, cr, uid, context: context.get('parent_id') and context[ 'parent_id'] or False, }
def _get_deferred_analytic_lines(self, cr, uid, ids, field_name, arg, context=None): res={} for expense in self.browse(cr, uid, ids): analytic_lines = [] for line in expense.line_ids: try: if line.deferred_line_ids: analytic_lines.extend([x.id for x in line.deferred_line_ids]) except orm.except_orm, e: if e.name != 'AccessError': raise e res[expense.id] = analytic_lines return res _columns={ 'deferred_analytics_id': fields.many2one('account.analytic.plan.instance', 'Deferred Analytic Distribution'), 'deferred_line_ids': fields.function(_get_deferred_analytic_lines, type='one2many', obj='account.analytic.line', method=True, string='Analytic Lines'), } def delete_analytic_lines(self, cr, uid, ids, context=None): analytic_line_obj = self.pool.get('account.analytic.line') for expense in self.browse(cr, uid, ids): for line in expense.deferred_line_ids: line.unlink() return True def create_analytic_lines(self, cr, uid, ids, context=None): analytic_line_obj = self.pool.get('account.analytic.line') journal_obj = self.pool.get('account.journal') expense_line_obj = self.pool.get('hr.expense.line')
class txt_iva(osv.osv): _name = "txt.iva" _order = 'date_end DESC' #~ _inherit = ['mail.thread'] def _get_amount_all(self, cr, uid, ids, field_name, arg, context=None): """ Return total amount withheld & base of each selected bill """ res = {} for item in self.browse(cr, uid, ids, context=context): amount_total_ret = 0 amount_total_base = 0 for txt_line in item.txt_ids: amount_total_ret += txt_line.amount_withheld amount_total_base += txt_line.untaxed res[item.id] = { 'amount_total_ret': amount_total_ret, 'amount_total_base': amount_total_base, } return res _columns = { 'name': fields.char('Description', 128, required=True, select=True, help="Description about statement of withholding income"), 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft': [('readonly', False)]}, help='Company'), 'state': fields.selection([('draft', 'Draft'), ('confirmed', 'Confirmed'), ('done', 'Done'), ('cancel', 'Cancelled')], 'Estado', select=True, readonly=True, help="proof status"), 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, states={'draft': [('readonly', False)]}, help='fiscal period'), 'type': fields.boolean('Retention Suppliers?', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Select the type of retention to make"), 'date_start': fields.date('Begin Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="Begin date of period"), 'date_end': fields.date('End date', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="End date of period"), 'txt_ids': fields.one2many( 'txt.iva.line', 'txt_id', readonly=True, states={'draft': [('readonly', False)]}, help='Txt field lines of ar required by SENIAT for VAT withholding' ), 'amount_total_ret': fields.function(_get_amount_all, method=True, digits=(16, 2), readonly=True, string='Withholding total amount', help="Monto Total Retenido", multi='all'), 'amount_total_base': fields.function(_get_amount_all, method=True, digits=(16, 2), readonly=True, string='Taxable total amount', help="Total de la Base Imponible", multi='all'), } _defaults = { 'state': lambda *a: 'draft', 'company_id': lambda self, cr, uid, context: \ self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id, 'type': lambda *a:True, 'period_id': lambda self,cr,uid,context: self.period_return(cr,uid,context), 'name':lambda self,cr,uid,context : 'Withholding Vat '+time.strftime('%m/%Y') } def period_return(self, cr, uid, context=None): """ Return current period """ context = context or {} period_obj = self.pool.get('account.period') fecha = time.strftime('%m/%Y') period_id = period_obj.search(cr, uid, [('code', '=', fecha)]) if period_id: return period_id[0] else: return False def name_get(self, cr, uid, ids, context=None): """ Return a list with id and name of the current register """ context = context or {} if not len(ids): return [] res = [(r['id'], r['name']) for r in self.read(cr, uid, ids, ['name'], context)] return res def action_anular(self, cr, uid, ids, context=None): """ Return document state to draft """ context = context or {} return self.write(cr, uid, ids, {'state': 'draft'}) def check_txt_ids(self, cr, uid, ids, context=None): """ Check that txt_iva has lines to process.""" context = context or {} ids = isinstance(ids, (int, long)) and [ids] or ids awi_brw = self.browse(cr, uid, ids[0], context=context) if not awi_brw.txt_ids: raise osv.except_osv(_("Missing Values !"), _("Missing VAT TXT Lines!!!")) return True def action_confirm(self, cr, uid, ids, context=None): """ Transfers the document status to confirmed """ context = context or {} self.check_txt_ids(cr, uid, ids, context=context) return self.write(cr, uid, ids, {'state': 'confirmed'}) def action_generate_lines_txt(self, cr, uid, ids, context=None): """ Current lines are cleaned and rebuilt """ context = context or {} rp_obj = self.pool.get('res.partner') voucher_obj = self.pool.get('account.wh.iva') txt_iva_obj = self.pool.get('txt.iva.line') voucher_ids = '' txt_brw = self.browse(cr, uid, ids[0]) txt_ids = txt_iva_obj.search(cr, uid, [('txt_id', '=', txt_brw.id)]) if txt_ids: txt_iva_obj.unlink(cr, uid, txt_ids) if txt_brw.type: draft_ids = voucher_obj.search( cr, uid, [('date_ret', '>=', txt_brw.date_start), ('date_ret', '<=', txt_brw.date_end), ('period_id', '=', txt_brw.period_id.id), ('state', '=', 'draft'), ('type', 'in', ['in_invoice', 'in_refund'])]) voucher_ids = voucher_obj.search( cr, uid, [('date_ret', '>=', txt_brw.date_start), ('date_ret', '<=', txt_brw.date_end), ('period_id', '=', txt_brw.period_id.id), ('state', '=', 'done'), ('type', 'in', ['in_invoice', 'in_refund'])]) else: draft_ids = voucher_obj.search( cr, uid, [('date_ret', '>=', txt_brw.date_start), ('date_ret', '<=', txt_brw.date_end), ('period_id', '=', txt_brw.period_id.id), ('state', '=', 'draft'), ('type', 'in', ['out_invoice', 'out_refund'])]) voucher_ids = voucher_obj.search( cr, uid, [('date_ret', '>=', txt_brw.date_start), ('date_ret', '<=', txt_brw.date_end), ('period_id', '=', txt_brw.period_id.id), ('state', '=', 'done'), ('type', 'in', ['out_invoice', 'out_refund'])]) if draft_ids: raise osv.except_osv( _('Error!'), _('Can\'t generate TXT lines while exists withholding ' + 'documents in draft for period')) for voucher in voucher_obj.browse(cr, uid, voucher_ids): acc_part_id = rp_obj._find_accounting_partner( voucher.third_party_id or voucher.partner_id) for voucher_lines in voucher.wh_lines: if voucher_lines.invoice_id.state not in ['open', 'paid']: continue for voucher_tax_line in voucher_lines.tax_line: data = { 'partner_id': acc_part_id.id, 'voucher_id': voucher.id, 'invoice_id': voucher_lines.invoice_id.id, 'txt_id': txt_brw.id, 'untaxed': voucher_tax_line.base, 'amount_withheld': voucher_tax_line.amount_ret, 'tax_wh_iva_id': voucher_tax_line.id, } if voucher_lines.invoice_id.type in ('in_refund', 'out_refund'): data.update({ 'untaxed': -voucher_tax_line.base, 'amount_withheld': -voucher_tax_line.amount_ret, }) txt_iva_obj.create(cr, uid, data) return True def action_done(self, cr, uid, ids, context=None): """ Transfer the document status to done """ context = context or {} root = self.generate_txt(cr, uid, ids) self._write_attachment(cr, uid, ids, root, context) self.write(cr, uid, ids, {'state': 'done'}) return True def get_type_document(self, cr, uid, txt_line): """ Return the document type @param txt_line: line of the current document """ type = '03' if txt_line.invoice_id.type in ['out_invoice', 'in_invoice']: type = '01' elif txt_line.invoice_id.type in ['out_invoice', 'in_invoice' ] and txt_line.invoice_id.parent_id: type = '02' return type def get_document_affected(self, cr, uid, txt_line, context=None): """ Return the reference or number depending of the case @param txt_line: line of the current document """ context = context or {} number = '0' if txt_line.invoice_id.type in ['in_invoice', 'in_refund' ] and txt_line.invoice_id.parent_id: number = txt_line.invoice_id.parent_id.supplier_invoice_number elif txt_line.invoice_id.parent_id: number = txt_line.invoice_id.parent_id.number return number def get_number(self, cr, uid, number, inv_type, long): """ Return a list of number for document number @param number: list of characters from number or reference of the bill @param inv_type: invoice type @param long: max size oh the number """ if not number: return '0' result = '' for i in number: if inv_type == 'vou_number' and i.isdigit(): if len(result) < long: result = i + result elif i.isalnum(): if len(result) < long: result = i + result return result[::-1].strip() def get_document_number(self, cr, uid, ids, txt_line, inv_type, context=None): """ Return the number o reference of the invoice into txt line @param txt_line: One line of the current txt document @param inv_type: invoice type into txt line """ context = context or {} number = 0 if txt_line.invoice_id.type in ['in_invoice', 'in_refund']: if not txt_line.invoice_id.supplier_invoice_number: raise osv.except_osv( _('Invalid action !'), _("Unable to make txt file, because the bill has no reference number free!" )) else: number = self.get_number( cr, uid, txt_line.invoice_id.supplier_invoice_number.strip(), inv_type, 20) elif txt_line.invoice_id.number: number = self.get_number(cr, uid, txt_line.invoice_id.number.strip(), inv_type, 20) return number def get_amount_exempt_document(self, cr, uid, txt_line): """ Return total amount not entitled to tax credit and the remaining amounts @param txt_line: One line of the current txt document """ tax = 0 amount_doc = 0 for tax_line in txt_line.invoice_id.tax_line: if 'SDCF' in tax_line.name or \ (tax_line.base and not tax_line.amount): tax = tax_line.base + tax else: amount_doc = tax_line.base + amount_doc return (abs(tax), abs(amount_doc)) def get_buyer_vendor(self, cr, uid, txt, txt_line): """ Return the buyer and vendor of the sale or purchase invoice @param txt: current txt document @param txt_line: One line of the current txt document """ rp_obj = self.pool.get('res.partner') vat_company = rp_obj._find_accounting_partner( txt.company_id.partner_id).vat[2:] vat_partner = rp_obj._find_accounting_partner( txt_line.partner_id).vat[2:] if txt_line.invoice_id.type in ['out_invoice', 'out_refund']: vendor = vat_company buyer = vat_partner else: buyer = vat_company vendor = vat_partner return (vendor, buyer) def get_max_aliquot(self, cr, uid, txt_line): """Get maximum aliquot per invoice""" list = [] for tax_line in txt_line.invoice_id.tax_line: list.append(int(tax_line.tax_id.amount * 100)) return max(list) def get_amount_line(self, cr, uid, txt_line, amount_exempt): """Method to compute total amount""" ali_max = self.get_max_aliquot(cr, uid, txt_line) exempt = 0 if ali_max == int(txt_line.tax_wh_iva_id.tax_id.amount * 100): exempt = amount_exempt total = txt_line.tax_wh_iva_id.base + txt_line.tax_wh_iva_id.amount + exempt return total, exempt def get_alicuota(self, cr, uid, txt_line): """ Return aliquot of the withholding into line @param txt_line: One line of the current txt document """ return int(txt_line.tax_wh_iva_id.tax_id.amount * 100) def generate_txt(self, cr, uid, ids, context=None): """ Return string with data of the current document """ context = context or {} txt_string = '' #~ rp_obj = self.pool.get('res.partner') for txt in self.browse(cr, uid, ids, context): #~ vat = rp_obj._find_accounting_partner(txt.company_id.partner_id).vat[2:] for txt_line in txt.txt_ids: vendor, buyer = self.get_buyer_vendor(cr, uid, txt, txt_line) #~ period = txt.period_id.name.split('/') period = txt.period_id.date_stop.split('-') period2 = period[0] + period[1] operation_type = 'V' if txt_line.invoice_id.type in [ 'out_invoice', 'out_refund' ] else 'C' document_type = self.get_type_document(cr, uid, txt_line) document_number = self.get_document_number( cr, uid, ids, txt_line, 'inv_number') control_number = self.get_number(cr, uid, txt_line.invoice_id.nro_ctrl, 'inv_ctrl', 20) document_affected = self.get_document_affected( cr, uid, txt_line) voucher_number = self.get_number(cr, uid, txt_line.voucher_id.number, 'vou_number', 14) amount_exempt, amount_untaxed = self.get_amount_exempt_document( cr, uid, txt_line) alicuota = self.get_alicuota(cr, uid, txt_line) amount_total, amount_exempt = self.get_amount_line( cr, uid, txt_line, amount_exempt) txt_string= txt_string + buyer +'\t'+period2.strip()+'\t'\ +txt_line.invoice_id.date_invoice+'\t'+operation_type+'\t'+document_type+'\t'+vendor+'\t'\ +document_number+'\t'+control_number+'\t'+str(round(amount_total,2))+'\t'\ +str(abs(round(txt_line.untaxed,2)))+'\t'\ +str(abs(round(txt_line.amount_withheld,2)))+'\t'+document_affected+'\t'+voucher_number+'\t'\ +str(round(amount_exempt,2))+'\t'+str(alicuota)+'\t'+'0'\ +'\r\n' return txt_string def _write_attachment(self, cr, uid, ids, root, context=None): """ Encrypt txt, save it to the db and view it on the client as an attachment @param root: location to save document """ context = context or {} fecha = time.strftime('%Y_%m_%d_%H%M') name = 'RET_IVA_' + fecha + '.' + 'txt' self.pool.get('ir.attachment').create( cr, uid, { 'name': name, 'datas': base64.encodestring(root), 'datas_fname': name, 'res_model': 'txt.iva', 'res_id': ids[0], }, context=context) cr.commit()
class view(osv.osv): _name = 'ir.ui.view' _columns = { 'name': fields.char('View Name',size=64, required=True), 'model': fields.char('Object', size=64, required=True), 'priority': fields.integer('Priority', required=True), 'type': fields.selection(( ('tree','Tree'), ('form','Form'), ('mdx','mdx'), ('graph', 'Graph'), ('calendar', 'Calendar'), ('diagram','Diagram'), ('gantt', 'Gantt'), ('search','Search')), 'View Type', required=True), 'arch': fields.text('View Architecture', required=True), 'inherit_id': fields.many2one('ir.ui.view', 'Inherited View', ondelete='cascade'), 'field_parent': fields.char('Child Field',size=64), 'xml_id': fields.function(osv.osv.get_xml_id, type='char', size=128, string="XML ID", method=True), } _defaults = { 'arch': '<?xml version="1.0"?>\n<tree string="My view">\n\t<field name="name"/>\n</tree>', 'priority': 16 } _order = "priority" _constraints = [ (_check_xml, 'Invalid XML for View Architecture!', ['arch']) ] def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'): if not isinstance(ids, (list, tuple)): ids = [ids] result = super(view, self).read(cr, uid, ids, fields, context, load) for rs in result: if rs.get('model') == 'board.board': cr.execute("select id,arch,ref_id from ir_ui_view_custom where user_id=%s and ref_id=%s", (uid, rs['id'])) oview = cr.dictfetchall() if oview: rs['arch'] = oview[0]['arch'] return result def write(self, cr, uid, ids, vals, context={}): if not isinstance(ids, (list, tuple)): ids = [ids] exist = self.pool.get('ir.ui.view').browse(cr, uid, ids[0]) if exist.model == 'board.board' and 'arch' in vals: vids = self.pool.get('ir.ui.view.custom').search(cr, uid, [('user_id','=',uid), ('ref_id','=',ids[0])]) vals2 = {'user_id': uid, 'ref_id': ids[0], 'arch': vals.pop('arch')} # write fields except arch to the `ir.ui.view` result = super(view, self).write(cr, uid, ids, vals, context) if not vids: self.pool.get('ir.ui.view.custom').create(cr, uid, vals2) else: self.pool.get('ir.ui.view.custom').write(cr, uid, vids, vals2) return result return super(view, self).write(cr, uid, ids, vals, context) def graph_get(self, cr, uid, id, model, node_obj, conn_obj, src_node, des_node,label,scale,context={}): if not label: label = [] nodes=[] nodes_name=[] transitions=[] start=[] tres={} labels={} no_ancester=[] blank_nodes = [] _Model_Obj=self.pool.get(model) _Node_Obj=self.pool.get(node_obj) _Arrow_Obj=self.pool.get(conn_obj) for model_key,model_value in _Model_Obj._columns.items(): if model_value._type=='one2many': if model_value._obj==node_obj: _Node_Field=model_key _Model_Field=model_value._fields_id flag=False for node_key,node_value in _Node_Obj._columns.items(): if node_value._type=='one2many': if node_value._obj==conn_obj: if src_node in _Arrow_Obj._columns and flag: _Source_Field=node_key if des_node in _Arrow_Obj._columns and not flag: _Destination_Field=node_key flag = True datas = _Model_Obj.read(cr, uid, id, [],context) for a in _Node_Obj.read(cr,uid,datas[_Node_Field],[]): if a[_Source_Field] or a[_Destination_Field]: nodes_name.append((a['id'],a['name'])) nodes.append(a['id']) else: blank_nodes.append({'id': a['id'],'name':a['name']}) if a.has_key('flow_start') and a['flow_start']: start.append(a['id']) else: if not a[_Source_Field]: no_ancester.append(a['id']) for t in _Arrow_Obj.read(cr,uid, a[_Destination_Field],[]): transitions.append((a['id'], t[des_node][0])) tres[str(t['id'])] = (a['id'],t[des_node][0]) label_string = "" if label: for lbl in eval(label): if t.has_key(str(lbl)) and str(t[lbl])=='False': label_string = label_string + ' ' else: label_string = label_string + " " + t[lbl] labels[str(t['id'])] = (a['id'],label_string) g = graph(nodes, transitions, no_ancester) g.process(start) g.scale(*scale) result = g.result_get() results = {} for node in nodes_name: results[str(node[0])] = result[node[0]] results[str(node[0])]['name'] = node[1] return {'nodes': results, 'transitions': tres, 'label' : labels, 'blank_nodes': blank_nodes}
class crm_lead2partner(osv.osv_memory): """ Converts lead to partner """ _name = 'crm.lead2partner' _description = 'Lead to Partner' _columns = { 'action': fields.selection([('exist', 'Link to an existing partner'), \ ('create', 'Create a new partner')], \ 'Action', required=True), 'partner_id': fields.many2one('res.partner', 'Partner'), } def view_init(self, cr, uid, fields, context=None): """ This function checks for precondition before wizard executes """ if context is None: context = {} model = context.get('active_model') model = self.pool.get(model) rec_ids = context and context.get('active_ids', []) for this in model.browse(cr, uid, rec_ids, context=context): if this.partner_id: raise osv.except_osv(_('Warning !'), _('A partner is already defined.')) def _select_partner(self, cr, uid, context=None): if context is None: context = {} lead = self.pool.get('crm.lead') partner = self.pool.get('res.partner') lead_ids = list(context and context.get('active_ids', []) or []) if not len(lead_ids): return False this = lead.browse(cr, uid, lead_ids[0], context=context) # Find partner address matches the email_from of the lead res = lead.message_partner_by_email(cr, uid, this.email_from, context=context) partner_id = res.get('partner_id', False) # Find partner name that matches the name of the lead if not partner_id and this.partner_name: partner_ids = partner.search(cr, uid, [('name', '=', this.partner_name)], context=context) if partner_ids and len(partner_ids): partner_id = partner_ids[0] return partner_id def default_get(self, cr, uid, fields, context=None): """ This function gets default values """ res = super(crm_lead2partner, self).default_get(cr, uid, fields, context=context) partner_id = self._select_partner(cr, uid, context=context) if 'partner_id' in fields: res.update({'partner_id': partner_id}) if 'action' in fields: res.update({'action': partner_id and 'exist' or 'create'}) return res def open_create_partner(self, cr, uid, ids, context=None): """ This function Opens form of create partner. """ view_obj = self.pool.get('ir.ui.view') view_id = view_obj.search(cr, uid, [('model', '=', self._name), \ ('name', '=', self._name+'.view')]) return { 'view_mode': 'form', 'view_type': 'form', 'view_id': view_id or False, 'res_model': self._name, 'context': context, 'type': 'ir.actions.act_window', 'target': 'new', } def _create_partner(self, cr, uid, ids, context=None): """ This function Creates partner based on action. """ if context is None: context = {} lead = self.pool.get('crm.lead') lead_ids = context and context.get('active_ids') or [] data = self.browse(cr, uid, ids, context=context)[0] partner_id = data.partner_id and data.partner_id.id or False partner_ids = lead.convert_partner(cr, uid, lead_ids, data.action, partner_id, context=context) return partner_ids[lead_ids[0]] def make_partner(self, cr, uid, ids, context=None): """ This function Makes partner based on action. """ partner_id = self._create_partner(cr, uid, ids, context=context) return self.pool.get('res.partner').redirect_partner_form( cr, uid, partner_id, context=context)
for i in sorted(self.imported_records): res_text+=i+': '+str(len(self.imported_records[i]))+'\n' self.imported_records.clear() self.warning_text = [] self.write(cr, uid, self_id, {'log':warning+res_text,'state':'done'}) return _columns = { 'name':fields.char('Name', size=64), 'date': fields.date('Date', required=True), 'import_model_ids':fields.many2many('migration.import_models', 'schedule_models_rel', 'schedule_id', 'import_model_id', 'Import Models'), 'actions_ids': fields.many2many('migration.model_actions', 'schedule_actions_rel', 'schedule_id', 'action_id', 'Actions'), 'state':fields.selection([('ready','Ready'),('running','Running'),('error','Error'),('done','Done'),('stop','Stopped')], 'State'), 'log': fields.text('Log'), 'print_log':fields.boolean('Print Log to Console'), 'cron_id':fields.many2one('ir.cron', 'Scheduler', readonly=True), } _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), 'state': lambda *a: 'ready', } def set_start(self, cr, uid, ids, context={}): self.write(cr, uid, ids, {'state':'ready'}) cron_id = self.browse(cr, uid, ids[0], {}).cron_id.id nextcall = (now()+DateTime.RelativeDateTime(seconds=30)).strftime('%Y-%m-%d %H:%M:%S') self.pool.get('ir.cron').write(cr, uid, cron_id, {'numbercall':1, 'active':True, 'nextcall':nextcall}) return True def set_stop(self, cr, uid, ids, context={}):
class email_server(osv.osv): _name = 'email.server' _description = "POP/IMAP Server" _columns = { 'name': fields.char('Name', size=256, required=True, readonly=False), 'active': fields.boolean('Active', required=False), 'state': fields.selection([ ('draft', 'Not Confirmed'), ('waiting', 'Waiting for Verification'), ('done', 'Confirmed'), ], 'State', select=True, readonly=True), 'server': fields.char('Server', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'port': fields.integer('Port', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'type': fields.selection([ ('pop', 'POP Server'), ('imap', 'IMAP Server'), ], 'Server Type', select=True, readonly=False), 'is_ssl': fields.boolean('SSL ?', required=False), 'attach': fields.boolean('Add Attachments ?', required=False, help="Fetches mail with attachments if true."), 'date': fields.date('Date', readonly=True, states={'draft': [('readonly', False)]}), 'user': fields.char('User Name', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'password': fields.char('Password', size=1024, invisible=True, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'note': fields.text('Description'), 'action_id': fields.many2one( 'ir.actions.server', 'Email Server Action', required=False, domain="[('state','=','email')]", help= "An Email Server Action. It will be run whenever an e-mail is fetched from server." ), 'object_id': fields.many2one( 'ir.model', "Model", required=True, help= "OpenObject Model. Generates a record of this model.\nSelect Object with message_new attrbutes." ), 'priority': fields.integer( 'Server Priority', readonly=True, states={'draft': [('readonly', False)]}, help= "Priority between 0 to 10, select define the order of Processing"), 'user_id': fields.many2one('res.users', 'User', required=False), 'message_ids': fields.one2many('mailgate.message', 'server_id', 'Messages', readonly=True), } _defaults = { 'state': lambda *a: "draft", 'active': lambda *a: True, 'priority': lambda *a: 5, 'date': lambda *a: time.strftime('%Y-%m-%d'), 'user_id': lambda self, cr, uid, ctx: uid, } def check_duplicate(self, cr, uid, ids, context=None): # RFC *-* Why this limitation? why not in SQL constraint? vals = self.read(cr, uid, ids, ['user', 'password'], context=context)[0] cr.execute( "select count(id) from email_server where user=%s and password=%s", (vals['user'], vals['password'])) res = cr.fetchone() if res: if res[0] > 1: return False return True def check_model(self, cr, uid, ids, context=None): if context is None: context = {} current_rec = self.read(cr, uid, ids, context) if current_rec: current_rec = current_rec[0] model_name = self.pool.get('ir.model').browse( cr, uid, current_rec.get('object_id')[0]).model model = self.pool.get(model_name) if hasattr(model, 'message_new'): return True return False _constraints = [ (check_duplicate, 'Warning! Can\'t have duplicate server configuration!', ['user', 'password']), (check_model, 'Warning! Record for selected Model can not be created\nPlease choose valid Model', ['object_id']) ] def onchange_server_type(self, cr, uid, ids, server_type=False, ssl=False): port = 0 if server_type == 'pop': port = ssl and 995 or 110 elif server_type == 'imap': port = ssl and 993 or 143 return {'value': {'port': port}} def set_draft(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'draft'}) return True def button_confirm_login(self, cr, uid, ids, context=None): if context is None: context = {} for server in self.browse(cr, uid, ids, context=context): logger.notifyChannel( 'imap', netsvc.LOG_INFO, 'fetchmail start checking for new emails on %s' % (server.name)) context.update({ 'server_id': server.id, 'server_type': server.type }) try: if server.type == 'imap': imap_server = None if server.is_ssl: imap_server = IMAP4_SSL(server.server, int(server.port)) else: imap_server = IMAP4(server.server, int(server.port)) imap_server.login(server.user, server.password) ret_server = imap_server elif server.type == 'pop': pop_server = None if server.is_ssl: pop_server = POP3_SSL(server.server, int(server.port)) else: pop_server = POP3(server.server, int(server.port)) #TODO: use this to remove only unread messages #pop_server.user("recent:"+server.user) pop_server.user(server.user) pop_server.pass_(server.password) ret_server = pop_server self.write(cr, uid, [server.id], {'state': 'done'}) if context.get('get_server', False): return ret_server except Exception, e: logger.notifyChannel(server.type, netsvc.LOG_WARNING, '%s' % (e)) return True
class calc_sale_price(osv.osv_memory): _name = 'calc.sale.price' _description = 'Sale Price Calculation Form RFQ' def default_get(self, cr, uid, fields, context=None): purchase_pool = self.pool.get('purchase.order') if context is None: context = {} res = super(calc_sale_price, self).default_get(cr, uid, fields, context=context) active_id = context.get('active_id', False) if active_id: warn = True purchase_obj = purchase_pool.browse(cr, uid, active_id, context=context) lines = [] for line in purchase_obj.order_line: vals = {} if line.select_line: warn = False vals = { 'sequence_no': line.sequence_no, 'product_id': line.product_id and line.product_id.id or False, 'cost_price': line.unit_price_lc or 0.00, 'pol_id': line.id or False } lines.append((0, 0, vals)) res['line_ids'] = lines if warn: raise osv.except_osv(_('Error !!!'), _('No Lines Selected !!')) cost_price = purchase_obj.total_products_cost or 0.00 cost_price_lc = purchase_obj.total_products_cost_lc or 0.00 freight_charges = purchase_obj.freight_charges or 0.00 freight_charges_lc = purchase_obj.freight_charges_lc or 0.00 fob_charges = purchase_obj.fob_charges or 0.00 fob_charges_lc = purchase_obj.fob_charges_lc or 0.00 other_charges = purchase_obj.other_charges or 0.00 other_charges_lc = purchase_obj.other_charges_lc or 0.00 total_cost = purchase_obj.total_amount_fc or 0.00 total_cost_lc = purchase_obj.total_amount_lc or 0.00 communication_charges = purchase_obj.communication_charges or 0.00 bank_charges = purchase_obj.bank_charges or 0.00 bank_interest = purchase_obj.bank_interest or 0.00 insurance_charges = purchase_obj.insurance_charges or 0.00 customs_duty = purchase_obj.customs_duty or 0.00 clg_agent_charges = purchase_obj.clg_agent_charges or 0.00 clearing_expenses = purchase_obj.clearing_expenses or 0.00 transport_delivery_expenses = purchase_obj.transport_delivery_expenses or 0.00 misc_expenses = purchase_obj.misc_expenses or 0.00 total_amount_lc = purchase_obj.total_expenses or 0.00 exchange_rate = purchase_obj.exchange_rate or 0.00 total_amount = float(total_amount_lc) + float(total_cost_lc) if cost_price_lc != 0.00: factor = float(total_amount) / float(cost_price_lc) total_sell_price = 0.00 for line in purchase_obj.order_line: if line.select_line: total_sell_price += float( line.unit_price_lc) * float(factor) * float( line.product_qty) res.update({ 'lead_id': purchase_obj.lead_id and purchase_obj.lead_id.id or False, 'po_id': active_id, 'partner_id': purchase_obj.partner_id and purchase_obj.partner_id.id or \ False, 'exchange_rate': exchange_rate, 'currency_id': purchase_obj.currency_id and purchase_obj.currency_id.id or \ False, 'local_currency_id': purchase_obj.company_id and \ purchase_obj.company_id.currency_id and \ purchase_obj.company_id.currency_id.id or False, 'cost_price_fc': cost_price, 'cost_price_lc': cost_price_lc, 'freight_charges_fc': freight_charges, 'freight_charges_lc': freight_charges_lc, 'fob_charges_fc': fob_charges, 'fob_charges_lc': fob_charges_lc, 'other_charges_fc': other_charges, 'other_charges_lc': other_charges_lc, 'total_cost_fc': total_cost, 'total_cost_lc': total_cost_lc, 'comm_charges': communication_charges, 'bank_charges': bank_charges, 'insu_charges': insurance_charges, 'bank_int': bank_interest, 'duty': customs_duty, 'agent_charge': clg_agent_charges, 'clearing_exp_port': clearing_expenses, 'trans_del_expense': transport_delivery_expenses, 'misc_exp': misc_expenses, 'total_exp': total_amount_lc, 'total_exp2': total_amount_lc, 'total_cost_lc2': total_cost_lc, 'total_sell_price': total_sell_price, 'factor': factor }) return res def onchange_margin(self, cr, uid, ids, margin, po_id=False, total_exp2=0.00, total_cost_lc2=0.00, cost_price_lc=0.00, context=None): po_pool = self.pool.get('purchase.order') res = {'value': {}} if po_id: po_obj = po_pool.browse(cr, uid, po_id, context=context) total_amount = float(margin) + float(total_exp2) + float( total_cost_lc2) factor = 1.000 if cost_price_lc != 0.00: factor = float(total_amount) / float(cost_price_lc) total_sell_price = 0.00 for line in po_obj.order_line: if line.select_line: unit_selling_price = float( line.unit_price_lc) * float(factor) total_sell_price += round(unit_selling_price, 2) * float( line.product_qty) res['value']['total_sell_price'] = total_sell_price res['value']['factor'] = factor return res _columns = { 'lead_id': fields.many2one('crm.lead', 'Enquiry No'), 'po_id': fields.many2one('purchase.order', 'Purchase Order'), 'partner_id': fields.many2one('res.partner', 'Supplier'), 'exchange_rate': fields.float('Exchange Rate', digits=(16, 5)), 'currency_id': fields.many2one('res.currency', 'Currency'), 'local_currency_id': fields.many2one('res.currency', 'Local Currency'), 'cost_price_lc': fields.float('Cost Price', digits_compute=dp.get_precision('Account')), 'cost_price_fc': fields.float('Cost Price', digits_compute=dp.get_precision('Account')), 'freight_charges_fc': fields.float('Freight Charges', digits_compute=dp.get_precision('Account')), 'freight_charges_lc': fields.float('Freight Charges', digits_compute=dp.get_precision('Account')), 'fob_charges_lc': fields.float('Fob Charges', digits_compute=dp.get_precision('Account')), 'fob_charges_fc': fields.float('Fob Charges', digits_compute=dp.get_precision('Account')), 'other_charges_lc': fields.float('Other Charges', digits_compute=dp.get_precision('Account')), 'other_charges_fc': fields.float('Other Charges', digits_compute=dp.get_precision('Account')), 'total_cost_fc': fields.float('Total Cost', digits_compute=dp.get_precision('Account')), 'total_cost_lc': fields.float('Total Cost', digits_compute=dp.get_precision('Account')), 'comm_charges': fields.float('Communication Charges', digits_compute=dp.get_precision('Account')), 'bank_charges': fields.float('Bank Charges', digits_compute=dp.get_precision('Account')), 'insu_charges': fields.float('Insurance Charges', digits_compute=dp.get_precision('Account')), 'bank_int': fields.float('Bank Interest 8% Days', digits_compute=dp.get_precision('Account')), 'duty': fields.float('Customs Duty 6%', digits_compute=dp.get_precision('Account')), 'agent_charge': fields.float('Clg. Agent Charges', digits_compute=dp.get_precision('Account')), 'clearing_exp_port': fields.float('Clearing Expense At Port', digits_compute=dp.get_precision('Account')), 'trans_del_expense': fields.float('Transport & Delivery Expense', digits_compute=dp.get_precision('Account')), 'misc_exp': fields.float('Misc. Expenses if Any', digits_compute=dp.get_precision('Account')), 'total_exp': fields.float('Total Expenses', digits_compute=dp.get_precision('Account')), 'total_exp2': fields.float('Total Expenses', digits_compute=dp.get_precision('Account')), 'total_cost_lc2': fields.float('Total Cost', digits_compute=dp.get_precision('Account')), 'margin': fields.float('Margin', digits_compute=dp.get_precision('Account')), 'total_sell_price': fields.float('Total Selling Price', digits_compute=dp.get_precision('Account')), 'factor': fields.float('Ratio', digits=(16, 8)), 'cost_sheet_required': fields.boolean('Cost Sheet Required ?'), 'line_ids': fields.one2many('calc.sale.price.line', 'wizard_id', 'Lines') } _defaults = { 'currency_id': 3, 'local_currency_id': 1, 'cost_sheet_required': True } def cal_sale_price(self, cr, uid, ids, context=None): crm_product_line_pool = self.pool.get('crm.product.lines') po_pool = self.pool.get('purchase.order') line_pool = self.pool.get('calc.sale.price.line') data = self.read(cr, uid, ids, context=context)[0] factor = data.get('factor', 1.0000) lead_id = data.get('lead_id', (False)) and data.get('lead_id', False)[0] po_id = data.get('po_id', (False))[0] margin = data.get('margin', 0.00) factor = data.get('factor', 0.00) cost_sheet_required = data.get('cost_sheet_required', False) lines = data.get('line_ids', []) if po_id: po_obj = po_pool.browse(cr, uid, po_id, context=context) po_obj.write({'sale_calculated': True}) if po_id and cost_sheet_required: total_sale = 0.00 for line in po_obj.order_line: unit_price_lc = line.unit_price_lc or 0.00 sale_price = float(line.unit_price_lc) * float(factor) total_sale += sale_price line.write({'sale_price': sale_price, 'sale_calculated': True}) po_obj.write({'margin': margin, 'factor': factor}) elif po_id and not cost_sheet_required: tot_margin = 0.00 for line_obj in line_pool.browse(cr, uid, lines, context=context): margin = line_obj.margin or 0.00 pol_obj = line_obj.pol_id or False if pol_obj: tot_margin += margin * pol_obj.product_qty pol_obj.write({ 'sale_price': line_obj.sale_price or 0.00, 'sale_calculated': True, 'margin': margin }) po_pool.write(cr, uid, po_id, { 'sale_calculated': True, 'margin': tot_margin }, context=context) return True
class tcv_bounced_cheq(osv.osv): _name = 'tcv.bounced.cheq' _description = 'Modulo de cheque devuelto' STATE_SELECTION = [ ('draft', 'Draft'), ('open', 'Open'), ('paid', 'Paid'), ('cancel', 'Canceled'), ] def send_workflow_signal(self, cr, uid, ids, signal): wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(uid, self._name, ids, signal, cr) def _amount_residual(self, cr, uid, ids, name, args, context=None): """ revisar si no tiene nada que ver con la conciliacion """ result = {} obj_bou = self.pool.get('tcv.bounced.cheq') for bounced in obj_bou.browse(cr, uid, ids, context=context): result[bounced.id] = bounced.amount if bounced.payment_ids: for p in bounced.payment_ids: result[bounced.id] -= (p.credit - p.debit) if bounced.state == 'open' and abs(result[bounced.id]) <= 0.0001: obj_bou.send_workflow_signal(cr, uid, bounced.id, 'button_paid') elif bounced.state == 'paid' and abs(result[bounced.id]) > 0.0001: obj_bou.send_workflow_signal(cr, uid, bounced.id, 'button_reopen') return result def _get_bounced_from_line(self, cr, uid, ids, context=None): """ Get a ids of account.move.line and return a list of tcv_bounced_cheq.ids - need to be recalculated """ obj_bou = self.pool.get('tcv.bounced.cheq') bou_ids = obj_bou.search(cr, uid, []) res = [] for item in obj_bou.browse(cr, uid, bou_ids, context={}): pay_ids = [x.id for x in item.payment_ids] if set(pay_ids) & set(ids): res.append(item.id) return res def _get_bounced_from_reconcile(self, cr, uid, ids, context=None): """ Get a ids of account.move.reconcile and return a list of tcv_bounced_cheq.ids - need to be recalculated """ obj_bou = self.pool.get('tcv.bounced.cheq') bou_ids = obj_bou.search(cr, uid, []) res = [] aml_ids = [] obj_rec = self.pool.get('account.move.reconcile') for rec_brw in obj_rec.browse(cr, uid, ids, context=context): aml_ids += [y.id for y in rec_brw.line_id] aml_ids += [z.id for z in rec_brw.line_partial_ids] for item in obj_bou.browse(cr, uid, bou_ids, context={}): pay_ids = [ x.id for x in item.payment_ids if x.reconcile_id or x.reconcile_partial_id ] if set(pay_ids) & set(aml_ids): res.append(item.id) return res def _get_use_fee_from_motive(self, cr, uid, ids, context=None): ''' Returns a list of tcv.bounced.cheq ids that need to recalculate the value of the field: button_fee ''' bounced_ids = self.pool.get('tcv.bounced.cheq').search( cr, uid, [('motive_id', 'in', ids)], context=context) return bounced_ids def _get_use_fee_from_config(self, cr, uid, ids, context=None): bounced_ids = self.pool.get('tcv.bounced.cheq').search( cr, uid, [('id', '!=', 0)], context=context) return bounced_ids def _get_use_fee_from_invoice(self, cr, uid, ids, context=None): bounced_ids = self.pool.get('tcv.bounced.cheq').search( cr, uid, [('fee_document_id', 'in', ids)], context=context) return bounced_ids def _compute_lines(self, cr, uid, ids, name, args, context=None): result = {} for bounced in self.browse(cr, uid, ids, context=context): src = [] lines = [] if bounced.move_id: for m in bounced.move_id.line_id: temp_lines = [] if m.reconcile_id: temp_lines = map(lambda x: x.id, m.reconcile_id.line_id) elif m.reconcile_partial_id: temp_lines = map( lambda x: x.id, m.reconcile_partial_id.line_partial_ids) lines += [x for x in temp_lines if x not in lines] src.append(m.id) lines = filter(lambda x: x not in src, lines) result[bounced.id] = lines return result def _get_fee_data(self, cr, uid, ids, name, args, context=None): result = {} obj_cfg = self.pool.get('tcv.bounced.cheq.config') comp_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.id config = obj_cfg.company_config_get(cr, uid, comp_id, context) for bou in self.browse(cr, uid, ids, context=context): result[bou.id] = config.use_fee and bou.motive_id.use_fee \ and not bou.fee_document_id return result _columns = { 'ref': fields.char('Reference', size=32, readonly=True), 'date': fields.date('Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, select=True), 'name': fields.char('Cheq number', size=32, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'deposit_line_id': fields.many2one( 'tcv.bank.deposit.line', 'Deposit line', readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict', help="You can select a registered cheq from bank deposit."), 'bank_journal_id': fields.many2one('account.journal', 'Bank journal', required=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'motive_id': fields.many2one('tcv.bounced.cheq.motive', 'Bounce motive', required=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'partner_id': fields.many2one('res.partner', 'Partner', required=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'amount': fields.float('Amount', digits_compute=dp.get_precision('Account'), required=True, readonly=True, states={'draft': [('readonly', False)]}), 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'currency_id': fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'move_id': fields.many2one('account.move', 'Account move', ondelete='restrict', help="The move of this entry line.", select=2, readonly=True), 'invoice_id': fields.many2one('account.invoice', 'Related invoice', ondelete='restrict', readonly=True, states={'draft': [('readonly', False)]}), 'button_fee': fields.function( _get_fee_data, method=True, string='charge fee', type='boolean', store={ 'tcv.bounced.cheq': (lambda self, cr, uid, ids, c={}: ids, ['motive_id', 'fee_document_id'], 10), 'tcv.bounced.cheq.motive': (_get_use_fee_from_motive, None, 50), 'tcv.bounced.cheq.config': (_get_use_fee_from_config, None, 50), 'account.invoice': (_get_use_fee_from_invoice, None, 50), }, ), 'fee_document_id': fields.many2one('account.invoice', 'Fee document', ondelete='set null', readonly=True), 'state': fields.selection(STATE_SELECTION, string='State', required=True, readonly=True), 'narration': fields.text('Notes', readonly=False), 'residual': fields.function(_amount_residual, method=True, digits_compute=dp.get_precision('Account'), string='Residual', store={ _name: (lambda self, cr, uid, ids, c={}: ids, [ 'amount', 'move_id', 'payment_ids', 'chq_location' ], 10), 'account.move.line': (_get_bounced_from_line, ['reconcile_id', 'reconcile_partial_id'], 20), 'account.move.reconcile': (_get_bounced_from_reconcile, None, 50), }, help="Remaining amount due."), 'payment_ids': fields.function(_compute_lines, method=True, relation='account.move.line', type="many2many", string='Payments'), 'user_id': fields.many2one( 'res.users', 'Notify user', readonly=True, states={'draft': [('readonly', False)] }, select=True, ondelete='restrict', help='Send a message to this user with bounced check\'s ' 'information'), 'chq_location': fields.selection([('bank', 'Bank'), ('coordination', 'Coordination'), ('company', 'Company'), ('customer', 'Customer')], string='Physical location', required=True, help='The physical location of the check', select=True), 'date_in_coordination': fields.datetime('Date in (Coordination)', required=False, select=True, help='Date of receipt of the check'), 'date_in_company': fields.datetime('Date in (company)', required=False, select=True, help='Date of receipt of the check'), 'date_out_partner': fields.datetime('Date out (to customer)', required=False, select=True, help='Customer delivery date'), 'partner_received_by': fields.char('Received by (customer)', size=64, required=False, help='Name of the receiver of the check (by customer)'), } _defaults = { 'ref': '/', 'date': lambda *a: time.strftime('%Y-%m-%d'), 'amount': lambda *a: 0.0, 'company_id': lambda self, cr, uid, c: self.pool.get('res.company'). _company_default_get(cr, uid, 'tcv_bounced_cheq', context=c), 'currency_id': lambda self, cr, uid, c: self.pool.get('res.users').browse( cr, uid, uid, c).company_id.currency_id.id, 'state': 'draft', 'chq_location': 'bank', } _sql_constraints = [ ('deposit_line_id_uniq', 'UNIQUE(deposit_line_id)', 'The cheq is already bounced !'), ('residual_range', 'CHECK(residual >= 0)', 'The residual amount must be >= 0.'), ('amount_range', 'CHECK(amount > 0)', 'The amount must be > 0.'), ] def _get_deposit_line_data(self, cr, uid, deposit_line_id): org = self.pool.get('tcv.bank.deposit.line').browse(cr, uid, deposit_line_id, context=None) res = { 'bank_journal_id': org.line_id.bank_journal_id.id, 'partner_id': org.partner_id.id, 'amount': org.amount, 'name': org.move_line.ref } return res def on_change_deposit_line_id(self, cr, uid, ids, deposit_line_id): res = {} if deposit_line_id: res = { 'value': self._get_deposit_line_data(cr, uid, deposit_line_id) } else: res = { 'value': { 'bank_journal_id': 0, 'partner_id': 0, 'amount': 0, 'name': '' } } return res def on_change_motive_id(self, cr, uid, ids, motive_id): context = {} res = {} if motive_id and ids: if type(ids) == int: ids = [ids] bou = self.browse(cr, uid, ids, context=context)[0] config = self.pool.get('tcv.bounced.cheq.config').\ company_config_get(cr, uid, bou.company_id.id, context) motive = self.pool.get('tcv.bounced.cheq.motive').\ browse(cr, uid, motive_id, context=context) res = { 'value': { 'button_fee': config.use_fee and motive.use_fee and not bou.fee_document_id } } return res def _gen_account_move_line(self, company_id, partner_id, account_id, name, debit, credit): return (0, 0, { 'auto': True, 'company_id': company_id, 'partner_id': partner_id, 'account_id': account_id, 'name': name, 'debit': debit, 'credit': credit, 'reconcile': False, }) def _gen_account_move(self, cr, uid, ids, context=None): obj_move = self.pool.get('account.move') obj_per = self.pool.get('account.period') move_id = None for bou in self.browse(cr, uid, ids, context={}): obj_cfg = self.pool.get('tcv.bounced.cheq.config') config = obj_cfg.company_config_get(cr, uid, bou.company_id.id, context) period_id = obj_per.find(cr, uid, bou.date)[0] move = { 'ref': '%s - Nro %s' % (context.get('bounced_cheq_ref', 'bch'), bou.name), 'journal_id': config.journal_id.id, 'date': bou.date, 'period_id': period_id, 'company_id': bou.company_id.id, 'state': 'draft', 'to_check': False, 'narration': '', } lines = [] lines.append( self._gen_account_move_line( bou.company_id.id, bou.partner_id.id, bou.partner_id.property_account_receivable.id, _('Bounced cheq #%s') % bou.name, bou.amount, 0)) lines.append( self._gen_account_move_line( bou.company_id.id, bou.partner_id.id, bou.bank_journal_id.default_credit_account_id.id, _('Bounced cheq #%s') % bou.name, 0, bou.amount)) lines.reverse() move.update({'line_id': lines}) move_id = obj_move.create(cr, uid, move, context) obj_move = self.pool.get('account.move') obj_move.post(cr, uid, [move_id], context=context) return move_id def bounced_cheq_pay(self, cr, uid, ids, context=None): if not ids: return [] bou = self.browse(cr, uid, ids[0], context=context) bounced_ids = [] for m in bou.move_id.line_id: if m.account_id.type in ('receivable', 'payable'): bounced_ids.append(m.id) return { 'name': _("Pay bounced cheq"), 'view_mode': 'form', 'view_id': False, 'view_type': 'form', 'res_model': 'account.voucher', 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'domain': '[]', 'context': { 'default_partner_id': bou.partner_id.id, 'default_amount': bou.residual, 'default_name': _('Replacement %s') % bou.name, 'close_after_process': True, 'invoice_type': 'out_invoice', 'move_line_ids': bounced_ids, 'default_type': 'receipt', 'default_narration': _('Bounced cheq payment\n\tRef: %s\n\tAmount: %.2f\n\t' 'Date: %s\n\tMotive: %s') % (bou.name, bou.amount, bou.date, bou.motive_id.name), } } def _notify_users(self, cr, uid, ids, notify_list, context=None): if not notify_list: return True request = self.pool.get('res.request') bounced = self.pool.get('tcv.bounced.cheq') for n in notify_list: bou = bounced.browse(cr, uid, n['bounced_id'], context=context) rq_id = request.create( cr, uid, { 'name': _("Bounced cheq"), 'act_from': uid, 'act_to': n['user_id'], 'body': n['message'], 'ref_partner_id': bou.partner_id.id, #~ 'ref_doc1': 'purchase.order,%d' % (po.id,), 'trigger_date': time.strftime(_('%Y-%m-%d %H:%M:%S')) }) request.request_send(cr, uid, [rq_id]) return True def _get_period(self, cr, uid, context={}): """ Return default account period value """ account_period_obj = self.pool.get('account.period') ids = account_period_obj.find(cr, uid, context=context) period_id = False if ids: period_id = ids[0] return period_id def _gen_fee_document(self, cr, uid, ids, context=None): obj_bou = self.pool.get('tcv.bounced.cheq') bou = obj_bou.browse(cr, uid, ids, context=context) obj_cfg = self.pool.get('tcv.bounced.cheq.config') cfg = obj_cfg.company_config_get(cr, uid, bou.company_id.id, context) taxes = map(lambda x: x.id, cfg.fee_product_id.taxes_id) line = { 'product_id': cfg.fee_product_id.id, 'concept_id': cfg.fee_product_id.concept_id.id, 'uos_id': cfg.fee_product_id.uom_id.id, 'quantity': 1, 'price_unit': cfg.fee_amount, 'discount': 0.0, 'name': _('%s [check: %s amount:%.2f]') % (cfg.fee_product_id.name, bou.name, bou.amount), 'account_id': cfg.fee_product_id.property_account_income.id, 'invoice_line_tax_id': [(6, 0, taxes)], } inv = { 'journal_id': cfg.fee_journal_id.id, 'currency_id': bou.currency_id.id, 'partner_id': bou.partner_id.id, 'address_invoice_id': self.pool.get('res.partner').address_get(cr, uid, [bou.partner_id.id], ['invoice'])['invoice'], 'date': time.strftime('%Y-%m-%d'), 'date_document': time.strftime('%Y-%m-%d'), 'type': 'out_invoice', 'account_id': bou.partner_id.property_account_receivable.id, 'company_id': bou.company_id.id, 'user_id': uid, 'name': _('Bounced check fee [%s]') % (bou.ref), 'origin': _('Bounced check fee: %s (Invoice #: %s)') % (bou.ref, bou.invoice_id.number if bou.invoice_id else 'N/A'), 'state': 'draft', 'invoice_line': [(0, 0, line)], } context.update({'fee_document_type': cfg.document_type}) if cfg.document_type == 'refund': inv.update({'parent_id': bou.invoice_id.id}) obj_inv = self.pool.get('account.invoice') res = obj_inv.create(cr, uid, inv, context) obj_inv.button_reset_taxes(cr, uid, [res], context) obj_bou.write(cr, uid, ids, {'fee_document_id': res}, context) return res def manual_fee_document(self, cr, uid, ids, context=None): context = context or {} bou = self.browse(cr, uid, ids[0], context=context) if not bou.invoice_id: raise osv.except_osv(_('Error!'), _("You must indicate a related invoice !")) mod_obj = self.pool.get('ir.model.data') res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form') res_id = res and res[1] or False, doc_id = self._gen_fee_document(cr, uid, ids[0], context) name = _( 'Debit Note (bounced check fee)') \ if context.get('fee_document_type') == 'refund' \ else _('Customer Invoices (bounced check fee)') return { 'name': name, 'view_type': 'form', 'view_mode': 'form', 'view_id': [res_id], 'res_model': 'account.invoice', 'context': "{'type':'out_invoice'}", 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'res_id': doc_id or False, } def create(self, cr, uid, vals, context=None): if vals.get('deposit_line_id'): vals.update( self._get_deposit_line_data(cr, uid, vals['deposit_line_id'])) return super(tcv_bounced_cheq, self).create(cr, uid, vals, context) def write(self, cr, uid, ids, vals, context=None): if vals.get('deposit_line_id'): vals.update( self._get_deposit_line_data(cr, uid, vals['deposit_line_id'])) return super(tcv_bounced_cheq, self).write(cr, uid, ids, vals, context) def unlink(self, cr, uid, ids, context=None): unlink_ids = [] for bou in self.browse(cr, uid, ids, context={}): if bou.state in ('draft', 'cancel'): unlink_ids.append(bou.id) else: raise osv.except_osv( _('Invalid action !'), _('Cannot delete Bounced that are already Validated!')) return super(tcv_bounced_cheq, self).unlink(cr, uid, unlink_ids, context) ##---------------------------------------------------------------- Workflow def test_open(self, cr, uid, ids, *args): so_brw = self.browse(cr, uid, ids, context={}) for bou in so_brw: if bou.deposit_line_id and \ not bou.deposit_line_id.origin.use_bounced_cheq: raise osv.except_osv( _('Error!'), _("Can't generate a bounced cheq form this deposit's " + "origin (%s)") % (bou.deposit_line_id.origin.name)) if bou.motive_id.need_note and not bou.narration: raise osv.except_osv(_('Error!'), _("This bounce motive requires a note")) if bou.invoice_id and \ bou.partner_id.id != bou.invoice_id.partner_id.id: raise osv.except_osv( _('Error!'), _("The related invoice's partner must be the same of " + "bounced check's partner")) return True def test_cancel(self, cr, uid, ids, *args): so_brw = self.browse(cr, uid, ids, context={}) #~ obj_inv = self.pool.get('account.invoice') for bou in so_brw: if bou.move_id.id: move = self.pool.get('account.move').browse(cr, uid, bou.move_id.id, context=None) for l in bou.move_id.line_id: if l.reconcile_id or l.reconcile_partial_id: raise osv.except_osv( _('Error!'), _('You can not cancel a bounced cheq while the ' + 'account move is reconciled.')) if move.state == 'posted': raise osv.except_osv( _('Error!'), _('You can not cancel a bounced cheq while the ' + 'account move is posted.')) if bou.fee_document_id: raise osv.except_osv( _('Error!'), _('You can not cancel a bounced with fee document ' + 'asigned (You must delete the fee document).')) return True def button_cancel(self, cr, uid, ids, context=None): obj_bou = self.pool.get('tcv.bounced.cheq') obj_mov = self.pool.get('account.move') res = {} vals = {'state': 'cancel'} for bou in self.browse(cr, uid, ids, context=context): if bou.state == 'open': if bou.move_id.id: move = obj_mov.browse(cr, uid, bou.move_id.id, context=None) if move.state == 'draft': vals.update({'move_id': 0}) if vals: res = obj_bou.write(cr, uid, ids, vals, context) if vals.get('move_id'): obj_mov.unlink(cr, uid, [move.id]) return res def button_draft(self, cr, uid, ids, context=None): vals = {'state': 'draft'} return self.write(cr, uid, ids, vals, context) def button_reopen(self, cr, uid, ids, context=None): context = context or {} if len(ids) != 1: raise osv.except_osv(_('Error!'), _('Multiplies validations not allowed.')) return self.write(cr, uid, ids, {'state': 'open'}, context) def button_open(self, cr, uid, ids, context=None): context = context or {} if len(ids) != 1: raise osv.except_osv(_('Error!'), _('Multiplies validations not allowed.')) notify_list = [] vals = {} cfg = False for bou in self.browse(cr, uid, ids, context={}): if not cfg: obj_cfg = self.pool.get('tcv.bounced.cheq.config') cfg = obj_cfg.company_config_get(cr, uid, bou.company_id.id, context) ref = bou.ref if bou.ref != '/' else self.pool.get( 'ir.sequence').get(cr, uid, 'bounced.cheq') context.update({'bounced_cheq_ref': ref}) if bou.user_id or (cfg.notify_salesman and bou.invoice_id): message = _( 'The check number: %s (%s), has been returned\n\t' + 'Motive: %s.\n\tRef: %s\n\tDate: %s\n\tAmount: %.2f') % ( bou.name, bou.partner_id.name, bou.motive_id.name, bou.ref, bou.date, bou.amount) if bou.user_id: notify_list.append({ 'user_id': bou.user_id.id, 'bounced_id': bou.id, 'message': message }) if cfg.notify_salesman and bou.invoice_id and \ bou.user_id.id != bou.invoice_id.user_id.id: notify_list.append({ 'user_id': bou.invoice_id.user_id.id, 'bounced_id': bou.id, 'message': message }) move_id = self._gen_account_move( cr, uid, ids, context) if not bou.move_id else bou.move_id.id obj = self.pool.get('tcv.bounced.cheq') vals.update({'state': 'open', 'ref': ref, 'move_id': move_id}) self._notify_users(cr, uid, ids, notify_list, context) return obj.write(cr, uid, ids, vals, context) def button_paid(self, cr, uid, ids, context=None): #~ print 'button_paid', button_paid vals = {'state': 'paid'} res = self.write(cr, uid, ids, vals, context) notify_list = [] for id in ids: bou = self.browse(cr, uid, id, context=context) if bou.user_id: message = _('The bounced check %s (%s), has been payed.\n\t' + 'Date: %s\n\tAmount: %.2f') % ( bou.ref, bou.partner_id.name, time.strftime(_("%Y-%m-%d")), bou.amount) notify_list.append({ 'user_id': bou.user_id.id, 'bounced_id': bou.id, 'message': message }) self._notify_users(cr, uid, ids, notify_list, context) return res
#print 'Eval success: %s - %s' % (rule, str(ret)) except Exception, e: print 'Wrong parsing "%s" from "%s"' % (rule, orig_rule) print 'Production calculating count: eval error - %s' % e.message raise osv.except_osv(u'Предупреждение', u'Неверная формула расчета') if ret % 1 > 0.95: ret = ret - (ret % 1) + 1 else: ret = ret - (ret % 1) self.write(cr, uid, ids, {'product_qty': ret}) return ret _columns = { 'tmpl_id': fields.dummy(string='Template', relation='product.template', type='many2one'), 'template_id': fields.many2one('product.template', u'Шаблон', required=True, readonly=True, states={'draft':[('readonly',False)]}), 'product_id': fields.many2one('product.product', u'Продукт', required=False, readonly=True, states={'draft':[('readonly',False)]}), #'multi': fields.dummy(string='Multi fields'), 'params': fields.dummy(string='Params fields'), } _defaults = { 'product_qty': 0, } def _check_qty(self, cr, uid, ids, context=None): # for order in self.browse(cr, uid, ids, context=context): # if order.product_qty <= 0: # return False return True
finally: ofile.close() return True def _set_image(self, cr, uid, id, name, value, arg, context=None): local_media_repository = self.pool.get('res.company').get_local_media_repository(cr, uid, context=context) if local_media_repository: image = self.browse(cr, uid, id, context=context) return self._save_file(os.path.join(local_media_repository, image.product_id.default_code), '%s%s'%(image.name, image.extention), value) return self.write(cr, uid, id, {'file_db_store' : value}, context=context) _columns = { 'name':fields.char('Image Title', size=100, required=True), 'extention': fields.char('file extention', size=6), 'link':fields.boolean('Link?', help="Images can be linked from files on your file system or remote (Preferred)"), 'file_db_store':fields.binary('Image stored in database'), 'file':fields.function(_get_image, fnct_inv=_set_image, type="binary", method=True, filters='*.png,*.jpg,*.gif'), 'url':fields.char('File Location', size=250), 'comments':fields.text('Comments'), 'product_id':fields.many2one('product.product', 'Product') } _defaults = { 'link': lambda *a: False, } _sql_constraints = [('uniq_name_product_id', 'UNIQUE(product_id, name)', _('A product can have only one image with the same name'))] product_images()
def _set_image(self, cr, uid, id, name, value, arg, context=None): image = self.browse(cr, uid, id, context=context) full_path = self._image_path(cr, uid, image, context=context) if full_path: return self._save_file(full_path, value) return self.write(cr, uid, id, {"file_db_store": value}, context=context) _columns = { "name": fields.char("Image Title", translate=True, size=100, required=True), "extention": fields.char("file extention", size=6), "link": fields.boolean( "Link?", help="Images can be linked from files on your file system or remote (Preferred)" ), "file_db_store": fields.binary("Image stored in database"), "file": fields.function( _get_image, fnct_inv=_set_image, type="binary", method=True, filters="*.png,*.jpg,*.gif" ), "url": fields.char("File Location", size=128), "comments": fields.text("Comments", translate=True), "product_id": fields.many2one("product.product", "Product"), } _defaults = {"link": lambda *a: False} _sql_constraints = [ ("uniq_name_product_id", "UNIQUE(product_id, name)", _("A product can have only one image with the same name")) ] product_images()
for id in ids: result[id] = False for record in data_results: result[record['res_id']] = '%(module)s.%(name)s' % record return result _columns = { 'charset':fields.selection(_get_encodings, string='Charset', required=True), 'content_fname': fields.char('Override Extension',size=64, help='Here you can override output file extension'), 'styles_mode': fields.selection([ ('default','Not used'), ('global', 'Global'), ('specified', 'Specified'), ], string='Stylesheet'), #'report_styles' : fields.binary('Template Styles', help='OpenOffice stylesheet (.odt)'), 'stylesheet_id':fields.many2one('report.stylesheets', 'Template Stylesheet'), 'preload_mode':fields.selection([ ('static',_('Static')), ('preload',_('Preload')), ],'Preload Mode'), 'tml_source':fields.selection([ ('database','Database'), ('file','File'), ('parser','Parser'), ],'Template source', select=True), 'parser_def': fields.text('Parser Definition'), 'parser_loc':fields.char('Parser location', size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}"), 'parser_state':fields.selection([ ('default',_('Default')), ('def',_('Definition')), ('loc',_('Location')),
input_model[ir_model_field.name] record_dict['fields'] = field_dict data_json.append(record_dict) out = base64.encodestring(json.dumps(data_json, indent=4)) return self.write(cr, uid, ids, { 'state': 'done', 'dm_export_data_wizard_data': out, 'name': json_exported_file_name }, context=context) EXPORT_TYPE = (('a', 'based on model'), ('b', 'based on module')) _columns = { 'name': fields.char('Filename', size=128, readonly=True), 'dm_export_data_wizard_type': fields.selection(EXPORT_TYPE, 'DM Export Data Wizard Type'), 'ir_model_id': fields.many2one('ir.model', 'IR Model'), 'ir_module_module_id': fields.many2one('ir.module.module', 'IR Module Module'), 'dm_export_data_wizard_data': fields.binary('Export Data Wizard Data', readonly=True), 'state': fields.selection([('init', 'init'), ('done', 'done')], 'state', readonly=True), } _defaults = {'state': 'init', 'dm_export_data_wizard_type': 'a'} DmExportDataWizard()
data_results = model_data_obj.read(cr, uid, data_ids, ["module", "name", "res_id"]) result = {} for id in ids: result[id] = False for record in data_results: result[record["res_id"]] = "%(module)s.%(name)s" % record return result _columns = { "charset": fields.selection(_get_encodings, string="Charset", required=True), "content_fname": fields.char("Override Extension", size=64, help="Here you can override output file extension"), "styles_mode": fields.selection( [("default", "Not used"), ("global", "Global"), ("specified", "Specified")], string="Stylesheet" ), #'report_styles' : fields.binary('Template Styles', help='OpenOffice stylesheet (.odt)'), "stylesheet_id": fields.many2one("report.stylesheets", "Template Stylesheet"), "preload_mode": fields.selection([("static", _("Static")), ("preload", _("Preload"))], "Preload Mode"), "tml_source": fields.selection( [("database", "Database"), ("file", "File"), ("parser", "Parser")], "Template source", select=True ), "parser_def": fields.text("Parser Definition"), "parser_loc": fields.char( "Parser location", size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}", ), "parser_state": fields.selection( [("default", _("Default")), ("def", _("Definition")), ("loc", _("Location"))], "State of Parser", select=True, ),
class purchase_order(osv.osv): _inherit = "purchase.order" def action_invoice_create(self, cr, uid, ids, *args): print "==============================================================================&&&***" print "Buat Invoice :::" res = False journal_obj = self.pool.get('account.journal') for o in self.browse(cr, uid, ids): il = [] todo = [] for ol in o.order_line: todo.append(ol.id) if ol.product_id: a = ol.product_id.product_tmpl_id.property_account_expense.id if not a: a = ol.product_id.categ_id.property_account_expense_categ.id if not a: raise osv.except_osv( _('Error !'), _('There is no expense account defined for this product: "%s" (id:%d)' ) % ( ol.product_id.name, ol.product_id.id, )) else: a = self.pool.get('ir.property').get( cr, uid, 'property_account_expense_categ', 'product.category').id fpos = o.fiscal_position or False a = self.pool.get('account.fiscal.position').map_account( cr, uid, fpos, a) il.append(self.inv_line_create(cr, uid, a, ol)) ################Landed Cost################## for cost in o.landed_cost_line: print "Landed Cost :xxx", cost.name landed_cost_line = (0, False, { 'name': cost.name or False, 'account_id': cost.account_id.id or False, 'price_unit': cost.amount or False, }) il.append(landed_cost_line) print "Tes INis" #################Down Payment################# for dp in o.downpayment_line: dp_amount = 0.0 dp_amount = dp_amount + dp.amount print "Amount DP ;_*****---------------->>", dp_amount ############################################## a = o.partner_id.property_account_payable.id journal_ids = journal_obj.search( cr, uid, [('type', '=', 'purchase'), ('company_id', '=', o.company_id.id)], limit=1) if not journal_ids: raise osv.except_osv( _('Error !'), _('There is no purchase journal defined for this company: "%s" (id:%d)' ) % (o.company_id.name, o.company_id.id)) inv = { 'name': o.partner_ref or o.name, 'reference': o.partner_ref or o.name, 'account_id': a, 'type': 'in_invoice', 'partner_id': o.partner_id.id, 'currency_id': o.pricelist_id.currency_id.id, 'address_invoice_id': o.partner_address_id.id, 'address_contact_id': o.partner_address_id.id, 'journal_id': len(journal_ids) and journal_ids[0] or False, 'origin': o.name, 'invoice_line': il, 'fiscal_position': o.fiscal_position.id or o.partner_id.property_account_position.id, 'payment_term': o.partner_id.property_payment_term and o.partner_id.property_payment_term.id or False, 'company_id': o.company_id.id, } inv_id = self.pool.get('account.invoice').create( cr, uid, inv, {'type': 'in_invoice'}) self.pool.get('account.invoice').button_compute( cr, uid, [inv_id], {'type': 'in_invoice'}, set_total=True) self.pool.get('purchase.order.line').write(cr, uid, todo, {'invoiced': True}) self.write(cr, uid, [o.id], {'invoice_ids': [(4, inv_id)]}) res = inv_id # #########Tambahan Untuk DP######## # print "INV_ID:::", inv_id # print "pur_id :::", o.id # account_voc_id_search = self.pool.get('account.voucher').search(cr, uid,[('purchase_id','=',o.id)]) # account_voc_id_browse = self.pool.get('account.voucher').browse(cr, uid,account_voc_id_search) # # # # for a in account_voc_id_browse: # print "=================>>>", a # if a: ## account_inv_id_search = self.pool.get('account.invoice').search(cr, uid,[('purchase_id','=',o.id),('state','!=','cancel')]) ## account_inv_id_browse = self.pool.get('account.invoice').browse(cr, uid,account_inv_id_search) ## ## for inv_id in account_inv_id_browse: ## inv_id.id # # # account_voc_id_search = self.pool.get('account.voucher').write(cr, uid,[a.id],{'invoice_id':inv_id}) # # print "IDS ::", o.id # # ################ return res _columns = { 'account_voc_line': fields.one2many('account.voucher', 'purchase_id', "Account Voc", readonly=True), 'dp': fields.boolean('DP'), 'landed_cost_line': fields.one2many('landed.cost', 'po_id', 'Landed Cost Line'), 'landed_cost_check': fields.selection([('free', 'Free'), ('landed_cost', 'Landed Cost')], 'Charges'), ########################################### 'downpayment_line': fields.one2many('downpayment.line', 'purchase_id', "Downpayment Lines", readonly=True), 'downpayment_id': fields.many2one('downpayment', 'Downpayment'), ########################################### } _defaults = { 'dp': False, 'landed_cost_check': 'free', }
'tracking_no': package.TrackingNumber.pyval, 'label_image': package.LabelImage.GraphicImage.pyval, 'state': 'accepted' } packages_obj.write( cursor, user, package_record_ids[packages.index(package)], register_vals, context) # changing state to accepted of shipping register record. self.write(cursor, user, shipping_register_record.id, {'state': 'accepted'}, context) return True _columns = { 'name': fields.char(string='Name', select="1", size=150, readonly=True), 'service_type': fields.many2one('ups.codes', 'Service Type', domain=[('type', '=', 'service')], select="1"), 'package_det': fields.one2many('ups.shippingregister.package', 'shipping_register_rel', string='Packages',), 'to_address': fields.many2one('res.partner.address', 'Shipping Address', required=True), 'from_address': fields.many2one('res.partner.address', 'From Address', required=True), 'shipper_address': fields.many2one('res.partner.address', 'Shipper Address', required=True), 'saturday_delivery': fields.boolean('Saturday Delivery?'), 'description': fields.text('Description'), 'state':fields.selection(STATE_SELECTION, 'Status', readonly=True,), # The following are UPS filled information 'billed_weight':fields.float('Billed Weight', digits=(10, 4), readonly=True, help=(
class mgmtsystem_nonconformity(osv.osv): """ Management System - Nonconformity """ _name = "mgmtsystem.nonconformity" _description = "Nonconformity of the management system" _rec_name = "description" _order = "date desc" _columns = { 'id': fields.integer('ID', readonly=True), 'ref': fields.char('Reference', size=64, required=True, readonly=True), 'date': fields.date('Date', required=True), 'partner_id': fields.many2one('res.partner', 'Partner', required=True), 'reference': fields.char('Related to', size=50), 'responsible_user_id': fields.many2one('res.users', 'Responsible', required=True), 'manager_user_id': fields.many2one('res.users', 'Manager', required=True), 'author_user_id': fields.many2one('res.users', 'Filled in by', required=True), 'origin_ids': fields.many2many('mgmtsystem.nonconformity.origin', 'mgmtsystem_nonconformity_origin_rel', 'nonconformity_id', 'origin_id', 'Origin', required=True), 'procedure_ids': fields.many2many('wiki.wiki', 'mgmtsystem_nonconformity_procedure_rel', 'nonconformity_id', 'procedure_id', 'Procedure'), 'description': fields.text('Description', required=True), 'cause_ids': fields.many2many('mgmtsystem.nonconformity.cause', 'mgmtsystem_nonconformity_cause_rel', 'nonconformity_id', 'cause_id', 'Cause'), 'analysis': fields.text('Analysis'), 'immediate_action_id': fields.many2one('mgmtsystem.action', 'Immediate action'), 'efficiency_immediate': fields.text('Efficiency of the immediate action'), 'corrective_action_id': fields.many2one('mgmtsystem.action', 'Corrective action'), 'efficiency_corrective': fields.text('Efficiency of the corrective action'), 'preventive_action_id': fields.many2one('mgmtsystem.action', 'Preventive action'), 'efficiency_preventive': fields.text('Efficiency of the preventive action'), 'state': fields.selection((('o', 'Open'), ('c', 'Closed')), 'State', size=16, readonly=True), } _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), 'state': 'o', 'author_user_id': lambda cr, uid, id, c={}: id, 'ref': 'NEW', } def create(self, cr, uid, vals, context=None): vals.update({ 'ref': self.pool.get('ir.sequence').get(cr, uid, 'mgmtsystem.nonconformity') }) return super(mgmtsystem_nonconformity, self).create(cr, uid, vals, context) def button_close(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'c'})
class partner_vat_intra(osv.osv_memory): """ Partner Vat Intra """ _name = "partner.vat.intra" _description = 'Partner VAT Intra' def _get_xml_data(self, cr, uid, context=None): if context.get('file_save', False): return base64.encodestring(context['file_save'].encode('utf8')) return '' def _get_europe_country(self, cursor, user, context=None): return self.pool.get('res.country').search(cursor, user, [ ('code', 'in', [ 'AT', 'BG', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'GB' ]) ]) _columns = { 'name': fields.char('File Name', size=32), 'period_code': fields.char( 'Period Code', size=6, required=True, help= '''This is where you have to set the period code for the intracom declaration using the format: ppyyyy PP can stand for a month: from '01' to '12'. PP can stand for a trimester: '31','32','33','34' The first figure means that it is a trimester, The second figure identify the trimester. PP can stand for a complete fiscal year: '00'. YYYY stands for the year (4 positions). '''), 'period_ids': fields.many2many( 'account.period', 'account_period_rel', 'acc_id', 'period_id', 'Period (s)', help= 'Select here the period(s) you want to include in your intracom declaration' ), 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', domain=[('parent_id', '=', False)]), 'test_xml': fields.boolean('Test XML file', help="Sets the XML output as test file"), 'mand_id': fields.char( 'MandataireId', size=14, required=True, help= "This identifies the representative of the sending company. This is a string of 14 characters" ), 'msg': fields.text('File created', size=14, readonly=True), 'no_vat': fields.text( 'Partner With No VAT', size=14, readonly=True, help= "The Partner whose VAT number is not defined they doesn't include in XML File." ), 'file_save': fields.binary('Save File', readonly=True), 'country_ids': fields.many2many('res.country', 'vat_country_rel', 'vat_id', 'country_id', 'European Countries'), } _defaults = { 'country_ids': _get_europe_country, 'file_save': _get_xml_data, 'name': 'vat_Intra.xml', } def create_xml(self, cursor, user, ids, context=None): obj_user = self.pool.get('res.users') obj_sequence = self.pool.get('ir.sequence') obj_partner = self.pool.get('res.partner') obj_partner_add = self.pool.get('res.partner.address') mod_obj = self.pool.get('ir.model.data') street = zip_city = country = p_list = data_clientinfo = '' seq = amount_sum = 0 if context is None: context = {} data_tax = self.browse(cursor, user, ids[0], context=context) if data_tax.tax_code_id: data_cmpny = data_tax.tax_code_id.company_id else: data_cmpny = obj_user.browse(cursor, user, user).company_id data = self.read(cursor, user, ids)[0] company_vat = data_cmpny.partner_id.vat if not company_vat: raise osv.except_osv( _('Data Insufficient'), _('No VAT Number Associated with Main Company!')) seq_controlref = obj_sequence.get(cursor, user, 'controlref') seq_declarantnum = obj_sequence.get(cursor, user, 'declarantnum') cref = company_vat[2:] + seq_controlref[-4:] dnum = cref + seq_declarantnum[-5:] if len(data['period_code']) != 6: raise osv.except_osv( _('Wrong Period Code'), _('The period code you entered is not valid.')) addr = obj_partner.address_get(cursor, user, [data_cmpny.partner_id.id], ['invoice']) if addr.get('invoice', False): ads = obj_partner_add.browse(cursor, user, [addr['invoice']])[0] zip_city = (ads.city or '') + ' ' + (ads.zip or '') if zip_city == ' ': zip_city = '' if ads.street: street = ads.street if ads.street2: street += ' ' street += ads.street2 if ads.country_id: country = ads.country_id.code comp_name = data_cmpny.name sender_date = time.strftime('%Y-%m-%d') data_file = '<?xml version="1.0"?>\n<VatIntra xmlns="http://www.minfin.fgov.be/VatIntra" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" RecipientId="VAT-ADMIN" SenderId="' + str( company_vat) + '"' data_file += ' ControlRef="' + cref + '" MandataireId="' + data[ 'mand_id'] + '" SenderDate="' + str(sender_date) + '"' data_file += ' VersionTech="1.3">' data_file += '\n\t<AgentRepr DecNumber="1">\n\t\t<CompanyInfo>\n\t\t\t<VATNum>' + str( company_vat ) + '</VATNum>\n\t\t\t<Name>' + comp_name + '</Name>\n\t\t\t<Street>' + street + '</Street>\n\t\t\t<CityAndZipCode>' + zip_city + '</CityAndZipCode>' data_file += '\n\t\t\t<Country>' + country + '</Country>\n\t\t</CompanyInfo>\n\t</AgentRepr>' data_comp = '\n\t\t<CompanyInfo>\n\t\t\t<VATNum>' + str( company_vat[2:] ) + '</VATNum>\n\t\t\t<Name>' + comp_name + '</Name>\n\t\t\t<Street>' + street + '</Street>\n\t\t\t<CityAndZipCode>' + zip_city + '</CityAndZipCode>\n\t\t\t<Country>' + country + '</Country>\n\t\t</CompanyInfo>' data_period = '\n\t\t<Period>' + data[ 'period_code'] + '</Period>' #trimester p_id_list = obj_partner.search(cursor, user, [('vat', '!=', False)]) if not p_id_list: raise osv.except_osv( _('Data Insufficient!'), _('No partner has a VAT Number asociated with him.')) if not data['period_ids']: raise osv.except_osv(_('Data Insufficient!'), _('Please select at least one Period.')) cursor.execute( '''SELECT p.name As partner_name, l.partner_id AS partner_id, p.vat AS vat, t.code AS intra_code, SUM(l.tax_amount) AS amount FROM account_move_line l LEFT JOIN account_tax_code t ON (l.tax_code_id = t.id) LEFT JOIN res_partner p ON (l.partner_id = p.id) WHERE t.code IN ('44a','44b','88') AND l.period_id IN %s GROUP BY p.name, l.partner_id, p.vat, t.code''', (tuple(data['period_ids']), )) for row in cursor.dictfetchall(): if not row['vat']: p_list += str(row['partner_name']) + ', ' continue seq += 1 amt = row['amount'] or 0 amt = int(round(amt * 100)) amount_sum += amt intra_code = row['intra_code'] == '88' and 'L' or ( row['intra_code'] == '44b' and 'T' or (row['intra_code'] == '44a' and 'S' or '')) data_clientinfo += '\n\t\t<ClientList SequenceNum="' + str( seq ) + '">\n\t\t\t<CompanyInfo>\n\t\t\t\t<VATNum>' + row['vat'][ 2:] + '</VATNum>\n\t\t\t\t<Country>' + row[ 'vat'][: 2] + '</Country>\n\t\t\t</CompanyInfo>\n\t\t\t<Amount>' + str( amt) + '</Amount>\n\t\t\t<Code>' + str( intra_code) + '</Code>\n\t\t</ClientList>' amount_sum = int(amount_sum) data_decl = '\n\t<DeclarantList SequenceNum="1" DeclarantNum="' + dnum + '" ClientNbr="' + str( seq) + '" AmountSum="' + str(amount_sum) + '" >' data_file += data_decl + data_comp + str( data_period ) + data_clientinfo + '\n\t</DeclarantList>\n</VatIntra>' model_data_ids = mod_obj.search(cursor, user, [('model', '=', 'ir.ui.view'), ('name', '=', 'view_vat_intra_save')], context=context) resource_id = mod_obj.read(cursor, user, model_data_ids, fields=['res_id'], context=context)[0]['res_id'] context['file_save'] = data_file return { 'name': _('Save'), 'context': context, 'view_type': 'form', 'view_mode': 'form', 'res_model': 'partner.vat.intra', 'views': [(resource_id, 'form')], 'view_id': 'view_vat_intra_save', 'type': 'ir.actions.act_window', 'target': 'new', }
# 'balance':balance, } } def _estado_defecto(self, cr, uid, context=None): estado = self.pool.get('bag.state').search(cr, uid, [('name', '=', 'Recibido')]) return estado _name = 'bag.service' _description = 'Service Order' _columns = { 'name': fields.char('Numero Orden', size=24), 'type': fields.selection([('particular', 'Particular'), ('airline', 'Aerolinea')], 'Type', required=True), 'date': fields.date('Fecha', required=True), 'date_promised': fields.date('Fecha Prometida', required=True), 'partner_id' : fields.many2one('res.partner', 'Cliente'), 'address_str': fields.related('partner_id', 'street', type='char', size='128'), 'address_num_str': fields.related('partner_id', 'street_num', type='char'), 'piso_dpto_str': fields.related('partner_id', 'piso_dpto', type='char', size='128'), 'phone_str': fields.related('partner_id', 'phone_str', type='char', size='128'), 'zone_str': fields.related('partner_id', 'street', type='char'), 'type_id': fields.many2one('bag.type', 'Tipo'), 'format_id': fields.many2one('bag.format', 'Formato'), 'color_id': fields.many2one('bag.color', 'Color'), 'material_id': fields.many2one('bag.material', 'Material'), 'size_id': fields.many2one('bag.size', 'Tamano'), 'description': fields.char('Descripcion', size=64), 'brand': fields.char('Marca', size=64), 'model': fields.char('Modelo', size=64), 'airline_id': fields.many2one('bag.airline', 'Aerolinea', required=True), 'branch': fields.char('Sucursal', size=32),
class ir_values(osv.osv): """Holds internal model-specific action bindings and user-defined default field values. definitions. This is a legacy internal model, mixing two different concepts, and will likely be updated or replaced in a future version by cleaner, separate models. You should not depend explicitly on it. The purpose of each ``ir.values`` entry depends on its type, defined by the ``key`` column: * 'default': user-defined default values, used when creating new records of this model: * 'action': binding of an action to a particular *action slot* of this model, making the action easily available in the user interface for this model. The ``key2`` column acts as a qualifier, further refining the type of the entry. The possible values are: * for 'default' entries: an optional condition restricting the cases where this particular default value will be applicable, or ``False`` for no condition * for 'action' entries: the ``key2`` qualifier is one of the available action slots, defining how this action can be invoked: * ``'client_print_multi'`` for report printing actions that will be available on views displaying items from this model * ``'client_action_multi'`` for assistants (wizards) actions that will be available in views displaying objects of this model * ``'client_action_relate'`` for links towards related documents that should be available in views displaying objects of this model * ``'tree_but_open'`` for actions that will be triggered when double-clicking an item from this model in a hierarchical tree view Each entry is specific to a model (``model`` column), and for ``'actions'`` type, may even be made specific to a given record of that model when the ``res_id`` column contains a record ID (``False`` means it's global for all records). The content of the entry is defined by the ``value`` column, which may either contain an arbitrary value, or a reference string defining the action that should be executed. .. rubric:: Usage: default values The ``'default'`` entries are usually defined manually by the users, and set by their UI clients calling :meth:`~.set_default`. These default values are then automatically used by the ORM every time a new record is about to be created, i.e. when :meth:`~openerp.osv.osv.osv.default_get` or :meth:`~openerp.osv.osv.osv.create` are called. .. rubric:: Usage: action bindings Business applications will usually bind their actions during installation, and OpenERP UI clients will apply them as defined, based on the list of actions included in the result of :meth:`~openerp.osv.osv.osv.fields_view_get`, or directly returned by explicit calls to :meth:`~.get_actions`. """ _name = 'ir.values' def _value_unpickle(self, cursor, user, ids, name, arg, context=None): res = {} for record in self.browse(cursor, user, ids, context=context): value = record[name[:-9]] if record.key == 'default' and value: # default values are pickled on the fly try: value = str(pickle.loads(value)) except Exception: pass res[record.id] = value return res def _value_pickle(self, cursor, user, id, name, value, arg, context=None): if context is None: context = {} ctx = context.copy() if self.CONCURRENCY_CHECK_FIELD in ctx: del ctx[self.CONCURRENCY_CHECK_FIELD] record = self.browse(cursor, user, id, context=context) if record.key == 'default': # default values are pickled on the fly value = pickle.dumps(value) self.write(cursor, user, id, {name[:-9]: value}, context=ctx) def onchange_object_id(self, cr, uid, ids, object_id, context=None): if not object_id: return {} act = self.pool.get('ir.model').browse(cr, uid, object_id, context=context) return {'value': {'model': act.model}} def onchange_action_id(self, cr, uid, ids, action_id, context=None): if not action_id: return {} act = self.pool.get('ir.actions.actions').browse(cr, uid, action_id, context=context) model = act.type if act.type != 'ir.actions.act_url' else 'ir.actions.url' return {'value': {'value_unpickle': "%s,%d" % (model, act.id)}} _columns = { 'name': fields.char('Name', size=128, required=True), 'model': fields.char('Model Name', size=128, select=True, required=True, help="Model to which this entry applies"), # TODO: model_id and action_id should be read-write function fields 'model_id': fields.many2one('ir.model', 'Model (change only)', size=128, help="Model to which this entry applies - " "helper field for setting a model, will " "automatically set the correct model name"), 'action_id': fields.many2one('ir.actions.actions', 'Action (change only)', help="Action bound to this entry - " "helper field for binding an action, will " "automatically set the correct reference"), 'value': fields.text('Value', help="Default value (pickled) or reference to an action"), 'value_unpickle': fields.function(_value_unpickle, fnct_inv=_value_pickle, type='text', string='Default value or action reference'), 'key': fields.selection( [('action', 'Action'), ('default', 'Default')], 'Type', size=128, select=True, required=True, help="- Action: an action attached to one slot of the given model\n" "- Default: a default value for a model field"), 'key2': fields.char( 'Qualifier', size=128, select=True, help="For actions, one of the possible action slots: \n" " - client_action_multi\n" " - client_print_multi\n" " - client_action_relate\n" " - tree_but_open\n" "For defaults, an optional condition", ), 'res_id': fields.integer( 'Record ID', select=True, help="Database identifier of the record to which this applies. " "0 = for all records"), 'user_id': fields.many2one( 'res.users', 'User', ondelete='cascade', select=True, help="If set, action binding only applies for this user."), 'company_id': fields.many2one( 'res.company', 'Company', ondelete='cascade', select=True, help="If set, action binding only applies for this company") } _defaults = { 'key': 'action', 'key2': 'tree_but_open', } def _auto_init(self, cr, context=None): super(ir_values, self)._auto_init(cr, context) cr.execute( 'SELECT indexname FROM pg_indexes WHERE indexname = \'ir_values_key_model_key2_res_id_user_id_idx\'' ) if not cr.fetchone(): cr.execute( 'CREATE INDEX ir_values_key_model_key2_res_id_user_id_idx ON ir_values (key, model, key2, res_id, user_id)' ) def set_default(self, cr, uid, model, field_name, value, for_all_users=True, company_id=False, condition=False): """Defines a default value for the given model and field_name. Any previous default for the same scope (model, field_name, value, for_all_users, company_id, condition) will be replaced and lost in the process. Defaults can be later retrieved via :meth:`~.get_defaults`, which will return the highest priority default for any given field. Defaults that are more specific have a higher priority, in the following order (highest to lowest): * specific to user and company * specific to user only * specific to company only * global to everyone :param string model: model name :param string field_name: field name to which the default applies :param value: the default field value to set :type value: any serializable Python value :param bool for_all_users: whether the default should apply to everybody or only the user calling the method :param int company_id: optional ID of the company to which the default should apply. If omitted, the default will be global. If True is passed, the current user's company will be used. :param string condition: optional condition specification that can be used to restrict the applicability of the default values (e.g. based on another field's value). This is an opaque string as far as the API is concerned, but client stacks typically use single-field conditions in the form ``'key=stringified_value'``. (Currently, the condition is trimmed to 200 characters, so values that share the same first 200 characters always match) :return: id of the newly created ir.values entry """ if isinstance(value, unicode): value = value.encode('utf8') if company_id is True: # should be company-specific, need to get company id user = self.pool.get('res.users').browse(cr, uid, uid) company_id = user.company_id.id # remove existing defaults for the same scope search_criteria = [('key', '=', 'default'), ('key2', '=', condition and condition[:200]), ('model', '=', model), ('name', '=', field_name), ('user_id', '=', False if for_all_users else uid), ('company_id', '=', company_id)] self.unlink(cr, uid, self.search(cr, uid, search_criteria)) return self.create( cr, uid, { 'name': field_name, 'value': pickle.dumps(value), 'model': model, 'key': 'default', 'key2': condition and condition[:200], 'user_id': False if for_all_users else uid, 'company_id': company_id, }) def get_defaults(self, cr, uid, model, condition=False): """Returns any default values that are defined for the current model and user, (and match ``condition``, if specified), previously registered via :meth:`~.set_default`. Defaults are global to a model, not field-specific, but an optional ``condition`` can be provided to restrict matching default values to those that were defined for the same condition (usually based on another field's value). Default values also have priorities depending on whom they apply to: only the highest priority value will be returned for any field. See :meth:`~.set_default` for more details. :param string model: model name :param string condition: optional condition specification that can be used to restrict the applicability of the default values (e.g. based on another field's value). This is an opaque string as far as the API is concerned, but client stacks typically use single-field conditions in the form ``'key=stringified_value'``. (Currently, the condition is trimmed to 200 characters, so values that share the same first 200 characters always match) :return: list of default values tuples of the form ``(id, field_name, value)`` (``id`` is the ID of the default entry, usually irrelevant) """ # use a direct SQL query for performance reasons, # this is called very often query = """SELECT v.id, v.name, v.value FROM ir_values v LEFT JOIN res_users u ON (v.user_id = u.id) WHERE v.key = %%s AND v.model = %%s AND (v.user_id = %%s OR v.user_id IS NULL) AND (v.company_id IS NULL OR v.company_id = (SELECT company_id from res_users where id = %%s) ) %s ORDER BY v.user_id, u.company_id""" params = ('default', model, uid, uid) if condition: query = query % 'AND v.key2 = %s' params += (condition[:200], ) else: query = query % 'AND v.key2 is NULL' cr.execute(query, params) # keep only the highest priority default for each field defaults = {} for row in cr.dictfetchall(): defaults.setdefault(row['name'], (row['id'], row['name'], pickle.loads(row['value'].encode('utf-8')))) return defaults.values() def set_action(self, cr, uid, name, action_slot, model, action, res_id=False): """Binds an the given action to the given model's action slot - for later retrieval via :meth:`~.get_actions`. Any existing binding of the same action to the same slot is first removed, allowing an update of the action's name. See the class description for more details about the various action slots: :class:`~ir_values`. :param string name: action label, usually displayed by UI client :param string action_slot: the action slot to which the action should be bound to - one of ``client_action_multi``, ``client_print_multi``, ``client_action_relate``, ``tree_but_open``. :param string model: model name :param string action: action reference, in the form ``'model,id'`` :param int res_id: optional record id - will bind the action only to a specific record of the model, not all records. :return: id of the newly created ir.values entry """ assert isinstance(action, basestring) and ',' in action, \ 'Action definition must be an action reference, e.g. "ir.actions.act_window,42"' assert action_slot in ACTION_SLOTS, \ 'Action slot (%s) must be one of: %r' % (action_slot, ACTION_SLOTS) # remove existing action definition of same slot and value search_criteria = [ ('key', '=', 'action'), ('key2', '=', action_slot), ('model', '=', model), ('res_id', '=', res_id or 0), # int field -> NULL == 0 ('value', '=', action), ] self.unlink(cr, uid, self.search(cr, uid, search_criteria)) return self.create( cr, uid, { 'key': 'action', 'key2': action_slot, 'model': model, 'res_id': res_id, 'name': name, 'value': action, }) def get_actions(self, cr, uid, action_slot, model, res_id=False, context=None): """Retrieves the list of actions bound to the given model's action slot. See the class description for more details about the various action slots: :class:`~.ir_values`. :param string action_slot: the action slot to which the actions should be bound to - one of ``client_action_multi``, ``client_print_multi``, ``client_action_relate``, ``tree_but_open``. :param string model: model name :param int res_id: optional record id - will bind the action only to a specific record of the model, not all records. :return: list of action tuples of the form ``(id, name, action_def)``, where ``id`` is the ID of the default entry, ``name`` is the action label, and ``action_def`` is a dict containing the action definition as obtained by calling :meth:`~openerp.osv.osv.osv.read` on the action record. """ assert action_slot in ACTION_SLOTS, 'Illegal action slot value: %s' % action_slot # use a direct SQL query for performance reasons, # this is called very often query = """SELECT v.id, v.name, v.value FROM ir_values v WHERE v.key = %s AND v.key2 = %s AND v.model = %s AND (v.res_id = %s OR v.res_id IS NULL OR v.res_id = 0) ORDER BY v.id""" cr.execute(query, ('action', action_slot, model, res_id or None)) results = {} for action in cr.dictfetchall(): if not action['value']: continue # skip if undefined action_model, id = action['value'].split(',') fields = [ field for field in self.pool.get(action_model)._all_columns if field not in EXCLUDED_FIELDS ] # FIXME: needs cleanup try: action_def = self.pool.get(action_model).read( cr, uid, int(id), fields, context) if action_def and not action_def.get('invisible'): if action_model in ('ir.actions.report.xml', 'ir.actions.act_window', 'ir.actions.wizard'): groups = action_def.get('groups_id') if groups: cr.execute( 'SELECT 1 FROM res_groups_users_rel WHERE gid IN %s AND uid=%s', (tuple(groups), uid)) if not cr.fetchone(): if action['name'] == 'Menuitem': raise osv.except_osv( 'Error !', 'You do not have the permission to perform this operation !!!' ) continue # keep only the first action registered for each action name results[action['name']] = (action['id'], action['name'], action_def) except except_orm, e: continue return sorted(results.values())
'cancel':lambda self,cr,uid,record, groups_code: record.state == 'draft', 'delete':lambda self,cr,uid,record, groups_code: record.state == 'draft', 'replan': lambda self,cr,uid,record, groups_code: record.state == 'done', 'normal_mode_finished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'open', 'normal_mode_unfinished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'open', 'light_mode_finished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'draft', 'light_mode_unfinished': lambda self,cr,uid,record, groups_code: self._task_survey_rights(cr, uid, record, groups_code) and record.state == 'draft', 'modify': lambda self,cr,uid,record, groups_code: True, } _columns = { 'active':fields.function(_get_active, method=True,type='boolean', store=False), 'ask_id': fields.many2one('openstc.ask', 'Demande', ondelete='set null', select="1"), 'project_id': fields.many2one('project.project', 'Intervention', ondelete='set null'), 'equipment_ids':fields.many2many('openstc.equipment', 'openstc_equipment_task_rel', 'task_id', 'equipment_id', 'Equipments'), 'consumable_ids':fields.many2many('openbase.consumable', 'openbase_consumable_task_rel', 'task_id', 'consumable_id', 'Fournitures'), 'parent_id': fields.many2one('project.task', 'Parent Task'), 'intervention_assignement_id':fields.many2one('openstc.intervention.assignement', 'Assignement'), 'absent_type_id':fields.many2one('openstc.absent.type', 'Type d''abscence'), 'category_id':fields.many2one('openstc.task.category', 'Category'), 'state': fields.selection([('absent', 'Absent'),('draft', 'New'),('open', 'In Progress'),('pending', 'Pending'), ('done', 'Done'), ('cancelled', 'Cancelled')], 'State', readonly=True, required=True, help='If the task is created the state is \'Draft\'.\n If the task is started, the state becomes \'In Progress\'.\n If review is needed the task is in \'Pending\' state.\ \n If the task is over, the states is set to \'Done\'.'), 'team_id': fields.many2one('openstc.team', 'Team'), 'km': fields.integer('Km', select=1), 'oil_qtity': fields.float('oil quantity', select=1), 'oil_price': fields.float('oil price', select=1),
class product_product(osv.osv): _name = 'product.product' _inherit = 'product.product' _columns = { 'tms_category': fields.selection([ ('no_tms_product', 'No TMS Product'), ('transportable', 'Transportable'), ('freight', 'Freight'), ('move', 'Move'), ('insurance', 'Insurance'), ('highway_tolls', 'Highway Tolls'), ('other', 'Other'), ('real_expense', 'Real Expense'), ('madeup_expense', 'Made-up Expense'), ('salary', 'Salary'), ('salary_retention', 'Salary Retention'), ('salary_discount', 'Salary Discount'), ('negative_balance', 'Negative Balance'), ('fuel', 'Fuel'), ('indirect_expense', 'Indirect Expense (Agreements)'), ], 'TMS Type', required=True, help="""Product Type for using with TMS Module - No TMS Product: Not related to TMS - Transportable: Transportable Product used in Waybills - Freight: Represents Freight Price used in Waybills - Move: Represents Moves Price used in Waybills - Insurance: Represents Insurance for Load used in Waybills - Highway Tolls: Represents Highway Tolls used in Waybills - Other: Represents any other charge for Freight Service used in Waybills - Real Expense: Represent real expenses related to Travel, those that will be used in Travel Expense Checkup. - Made-Up Expense: Represent made-up expenses related to Travel, those that will be used in Travel Expense Checkup. - Fuel: Used for filtering products used in Fuel Vouchers. - Indirect Expense (Agreements): Used to define Accounts for Agreements Indirect Expenses. All of these products MUST be used as a service because they will never interact with Inventory. """, translate=True), 'tms_account_ids': fields.many2many('account.account', 'tms_product_account_rel', 'product_id', 'account_id', 'Accounts for this product'), 'tms_activity_duration': fields.float('Duration', digits=(14, 2), help="Activity duration in hours"), 'tms_property_account_income': fields.many2one( 'account.account', 'Breakdown Income Account', help= 'Use this to define breakdown income account per vehicle for Freights, Moves, Insurance, etc.', required=False), 'tms_property_account_expense': fields.many2one( 'account.account', 'Breakdown Expense Account', help= 'Use this to define breakdown expense account per vehicle for Fuel, Travel Expenses, etc.', required=False), 'tms_default_freight': fields.boolean( 'Default Freight', help='Use this as default product for Freight in Waybills'), 'tms_default_supplier_freight': fields.boolean( 'Default Supplier Freight', help='Use this as default product for Supplier Freight in Waybills' ), 'tms_default_salary': fields.boolean( 'Default Salary', help= 'Use this as default product for Salary in Travel Expense Records' ), 'tms_default_fuel_discount': fields.boolean( 'Default Fuel Discount', help= 'Use this as default product for Fuel Difference Discount in Travel Expense Records' ), } _default = { 'tms_category': lambda *a: 'no_tms_product', } def _check_tms_product(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): if record.tms_category in ['transportable']: return (record.type == 'service' and record.procure_method == 'make_to_stock' and record.supply_method == 'buy' and not record.sale_ok and not record.purchase_ok) elif record.tms_category in [ 'freight', 'move', 'insurance', 'highway_tolls', 'other' ]: return (record.type == 'service' and record.procure_method == 'make_to_stock' and record.supply_method == 'buy' and record.sale_ok) elif record.tms_category in [ 'real_expense', 'madeup_expense', 'salary', 'salary_retention', 'salary_discount', 'negative_balance', 'indirect_expense' ]: return (record.type == 'service' and record.procure_method == 'make_to_stock' and record.supply_method == 'buy' and record.purchase_ok) elif record.tms_category in ['fuel']: return (record.type == 'product' and record.procure_method == 'make_to_stock' and record.supply_method == 'buy' and record.purchase_ok) return True def _check_default_fuel_discount(self, cr, uid, ids, context=None): prod_obj = self.pool.get('product.product') for record in self.browse(cr, uid, ids, context=context): if record.tms_category == 'salary_discount' and record.tms_default_fuel_discount: res = prod_obj.search(cr, uid, [('tms_default_fuel_discount', '=', 1)], context=None) if res and res[0] and res[0] != record.id: return False return True def _check_default_freight(self, cr, uid, ids, context=None): prod_obj = self.pool.get('product.product') for record in self.browse(cr, uid, ids, context=context): if record.tms_category == 'freight' and record.tms_default_freight: res = prod_obj.search(cr, uid, [('tms_default_freight', '=', 1)], context=None) if res and res[0] and res[0] != record.id: return False return True def _check_default_supplier_freight(self, cr, uid, ids, context=None): prod_obj = self.pool.get('product.product') for record in self.browse(cr, uid, ids, context=context): if record.tms_category == 'freight' and record.tms_default_supplier_freight: res = prod_obj.search( cr, uid, [('tms_default_supplier_freight', '=', 1)], context=None) if res and res[0] and res[0] != record.id: return False return True def _check_default_salary(self, cr, uid, ids, context=None): prod_obj = self.pool.get('product.product') for record in self.browse(cr, uid, ids, context=context): if record.tms_category == 'salary' and record.tms_default_salary: res = prod_obj.search(cr, uid, [('tms_default_salary', '=', 1)], context=None) if res and res[0] and res[0] != record.id: return False return True _constraints = [ (_check_tms_product, 'Error ! Product is not defined correctly...Please see tooltip for TMS Category', ['tms_category']), (_check_default_freight, 'Error ! You can not have two or more products defined as Default Freight', ['tms_default_freight']), (_check_default_supplier_freight, 'Error ! You can not have two or more products defined as Default Supplier Freight', ['tms_default_supplier_freight']), (_check_default_salary, 'Error ! You can not have two or more products defined as Default Salary', ['tms_default_salary']), (_check_default_fuel_discount, 'Error ! You can not have two or more products defined as Default Fuel Discount', ['tms_default_fuel_discount']), ] def write(self, cr, uid, ids, values, context=None): if context is None: context = {} if 'tms_category' in values: raise osv.except_osv( _('Warning !'), _('You can not change TMS Category for any product...')) return super(product_product, self).write(cr, uid, ids, values, context=context) def onchange_tms_category(self, cr, uid, ids, tms_category): val = {} if not tms_category or tms_category == 'standard': return val if tms_category in [ 'transportable', 'freight', 'move', 'insurance', 'highway_tolls', 'other', 'real_expense', 'madeup_expense', 'salary', 'salary_retention', 'salary_discount', 'negative_balance' ]: val = { 'type': 'service', 'procure_method': 'make_to_stock', 'supply_method': 'buy', 'purchase': False, 'sale': False, } return {'value': val}
), "nbr_source_line": fields.integer( "Source Line of Code", help="number of source line of code of uploaded module" ), "module_zip": fields.binary("Module Zip File"), "state": fields.selection( [("draft", "Draft"), ("open", "Open"), ("failed", "Failed"), ("done", "Done"), ("cancel", "Cancel")], "State", readonly=True, ), "test_ids": fields.one2many("test", "module_id", "Tests"), "test_tech_ids": one2many_mod_advert("test", "id", "Tests"), "test_func_ids": one2many_mod_advert("test", "id", "Tests"), "tech_certificate": fields.boolean("Technicle certificate", help="tick if you want technicle certificate"), "func_certificate": fields.boolean("Functional certificate", help="tick if you want functional certificate"), "tech_user_id": fields.many2one("res.users", "Technicle User", help="User for Technicle tests"), "func_user_id": fields.many2one("res.users", "Functional User", help="User for Functional tests"), } _defaults = { "technical_certificate": lambda *a: "not_started", "functional_certificate": lambda *a: "not_started", "state": lambda *a: "draft", } def refresh(self, cr, uid): def get_version(terp): return "%s.%s" % (release.major_version, terp["version"]) def get_terp(moddir): try:
class product_product(osv.osv): _inherit = 'product.product' _name = 'product.product' def rounding(self, f, r): if not r: return f return round(f / r) * r def _search_values(self, cr, uid, product_id, bulk_id, context=None): result = {'qty': None, 'uom': None} bom_ids = self.pool.get('mrp.bom').search( cr, uid, [('product_id', '=', product_id)], context=context) for bom in self.pool.get('mrp.bom').browse(cr, uid, bom_ids, context=context): value = False for line in bom.bom_lines: if line.product_id.id == bulk_id: value += round(line.product_qty, 5) uom_id = line.product_uom.id # break NOTE: I remove break because I found more than one bom with same components more than one time. result['qty'] = round(value, 5) result['uom'] = uom_id return result def _get_qty_available(self, cr, uid, ids, field_name, field_value, context=None): result = {} for product in self.browse(cr, uid, ids, context): #search stock of this product if field_name == 'bulk_qty_available': product_stock_qty = product.qty_available else: product_stock_qty = product.virtual_available #search stock of bulk #-------------------- bulk_stock = 0.0 for product_bulk in product.bulk_of_product_ids: #search unit_convertion factor = 0.0 #seach bom factor and uom_dest res = self._search_values(cr, uid, product_bulk.id, product.id, context=context) factor = res['qty'] uom_dest = res['uom'] #search stock and uom of bulk #for bulk_product in self.browse(cr, uid, [product_bulk.id], context=context): if field_name == 'bulk_qty_available': bulk_qty = product_bulk.qty_available else: bulk_qty = product_bulk.virtual_available uom_id = product.uom_id.id #convert bulk stock to Udm of this product amount = self.pool.get('product.uom')._compute_qty( cr, uid, uom_dest, factor, uom_id) if factor > 0.0: bulk_stock += amount * bulk_qty #sumatory of stocks result[product.id] = self.rounding(product_stock_qty + bulk_stock, product.uom_id.rounding) return result def _bulk(self, cr, uid, ids, field_name, field_value, context=None): result = {} for product in self.browse(cr, uid, ids, context): if product.bulk_of_product_ids and len( product.bulk_of_product_ids) > 0: result[product.id] = True else: result[product.id] = False return result _columns = { 'bulk_id': fields.many2one('product.product', 'Bulk', select=1, help='Bulk related with this product'), 'bulk_of_product_ids': fields.one2many( 'product.product', 'bulk_id', 'Bulk Of', help='List of all products that have the current one as a bulk.'), 'bulk': fields.function( _bulk, method=True, type='boolean', string='Is Bulk?', help= 'A product is a bulk if there are products that have this as bulk.' ), 'bulk_qty_available': fields.function(_get_qty_available, method=True, type='float', string='Bulk Stock'), 'bulk_virtual_available': fields.function(_get_qty_available, method=True, type='float', string='Virt. bulk stock'), }
user_id = res[0] elif conf['create_user']: _logger.debug("Creating new OpenERP user \"%s\" from LDAP" % login) user_obj = self.pool.get('res.users') values = self.map_ldap_attributes(cr, uid, conf, login, ldap_entry) if conf['user']: user_id = user_obj.copy(cr, SUPERUSER_ID, conf['user'], default={'active': True}) user_obj.write(cr, SUPERUSER_ID, user_id, values) else: user_id = user_obj.create(cr, SUPERUSER_ID, values) return user_id _columns = { 'sequence': fields.integer('Sequence'), 'company': fields.many2one('res.company', 'Company', required=True, ondelete='cascade'), 'ldap_server': fields.char('LDAP Server address', size=64, required=True), 'ldap_server_port': fields.integer('LDAP Server port', required=True), 'ldap_binddn': fields.char('LDAP binddn', size=64, help=("The user account on the LDAP server that is used to query " "the directory. Leave empty to connect anonymously.")), 'ldap_password': fields.char('LDAP password', size=64, help=("The password of the user account on the LDAP server that is " "used to query the directory.")), 'ldap_filter': fields.char('LDAP filter', size=256, required=True), 'ldap_base': fields.char('LDAP base', size=64, required=True), 'user': fields.many2one('res.users', 'Model User', help="Model used for user creation"), 'create_user': fields.boolean('Create user', help="Create the user if not in database"), 'ldap_tls': fields.boolean('Use TLS',
class AccountInvoice(orm.Model): _inherit = 'account.invoice' _columns = { 'payment_type': fields.many2one('payment.type', 'Payment type'), } def onchange_partner_id(self, cr, uid, ids, type, partner_id, date_invoice=False, payment_term=False, partner_bank_id=False, company_id=False): # Copy partner data to invoice, also the new field payment_type result = super(AccountInvoice, self).onchange_partner_id(cr, uid, ids, type, partner_id, date_invoice, payment_term, partner_bank_id, company_id) payment_type = False if partner_id: partner_line = self.pool['res.partner'].browse(cr, uid, partner_id) if partner_line: if type in ('in_invoice', 'in_refund'): payment_type = partner_line.payment_type_supplier.id else: payment_type = partner_line.payment_type_customer.id if payment_type: result['value']['payment_type'] = payment_type return self.onchange_payment_type(cr, uid, ids, payment_type, partner_id, result) def onchange_payment_type(self, cr, uid, ids, payment_type, partner_id, result=None): if result is None: result = {'value': {}} if payment_type and partner_id: bank_types = self.pool['payment.type'].browse( cr, uid, payment_type).suitable_bank_types if bank_types: # If the payment type is related with a bank account bank_types = [bt.code for bt in bank_types] partner_bank_obj = self.pool.get('res.partner.bank') args = [('partner_id', '=', partner_id), ('default_bank', '=', 1), ('state', 'in', bank_types)] bank_account_id = partner_bank_obj.search(cr, uid, args) if bank_account_id: result['value']['partner_bank_id'] = bank_account_id[0] return result result['value']['partner_bank_id'] = False return result def action_move_create(self, cr, uid, ids, *args): ret = super(AccountInvoice, self).action_move_create(cr, uid, ids, *args) if ret: for inv in self.browse(cr, uid, ids): move_line_ids = [] for move_line in inv.move_id.line_id: if move_line.account_id.type in ('receivable', 'payable') \ and move_line.state != 'reconciled' and \ not move_line.reconcile_id.id: move_line_ids.append(move_line.id) if len(move_line_ids) and inv.partner_bank_id: aml_obj = self.pool.get("account.move.line") aml_obj.write(cr, uid, move_line_ids, {'partner_bank_id': inv.partner_bank_id.id}) return ret
cursor.execute("select serial_number from mttl_serials where id=(select max(id) from mttl_serials)") for item in cursor.dictfetchall(): serial_number = int(item["serial_number"]) + 1 return serial_number except Exception, ex: return False _name = "mttl.serials" _description = "Serials" _rec_name="serial" _order = "id desc" _columns = { 'serial':fields.char('Serial', size=50, help="Add text here"), # Information 'model':fields.many2one('mttl.models', 'Model', required=True, help="Metro Tow Trucks Model"), 'year':fields.many2one('mttl.years', 'Year', required=True, help="Year of model"), 'location':fields.many2one('mttl.locations', 'Location', required=True, help="Manufacture location"), 'country':fields.many2one('mttl.countries', 'Country', required=True, help="Country of manufacture"), 'chassis':fields.many2one('mttl.chassis', 'Chassis', required=True, help="Who supplied the chassis, or was it sold as a kit?"), 'partner_id':fields.many2one('res.partner', 'Customer', change_default=True, help="Last known owner of this unit", domain="[('customer','=',True)]"), 'dealer_id':fields.many2one('res.partner', 'Dealer', change_default=True, help="Last known owner of this unit", domain="[('dealer','=',True)]"), 'destination_id':fields.many2one('res.partner', 'Destination', change_default=True, help="Last known location of this unit", domain="[('customer','=',True)]"), 'serial_number':fields.char('Serial Number',size=17, required=True, help="The Computed Serial Number. Verify that no periods or question marks are present"), #Vehicle Information 'chassis_weight': fields.char("Chassis Weight", size=10, help="Weight of Chassis without Wrecker"), 'wrecker_weight': fields.char("Wrecker Weight", size=10, help="Weight of Wrecker without Chassis"), 'installed_weight':fields.char("Installed Weight", size=10, help="Completed Vehicle Weight including accessories and fluids"), 'vehicle_model':fields.many2one("mttl.vehicle.model",'Model', help="Chassis Model"), 'vehicle_make':fields.many2one('mttl.vehicle.make','Make', help="Chassis Make"),
class account_transfer(osv.osv): _name = 'account.transfer' _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = 'Traspaso Bancario' _order = 'name desc' def _get_balance(self, src_journal, dst_journal, company): """ Obtiene la informacion del saldo sobre el diario origen y destino """ src_balance = dst_balance = 0.0 #import pdb; pdb.set_trace() if src_journal.default_credit_account_id.id == src_journal.default_debit_account_id.id: if not src_journal.currency or company.currency_id.id == src_journal.currency.id: src_balance = src_journal.default_credit_account_id.balance else: src_balance = src_journal.default_credit_account_id.foreign_balance else: if not src_journal.currency or company.currency_id.id == src_journal.currency.id: src_balance = src_journal.default_debit_account_id.balance - src_journal.default_credit_account_id.balance else: src_balance = src_journal.default_debit_account_id.foreign_balance - src_journal.default_credit_account_id.foreign_balance if dst_journal.default_credit_account_id.id == dst_journal.default_debit_account_id.id: if not dst_journal.currency or company.currency_id.id == dst_journal.currency.id: dst_balance = dst_journal.default_credit_account_id.balance else: dst_balance = dst_journal.default_credit_account_id.foreign_balance else: if not dst_journal.currency or company.currency_id.id == dst_journal.currency.id: dst_balance = dst_journal.default_debit_account_id.balance - dst_journal.default_credit_account_id.balance else: dst_balance = dst_journal.default_debit_account_id.foreign_balance - dst_journal.default_credit_account_id.foreign_balance return (src_balance, dst_balance) def _balance(self, cr, uid, ids, field_name, arg, context=None): """ Obtiene la informacion de los saldos sobre los diarios en los que aplica la transferencia """ res = {} for trans in self.browse(cr, uid, ids, context=context): src_balance, dst_balance = self._get_balance( trans.src_journal_id, trans.dst_journal_id, trans.company_id) exchange = False if trans.dst_journal_id.currency.id != trans.src_journal_id.currency.id: exchange = True res[trans.id] = { 'src_balance': src_balance, 'dst_balance': dst_balance, 'exchange': exchange, 'exchange_inv': (trans.exchange_rate and 1.0 / trans.exchange_rate or 0.0) } return res def get_period_on_date(self, cr, uid, date, context=None): """ Obtiene el periodo en base a una fecha """ period_obj = self.pool.get('account.period') period_ids = period_obj.find(cr, uid, date, context=context) return period_ids and period_ids[0] or False def _get_type(self, cr, uid, context=None): """ Retorna un arreglo con la lista de los tipos disponibles sobre el traspaso """ return [('transfer', 'Transferencia')] STATE_SELECTION = [ ('draft', 'Borrador'), ('confirm', 'Confirmado'), ('done', 'Finalizado'), ('cancel', 'Cancelado'), ] _columns = { 'company_id': fields.many2one('res.company', 'Compañia', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'type': fields.selection(_get_type, 'Tipo', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'name': fields.char('Numero', size=32, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'date': fields.date('Fecha', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'origin': fields.char('Origen', size=128, readonly=True, states={'draft': [('readonly', False)]}, help="Ducumento de origen o referencia"), 'account_analytic_id': fields.many2one('account.analytic.account', 'Cuenta Analitica', readonly=True, states={'draft': [('readonly', False)]}), 'voucher_ids': fields.one2many('account.voucher', 'transfer_id', string='Pagos', readonly=True, states={ 'draft': [('readonly', False)], 'confirm': [('readonly', False)] }), 'src_journal_id': fields.many2one('account.journal', 'Banco Origen', required=True, domain=[('type', 'in', ['cash', 'bank'])], select=True, readonly=True, states={'draft': [('readonly', False)]}), 'src_partner_id': fields.many2one('res.partner', 'Contacto Origen', select=True), 'src_balance': fields.function( _balance, digits_compute=dp.get_precision('Account'), string='Saldo Banco origen', type='float', readonly=True, multi='balance', help="Saldo actual sobre la cuenta asignada al diario"), 'src_amount': fields.float('Monto a Transferir', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'src_have_partner': fields.related('src_journal_id', 'have_partner', type='boolean', string='Contacto Requerido', readonly=True), 'dst_journal_id': fields.many2one('account.journal', 'Banco Destino', required=True, domain=[('type', 'in', ['cash', 'bank'])], select=True, readonly=True, states={'draft': [('readonly', False)]}), 'dst_partner_id': fields.many2one('res.partner', 'Contacto Destino', select=True), 'dst_balance': fields.function( _balance, digits_compute=dp.get_precision('Account'), string='Saldo Banco destino', type='float', readonly=True, multi='balance', help="Saldo actual sobre la cuenta asignada al diario"), 'dst_amount': fields.float('Monto transferido', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'dst_have_partner': fields.related('dst_journal_id', 'have_partner', type='boolean', string='Contacto Requerido', readonly=True), 'exchange_rate': fields.float('Tipo de cambio', digits_compute=dp.get_precision('Exchange'), readonly=True, states={'draft': [('readonly', False)]}), 'exchange': fields.function(_balance, string='Cambia Moneda', type='boolean', readonly=True, multi='balance'), 'exchange_inv': fields.function(_balance, string='1 / Cambia moneda', type='float', digits_compute=dp.get_precision('Exchange'), readonly=True, multi='balance'), 'adjust_move': fields.many2one( 'account.move', 'Ajustar movimiento', readonly=True, help= "Ajuste del movimiento usualmente aplicado por el cambio de moneda" ), 'state': fields.selection(STATE_SELECTION, string='Estado', track_visibility='onchange', readonly=True), 'period_id': fields.many2one('account.period', 'Periodo') } def _get_default_partner_company(self, cr, uid, context=None): """ Obtiene el partner de la compañia """ partner_id = False user = self.pool.get('res.users').browse(cr, uid, uid, context=context) partner_id = user.company_id and user.company_id.partner_id and user.company_id.partner_id.id or False return partner_id _defaults = { 'type': 'transfer', 'name': lambda s, cr, u, c: s.pool.get('ir.sequence').get( cr, u, 'account.transfer'), 'company_id': lambda s, cr, u, c: s.pool.get('res.users').browse(cr, u, u).company_id .id, 'date': lambda *a: time.strftime('%Y-%m-%d'), 'exchange_rate': 1.0, 'exchange_inv': 1.0, 'state': 'draft', 'src_partner_id': _get_default_partner_company, 'dst_partner_id': _get_default_partner_company, } _sql_constraints = [('name_unique', 'unique(company_id,name)', _('El numero debe ser unico!'))] def voucher_get(self, cr, uid, trans, context=None): res = {} res['transfer_id'] = trans.id res['type'] = 'transfer' res['company_id'] = trans.company_id.id res['reference'] = trans.name + str(trans.origin and (' - ' + trans.origin) or '') res['line_ids'] = [(0, 0, {})] res['line_ids'][0][2][ 'account_analytic_id'] = trans.account_analytic_id and trans.account_analytic_id.id or 0 res['line_ids'][0][2]['name'] = trans.origin return res def unlink(self, cr, uid, ids, context=None): """ Valida que no se puedan eliminar traspasos que no esten en borrador """ for trans in self.browse(cr, uid, ids, context=context): if trans.state not in ('draft'): raise osv.except_osv( _('User Error!'), _('No puedes eliminar un, traspaso que no este en estado borrador: "%s"' ) % trans.name) return super(account_transfer, self).unlink(cr, uid, ids, context=context) def copy(self, cr, uid, id, defaults, context=None): """ Pasa a borrador el documento duplicado y no relaciona los pagos """ defaults['name'] = self.pool.get('ir.sequence').get( cr, uid, 'account.transfer') defaults['voucher_ids'] = [] defaults['state'] = 'draft' return super(account_transfer, self).copy(cr, uid, id, defaults, context=context) def onchange_amount(self, cr, uid, ids, field, src_amount, dst_amount, exchange_rate): """ Actualiza el monto a traspasado """ res = {'value': {}} if field == 'src_amount': res['value']['src_amount'] = src_amount res['value']['dst_amount'] = src_amount * exchange_rate res['value']['exchange_rate'] = exchange_rate res['value'][ 'exchange_inv'] = exchange_rate and 1.0 / exchange_rate or 0.0 elif field == 'dst_amount': res['value'][ 'src_amount'] = exchange_rate and dst_amount / exchange_rate or 0.0 res['value']['dst_amount'] = dst_amount res['value']['exchange_rate'] = exchange_rate res['value'][ 'exchange_inv'] = exchange_rate and 1.0 / exchange_rate or 0.0 elif field == 'exchange_rate': res['value']['src_amount'] = src_amount res['value']['dst_amount'] = src_amount * exchange_rate res['value']['exchange_rate'] = exchange_rate res['value'][ 'exchange_inv'] = exchange_rate and 1.0 / exchange_rate or 0.0 return res def onchange_journal(self, cr, uid, ids, src_journal_id, dst_journal_id, date, exchange_rate, src_amount): """ Actualiza la informacion en base al diario """ res = {'value': {}} if not (src_journal_id and dst_journal_id): return res src_journal = self.pool.get('account.journal').browse( cr, uid, src_journal_id) dst_journal = self.pool.get('account.journal').browse( cr, uid, dst_journal_id) res['value']['src_balance'], res['value'][ 'dst_balance'] = self._get_balance(src_journal, dst_journal, src_journal.company_id) res['value']['exchange'] = (src_journal.currency.id != dst_journal.currency.id) res['value']['src_have_partner'], res['value'][ 'dst_have_partner'] = src_journal.have_partner, dst_journal.have_partner res['value']['exchange_rate'] = exchange_rate if res['value']['exchange']: res['value']['exchange_rate'] = ( src_journal.currency and src_journal.currency.rate or src_journal.company_id.currency_id.rate) and ( (dst_journal.currency and dst_journal.currency.rate or dst_journal.company_id.currency_id.rate) / (src_journal.currency and src_journal.currency.rate or src_journal.company_id.currency_id.rate)) or 0.0 else: res['value']['exchange_rate'] = 1.0 res['value']['exchange_inv'] = res['value']['exchange_rate'] and ( 1.0 / res['value']['exchange_rate']) or 0.0 res['value']['dst_amount'] = res['value']['exchange_rate'] * src_amount return res def action_confirm(self, cr, uid, ids, context=None): """ Pasa el traspaso a confirmado """ voucher_obj = self.pool.get('account.voucher') for trans in self.browse(cr, uid, ids, context=context): sval = self.voucher_get(cr, uid, trans, context=context) dval = self.voucher_get(cr, uid, trans, context=context) sval['journal_id'] = trans.src_journal_id.id dval['journal_id'] = trans.dst_journal_id.id sval[ 'account_id'] = trans.src_journal_id.default_credit_account_id.id dval[ 'account_id'] = trans.dst_journal_id.default_debit_account_id.id sval[ 'payment_rate'] = trans.src_journal_id.currency.id and trans.company_id.currency_id.id <> trans.src_journal_id.currency.id and trans.exchange_rate or 1.0 dval[ 'payment_rate'] = trans.dst_journal_id.currency.id and trans.company_id.currency_id.id <> trans.dst_journal_id.currency.id and trans.exchange_inv or 1.0 dval[ 'payment_rate_currency_id'] = trans.dst_journal_id.currency.id or trans.company_id.currency_id.id sval[ 'payment_rate_currency_id'] = trans.src_journal_id.currency.id or trans.company_id.currency_id.id sval['journal_id_transfer'] = trans.dst_journal_id.id dval['journal_id_transfer'] = trans.src_journal_id.id sval['type'] = trans.type dval['type'] = trans.type # Agrega la fecha al registro if trans.date: sval['date'] = trans.date dval['date'] = trans.date #import pdb; pdb.set_trace() sval['line_ids'][0][2]['amount'] = sval[ 'amount'] = trans.src_amount dval['line_ids'][0][2]['amount'] = dval[ 'amount'] = trans.dst_amount sval['line_ids'][0][2]['type'] = 'dr' dval['line_ids'][0][2]['type'] = 'cr' sval['line_ids'][0][2][ 'account_id'] = trans.dst_journal_id.default_debit_account_id.id dval['line_ids'][0][2][ 'account_id'] = trans.dst_journal_id.default_debit_account_id.id # Agrega el contacto para el traspaso sval[ 'partner_id'] = trans.src_have_partner and trans.src_partner_id.id or trans.company_id.partner_id.id dval[ 'partner_id'] = trans.dst_have_partner and trans.dst_partner_id.id or trans.company_id.partner_id.id # Obtiene el periodo segun la fecha period_id = self.get_period_on_date(cr, uid, trans.date, context=context) if period_id: self.write(cr, uid, [trans.id], {'period_id': period_id}, context=context) sval['period_id'] = period_id or False dval['period_id'] = period_id or False #if not trans.src_partner_id.id ^ trans.dst_partner_id.id: # sval['partner_id'] = trans.src_have_partner and trans.src_partner_id.id or trans.dst_partner_id.id #else: # sval['partner_id'] = trans.src_have_partner and trans.src_partner_id.id or trans.company_id.partner_id.id # dval['partner_id'] = trans.dst_have_partner and trans.dst_partner_id.id or trans.company_id.partner_id.id # sval['line_ids'][0][2]['account_id'] = dval['line_ids'][0][2]['account_id'] = trans.src_journal_id.account_transit.id # voucher_obj.create(cr, uid, dval, context=context) voucher_obj.create(cr, uid, sval, context=context) return self.write(cr, uid, ids, {'state': 'confirm'}, context=context) def action_done(self, cr, uid, ids, context=None): """ Confirma el documento y genera el traspaso sobre las cuentas """ voucher_obj = self.pool.get('account.voucher') move_obj = self.pool.get('account.move') for trans in self.browse(cr, uid, ids, context=context): paid_amount = [] for voucher in trans.voucher_ids: (voucher.state == 'draft') and voucher_obj.proforma_voucher( cr, uid, [voucher.id], context=context) sign = (voucher.journal_id.id == trans.src_journal_id.id) and 1 or -1 paid_amount.append( sign * voucher_obj._paid_amount_in_company_currency( cr, uid, [voucher.id], '', '')[voucher.id]) #paid_amount.append(sign * voucher.paid_amount_in_company_currency) sum_amount = sum(paid_amount) if len(paid_amount) > 1 and sum_amount != 0.0: periods = self.pool.get('account.period').find(cr, uid) move = {} move['journal_id'] = trans.dst_journal_id.id move['period_id'] = periods and periods[0] or False move['ref'] = trans.name + str(trans.origin and (' - ' + trans.origin) or '') move['date'] = trans.date move['line_id'] = [(0, 0, {}), (0, 0, {})] move['line_id'][0][2]['name'] = trans.name move['line_id'][1][2]['name'] = trans.name if sum_amount > 0: move['line_id'][0][2][ 'account_id'] = trans.dst_journal_id.default_debit_account_id.id move['line_id'][1][2][ 'account_id'] = trans.src_journal_id.account_transit.id #trans.company_id.income_currency_exchange_account_id.id move['line_id'][0][2]['debit'] = sum_amount move['line_id'][1][2]['credit'] = sum_amount else: move['line_id'][0][2][ 'account_id'] = trans.dst_journal_id.default_credit_account_id.id move['line_id'][1][2][ 'account_id'] = trans.src_journal_id.account_transit.id #trans.company_id.expense_currency_exchange_account_id.id move['line_id'][1][2]['debit'] = -1 * sum_amount move['line_id'][0][2]['credit'] = -1 * sum_amount move_id = move_obj.create(cr, uid, move, context=context) self.write(cr, uid, [trans.id], {'adjust_move': move_id}, context=context) return self.write(cr, uid, ids, {'state': 'done'}, context=context) def action_cancel(self, cr, uid, ids, context=None): """ Cancela el traspaso generado """ voucher_obj = self.pool.get('account.voucher') move_obj = self.pool.get('account.move') #import pdb; pdb.set_trace() for trans in self.browse(cr, uid, ids, context=context): for voucher in trans.voucher_ids: # Cancela el voucher antes de eliminarlo voucher_obj.cancel_voucher(cr, uid, [voucher.id], context=context) # Elimina el voucher voucher_obj.unlink(cr, uid, [voucher.id], context=context) trans.adjust_move and move_obj.unlink( cr, uid, [trans.adjust_move.id], context=context) return self.write(cr, uid, ids, {'state': 'cancel'}, context=context) def action_draft(self, cr, uid, ids, context=None): """ Pasa el traspaso a borrador """ self.write(cr, uid, ids, {'state': 'draft'}) # wf_service = netsvc.LocalService("workflow") # for trans_id in ids: # wf_service.trg_delete(uid, 'account.transfer', trans_id, cr) # wf_service.trg_create(uid, 'account.transfer', trans_id, cr) return True
_logger.warning( 'Data not found for items of %s', module_rec.name) except AttributeError, e: _logger.warning( 'Data not found for items of %s %s', module_rec.name, str(e)) except Exception, e: _logger.warning('Unknown error while fetching data of %s', module_rec.name, exc_info=True) for key, value in res.iteritems(): for k, v in res[key].iteritems(): res[key][k] = "\n".join(sorted(v)) return res _columns = { 'name': fields.char("Name", size=128, readonly=True, required=True, select=True), 'category_id': fields.many2one('ir.module.category', 'Category', readonly=True, select=True), 'shortdesc': fields.char('Short Description', size=256, readonly=True, translate=True), 'description': fields.text("Description", readonly=True, translate=True), 'author': fields.char("Author", size=128, readonly=True), 'maintainer': fields.char('Maintainer', size=128, readonly=True), 'contributors': fields.text('Contributors', readonly=True), 'website': fields.char("Website", size=256, readonly=True), # attention: Incorrect field names !! # installed_version refer the latest version (the one on disk) # latest_version refer the installed version (the one in database) # published_version refer the version available on the repository 'installed_version': fields.function(_get_latest_version, string='Latest version', type='char'), 'latest_version': fields.char('Installed version', size=64, readonly=True), 'published_version': fields.char('Published Version', size=64, readonly=True),
class tcv_sigesic_0901(osv.osv): _name = 'tcv.sigesic.0901' _description = 'Inputs and/or raw materials required' _csv_file_name = 'insumos_materia_prima_%s.csv' ##------------------------------------------------------------------------- ##------------------------------------------------------- _internal methods def _csv_header(self, cr, uid, ids, context): return ( 'CODIGO ARANCELARIO', 'NOMBRE DEL INSUMO', 'ESPECIFICACIONES TECNICAS', 'MARCA', 'UNIDAD DE MEDIDA', 'PESO UNITARIO (KG/U)', 'CANTIDAD COMPRADA NACIONAL ANHO CONCLUIDO', 'CANTIDAD COMPRADA IMPORTADA ANHO CONCLUIDO', 'PRECIO DE ADQUISICION NACIONAL ANHO CONCLUIDO (Bs.)', 'PRECIO DE ADQUISICION INTERNACIONAL (FOB) ANHO CONCLUIDO (Bs.)', 'NUMERO DE PROVEEDORES', 'SEGUN EL PLAN DE PRODUCCION, QUE CANTIDAD DE UNIDADES ESTIMA ' + 'NECESITARA EN EL ANHO ACTUAL?', ) def _get_full_name(self, item): return '%s. Marca: %s. Esp. Tec.: %s' % \ (item.name.strip() or '', item.product_id and item.product_id.name.strip() or '', item.tech_specs.strip() or '') def name_get(self, cr, uid, ids, context): if not len(ids): return [] res = [] so_brw = self.browse(cr, uid, ids, context) for item in so_brw: res.append((item.id, self._get_full_name(item))) return res ##--------------------------------------------------------- function fields _columns = { 'hs_code_id': fields.many2one('tcv.sigesic.9901', 'HS Code', ondelete='restrict'), 'name': fields.char('Name', size=100, required=False, readonly=False, help="Nombre genérico del insumo requerido."), 'product_id': fields.many2one('product.product', 'Product', ondelete='restrict', required=True, help="Denominación o nombre " + "comercial del producto (Marca)"), 'tech_specs': fields.related('product_id', 'tech_specs', type='text', string='Tech specs', store=False, readonly=True, help="Composición o características " + "físicas y/o químicas del producto"), 'uom_id': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Uom', store=False, readonly=True), 'weight': fields.related('product_id', 'weight', type='float', string='Gross weight', store=False, readonly=True, digits=(3, 5)), 'local_qty': fields.float('Local qty', digits=(15, 2), readonly=False, help="Número de unidades compradas en el " + "mercado nacional, de acuerdo a la Udm"), 'import_qty': fields.float('Imported qty', digits=(15, 2), readonly=False, help="Número de unidades compradas en el " + "mercado internacional, de acuerdo a la " + "Udm"), 'local_cost': fields.float('Local price', digits=(15, 2), readonly=False), 'import_cost': fields.float('Imported price', digits=(15, 2), readonly=False), 'supplier_qty': fields.integer('Supplier qty'), 'required_qty': fields.float('Required qty', digits=(15, 2), readonly=False, help="Según el Plan de Producción, " + "número de unidades que estima " + "necesitará en el año actual, de " + "acuerdo a la Udm"), 'seller_ids': fields.related('product_id', 'seller_ids', type='one2many', relation='product.supplierinfo', string='Suppliers', store=False, readonly=True), 'data_year': fields.integer('Year', required=True, help="El año al que corresponden los datos"), } _defaults = { 'supplier_qty': 1, } _sql_constraints = [ ('product_id_uniq', 'UNIQUE(data_year,product_id)', 'The product must be unique!'), ] ##------------------------------------------------------------------------- ##---------------------------------------------------------- public methods def get_data_lines_ids(self, cr, uid, line_id, data_year, context): return self.search(cr, uid, [('data_year', '=', data_year)]) def get_data_line(self, cr, uid, line_id, context): def str_uom(uom): uoms = { 'm2': u'm²', 'm3': u'm³', 'Unidad': u'unid', 'ml': u'm', } return uom and uoms.get(uom, uom) or '' def str_line(name): return name and name.replace(';', ',').strip() or '' line = self.browse(cr, uid, line_id, context=context) return ( str_line(line.hs_code_id and line.hs_code_id.code), str_line(line.name), str_line(line.tech_specs), str_line(line.product_id and line.product_id.name), str_uom(line.uom_id and line.uom_id.name), str_line('%.2f' % line.weight), str_line('%.2f' % line.local_qty), str_line('%.2f' % line.import_qty), str_line('%.2f' % line.local_cost), str_line('%.2f' % line.import_cost), str_line('%d' % line.supplier_qty), str_line('%.2f' % line.required_qty), ) ##-------------------------------------------------------- buttons (object) ##------------------------------------------------------------ on_change... def on_change_hs_code_id(self, cr, uid, ids, hs_code_id, product_id): if product_id and hs_code_id: obj_prd = self.pool.get('product.product') prd = obj_prd.browse(cr, uid, product_id, context=None) if not prd.hs_code or hs_code_id != prd.hs_code: obj_hsc = self.pool.get('tcv.sigesic.9901') hsc = obj_hsc.browse(cr, uid, hs_code_id, context=None) obj_prd.write(cr, uid, prd.id, {'hs_code': hsc.code}, context=None) return {'value': {}} def on_change_product_id(self, cr, uid, ids, product_id): res = {} if product_id: obj_prd = self.pool.get('product.product') prd = obj_prd.browse(cr, uid, product_id, context=None) supplier_qty = len(prd.seller_ids) or 1 res.update({ 'tech_specs': prd.tech_specs, 'uom_id': prd.uom_id.id, 'weight': prd.weight, 'supplier_qty': supplier_qty, }) if prd.hs_code: ids = self.pool.get('tcv.sigesic.9901').\ search(cr, uid, [('code', '=', prd.hs_code)]) if ids and len(ids) == 1: res.update({'hs_code_id': ids[0]}) return {'value': res}
cr.execute("SELECT id, state FROM ir_module_module WHERE name='deferred_processing'") deferred_proc_module = cr.dictfetchone() if deferred_proc_module and deferred_proc_module['state'] in ('installed', 'to upgrade'): result.append('deferred_processing') ############################################ return dict.fromkeys(ids, ','.join(result)) _columns = { 'charset':fields.selection(_get_encodings, string='Charset', required=True), 'content_fname': fields.char('Override Extension',size=64, help='Here you can override output file extension'), 'styles_mode': fields.selection([ ('default','Not used'), ('global', 'Global'), ('specified', 'Specified'), ], string='Stylesheet'), 'stylesheet_id':fields.many2one('report.stylesheets', 'Template Stylesheet'), 'preload_mode':fields.selection([ ('static',_('Static')), ('preload',_('Preload')), ],'Preload Mode'), 'tml_source':fields.selection([ ('database','Database'), ('file','File'), ('parser','Parser'), ],'Template source', select=True), 'parser_def': fields.text('Parser Definition'), 'parser_loc':fields.char('Parser location', size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}"), 'parser_state':fields.selection([ ('default',_('Default')), ('def',_('Definition')), ('loc',_('Location')),
class PoweremailMailboxConversation(osv.osv): _inherit = "poweremail.mailbox" _columns = { 'conversation_id': fields.many2one('poweremail.conversation', 'Conversation') }