def get_columns(self):
     return {
         self.one2many_name: fields.one2many(self.model,
                                             'node_id',
                                             self.field_name, context={
             'via_reporting_tree.tree_node_specialization_name':
                 self.tree_node_type,
         })
     }
示例#2
0
class stock_picking(osv.osv):
    _inherit = "stock.picking"

    # override copy and copy_data method to prevent copying landing cost when creating returns
    def copy(self, cr, uid, id, default=None, context=None):
        if default is None:
            default = {}
        default['landing_costs_line_ids'] = []
        res = super(stock_picking, self).copy(cr, uid, id, default, context)
        return res

    def copy_data(self, cr, uid, id, default=None, context=None):
        res = super(stock_picking, self).copy_data(cr, uid, id, default,
                                                   context)
        if res.get('landing_costs_line_ids', False):
            res['landing_costs_line_ids'] = []
        return res

    # per amount landing costs amount
    def _landing_costs_per_value(self, cr, uid, ids, name, args, context):
        if not ids:
            return {}
        result = {}
        for line in self.browse(cr, uid, ids):
            per_value = 0.0
            if line.landing_costs_line_ids:
                for costs in line.landing_costs_line_ids:
                    if costs.distribution_type == 'per_value':
                        per_value += costs.amount
            result[line.id] = per_value
        return result

    # per unit landing costs amount
    def _landing_costs_per_unit(self, cr, uid, ids, name, args, context):
        if not ids:
            return {}
        result = {}
        for line in self.browse(cr, uid, ids):
            per_unit = 0.0
            if line.landing_costs_line_ids:
                for costs in line.landing_costs_line_ids:
                    if costs.distribution_type == 'per_unit':
                        per_unit += costs.amount
            result[line.id] = per_unit
        return result

    # picking quantity for cost calculation
    def _landing_costs_base_quantity(self, cr, uid, ids, name, args, context):
        if not ids:
            return {}
        result = {}
        for line in self.browse(cr, uid, ids):
            base_quantity = 0.0
            if line.move_lines:
                for ml in line.move_lines:
                    if ml.product_id.landing_cost_calculate:
                        base_quantity += ml.product_qty
            result[line.id] = base_quantity
        return result

    # picking amount for costs calculation
    def _landing_costs_base_amount(self, cr, uid, ids, name, args, context):
        if not ids:
            return {}
        result = {}
        for line in self.browse(cr, uid, ids):
            base_amount = 0.0
            if line.move_lines:
                for ml in line.move_lines:
                    if ml.product_id.landing_cost_calculate:
                        base_amount += ml.price_unit * ml.product_qty
            result[line.id] = base_amount
        return result

    _columns = {
        'landing_costs_line_ids':
        fields.one2many('purchase.landing.cost.position', 'picking_id',
                        'Landing Costs'),
        'landing_costs_per_value':
        fields.function(
            _landing_costs_per_value,
            digits_compute=dp.get_precision('Product Price'),
            string='Landing Costs Amount Per Value For Average Price'),
        'landing_costs_per_unit':
        fields.function(
            _landing_costs_per_unit,
            digits_compute=dp.get_precision('Product Price'),
            string='Landing Costs Amount Per Unit For Average Price'),
        'landing_costs_base_quantity':
        fields.function(_landing_costs_base_quantity,
                        digits_compute=dp.get_precision('Product Price'),
                        string='Picking Quantity For Per Unit Calculation'),
        'landing_costs_base_amount':
        fields.function(_landing_costs_base_amount,
                        digits_compute=dp.get_precision('Product Price'),
                        string='Picking Amount For Per Value Calculation'),
    }
示例#3
0
class product_supplierinfo(osv.osv):
    _name = "product.supplierinfo"
    _description = "Information about a product supplier"
    def _calc_qty(self, cr, uid, ids, fields, arg, context=None):
        result = {}
        product_uom_pool = self.pool.get('product.uom')
        for supplier_info in self.browse(cr, uid, ids, context=context):
            for field in fields:
                result[supplier_info.id] = {field:False}
            qty = supplier_info.min_qty
            result[supplier_info.id]['qty'] = qty
        return result

    _columns = {
        'name' : fields.many2one('res.partner', 'Supplier', required=True,domain = [('supplier','=',True)], ondelete='cascade', help="Supplier of this product"),
        'product_name': fields.char('Supplier Product Name', size=128, help="This supplier's product name will be used when printing a request for quotation. Keep empty to use the internal one."),
        'product_code': fields.char('Supplier Product Code', size=64, help="This supplier's product code will be used when printing a request for quotation. Keep empty to use the internal one."),
        'sequence' : fields.integer('Sequence', help="Assigns the priority to the list of product supplier."),
        'product_uom': fields.related('product_id', 'uom_po_id', type='many2one', relation='product.uom', string="Supplier UoM", readonly="1", help="This comes from the product form."),
        'min_qty': fields.float('Minimal Quantity', required=True, help="The minimal quantity to purchase to this supplier, expressed in the supplier Product UoM if not empty, in the default unit of measure of the product otherwise."),
        'qty': fields.function(_calc_qty, store=True, type='float', string='Quantity', multi="qty", help="This is a quantity which is converted into Default Uom."),
        'product_id' : fields.many2one('product.template', 'Product', required=True, ondelete='cascade', select=True),
        'delay' : fields.integer('Delivery Lead Time', required=True, help="Lead time in days between the confirmation of the purchase order and the reception of the products in your warehouse. Used by the scheduler for automatic computation of the purchase order planning."),
        'pricelist_ids': fields.one2many('pricelist.partnerinfo', 'suppinfo_id', 'Supplier Pricelist'),
        'company_id':fields.many2one('res.company','Company',select=1),
    }
    _defaults = {
        'qty': lambda *a: 0.0,
        'sequence': lambda *a: 1,
        'delay': lambda *a: 1,
        'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'product.supplierinfo', context=c),
    }
    def price_get(self, cr, uid, supplier_ids, product_id, product_qty=1, context=None):
        """
        Calculate price from supplier pricelist.
        @param supplier_ids: Ids of res.partner object.
        @param product_id: Id of product.
        @param product_qty: specify quantity to purchase.
        """
        if type(supplier_ids) in (int,long,):
            supplier_ids = [supplier_ids]
        res = {}
        product_pool = self.pool.get('product.product')
        partner_pool = self.pool.get('res.partner')
        pricelist_pool = self.pool.get('product.pricelist')
        currency_pool = self.pool.get('res.currency')
        currency_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
        for supplier in partner_pool.browse(cr, uid, supplier_ids, context=context):
            # Compute price from standard price of product
            price = product_pool.price_get(cr, uid, [product_id], 'standard_price', context=context)[product_id]

            # Compute price from Purchase pricelist of supplier
            pricelist_id = supplier.property_product_pricelist_purchase.id
            if pricelist_id:
                price = pricelist_pool.price_get(cr, uid, [pricelist_id], product_id, product_qty, context=context).setdefault(pricelist_id, 0)
                price = currency_pool.compute(cr, uid, pricelist_pool.browse(cr, uid, pricelist_id).currency_id.id, currency_id, price)

            # Compute price from supplier pricelist which are in Supplier Information
            supplier_info_ids = self.search(cr, uid, [('name','=',supplier.id),('product_id','=',product_id)])
            if supplier_info_ids:
                cr.execute('SELECT * ' \
                    'FROM pricelist_partnerinfo ' \
                    'WHERE suppinfo_id IN %s' \
                    'AND min_quantity <= %s ' \
                    'ORDER BY min_quantity DESC LIMIT 1', (tuple(supplier_info_ids),product_qty,))
                res2 = cr.dictfetchone()
                if res2:
                    price = res2['price']
            res[supplier.id] = price
        return res
    _order = 'sequence'
示例#4
0
class product_template(osv.osv):
    _name = "product.template"
    _description = "Product Template"

    def _get_main_product_supplier(self, cr, uid, product, context=None):
        """Determines the main (best) product supplier for ``product``, 
        returning the corresponding ``supplierinfo`` record, or False
        if none were found. The default strategy is to select the
        supplier with the highest priority (i.e. smallest sequence).

        :param browse_record product: product to supply
        :rtype: product.supplierinfo browse_record or False
        """
        sellers = [(seller_info.sequence, seller_info)
                       for seller_info in product.seller_ids or []
                       if seller_info and isinstance(seller_info.sequence, (int, long))]
        return sellers and sellers[0][1] or False

    def _calc_seller(self, cr, uid, ids, fields, arg, context=None):
        result = {}
        for product in self.browse(cr, uid, ids, context=context):
            main_supplier = self._get_main_product_supplier(cr, uid, product, context=context)
            result[product.id] = {
                'seller_info_id': main_supplier and main_supplier.id or False,
                'seller_delay': main_supplier and main_supplier.delay or 1,
                'seller_qty': main_supplier and main_supplier.qty or 0.0,
                'seller_id': main_supplier and main_supplier.name.id or False
            }
        return result

    _columns = {
        'name': fields.char('Name', size=128, required=True, translate=True, select=True),
        'product_manager': fields.many2one('res.users','Product Manager',help="This is use as task responsible"),
        'description': fields.text('Description',translate=True),
        'description_purchase': fields.text('Purchase Description',translate=True),
        'description_sale': fields.text('Sale Description',translate=True),
        'type': fields.selection([('product','Stockable Product'),('consu', 'Consumable'),('service','Service')], 'Product Type', required=True, help="Will change the way procurements are processed. Consumable are product where you don't manage stock."),
        'supply_method': fields.selection([('produce','Produce'),('buy','Buy')], 'Supply method', required=True, help="Produce will generate production order or tasks, according to the product type. Buy will trigger purchase orders when requested."),
        'sale_delay': fields.float('Customer Lead Time', help="This is the average delay in days between the confirmation of the customer order and the delivery of the finished products. It's the time you promise to your customers."),
        'produce_delay': fields.float('Manufacturing Lead Time', help="Average delay in days to produce this product. This is only for the production order and, if it is a multi-level bill of material, it's only for the level of this product. Different lead times will be summed for all levels and purchase orders."),
        'procure_method': fields.selection([('make_to_stock','Make to Stock'),('make_to_order','Make to Order')], 'Procurement Method', required=True, help="'Make to Stock': When needed, take from the stock or wait until re-supplying. 'Make to Order': When needed, purchase or produce for the procurement request."),
        'rental': fields.boolean('Can be Rent'),
        'categ_id': fields.many2one('product.category','Category', required=True, change_default=True, domain="[('type','=','normal')]" ,help="Select category for the current product"),
        'list_price': fields.float('Sale Price', digits_compute=dp.get_precision('Sale Price'), help="Base price for computing the customer price. Sometimes called the catalog price."),
        'standard_price': fields.float('Cost Price', required=True, digits_compute=dp.get_precision('Purchase Price'), help="Product's cost for accounting stock valuation. It is the base price for the supplier price."),
        'volume': fields.float('Volume', help="The volume in m3."),
        'weight': fields.float('Gross weight', digits_compute=dp.get_precision('Stock Weight'), help="The gross weight in Kg."),
        'weight_net': fields.float('Net weight', digits_compute=dp.get_precision('Stock Weight'), help="The net weight in Kg."),
        'cost_method': fields.selection([('standard','Standard Price'), ('average','Average Price')], 'Costing Method', required=True,
            help="Standard Price: the cost price is fixed and recomputed periodically (usually at the end of the year), Average Price: the cost price is recomputed at each reception of products."),
        'warranty': fields.float('Warranty (months)'),
        'sale_ok': fields.boolean('Can be Sold', help="Determines if the product can be visible in the list of product within a selection from a sale order line."),
        'purchase_ok': fields.boolean('Can be Purchased', help="Determine if the product is visible in the list of products within a selection from a purchase order line."),
        'state': fields.selection([('',''),
            ('draft', 'In Development'),
            ('sellable','Normal'),
            ('end','End of Lifecycle'),
            ('obsolete','Obsolete')], 'Status', help="Tells the user if he can use the product or not."),
        'uom_id': fields.many2one('product.uom', 'Default Unit Of Measure', required=True, help="Default Unit of Measure used for all stock operation."),
        'uom_po_id': fields.many2one('product.uom', 'Purchase Unit of Measure', required=True, help="Default Unit of Measure used for purchase orders. It must be in the same category than the default unit of measure."),
        'uos_id' : fields.many2one('product.uom', 'Unit of Sale',
            help='Used by companies that manage two units of measure: invoicing and inventory management. For example, in food industries, you will manage a stock of ham but invoice in Kg. Keep empty to use the default UOM.'),
        'uos_coeff': fields.float('UOM -> UOS Coeff', digits_compute= dp.get_precision('Product UoS'),
            help='Coefficient to convert UOM to UOS\n'
            ' uos = uom * coeff'),
        'mes_type': fields.selection((('fixed', 'Fixed'), ('variable', 'Variable')), 'Measure Type', required=True),
        'seller_info_id': fields.function(_calc_seller, type='many2one', relation="product.supplierinfo", multi="seller_info"),
        'seller_delay': fields.function(_calc_seller, type='integer', string='Supplier Lead Time', multi="seller_info", help="This is the average delay in days between the purchase order confirmation and the reception of goods for this product and for the default supplier. It is used by the scheduler to order requests based on reordering delays."),
        'seller_qty': fields.function(_calc_seller, type='float', string='Supplier Quantity', multi="seller_info", help="This is minimum quantity to purchase from Main Supplier."),
        'seller_id': fields.function(_calc_seller, type='many2one', relation="res.partner", string='Main Supplier', help="Main Supplier who has highest priority in Supplier List.", multi="seller_info"),
        'seller_ids': fields.one2many('product.supplierinfo', 'product_id', 'Partners'),
        'loc_rack': fields.char('Rack', size=16),
        'loc_row': fields.char('Row', size=16),
        'loc_case': fields.char('Case', size=16),
        'company_id': fields.many2one('res.company', 'Company',select=1),
    }

    def _get_uom_id(self, cr, uid, *args):
        cr.execute('select id from product_uom order by id limit 1')
        res = cr.fetchone()
        return res and res[0] or False

    def _default_category(self, cr, uid, context=None):
        if context is None:
            context = {}
        if 'categ_id' in context and context['categ_id']:
            return context['categ_id']
        md = self.pool.get('ir.model.data')
        res = False
        try:
            res = md.get_object_reference(cr, uid, 'product', 'cat0')[1]
        except ValueError:
            res = False
        return res

    def onchange_uom(self, cursor, user, ids, uom_id,uom_po_id):
        if uom_id:
            return {'value': {'uom_po_id': uom_id}}
        return {}

    def write(self, cr, uid, ids, vals, context=None):
        if 'uom_po_id' in vals:
            new_uom = self.pool.get('product.uom').browse(cr, uid, vals['uom_po_id'], context=context)
            for product in self.browse(cr, uid, ids, context=context):
                old_uom = product.uom_po_id
                if old_uom.category_id.id != new_uom.category_id.id:
                    raise osv.except_osv(_('UoM categories Mismatch!'), _("New UoM '%s' must belong to same UoM category '%s' as of old UoM '%s'. If you need to change the unit of measure, you may desactivate this product from the 'Procurement & Locations' tab and create a new one.") % (new_uom.name, old_uom.category_id.name, old_uom.name,))
        return super(product_template, self).write(cr, uid, ids, vals, context=context)

    _defaults = {
        'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'product.template', context=c),
        'list_price': lambda *a: 1,
        'cost_method': lambda *a: 'standard',
        'supply_method': lambda *a: 'buy',
        'standard_price': lambda *a: 1,
        'sale_ok': lambda *a: 1,
        'sale_delay': lambda *a: 7,
        'produce_delay': lambda *a: 1,
        'purchase_ok': lambda *a: 1,
        'procure_method': lambda *a: 'make_to_stock',
        'uom_id': _get_uom_id,
        'uom_po_id': _get_uom_id,
        'uos_coeff' : lambda *a: 1.0,
        'mes_type' : lambda *a: 'fixed',
        'categ_id' : _default_category,
        'type' : lambda *a: 'consu',
    }

    def _check_uom(self, cursor, user, ids, context=None):
        for product in self.browse(cursor, user, ids, context=context):
            if product.uom_id.category_id.id <> product.uom_po_id.category_id.id:
                return False
        return True

    def _check_uos(self, cursor, user, ids, context=None):
        for product in self.browse(cursor, user, ids, context=context):
            if product.uos_id \
                    and product.uos_id.category_id.id \
                    == product.uom_id.category_id.id:
                return False
        return True

    _constraints = [
        (_check_uom, 'Error: The default UOM and the purchase UOM must be in the same category.', ['uom_id']),
    ]

    def name_get(self, cr, user, ids, context=None):
        if context is None:
            context = {}
        if 'partner_id' in context:
            pass
        return super(product_template, self).name_get(cr, user, ids, context)
示例#5
0
class fleet_vehicle(osv.osv):
    """ 
    To manage operation of fleet vehicle
    """
    def get_uom_domin(self, cr, uid, ids, pro_id, context=None):
        """ 
        On change product id field value function gets the domin of Product uom.

        @param pro_id: id of current product
        @return: Dictionary of product_uom default value with product_uom domin
        """
        res = {'value': {}, 'domain': {}}
        if pro_id:
            pro_cat = self.pool.get('product.product').browse(
                cr, uid, pro_id, context=context).uom_id
            res = {
                'value': {
                    'product_uom': pro_cat.id,
                },
                'domain': {
                    'product_uom':
                    [('category_id', '=', pro_cat.category_id.id)],
                }
            }
        return res

    def get_product_qty(self,
                        cr,
                        uid,
                        ids,
                        typee,
                        location,
                        employee_id,
                        use,
                        company_id,
                        fuel_type,
                        department_id,
                        belong_to,
                        context={}):
        """ 
        On change product id field value function gets the domin of Product uom.

        @param pro_id: id of current product
        @return: Dictionary of product_uom default value with product_uom domin
        """
        vals = {}
        domain_vals = {}
        fuel_amount_obj = self.pool.get('fuel.amount')
        emp_obj = self.pool.get('hr.employee')
        custody_obj = self.pool.get('fleet.vehicle.custody')
        # To make employee_id and department_id requierd base on use type
        vals['employee_id'] = False
        vals['department_id'] = False
        vals['use_type'] = False
        domain_vals['employee_id'] = [('id', 'in', [])]
        domain_vals['department_id'] = [('id', 'in', [])]
        #To set custodys value and domain base on type
        if typee:
            ttype = []
            custodys = custody_obj.search(cr, uid, [('default', '=', True)])
            custodyss = custody_obj.browse(cr, uid, custodys, context=context)
            for custody in custodyss:
                for t in custody.vehicle_type:
                    if t.id == typee:
                        ttype.append(custody.id)
            vals['custody_ids'] = ttype

            ttype = []
            custodys = custody_obj.search(cr, uid, [])
            custodyss = custody_obj.browse(cr, uid, custodys, context=context)
            for custody in custodyss:
                for t in custody.vehicle_type:
                    if t.id == typee:
                        ttype.append(custody.id)
            domain_vals['custody_ids'] = [('id', 'in', ttype)]
        if use:
            vals['use_type'] = self.pool.get('fleet.vehicle.use').browse(
                cr, uid, use, context=context).type
            if not belong_to or belong_to == 'in':
                if vals['use_type'] == 'dedicated':
                    vals['employee_id'] = False
                    vals['department_id'] = False
                    domain_vals['employee_id'] = [('state', '=', 'approved')]
                    domain_vals['department_id'] = [('id', 'in', [])]
                    if employee_id:
                        department = emp_obj.browse(
                            cr, uid, employee_id).department_id.id
                        vals['department_id'] = department
                        domain_vals['department_id'] = [('id', 'in',
                                                         [department])]
                        vals['employee_id'] = employee_id
                else:
                    vals['employee_id'] = False
                    vals['department_id'] = False
                    domain_vals['employee_id'] = [('id', 'in', [])]
                    dep_ids = self.pool.get('hr.department').search(
                        cr, uid, [])
                    domain_vals['department_id'] = [('id', 'in', dep_ids)]
                    if department_id:
                        #department = emp_obj.browse(cr, uid, employee_id).department_id.id
                        domain_vals['employee_id'] = [('department_id', 'in',
                                                       [department_id])]
                        vals['department_id'] = department_id
                        if employee_id:
                            department = emp_obj.browse(
                                cr, uid, employee_id).department_id.id
                            vals['employee_id'] = department in [
                                department_id
                            ] and employee_id or False

        vals['product_qty'] = 0.0
        vals['product_id'] = False
        vals['fuel_amount_id'] = False
        if typee and location and use and company_id:

            domain = [('vehicle_category', '=', typee),
                      ('vehicle_place', '=', location),
                      ('company_id', '=', company_id),
                      ('vehicle_use', '=', use)]
            if vals['use_type'] in ['dedicated', 'dedicated_managemnet'
                                    ] and employee_id:
                degree = emp_obj.browse(cr, uid, employee_id).degree_id.id
                department = emp_obj.browse(cr, uid,
                                            employee_id).department_id.id
                domain.append(('degree_id', '=', degree))

            idss = fuel_amount_obj.search(cr, uid, domain, context=context)
            if idss:
                amount = fuel_amount_obj.browse(cr, uid, idss[0]).fuel_amount
                vals['product_qty'] = amount
                vals['fuel_amount_id'] = idss[0]
            else:
                vals['product_qty'] = 0.0
                vals['fuel_amount_id'] = False

        if location and fuel_type:
            product_id = self.pool.get('product.product').search(
                cr, uid, [('fuel_ok', '=', True), ('location', '=', location),
                          ('fuel_type', '=', fuel_type)])
            if product_id:
                vals['product_id'] = product_id[0]
                vals['product_uom'] = self.get_uom_domin(
                    cr, uid, ids, product_id[0],
                    context)['value']['product_uom']

        return {'value': vals, 'domain': domain_vals}

    def reset_id(self, cr, uid, ids, context=None):
        """ 
        On change fuel type field value function rest product id value.

        @return: Dictionary of product_id new value
        """
        return {
            'value': {
                'product_id': False,
                'product_uom': False,
            }
        }

    def _check_negative(self, cr, uid, ids, context=None):
        """ 
        Check the value of fuel tank capacity and quantity,
        if greater than zero or not.

        @return: Boolean of True or False
        """
        count = 0
        for fuel in self.browse(cr, uid, ids, context=context):
            message = _("The Value Of ")
            if (fuel.fueltankcap <= 0) and fuel.state != 'draft':
                raise osv.except_osv(
                    _('ValidateError'),
                    _("The Value Of Tank Capacity Must Be Greater Than Zero!"))
            '''if fuel.monthly_plan == True and rec.state == 'confirm':
                if (fuel.product_qty <= 0):
                    if (count > 0):
                        message += _(" And ")
                    message += _("Fuel Quantity")
                    count += 1
                    raise osv.except_osv(_('ValidateError'), _("You should Have Fuel amount For The Type %s and The Degree %s and The Location %s and The Use %s and the Company %s !")%(fuel.type.name, fuel.employee_id.degree_id.name, fuel.location.name, fuel.use.name, fuel.company_id.name))'''
        return True

    def _check_fuel_amount(self, cr, uid, ids, context=None):
        """ 
        Check the value of fuel tank capacity and quantity,
        if greater than zero or not.

        @return: Boolean of True or False
        """
        fuel_amount_obj = self.pool.get('fuel.amount')
        count = 0
        for rec in self.browse(cr, uid, ids, context=context):
            if rec.state == 'confirm' and rec.status == 'active':
                if rec.monthly_plan and rec.product_qty <= 0.0:
                    domain = [('vehicle_category', '=', rec.type.id),
                              ('vehicle_place', '=', rec.location.id),
                              ('company_id', '=', rec.company_id.id),
                              ('vehicle_use', '=', rec.use.id)]
                    if rec.use.type in ['dedicated', 'dedicated_managemnet'
                                        ] and rec.degree_id:
                        domain.append(('degree_id', '=', rec.degree_id.id))
                    idss = fuel_amount_obj.search(cr,
                                                  uid,
                                                  domain,
                                                  context=context)
                    if not idss and rec.use.type == 'dedicated':
                        raise osv.except_osv(
                            _('ValidateError'),
                            _("You should Have Fuel amount For The Type %s and The Degree %s and The Location %s and The Use %s and the Company %s !"
                              ) %
                            (rec.type.name, rec.employee_id.degree_id.name,
                             rec.location.name, rec.use.name,
                             rec.company_id.name))

                    elif not idss:
                        raise osv.except_osv(
                            _('ValidateError'),
                            _("You should Have Fuel amount For The Type %s and The Location %s and The Use %s and the Company %s !"
                              ) % (rec.type.name, rec.location.name,
                                   rec.use.name, rec.company_id.name))

                    else:
                        if idss and fuel_amount_obj.browse(
                                cr, uid, idss[0], context).fuel_amount == 0.0:
                            raise osv.except_osv(
                                _('ValidateError'),
                                _("You should Have Fuel amount greater than 0 For The Type %s and The Location %s and The Use %s and the Company %s !"
                                  ) % (rec.type.name, rec.location.name,
                                       rec.use.name, rec.company_id.name))

                if rec.monthly_plan and not rec.product_id:
                    raise osv.except_osv(
                        _('ValidateError'),
                        _("There Is No fuel with The selected location and fuel type"
                          ))
        return True

    _inherit = "fleet.vehicle"

    _columns = {
        'monthly_plan':
        fields.boolean('Monthly Plan', ),
        'fueltankcap':
        fields.float(
            'Tank Capacity',
            states={'confirm': [('readonly', True)]},
            help=
            "The unit of measurement Of Tank Capacity depends on the measuring unit of Car fuel"
        ),
        'product_id':
        fields.many2one('product.product',
                        'Fuel',
                        states={'confirm': [('readonly', True)]}),
        'product_qty':
        fields.float('Fuel Quantity', ),
        'product_uom':
        fields.many2one('product.uom',
                        'Unit of Measure',
                        states={'confirm': [('readonly', True)]}),
        'fuel_plan_ids':
        fields.one2many('fuel.qty.line',
                        'vehicles_id',
                        string='Fuel Plans',
                        readonly=True),
        'additional_qty':
        fields.float('Fuel Additional Quantity', ),
        'fuel_amount_id':
        fields.many2one('fuel.amount', 'Fuel Amount'),
        'fuel_exchange_status':
        fields.selection([('exchange', 'Currently Disbursed'),
                          ('stop', 'Stopped')], 'Fuel Exchange Status'),
        'fuel_stop_reason_id':
        fields.many2one('fuel.stop.reasons', 'Fuel Stopped Reason'),
    }

    _constraints = [
        #(_check_negative, '', []),
        (_check_fuel_amount, '', []),
    ]

    def create(self, cr, uid, vals, context=None):
        """
        To set status of vehicle inactive base on vehicle_status
        """

        typee = 'type' in vals and vals['type'] or False
        location = 'location' in vals and vals['location'] or False
        employee_id = 'employee_id' in vals and vals['employee_id'] or False
        use = 'use' in vals and vals['use'] or False
        fuel_type = 'fuel_type' in vals and vals['fuel_type'] or False
        company_id = 'company_id' in vals and vals['company_id'] or False
        department_id = 'department_id' in vals and vals[
            'department_id'] or False
        belong_to = 'belong_to' in vals and vals['belong_to'] or False

        onchange_vals = self.get_product_qty(cr, uid, [], typee, location,
                                             employee_id, use, company_id,
                                             fuel_type, department_id,
                                             belong_to, context)

        vals['product_qty'] = onchange_vals['value']['product_qty']
        vals['product_id'] = 'product_id' in onchange_vals[
            'value'] and onchange_vals['value']['product_id'] or False
        vals['fuel_amount_id'] = onchange_vals['value']['fuel_amount_id']
        onchange_val2 = self.get_uom_domin(cr, uid, [], vals['product_id'],
                                           context)
        vals['product_uom'] = 'product_uom' in onchange_val2[
            'value'] and onchange_val2['value']['product_uom'] or False

        return super(fleet_vehicle, self).create(cr,
                                                 uid,
                                                 vals,
                                                 context=context)

    def write(self, cr, uid, ids, vals, context=None):
        """
        To set product_qty and product_id
        """
        rec = self.browse(cr, uid, ids[0], context)

        typee = 'type' in vals and vals['type'] or (rec.type
                                                    and rec.type.id) or False
        location = 'location' in vals and vals['location'] or (
            rec.location and rec.location.id) or False
        employee_id = 'employee_id' in vals and vals['employee_id'] or (
            rec.employee_id and rec.employee_id.id) or False
        use = 'use' in vals and vals['use'] or (rec.use
                                                and rec.use.id) or False
        fuel_type = 'fuel_type' in vals and vals['fuel_type'] or (
            rec.fuel_type and rec.fuel_type) or False
        company_id = 'company_id' in vals and vals['company_id'] or (
            rec.company_id and rec.company_id.id) or False
        department_id = 'department_id' in vals and vals['department_id'] or (
            rec.department_id and rec.department_id.id) or False
        belong_to = 'belong_to' in vals and vals['belong_to'] or (
            rec.belong_to and rec.belong_to) or False

        onchange_vals = self.get_product_qty(cr, uid, ids, typee, location,
                                             employee_id, use, company_id,
                                             fuel_type, department_id,
                                             belong_to, context)

        vals['product_qty'] = onchange_vals['value']['product_qty']
        vals['product_id'] = 'product_id' in onchange_vals[
            'value'] and onchange_vals['value']['product_id'] or False
        vals['fuel_amount_id'] = onchange_vals['value']['fuel_amount_id']
        onchange_val2 = self.get_uom_domin(cr, uid, ids, vals['product_id'],
                                           context)
        vals['product_uom'] = 'product_uom' in onchange_val2[
            'value'] and onchange_val2['value']['product_uom'] or False

        return super(fleet_vehicle, self).write(cr, uid, ids, vals, context)
        ('confirmed', 'Waiting Procurement Manager Approve'),
        ('confirmed2', 'Waiting Head of Procurement Division'),
        ('confirmed3', 'Waiting Head of Division Approve'),
        ('confirmed4', 'Waiting CEO Approve'),
        ('approved', 'Approved'),
        ('except_picking', 'Shipping Exception'),
        ('except_invoice', 'Invoice Exception'),
        ('done', 'Done'),
        ('cancel', 'Cancelled')
    ]

    _columns = {
        'state'                 : fields.selection(STATE_SELECTION, 'State', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
        'budget_info_ids_po'    : fields.many2many('budget.info.po', 'budget_info_rel_po', 'order_id', 'budget_info_id_po', 'Budget Line', readonly=True),
        'budget_note'           : fields.text('Budget Note'),
        'budget_note_line_ids'  : fields.one2many('budget.note.po', 'order_id', 'Budget Note History'),
        
        #######DICOUNT#####################
        'amount_untaxed': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Untaxed Amount',
            store={
                'purchase.order.line': (_get_order, None, 10),
                'purchase.order': (lambda self, cr, uid, ids, c={}: ids, ['discount_total'], 20),
            }, multi="sums", help="The amount without tax"),
        'amount_tax': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Taxes',
            store={
                'purchase.order.line': (_get_order, None, 10),
                'purchase.order': (lambda self, cr, uid, ids, c={}: ids, ['discount_total'], 20),
            }, multi="sums", help="The tax amount"),
        'amount_total': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Total',
            store={
                'purchase.order.line': (_get_order, None, 10),
示例#7
0
		'prepayment': fields.float(digits=(12,2)),
		'shipping_cost': fields.float('Costo Envio', digits=(12, 2)),
		'action': fields.selection([('reparar', 'Reparar'), ('reemplazar', 'Reemplazar')], 'Action', required=True),
		'user_id': fields.many2one('res.users', 'Usuario'),
		'state_id': fields.many2one('bag.state', 'Estado', required=True),
		'shelving_id': fields.many2one('bag.shelving', 'Estanteria'),
		'urgent': fields.boolean('Urgente'),
		'papers': fields.boolean('Papeles'),
		'attention': fields.boolean('Atencion'),
		'monitoring': fields.boolean('Seguimiento'),
		'send': fields.boolean('Enviar'),
		'send_id': fields.many2one('bag.sending', 'Envio'),
		'taxi': fields.boolean('Remisero'),
		'baby_carriage': fields.boolean('Coche BB'),
		'date_return': fields.date('Fecha Entregado'),
		'work_to_be_done': fields.one2many('bag.work_to_be_done', 'service_id', 'Trabajo a realizar'),
		'quotation_notes': fields.text('Observaciones de las Tareas'),  # Tarea Observacion
		'work_done': fields.one2many('bag.work_done', 'service_id', 'Trabajo realizado'),
		'location_id': fields.many2one('bag.location', 'Ubicacion Actual'),
		'retires_location_id': fields.many2one('bag.location', 'Retira en'),
		'work_made': fields.text('Nota en Reparacion'),  # Trabajo Realizado
		'repaired_by_id': fields.many2one('res.users', 'Reparado por'),
		'labor_price': fields.float('Mano de Obra', digits=(12, 2)),
		'materials_price': fields.float('Materiales', digits=(12, 2)),
		'price': fields.float('Importe', digits=(12, 2)),
		'free': fields.boolean('Sin cargo'),
		'summary_number': fields.char('Nro. Resumen', size=32),
		'route_sheet_number': fields.char('Nro. Hoja de Ruta', size=32),
		'invoice_number': fields.char('Nro. Factura', size=32),
		'marca_resumen': fields.boolean('Marca Resumen'),
		'marca_hoja_ruta': fields.boolean('Marca Hoja Ruta'),
	_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)
	
    _columns = {
		'name': fields.char('Description', size=128),
		'layout_id': fields.many2one('pallet.stack.layout', 'Pallet Stack Layout', ondelete='cascade'),
		'num_layers': fields.integer('Number of layers'),
示例#9
0
class process_process(osv.osv):
    _name = "process.process"
    _description = "Process"
    _columns = {
        'name':
        fields.char('Name', size=30, required=True, translate=True),
        'active':
        fields.boolean(
            'Active',
            help=
            "If the active field is set to False, it will allow you to hide the process without removing it."
        ),
        'model_id':
        fields.many2one('ir.model', 'Object', ondelete='set null'),
        'note':
        fields.text('Notes', translate=True),
        'node_ids':
        fields.one2many('process.node', 'process_id', 'Nodes')
    }
    _defaults = {
        'active': lambda *a: True,
    }

    def search_by_model(self, cr, uid, res_model, context=None):
        pool = pooler.get_pool(cr.dbname)
        model_ids = (res_model or None) and pool.get('ir.model').search(
            cr, uid, [('model', '=', res_model)])

        domain = (model_ids or []) and [('model_id', 'in', model_ids)]
        result = []

        # search all processes
        res = pool.get('process.process').search(cr, uid, domain)
        if res:
            res = pool.get('process.process').browse(cr,
                                                     uid,
                                                     res,
                                                     context=context)
            for process in res:
                result.append((process.id, process.name))
            return result

        # else search process nodes
        res = pool.get('process.node').search(cr, uid, domain)
        if res:
            res = pool.get('process.node').browse(cr,
                                                  uid,
                                                  res,
                                                  context=context)
            for node in res:
                if (node.process_id.id, node.process_id.name) not in result:
                    result.append((node.process_id.id, node.process_id.name))

        return result

    def graph_get(self, cr, uid, id, res_model, res_id, scale, context=None):

        pool = pooler.get_pool(cr.dbname)

        process = pool.get('process.process').browse(cr,
                                                     uid,
                                                     id,
                                                     context=context)

        name = process.name
        resource = False
        state = 'N/A'

        expr_context = {}
        states = {}
        perm = False

        if res_model:
            states = dict(
                pool.get(res_model).fields_get(cr, uid, context=context).get(
                    'state', {}).get('selection', {}))

        if res_id:
            current_object = pool.get(res_model).browse(cr,
                                                        uid,
                                                        res_id,
                                                        context=context)
            current_user = pool.get('res.users').browse(cr,
                                                        uid,
                                                        uid,
                                                        context=context)
            expr_context = Env(current_object, current_user)
            resource = current_object.name
            if 'state' in current_object:
                state = states.get(current_object.state, 'N/A')
            perm = pool.get(res_model).perm_read(cr,
                                                 uid, [res_id],
                                                 context=context)[0]

        notes = process.note or "N/A"
        nodes = {}
        start = []
        transitions = {}

        for node in process.node_ids:
            data = {}
            data['name'] = node.name
            data['model'] = (node.model_id or None) and node.model_id.model
            data['kind'] = node.kind
            data['subflow'] = (node.subflow_id or False) and [
                node.subflow_id.id, node.subflow_id.name
            ]
            data['notes'] = node.note
            data['active'] = False
            data['gray'] = False
            data['url'] = node.help_url
            data['model_states'] = node.model_states

            # get assosiated workflow
            if data['model']:
                wkf_ids = self.pool.get('workflow').search(
                    cr, uid, [('osv', '=', data['model'])])
                data['workflow'] = (wkf_ids or False) and wkf_ids[0]

            if 'directory_id' in node and node.directory_id:
                data['directory_id'] = node.directory_id.id
                data['directory'] = self.pool.get(
                    'document.directory').get_resource_path(
                        cr, uid, data['directory_id'], data['model'], False)

            if node.menu_id:
                data['menu'] = {
                    'name': node.menu_id.complete_name,
                    'id': node.menu_id.id
                }

            try:
                gray = True
                for cond in node.condition_ids:
                    if cond.model_id and cond.model_id.model == res_model:
                        gray = gray and eval(cond.model_states, expr_context)
                data['gray'] = not gray
            except:
                pass

            if not data['gray']:
                if node.model_id and node.model_id.model == res_model:
                    try:
                        data['active'] = eval(node.model_states, expr_context)
                    except Exception:
                        pass

            nodes[node.id] = data
            if node.flow_start:
                start.append(node.id)

            for tr in node.transition_out:
                data = {}
                data['name'] = tr.name
                data['source'] = tr.source_node_id.id
                data['target'] = tr.target_node_id.id
                data['notes'] = tr.note
                data['buttons'] = buttons = []
                for b in tr.action_ids:
                    button = {}
                    button['name'] = b.name
                    button['state'] = b.state
                    button['action'] = b.action
                    buttons.append(button)
                data['groups'] = groups = []
                for r in tr.transition_ids:
                    if r.group_id:
                        groups.append({'name': r.group_id.name})
                for r in tr.group_ids:
                    groups.append({'name': r.name})
                transitions[tr.id] = data

        # now populate resource information
        def update_relatives(nid, ref_id, ref_model):
            relatives = []

            for dummy, tr in transitions.items():
                if tr['source'] == nid:
                    relatives.append(tr['target'])
                if tr['target'] == nid:
                    relatives.append(tr['source'])

            if not ref_id:
                nodes[nid]['res'] = False
                return

            nodes[nid]['res'] = resource = {'id': ref_id, 'model': ref_model}

            refobj = pool.get(ref_model).browse(cr,
                                                uid,
                                                ref_id,
                                                context=context)
            fields = pool.get(ref_model).fields_get(cr, uid, context=context)

            # check for directory_id from inherited from document module
            if nodes[nid].get('directory_id', False):
                resource['directory'] = self.pool.get(
                    'document.directory').get_resource_path(
                        cr, uid, nodes[nid]['directory_id'], ref_model, ref_id)

            resource['name'] = refobj.name_get(context)[0][1]
            resource['perm'] = pool.get(ref_model).perm_read(
                cr, uid, [ref_id], context)[0]

            ref_expr_context = Env(refobj, current_user)
            try:
                if not nodes[nid]['gray']:
                    nodes[nid]['active'] = eval(nodes[nid]['model_states'],
                                                ref_expr_context)
            except:
                pass
            for r in relatives:
                node = nodes[r]
                if 'res' not in node:
                    for n, f in fields.items():
                        if node['model'] == ref_model:
                            update_relatives(r, ref_id, ref_model)

                        elif f.get('relation') == node['model']:
                            rel = refobj[n]
                            if rel and isinstance(rel, list):
                                rel = rel[0]
                            try:  # XXX: rel has been reported as string (check it)
                                _id = (rel or False) and rel.id
                                _model = node['model']
                                update_relatives(r, _id, _model)
                            except:
                                pass

        if res_id:
            for nid, node in nodes.items():
                if not node['gray'] and (node['active']
                                         or node['model'] == res_model):
                    update_relatives(nid, res_id, res_model)
                    break

        # calculate graph layout
        g = tools.graph(
            nodes.keys(),
            map(lambda x: (x['source'], x['target']), transitions.values()))
        g.process(start)
        g.scale(*scale)  #g.scale(100, 100, 180, 120)
        graph = g.result_get()

        # fix the height problem
        miny = -1
        for k, v in nodes.items():
            x = graph[k]['x']
            y = graph[k]['y']
            if miny == -1:
                miny = y
            miny = min(y, miny)
            v['x'] = x
            v['y'] = y

        for k, v in nodes.items():
            y = v['y']
            v['y'] = min(y - miny + 10, y)

        nodes = dict([str(n_key), n_val] for n_key, n_val in nodes.iteritems())
        transitions = dict([str(t_key), t_val]
                           for t_key, t_val in transitions.iteritems())
        return dict(name=name,
                    resource=resource,
                    state=state,
                    perm=perm,
                    notes=notes,
                    nodes=nodes,
                    transitions=transitions)

    def copy(self, cr, uid, id, default=None, context=None):
        """ Deep copy the entire process.
        """

        if not default:
            default = {}

        pool = pooler.get_pool(cr.dbname)
        process = pool.get('process.process').browse(cr,
                                                     uid,
                                                     id,
                                                     context=context)

        nodes = {}
        transitions = {}

        # first copy all nodes and and map the new nodes with original for later use in transitions
        for node in process.node_ids:
            for t in node.transition_in:
                tr = transitions.setdefault(t.id, {})
                tr['target'] = node.id
            for t in node.transition_out:
                tr = transitions.setdefault(t.id, {})
                tr['source'] = node.id
            nodes[node.id] = pool.get('process.node').copy(cr,
                                                           uid,
                                                           node.id,
                                                           context=context)

        # then copy transitions with new nodes
        for tid, tr in transitions.items():
            vals = {
                'source_node_id': nodes[tr['source']],
                'target_node_id': nodes[tr['target']]
            }
            tr = pool.get('process.transition').copy(cr,
                                                     uid,
                                                     tid,
                                                     default=vals,
                                                     context=context)

        # and finally copy the process itself with new nodes
        default.update({'active': True, 'node_ids': [(6, 0, nodes.values())]})
        return super(process_process, self).copy(cr, uid, id, default, context)
示例#10
0
class mrp_production(osv.osv):
    _inherit = 'mrp.production'

    _columns = {
        'merged_into_id':
        fields.many2one(
            'mrp.production',
            'Merged into',
            required=False,
            readonly=True,
            help=
            'Production order in which this production order has been merged into.'
        ),
        'merged_from_ids':
        fields.one2many(
            'mrp.production',
            'merged_into_id',
            'Merged from',
            help=
            'List of production orders that have been merged into the current one.'
        ),
    }

    def _do_merge(self, cr, uid, ids, invalid_ids=[], context=None):

        main_obj = self.browse(cr, uid, ids[0], context=context)
        wizard = self.pool.get('change.production.qty')
        product_qty = 0.0
        picking_ids = []

        if main_obj.state not in ['confirmed', 'ready']:
            raise osv.except_osv(
                _('Error !'),
                _('Production order "%s" must be in status "confirmed" or "ready".'
                  ) % main_obj.name)
        product_qty += main_obj.product_qty
        for production in self.pool.get('mrp.production').browse(cr,
                                                                 uid,
                                                                 invalid_ids,
                                                                 context=None):
            if production.state not in ['confirmed', 'ready']:
                raise osv.except_osv(
                    _('Error !'),
                    _('Production order "%s" must be in status "confirmed"or "ready".'
                      ) % production.name)

            if production.product_id != main_obj.product_id:
                raise osv.except_osv(
                    _('Error !'),
                    _('Production order "%s" product is different from the one in the first selected order.'
                      ) % production.name)
            if production.product_uom != main_obj.product_uom:
                raise osv.except_osv(
                    _('Error !'),
                    _('Production order "%s" UOM is different from the one in the first selected order.'
                      ) % production.name)

            if production.bom_id != main_obj.bom_id:
                raise osv.except_osv(
                    _('Error !'),
                    _('Production order "%s" BOM is different from the one in the first selected order.'
                      ) % production.name)

            if production.routing_id != main_obj.routing_id:
                raise osv.except_osv(
                    _('Error !'),
                    _('Production order "%s" routing is different from the one in the first selected order.%s - %s'
                      ) % (production.name, production.routing_id,
                           main_obj.routing_id))

            if production.product_uos != main_obj.product_uos:
                raise osv.except_osv(
                    _('Error !'),
                    _('Production order "%s" UOS is different from the one in the first selected order.'
                      ) % production.name)

            product_qty += production.product_qty
            picking_ids.append(production.picking_id.id)

        self.write(cr, uid, ids, {
            'merged_into_id': main_obj.id,
        }, context)

        workflow = netsvc.LocalService("workflow")

        # Cancel 'old' production: We must cancel pickings before cancelling production orders
        for id in picking_ids:
            workflow.trg_validate(uid, 'stock.picking', id, 'button_cancel',
                                  cr)
        for id in invalid_ids:
            workflow.trg_validate(uid, 'mrp.production', id, 'button_cancel',
                                  cr)

        ctx = context.copy()
        ctx['active_id'] = ids[0]
        wizard.change_prod_qty(
            cr, uid, [wizard.create(cr, uid, {'product_qty': product_qty})],
            ctx)

        return ids[0]
示例#11
0
class inherits(osv.osv):
    _name = 'product.product'
    _description = 'product.product'
    _inherit = "product.product"

    _columns = {
        'gii_cc':
        fields.char('Course Code', size=64, required=False, readonly=False),
        'gii_ver':
        fields.char('Version', size=64, required=False, readonly=False),
        'gii_effect':
        fields.date('Effective Date', size=64, required=False, readonly=False),
        'gii_with':
        fields.date('Withdrawn Date', size=64, required=False, readonly=False),
        'gii_with':
        fields.date('Withdrawn Date', size=64, required=False, readonly=False),
        'gii_language':
        fields.many2one('gii.language', 'Language', ondelete='set null'),
        'gii_reccomended_study':
        fields.integer('Recommended Study Hours',
                       size=64,
                       required=False,
                       readonly=False),
        'gii_minimum_attendance':
        fields.integer('Min Attendance Rate Required',
                       size=64,
                       required=False,
                       readonly=False),
        'gii_glh':
        fields.integer('GLH', size=64, required=False, readonly=False),
        'gii_qf_id':
        fields.many2one('gii.qflevel', 'QF Level', ondelete='set null'),
        'gii_name':
        fields.text('Reccomended for', size=64, required=False,
                    readonly=False),
        'gii_lo':
        fields.text('Learning Objectives',
                    size=64,
                    required=False,
                    readonly=False),
        'gii_credit_id':
        fields.one2many('gii.accreditations', 'product_id', 'Accreditations'),
        'gii_grading_id':
        fields.one2many('gii.grading', 'product_id', 'Grading'),
        'gii_events_id':
        fields.one2many('event.event', 'productid_event', 'Events'),
        'gii_fees_id':
        fields.one2many('gii.fee', 'product_id', 'Fees'),
        'gii_resources_id':
        fields.one2many('gii.resources', 'product_id', 'Resources'),
        'gii_coursetutors_id':
        fields.one2many('gii.coursetutors', 'product_id', 'Course Tutors'),
        'gii_assmnt_id':
        fields.many2one('gii.assessment',
                        'Assesment Type',
                        ondelete='set null'),
        'gii_target_id':
        fields.many2one('gii.target', 'Target Audience', ondelete='set null'),
        'gii_awardingbody_id':
        fields.many2one('test',
                        'Awarding Body',
                        required=True,
                        ondelete='set null'),
        'gii_qualification_id':
        fields.many2one('gii.qualification',
                        'Qualification',
                        required=True,
                        ondelete='set null')
    }
class shipping_general_payment(osv.osv):
    def _amount_paid(self, cr, uid, ids, name, args, context=None):
        vals = {}
        paid_cash = 0.0
        for advanced in self.browse(cr, uid, ids):
            for cash in advanced.cash_line_ids:
                paid_cash += cash.amount
            paid_total = paid_cash
            vals[advanced.id] = {
                "paid_cash": paid_cash,
                "paid_total": paid_total,
            }
        return vals

    def _remaining(self, cr, uid, ids, name, args, context=None):
        vals = {}
        for pay_receive in self.browse(cr, uid, ids, context=context):
            tot_adv = pay_receive.cash_total
        return vals

    _name = "shipping.general.payment"
    _description = "Shipping General Payment Received"

    _columns = {
        'name':
        fields.char('Name', size=16),
        'origin':
        fields.char('Original', size=50),
        'invoice':
        fields.char('Invoice', size=50),
        'company_id':
        fields.many2one('res.company',
                        'Company',
                        required=True,
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'journal_id':
        fields.many2one('account.journal',
                        'Journal',
                        required=True,
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'cash_line_ids':
        fields.one2many('payment.move.line',
                        'general_payment_id',
                        'Payment Lines',
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'journal_entry_id':
        fields.many2one('account.move', 'Journal Entry', readonly=True),
        'doc_date':
        fields.date('Doc Date',
                    required=True,
                    select=True,
                    help="Effective date for accounting entries",
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'auto_posted':
        fields.boolean(
            'Auto Posted',
            readonly=True,
            states={'draft': [('readonly', False)]},
            help=
            "Check this box if you want to post the Journal Entry automatically."
        ),
        'paid_cash':
        fields.function(_amount_paid,
                        method=True,
                        string='Paid Cash',
                        type='float',
                        multi="amount_paid"),
        'paid_total':
        fields.function(_amount_paid,
                        method=True,
                        string='Paid Total',
                        type='float',
                        multi="amount_paid"),
        'amount_total':
        fields.float('Amount Total'),
        'amount_currency':
        fields.float(
            'Amount Currency',
            help="The amount expressed in an optional other currency."),
        'currency_id':
        fields.many2one('res.currency', 'Currency'),
        'partner_id':
        fields.many2one('res.partner', 'Partner'),
        'debit_account_id':
        fields.many2one('account.account', 'Debit'),
        'credit_account_id':
        fields.many2one('account.account', 'Credit'),
        'state':
        fields.selection([('draft', 'Draft'), ('paid', 'Paid'),
                          ('cancel', 'Cancel')],
                         'State',
                         readonly=True,
                         size=32),
        'ref':
        fields.char('Reference', size=16),
        'resource':
        fields.char('Resource', size=50),
        'notes':
        fields.char(
            'Notes',
            size=300,
        ),
        'period_id':
        fields.many2one('account.period',
                        'Period',
                        required=True,
                        states={'posted': [('readonly', True)]}),
    }

    _defaults = {
        'name':
        '/',
        'state':
        'draft',
        'period_id':
        _get_period,
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.users').browse(
            cr, uid, uid, c).company_id.id,
    }

    def create(self, cr, uid, vals, context=None):
        if vals.get('name', '/') == '/':
            vals['name'] = self.pool.get('ir.sequence').get(
                cr, uid, 'shipping.general.payment') or '/'
        return super(shipping_general_payment, self).create(cr,
                                                            uid,
                                                            vals,
                                                            context=context)

    def button_validate_payment(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        self.create_payment_move_lines(cr, uid, ids, context=context)

        if self.test_paid(cr, uid, ids, context=context):
            self.write(cr, uid, ids, {'state': 'paid'}, context=context)

        return True

    def create_payment_move_lines(self, cr, uid, ids, context=None):
        move_pool = self.pool.get('account.move')
        period_pool = self.pool.get('account.period')
        account_journal_pool = self.pool.get('account.journal.mapping')
        journal_pool = self.pool.get('account.journal')
        account_pool = self.pool.get('account.account')
        cur_obj = self.pool.get('res.currency')

        timenow = time.strftime('%Y-%m-%d')

        for payment in self.browse(cr, uid, ids, context=context):
            journal_obj = payment.journal_id

            line_ids = []

            period_id = payment.period_id.id
            journal_id = payment.journal_id.id

            name = payment.name
            move = {
                'narration': payment.notes,
                'date': payment.doc_date,
                'ref': payment.ref,
                'journal_id': journal_obj.id,
                'period_id': period_id,
            }
            company = self.pool.get('res.users').browse(cr, uid,
                                                        uid).company_id

            debit_account_id = payment.debit_account_id.id
            credit_account_id = payment.credit_account_id.id

            amount_total = 0
            amount_currency = 0
            amount_currency_total = 0

            for line in payment.cash_line_ids:

                if line.currency_id.id != company.currency_id.id:
                    amount_currency = line.amount
                    amt = cur_obj.compute(
                        cr,
                        uid,
                        journal_obj.default_debit_account_id.currency_id.id,
                        journal_obj.default_debit_account_id.company_id.
                        currency_id.id,
                        amount_currency,
                        context=context)
                else:
                    amt = line.amount

                amount_currency_total += amount_currency
                amount_total += amt

                if debit_account_id:

                    debit_line = (0, 0, {
                        'name': payment.name,
                        'date': payment.doc_date or timenow,
                        'partner_id': False,
                        'account_id': debit_account_id,
                        'journal_id': journal_id,
                        'period_id': period_id,
                        'debit': amt > 0.0 and amt or 0.0,
                        'credit': amt < 0.0 and -amt or 0.0,
                        'amount_currency': amount_currency,
                    })
                    line_ids.append(debit_line)

            if credit_account_id:

                credit_line = (0, 0, {
                    'name':
                    payment.name,
                    'date':
                    payment.doc_date or timenow,
                    'account_id':
                    credit_account_id,
                    'journal_id':
                    journal_id,
                    'period_id':
                    period_id,
                    'amount_currency':
                    amount_currency_total,
                    'debit':
                    amount_total < 0.0 and -amount_total or 0.0,
                    'credit':
                    amount_total > 0.0 and amount_total or 0.0,
                })
                line_ids.append(credit_line)

            move.update({'line_id': line_ids})
            move_id = move_pool.create(cr, uid, move, context=context)

        return True

    def button_cancel(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
        return True

    def test_paid(self, cr, uid, ids, context=None):
        """Payment is paid when the sum of amount total equal to paid amount
        @return: True
        """
        for payment in self.browse(cr, uid, ids, context=context):
            if payment.cash_line_ids and not payment.amount_total:
                return True
            if payment.cash_line_ids and (
                    abs(payment.amount_total - payment.paid_total) > 0.00001):
                return False
        return True

    def action_view_payment(self, cr, uid, payment_ids, context=None):
        '''
        This function returns an action that display existing invoices of given sales order ids. It can either be a in a list or in a form view, if there is only one invoice to show.
        '''
        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')
        result = mod_obj.get_object_reference(
            cr, uid, 'container_management', 'action_shipping_general_payment')
        id = result and result[1] or False
        result = act_obj.read(cr, uid, [id], context=context)[0]

        #choose the view_mode accordingly
        if len(payment_ids) > 1:
            result['domain'] = "[('id','in',[" + ','.join(map(
                str, payment_ids)) + "])]"
        else:
            res = mod_obj.get_object_reference(
                cr, uid, 'container_management',
                'view_shipping_general_payment_form')
            result['views'] = [(res and res[1] or False, 'form')]
            result['res_id'] = payment_ids and payment_ids[0] or False
        return result

    def print_report(self, cr, uid, ids, context=None):
        company = self.pool.get('res.users').browse(cr, uid, uid).company_id
        comm_obj = self.browse(cr, uid, ids[0], context=context)

        report_param = {
            'company_name':
            company and company.name or '',
            'address':
            company.partner_id.complete_address,
            'tel_fax':
            company
            and "Tel/Fax: %s , %s " % (company.phone and company.phone or '',
                                       company.fax and company.fax or ''),
            'invoice_id':
            ids[0],
        }

        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'general.receipt.invoice',
            'datas': {
                'parameters': report_param
            },
        }
示例#13
0
class report_xml(osv.osv):
    _name = 'ir.actions.report.xml'
    _inherit = 'ir.actions.report.xml'
    _columns = {
        'jasper_output':
        fields.selection([('html', 'HTML'), ('csv', 'CSV'), ('xls', 'XLS'),
                          ('rtf', 'RTF'), ('odt', 'ODT'), ('ods', 'ODS'),
                          ('txt', 'Text'), ('pdf', 'PDF')], 'Jasper Output'),
        'jasper_file_ids':
        fields.one2many('ir.actions.report.xml.file',
                        'report_id',
                        'Files',
                        help=''),
        'jasper_model_id':
        fields.many2one('ir.model', 'Model', help=''),  # We use jas-er_model
        'jasper_report':
        fields.boolean('Is Jasper Report?', help=''),
    }
    _defaults = {
        'jasper_output':
        lambda self, cr, uid, context: context and context.get('jasper_report')
        and 'pdf' or False,
    }

    def create(self, cr, uid, vals, context=None):
        if context and context.get('jasper_report'):
            vals['model'] = self.pool.get('ir.model').browse(
                cr, uid, vals['jasper_model_id'], context).model
            vals['type'] = 'ir.actions.report.xml'
            vals['report_type'] = 'pdf'
            vals['jasper_report'] = True
        return super(report_xml, self).create(cr, uid, vals, context)

    def write(self, cr, uid, ids, vals, context=None):
        if context and context.get('jasper_report'):
            if 'jasper_model_id' in vals:
                vals['model'] = self.pool.get('ir.model').browse(
                    cr, uid, vals['jasper_model_id'], context).model
            vals['type'] = 'ir.actions.report.xml'
            vals['report_type'] = 'pdf'
            vals['jasper_report'] = True
        return super(report_xml, self).write(cr, uid, ids, vals, context)

    def update(self, cr, uid, ids, context={}):
        for report in self.browse(cr, uid, ids):
            has_default = False
            # Browse attachments and store .jrxml and .properties into jasper_reports/custom_reports
            # directory. Also add or update ir.values data so they're shown on model views.
            #for attachment in self.pool.get('ir.attachment').browse( cr, uid, attachmentIds ):
            for attachment in report.jasper_file_ids:
                content = attachment.file
                fileName = attachment.filename
                if not fileName or not content:
                    continue
                path = self.save_file(fileName, content)
                if '.jrxml' in fileName:
                    if attachment.default:
                        if has_default:
                            raise osv.except_osv(
                                _('Error'),
                                _('There is more than one report marked as default'
                                  ))
                        has_default = True
                        # Update path into report_rml field.
                        self.write(cr, uid, [report.id], {'report_rml': path})
                        valuesId = self.pool.get('ir.values').search(
                            cr, uid,
                            [('value', '=',
                              'ir.actions.report.xml,%s' % report.id)])
                        data = {
                            'name': report.name,
                            'model': report.model,
                            'key': 'action',
                            'object': True,
                            'key2': 'client_print_multi',
                            'value': 'ir.actions.report.xml,%s' % report.id
                        }
                        if not valuesId:
                            valuesId = self.pool.get('ir.values').create(
                                cr, uid, data, context=context)
                        else:
                            self.pool.get('ir.values').write(cr,
                                                             uid,
                                                             valuesId,
                                                             data,
                                                             context=context)
                            valuesId = valuesId[0]

            if not has_default:
                raise osv.except_osv(
                    _('Error'), _('No report has been marked as default.'))

            # Ensure the report is registered so it can be used immediately
            jasper_report.register_jasper_report(report.report_name,
                                                 report.model)
        return True

    def save_file(self, name, value):
        path = os.path.abspath(os.path.dirname(__file__))
        path += '/custom_reports/%s' % name
        f = open(path, 'wb+')
        try:
            f.write(base64.decodestring(value))
        finally:
            f.close()
        path = 'jasper_reports/custom_reports/%s' % name
        return path

    def normalize(self, text):
        if isinstance(text, unicode):
            text = text.encode('utf-8')
        return text

    def unaccent(self, text):
        if isinstance(text, str):
            text = unicode(text, 'utf-8')
        output = text
        for c in xrange(len(src_chars)):
            if c >= len(dst_chars):
                break
            output = output.replace(src_chars[c], dst_chars[c])
        output = unicodedata.normalize('NFKD',
                                       output).encode('ASCII', 'ignore')
        return output.strip('_').encode('utf-8')

    def generate_xml(self, cr, uid, context, pool, modelName, parentNode,
                     document, depth, first_call):
        # First of all add "id" field
        fieldNode = document.createElement('id')
        parentNode.appendChild(fieldNode)
        valueNode = document.createTextNode('1')
        fieldNode.appendChild(valueNode)
        #language = context.get('lang')
        # if language == 'en_US':
        language = False

        # Then add all fields in alphabetical order
        model = pool.get(modelName)
        fields = model._columns.keys()
        fields += model._inherit_fields.keys()
        # Remove duplicates because model may have fields with the
        # same name as it's parent
        fields = sorted(list(set(fields)))
        for field in fields:
            # name = False
            # if language:
            #     # Obtain field string for user's language.
            #     name = pool.get('ir.translation')._get_source(cr, uid, modelName + ',' + field, 'field', language)
            # if not name:
            #     # If there's not description in user's language, use default (english) one.
            #     if field  in model._columns.keys():
            #         name = model._columns[field].string
            #     else:
            #         name = model._inherit_fields[field][2].string
            #
            # if name:
            #     name = self.unaccent( name )
            # # After unaccent the name might result in an empty string
            # if name:
            #     name = '%s-%s' % (self.unaccent( name ), field )
            # else:
            #     name = field
            name = field
            fieldNode = document.createElement(name)

            parentNode.appendChild(fieldNode)
            if field in pool.get(modelName)._columns:
                fieldType = model._columns[field]._type
            else:
                fieldType = model._inherit_fields[field][2]._type
            if fieldType in ('many2one', 'one2many', 'many2many'):
                if depth <= 1:
                    continue
                if field in model._columns:
                    newName = model._columns[field]._obj
                else:
                    newName = model._inherit_fields[field][2]._obj
                self.generate_xml(cr, uid, context, pool, newName, fieldNode,
                                  document, depth - 1, False)
                continue

            if fieldType == 'float':
                value = '12345.67'
            elif fieldType == 'integer':
                value = '12345'
            elif fieldType == 'date':
                value = '2009-12-31 00:00:00'
            elif fieldType == 'time':
                value = '12:34:56'
            elif fieldType == 'datetime':
                value = '2009-12-31 12:34:56'
            else:
                value = field

            valueNode = document.createTextNode(value)
            fieldNode.appendChild(valueNode)

        if depth > 1 and modelName != 'Attachments':
            # Create relation with attachments
            fieldNode = document.createElement('%s-Attachments' %
                                               self.unaccent(_('Attachments')))
            parentNode.appendChild(fieldNode)
            self.generate_xml(cr, uid, context, pool, 'ir.attachment',
                              fieldNode, document, depth - 1, False)

        if first_call:
            # Create relation with user
            fieldNode = document.createElement('%s-User' %
                                               self.unaccent(_('User')))
            parentNode.appendChild(fieldNode)
            self.generate_xml(cr, uid, context, pool, 'res.users', fieldNode,
                              document, depth - 1, False)

            # Create special entries
            fieldNode = document.createElement('%s-Special' %
                                               self.unaccent(_('Special')))
            parentNode.appendChild(fieldNode)

            newNode = document.createElement('copy')
            fieldNode.appendChild(newNode)
            valueNode = document.createTextNode('1')
            newNode.appendChild(valueNode)

            newNode = document.createElement('sequence')
            fieldNode.appendChild(newNode)
            valueNode = document.createTextNode('1')
            newNode.appendChild(valueNode)

            newNode = document.createElement('subsequence')
            fieldNode.appendChild(newNode)
            valueNode = document.createTextNode('1')
            newNode.appendChild(valueNode)

    def create_xml(self, cr, uid, model, depth, context):
        document = getDOMImplementation().createDocument(None, 'data', None)
        topNode = document.documentElement
        recordNode = document.createElement('record')
        topNode.appendChild(recordNode)
        self.generate_xml(cr, uid, context, self.pool, model, recordNode,
                          document, depth, True)
        topNode.toxml()
        return topNode.toxml()
示例#14
0
class account_analytic_account(osv.osv):

    _inherit = "account.analytic.account"
    _columns = {
        'user_product_ids': fields.one2many('analytic.user.funct.grid', 'account_id', 'Users/Products Rel.'),
    }
示例#15
0
class res_company(osv.osv):
    _name = "res.company"
    _description = 'Companies'
    _order = 'name'
    _columns = {
        'name': fields.char('Company Name', size=64, required=True),
        '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_header1': fields.char('Report Header', size=200),
        'rml_footer1': fields.char('Report Footer 1', size=200),
        'rml_footer2': fields.char('Report Footer 2', size=200),
        'rml_header' : fields.text('RML Header', required=True),
        'rml_header2' : fields.text('RML Internal Header', required=True),
        'rml_header3' : fields.text('RML Internal Header', required=True),
        'logo' : fields.binary('Logo'),
        '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),
    }

    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 = {}
        user_preference = context.get('user_preference', False)
        if 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, 1, 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 = {}

            # When migrating from 5.0, the multi_company_default table doesn't
            # even exist. However, there is not much we can do here without
            # bloating this code.
        proxy = self.pool.get('multi_company.default')
        args = [
            ('object_id.model', '=', object),
            ('field_id', '=', field),
        ]

        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        for rule in proxy.browse(cr, uid, args, context):
            if eval(rule.expression, {'context': context, 'user': user}):
                return rule.company_dest_id.id
        return user.company_id.id

    def _get_child_ids(self, cr, uid, uid2, context={}):
        company = self.pool.get('res.users').company_get(cr, uid, uid2)
        ids = self._get_company_children(cr, uid, company)
        return ids

    @tools.cache()
    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(cr.dbname)

    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']}, 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, *args, **argv):
        self.cache_restart(cr)
        return super(res_company, self).write(cr, *args, **argv)

    def _get_euro(self, cr, uid, context={}):
        try:
            return self.pool.get('res.currency').search(cr, uid, [])[0]
        except:
            return False

    def _get_logo(self, cr, uid, ids):
        # Note: we do not try to access files above our root_path, because
        # at a production system root_path/../pixmaps is arbitrary!
        # At a developer or tar.gz setup, we'd better fix our paths.
        
        pixmap_path = tools.config.get_misc('paths','pixmaps', './')
        fname = os.path.join(pixmap_path, 'openerp-header.png')
        if os.path.isfile(fname):
            return open(fname, 'rb') .read().encode('base64')
        else:
            logging.getLogger('init').warning('Cannot find default company logo at "%s"' % fname)
            return None

    def _get_header3(self,cr,uid,ids):
        return """
<header>
<pageTemplate>
    <frame id="first" x1="28.0" y1="28.0" width="786" height="525"/>
    <pageGraphics>
        <fill color="black"/>
        <stroke color="black"/>
        <setFont name="DejaVu Sans" size="8"/>
        <drawString x="25" y="555"> [[ formatLang(time.strftime("%Y-%m-%d"), date=True) ]]  [[ time.strftime("%H:%M") ]]</drawString>
        <setFont name="DejaVu Sans Bold" size="10"/>
        <drawString x="382" y="555">[[ company.partner_id.name ]]</drawString>
        <stroke color="#000000"/>
        <lines>25 550 818 550</lines>
    </pageGraphics>
    </pageTemplate>
</header>"""
    def _get_header2(self,cr,uid,ids):
        return """
        <header>
        <pageTemplate>
        <frame id="first" x1="28.0" y1="28.0" width="539" height="772"/>
        <pageGraphics>
        <fill color="black"/>
        <stroke color="black"/>
        <setFont name="DejaVu Sans" size="8"/>
        <drawString x="1.0cm" y="28.3cm"> [[ formatLang(time.strftime("%Y-%m-%d"), date=True) ]]  [[ time.strftime("%H:%M") ]]</drawString>
        <setFont name="DejaVu Sans Bold" size="10"/>
        <drawString x="9.3cm" y="28.3cm">[[ company.partner_id.name ]]</drawString>
        <stroke color="#000000"/>
        <lines>1.0cm 28.1cm 20.1cm 28.1cm</lines>
        </pageGraphics>
        </pageTemplate>
</header>"""
    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 """
    <header>
    <pageTemplate>
        <frame id="first" x1="1.3cm" y1="2.5cm" height="23.0cm" width="19cm"/>
        <pageGraphics>
            <!-- You Logo - Change X,Y,Width and Height -->
            <image x="1.3cm" y="27.6cm" height="40.0" >[[ company.logo or removeParentNode('image') ]]</image>
            <setFont name="DejaVu Sans" size="8"/>
            <fill color="black"/>
            <stroke color="black"/>
            <lines>1.3cm 27.7cm 20cm 27.7cm</lines>

            <drawRightString x="20cm" y="27.8cm">[[ company.rml_header1 ]]</drawRightString>


            <drawString x="1.3cm" y="27.2cm">[[ company.partner_id.name ]]</drawString>
            <drawString x="1.3cm" y="26.8cm">[[ company.partner_id.address and company.partner_id.address[0].street or  '' ]]</drawString>
            <drawString x="1.3cm" y="26.4cm">[[ company.partner_id.address and company.partner_id.address[0].zip or '' ]] [[ company.partner_id.address and company.partner_id.address[0].city or '' ]] - [[ company.partner_id.address and company.partner_id.address[0].country_id and company.partner_id.address[0].country_id.name  or '']]</drawString>
            <drawString x="1.3cm" y="26.0cm">Phone:</drawString>
            <drawRightString x="7cm" y="26.0cm">[[ company.partner_id.address and company.partner_id.address[0].phone or '' ]]</drawRightString>
            <drawString x="1.3cm" y="25.6cm">Mail:</drawString>
            <drawRightString x="7cm" y="25.6cm">[[ company.partner_id.address and company.partner_id.address[0].email or '' ]]</drawRightString>
            <lines>1.3cm 25.5cm 7cm 25.5cm</lines>

            <!--page bottom-->

            <lines>1.2cm 2.15cm 19.9cm 2.15cm</lines>

            <drawCentredString x="10.5cm" y="1.7cm">[[ company.rml_footer1 ]]</drawCentredString>
            <drawCentredString x="10.5cm" y="1.25cm">[[ company.rml_footer2 ]]</drawCentredString>
            <drawCentredString x="10.5cm" y="0.8cm">Contact : [[ user.name ]] - Page: <pageNumber/></drawCentredString>
        </pageGraphics>
    </pageTemplate>
</header>"""
    _defaults = {
        'currency_id': _get_euro,
        'rml_header':_get_header,
        'rml_header2': _get_header2,
        'rml_header3': _get_header3,
        #'logo':_get_logo
    }

    _constraints = [
        (osv.osv._check_recursion, 'Error! You can not create recursive companies.', ['parent_id'])
    ]
    _columns = {
        'name': fields.char('Item ID', size=64),
        'prod_list':fields.many2one('product.product', string='Product Name',readonly= True),
        'shop_id':fields.many2one('sale.shop', string='Shop Name'),
        'ebay_end_time':fields.datetime('End Time',size=64),
        'start_time':fields.datetime('Start Time',size=64),
        'is_cancel':fields.boolean('Is Cancelled',readonly=True),
        'cancel_listing' : fields.boolean('Cancel Listing'),
        'ending_reason': fields.selection([('Incorrect','The start price or reserve price is incorrect'),('LostOrBroken','The item was lost or broken'),('NotAvailable','The item is no longer available for sale'),('OtherListingError','The listing contained an error'),('SellToHighBidder','The listing has qualifying bids')],'Ending Reason'),
        'type': fields.char('Type',size=64),
        'related_template':fields.many2one('ebayerp.template','Template'),
        'listing_duration' : fields.char('Listing Duration',size=64),
        'time_remain' : fields.char('Time Remaining',size=64),
        'time_remain_function': fields.function(_get_time_remain_funtion, method=True, string='Remaining Time', type='char', multi='_get_time_remain_funtion'),
        'product_listing_id': fields.one2many('current.details', 'current_details_ids','Product listing id'),
        'state':fields.selection([('Active','Active'),('Inactive','Expired')],'Status',readonly=True),
        'condtn':fields.selection([('1000','New'),('1500','New other (see details)'),('2000','Manufacturer refurbished'),('2500','Seller refurbished'),('3000','Used'),('7000','For parts or not working')],'Condition'),
        'ebay_name':fields.char('Ebay Title',size=256),
        'time_rem':fields.char('Time Remain',size=256),
    }
    _defaults = {
        'state': 'Active',
    }
product_listing()

class product_listing(ebayerp_osv.ebayerp_osv):
    _name = 'product.listing'
    _inherit = 'product.listing'
product_listing()
示例#17
0
class jmdencuestas(osv.Model):
    _name = "ea.encuesta"
    _inherit = "mail.thread"

    #Workflow functions
    #new state

    def action_new(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'new'})
        # ... perform other tasks
        return True

    def action_aprobado(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'aprobado', 'usr_1': uid})
        # ... perform other tasks
        return True

    def action_segunda(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'segunda', 'usr_2': uid})
        # ... perform other tasks
        return True

    def action_tercera(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'tercera', 'usr_3': uid})
        # ... perform other tasks
        return True

    def action_cliente(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'cliente', 'usr_4': uid})
        # ... perform other tasks
        return True

    def action_cancelado(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'cancelado'})
        # ... perform other tasks
        return True

    def action_ec(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'ec'})
        # ... perform other tasks
        return True

    def reiniciar(self, cr, uid, ids, context="None"):
        self.write(cr, uid, ids, {'state': 'new'})
        return True

    def on_change_odt(self, cr, uid, ids, odt_id, context=None):
        ret = {}
        values = {}
        odt_object = self.pool.get("ea.project_wizard")
        for i in odt_object.browse(cr, uid, [odt_id], context):
            values['name'] = i.name
        ret['value'] = values
        return ret

    _columns = {
        'name':
        fields.char(string="Nombre", size=40),
        'state':
        fields.selection([('new', 'Nuevo'), ('aprobado', 'Kick Off'),
                          ('segunda', 'Campo'), ('tercera', 'Procesamiento'),
                          ('ec', 'Ejecutivo de Cuenta'),
                          ('cliente', 'Ok Cliente'),
                          ('cancelado', 'Cancelado')],
                         "Estado",
                         readonly=True),
        'ejecutivo':
        fields.many2one("hr.employee", string="Ejecutivo"),
        'encuesta':
        fields.binary("Cuestionario aprobado"),
        'fieldname':
        fields.char("Nombre del Archivo"),
        'proyecto':
        fields.many2one("project.project", "Clave"),
        'nombre_corto':
        fields.related('proyecto',
                       'nombre_corto',
                       string="Nombre Corto",
                       type="char"),
        'aprobadopor':
        fields.char(string="Aprobación del cliente", size=40, translate=True),
        'aprobacion':
        fields.date(string="Fecha de aprobación"),
        'medio':
        fields.selection([("telefono", "LLamada telefónica"),
                          ("mail", "Correo electrónico"),
                          ("visita", "Presencial")],
                         string="Medio de Confirmación"),
        'salario_ids':
        fields.one2many("ea.encuesta_salario", "encuesta", string="Salarios"),
        'odt_id':
        fields.many2one("ea.project_wizard", "Orden de Trabajo"),
        'adicionales':
        fields.boolean("Desbloquear el Cuestionario"),
        'ad_txt':
        fields.text("Cambios"),
        'ad_pers':
        fields.char("Quien autoriza cambios"),
        'bloquear':
        fields.boolean("Bloquear Cuestionario"),
        'criterio_ids':
        fields.one2many("ea.salario.concepto",
                        "encuesta_id",
                        string="Criterios Habilitados"),
        'usr_1':
        fields.many2one("res.users", string="Aprobó"),
        'usr_2':
        fields.many2one("res.users", string="Segundo Aprobador"),
        'usr_3':
        fields.many2one("res.users", string="Tercer Aprobador"),
        'usr_4':
        fields.many2one("res.users", string="Capturó Ok Cliente"),
    }
示例#18
0
class nan_koo_settings(osv.osv):
    _inherit = 'nan.koo.settings'
    _columns = {
        'user_ids': fields.one2many('res.users', 'koo_settings_id', 'Users'),
    }
                                        'message': etree.tostring(
                                            response, pretty_print=True)})]
            else:
                xml_messages = []

            self.write(cursor, user, shipping_register_record.id,
                       {'state': 'cancelled',
                 'xml_messages': xml_messages}, 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,),
        'xml_messages': fields.one2many('ups.message',
                                        'shipping_register_rel',
                                        'XML Messages'),
        # The following are UPS filled information
        'billed_weight': fields.float('Billed Weight', digits=(10, 4),
            readonly=True, help=(
示例#20
0
class res_partner_contact(osv.osv):
    """ Partner Contact """

    _name = "res.partner.contact"
    _description = "Contact"

    def _main_job(self, cr, uid, ids, fields, arg, context=None):
        """
            @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param uid: the current user’s ID for security checks,
            @param ids: List of partner contact’s IDs
            @fields: Get Fields
            @param context: A standard dictionary for contextual values
            @param arg: list of tuples of form [(‘name_of_the_field’, ‘operator’, value), ...]. """
        res = dict.fromkeys(ids, False)

        res_partner_job_obj = self.pool.get('res.partner.job')
        all_job_ids = res_partner_job_obj.search(cr, uid, [])
        all_job_names = dict(zip(all_job_ids, res_partner_job_obj.name_get(cr, uid, all_job_ids, context=context)))

        for contact in self.browse(cr, uid, ids, context=context):
            if contact.job_ids:
                res[contact.id] = all_job_names.get(contact.job_ids[0].id, False)

        return res

    _columns = {
        'name': fields.char('Last Name', size=64, required=True),
        'first_name': fields.char('First Name', size=64),
        'mobile': fields.char('Mobile', size=64),
        'title': fields.many2one('res.partner.title','Title'),
        'website': fields.char('Website', size=120),
        'lang_id': fields.many2one('res.lang', 'Language'),
        'job_ids': fields.one2many('res.partner.job', 'contact_id', 'Functions and Addresses'),
        'country_id': fields.many2one('res.country','Nationality'),
        'birthdate': fields.date('Birth Date'),
        'active': fields.boolean('Active', help="If the active field is set to False,\
                 it will allow you to hide the partner contact without removing it."),
        'partner_id': fields.related('job_ids', 'address_id', 'partner_id', type='many2one',\
                         relation='res.partner', string='Main Employer'),
        'function': fields.related('job_ids', 'function', type='char', \
                                 string='Main Function'),
        'job_id': fields.function(_main_job, method=True, type='many2one',\
                                 relation='res.partner.job', string='Main Job'),
        'email': fields.char('E-Mail', size=240),
        'comment': fields.text('Notes', translate=True),
        'photo': fields.binary('Image'),

    }
    _defaults = {
        'active' : lambda *a: True,
    }

    _order = "name,first_name"

    def name_get(self, cr, user, ids, context=None):

        """ will return name and first_name.......
            @param self: The object pointer
            @param cr: the current row, from the database cursor,
            @param user: the current user’s ID for security checks,
            @param ids: List of create menu’s IDs
            @return: name and first_name
            @param context: A standard dictionary for contextual values
        """

        if not len(ids):
            return []
        res = []
        for contact in self.browse(cr, user, ids, context=context):
            _contact = ""
            if contact.title:
                _contact += "%s "%(contact.title.name)
            _contact += contact.name or ""
            if contact.name and contact.first_name:
                _contact += " "
            _contact += contact.first_name or ""
            res.append((contact.id, _contact))
        return res
    
    def name_search(self, cr, uid, name='', args=None, operator='ilike', context=None, limit=None):
        if not args:
            args = []
        if context is None:
            context = {}
        if name:
            ids = self.search(cr, uid, ['|',('name', operator, name),('first_name', operator, name)] + args, limit=limit, context=context)
        else:
            ids = self.search(cr, uid, args, limit=limit, context=context)
        return self.name_get(cr, uid, ids, context=context)
                    '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=(
                'The billed weght may be different from the actual weight.'
                'This is computed by UPS.')),
class create_re_delivery(osv.osv_memory):
    _name = 'create.re.delivery'
    
    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        rej_pool = self.pool.get('rejection.model')
        res = super(create_re_delivery, self).default_get(cr, uid, fields, context=context)
        active_id = context.get('active_id', False)
        if active_id:
            rej_obj = rej_pool.browse(cr, uid, active_id, context=context)
            res['picking_id'] = rej_obj.picking_id and rej_obj.picking_id.id or False
            res['reject_id'] = active_id
            lines = []
            for line in rej_obj.line_ids:
                if line.rem_qty_resupply > 0.00:
                    vals = {
                            'product_id': line.product_id and line.product_id.id or False,
                            'lot_id': line.lot_id and line.lot_id.id or False,
                            'qty': line.rem_qty_resupply or 0.00,
                            'uom_id': line.uom_id and line.uom_id.id or False,
                            'move_id': line.move_id and line.move_id.id or False,
                            'rej_line_id': line.id or False
                            }
                    lines.append((0, 0, vals))
            res['line_ids'] = lines
            if not lines:
                raise osv.except_osv(_("Error!!!"),
                                     _("New Picking for all lines are already created !!!!"))
        return res
    
    _columns = {
                'picking_id': fields.many2one('stock.picking', 'Related Picking'),
                'reject_id': fields.many2one('rejection.model', 'Related Rejections'),
                'line_ids': fields.one2many('re.delivery.line', 'wizard_id',
                                            'Line(s)')
                }
    
    def create_picking(self, cr, uid, ids, context=None):
        data = self.read(cr, uid, ids, context=context)[0]
        parent_picking_id = data['picking_id'][0]
        line_ids = data['line_ids']
        reject_id = data['reject_id'][0]
        picking_pool = self.pool.get('stock.picking')
        line_pool = self.pool.get('re.delivery.line')
        move_pool = self.pool.get('stock.move')
        reject_pool = self.pool.get('rejection.model')
        reject_line_pool = self.pool.get('rejection.line')
        if not line_ids:
            raise osv.except_osv(_("Error!!!"),
                                 _("No Lines selected to create new picking !!!!"))
        if reject_id and line_ids:
            picking_obj = picking_pool.browse(cr, uid, parent_picking_id,
                                              context=context)
            rej_parent_picking_id = picking_obj.rej_parent_picking_id and \
                                        picking_obj.rej_parent_picking_id.id or \
                                        picking_obj.id
            new_picking_id = picking_pool.copy(cr, uid, parent_picking_id,
                                               {'state': 'draft', 'move_lines': [],
                                                'reject_ids': [],
                                                'rej_parent_picking_id': rej_parent_picking_id})
            if picking_obj.sale_id:
                picking_pool.write(cr, uid, new_picking_id,
                                   {'origin': picking_obj.sale_id.name or ''})
            for line in line_pool.browse(cr, uid, line_ids, context=context):
                if line.qty <= 0.00:
                    raise osv.except_osv(_("Error !!!"),
                                         _("Line with Qty as 0.00 not allowed !!!"))
                def_vals = {
                            'state': 'draft',
                            'prodlot_id': line.lot_id and line.lot_id.id or False,
                            'product_qty': line.qty or 1.00,
                            'product_uom': line.uom_id and line.uom_id.id or False,
                            'picking_id': new_picking_id
                            }
                new_move_id = move_pool.copy(cr, uid, line.move_id.id, def_vals,
                                             context=context)
                line.rej_line_id.write({'return_move_ids': [(4, new_move_id)]})
            picking_pool.draft_force_assign(cr, uid, [new_picking_id])
            picking_pool.force_assign(cr, uid, [new_picking_id])
            reject_pool.write(cr, uid, reject_id, {'repicking_ids': [(4, new_picking_id)]},
                              context=context)
            reject_pool.check_rejection(cr, uid, [reject_id], context=context)
        return True
示例#23
0
class account_loan_bank_cheque(osv.osv):
    _name = 'account.loan.bank.cheque'
    _description = 'Bank Account Cheque'
    _rec_name = 'code'
    _columns = {
        'loan_id':
        fields.many2one('account.loan', 'Loan', required=False),
        'code':
        fields.char('Code', size=32, required=True),
        'name':
        fields.char('Name', size=32, required=True),
        'partner_id':
        fields.many2one('res.partner', 'Customer', required=True),
        'loan_bank_id':
        fields.many2one('res.partner.bank', 'Bank', required=True),
        'loan':
        fields.float('Loan Amount', size=32),
        'interest':
        fields.float('Interest Amount', size=32),
        'cheque_amount':
        fields.float('Cheque Amount', size=32, required=True),
        'account_id':
        fields.many2one('account.account',
                        'General Account',
                        required=True,
                        select=True),
        'state':
        fields.selection([('draft', 'Draft'), ('posted', 'Posted'),
                          ('clear', 'Clear'), ('return', 'Return'),
                          ('cancel', 'Cancel'), ('done', 'Done')],
                         'State',
                         readonly=True,
                         select=True),
        'date':
        fields.date('Date', required=True),
        'clear_date':
        fields.date('Cheque Clearing Date', required=False, readonly=True),
        'return_date':
        fields.date('Cheque Return Date', required=False, readonly=True),
        'note':
        fields.text('Notes'),
        'cheque_id':
        fields.one2many('account.loan.installment', 'cheque_id',
                        'Installments'),
        'voucher_id':
        fields.many2one('account.voucher', 'Voucher', readonly=True),
    }
    _defaults = {
        'state': lambda *a: 'draft',
        'date': lambda *a: time.strftime('%Y-%m-%d'),
    }

    def onchange_bank_id(self, cr, uid, ids, part):
        val = {'loan_bank_id': False, 'account_id': False, 'loan_id': False}
        if not part:
            return {'value': val}
        else:
            bank_ids = self.pool.get('res.partner.bank').search(
                cr, uid, [('partner_id', '=', part)])
            loan_ids = self.pool.get('account.loan').search(
                cr, uid, [('partner_id', '=', part)])
            obj = self.pool.get('account.loan').browse(cr, uid, part)
            bank_acc = obj.bank_acc.id
            if loan_ids.__len__() > 0:
                val['loan_id'] = loan_ids[0]
            if bank_ids.__len__() > 0:
                acc_ids = self.pool.get('account.account').search(
                    cr, uid, [('id', '=', bank_acc)])

                if acc_ids:
                    val['loan_bank_id'] = bank_ids[0]
                    val['account_id'] = acc_ids[0]
                    return {'value': val}
                else:
                    val['loan_bank_id'] = bank_ids[0]
                    return {'value': val}
            else:
                return {'value': val}

    def post_bank(self, cr, uid, ids, context={}):
        res = False
        invoices = {}
        invoice_ids = []

        def make_voucher(loan):
            b = loan.partner_id.property_account_payable.id
            ln_id = loan.loan_id
            int_acc = ln_id.int_acc.id
            cus_acc = ln_id.cus_pay_acc.id
            create_ids = []

            inv_id = self.pool.get('account.voucher.line').create(
                cr, uid, {
                    'partner_id': loan.partner_id.id,
                    'name': loan.name,
                    'amount': loan.loan,
                    'account_id': cus_acc,
                    'type': 'cr'
                })

            inv_id1 = self.pool.get('account.voucher.line').create(
                cr, uid, {
                    'partner_id': loan.partner_id.id,
                    'name': loan.name,
                    'amount': loan.interest,
                    'account_id': int_acc,
                    'type': 'cr'
                })
            create_ids.append(inv_id1)
            create_ids.append(inv_id)

            inv = {
                'name': loan.loan_id.loan_id,
                'type': 'bank_rec_voucher',
                'account_id': loan.account_id.id,
                'narration': loan.name,
                'payment_ids': [(6, 0, create_ids)],
                'date': loan.date
            }

            inv_obj = self.pool.get('account.voucher')
            inv_id = inv_obj.create(cr, uid, inv)
            for o in self.pool.get('account.loan').browse(cr, uid, ids):
                self.write(cr, uid, [o.id], {'voucher_id': inv_id})
            return inv_id

        for o in self.pool.get('account.loan.bank.cheque').browse(
                cr, uid, ids):
            res = make_voucher(o)

        voucher_dict = {
            'draft': ['open_voucher', 'proforma_voucher'],
            'proforma': ['proforma_voucher']
        }
        voucher_pool = self.pool.get('account.voucher')
        for this_obj in self.browse(cr, uid, ids):
            voucher_obj = this_obj.voucher_id and this_obj.voucher_id or False
            voucher_state = voucher_obj and voucher_obj.state or False
            if voucher_state and voucher_state in voucher_dict:
                for voucher_method in voucher_dict[voucher_state]:
                    getattr(voucher_pool,
                            voucher_method)(cr,
                                            uid, [this_obj.voucher_id.id],
                                            context=context)

            move_ids = voucher_obj and [x.id
                                        for x in voucher_obj.move_ids] or []
            if move_ids:
                self.pool.get('account.move.line').write(
                    cr, uid, move_ids, {'acc_loan_id': this_obj.loan_id.id})

        return res

    def cheque_return(self, cr, uid, ids, context={}):
        for o in self.pool.get('account.loan.bank.cheque').browse(
                cr, uid, ids):
            self.write(cr, uid, [o.id],
                       {'return_date': time.strftime('%Y-%m-%d')})

        res = False
        invoices = {}
        invoice_ids = []

        def make_voucher(loan):
            b = loan.partner_id.property_account_payable.id
            ln_id = loan.loan_id
            int_acc = ln_id.int_acc.id
            cus_acc = ln_id.cus_pay_acc.id
            create_ids = []

            inv_id = self.pool.get('account.voucher.line').create(
                cr, uid, {
                    'partner_id': loan.partner_id.id,
                    'name': loan.name,
                    'amount': loan.loan,
                    'account_id': cus_acc,
                    'type': 'dr'
                })
            inv_id1 = self.pool.get('account.voucher.line').create(
                cr, uid, {
                    'partner_id': loan.partner_id.id,
                    'name': loan.name,
                    'amount': loan.interest,
                    'account_id': int_acc,
                    'type': 'dr'
                })
            create_ids.append(inv_id1)
            create_ids.append(inv_id)

            inv = {
                'name': loan.loan_id.loan_id,
                'type': 'bank_pay_voucher',
                'account_id': loan.account_id.id,
                'narration': loan.name,
                'payment_ids': [(6, 0, create_ids)],
                'date': loan.date
            }
            inv_obj = self.pool.get('account.voucher')
            inv_id = inv_obj.create(cr, uid, inv)
            for o in self.pool.get('account.loan').browse(cr, uid, ids):
                self.write(cr, uid, [o.id], {'voucher_id': inv_id})
            return inv_id

        for o in self.pool.get('account.loan.bank.cheque').browse(
                cr, uid, ids):
            res = make_voucher(o)

        voucher_dict = {
            'draft': ['open_voucher', 'proforma_voucher'],
            'proforma': ['proforma_voucher']
        }
        voucher_pool = self.pool.get('account.voucher')
        for this_obj in self.browse(cr, uid, ids):
            voucher_obj = this_obj.voucher_id and this_obj.voucher_id or False
            voucher_state = voucher_obj and voucher_obj.state or False
            if voucher_state and voucher_state in voucher_dict:
                for voucher_method in voucher_dict[voucher_state]:
                    getattr(voucher_pool,
                            voucher_method)(cr,
                                            uid, [this_obj.voucher_id.id],
                                            context=context)

            move_ids = voucher_obj and [x.id
                                        for x in voucher_obj.move_ids] or []
            if move_ids:
                self.pool.get('account.move.line').write(
                    cr, uid, move_ids, {'acc_loan_id': this_obj.loan_id.id})
        return res

    def cheque_clear(self, cr, uid, ids, context={}):
        res = False
        for o in self.pool.get('account.loan.bank.cheque').browse(
                cr, uid, ids):
            self.write(cr, uid, [o.id],
                       {'clear_date': time.strftime('%Y-%m-%d')})
示例#24
0
class delivery_grid(osv.osv):
    _name = "delivery.grid"
    _description = "Delivery Grid"
    _columns = {
        'name':
        fields.char('Grid Name', size=64, required=True),
        'sequence':
        fields.integer(
            'Sequence',
            size=64,
            required=True,
            help=
            "Gives the sequence order when displaying a list of delivery grid."
        ),
        'carrier_id':
        fields.many2one('delivery.carrier',
                        'Carrier',
                        required=True,
                        ondelete='cascade'),
        'country_ids':
        fields.many2many('res.country', 'delivery_grid_country_rel', 'grid_id',
                         'country_id', 'Countries'),
        'state_ids':
        fields.many2many('res.country.state', 'delivery_grid_state_rel',
                         'grid_id', 'state_id', 'States'),
        'zip_from':
        fields.char('Start Zip', size=12),
        'zip_to':
        fields.char('To Zip', size=12),
        'line_ids':
        fields.one2many('delivery.grid.line', 'grid_id', 'Grid Line'),
        'active':
        fields.boolean(
            'Active',
            help=
            "If the active field is set to False, it will allow you to hide the delivery grid without removing it."
        ),
    }
    _defaults = {
        'active': lambda *a: 1,
        'sequence': lambda *a: 1,
    }
    _order = 'sequence'

    def get_price(self, cr, uid, id, order, dt, context=None):
        total = 0
        weight = 0
        volume = 0
        for line in order.order_line:
            if not line.product_id:
                continue
            total += line.price_subtotal or 0.0
            weight += (line.product_id.weight or 0.0) * line.product_uom_qty
            volume += (line.product_id.volume or 0.0) * line.product_uom_qty

        return self.get_price_from_picking(cr,
                                           uid,
                                           id,
                                           total,
                                           weight,
                                           volume,
                                           context=context)

    def get_price_from_picking(self,
                               cr,
                               uid,
                               id,
                               total,
                               weight,
                               volume,
                               context=None):
        grid = self.browse(cr, uid, id, context=context)
        price = 0.0
        ok = False

        for line in grid.line_ids:
            price_dict = {
                'price': total,
                'volume': volume,
                'weight': weight,
                'wv': volume * weight
            }
            test = eval(line.type + line.operator + str(line.max_value),
                        price_dict)
            if test:
                if line.price_type == 'variable':
                    price = line.list_price * price_dict[line.variable_factor]
                else:
                    price = line.list_price
                ok = True
                break
        if not ok:
            raise osv.except_osv(
                _('No price available !'),
                _('No line matched this order in the choosed delivery grids !')
            )

        return price
示例#25
0
class personal_account(osv.osv):
    _name = "personal.base.account"
    _description = "Account"
    _order = "name"

    #    def _account_type_code_get(self, cr, uid, context={}):
    #        acc_type_obj = self.pool.get('personal.base.account.type')
    #        ids = acc_type_obj.search(cr, uid, [])
    #        res = acc_type_obj.read(cr, uid, ids, ['id', 'name'], context)
    #        return [(r['id'], r['name']) for r in res]

    def _get_balance_fnc(self, cr, uid, ids, prop, unknow_none, context):
        currency_pool = self.pool.get('res.currency')
        res = {}
        cr.execute(("SELECT a.id, " \
                    "SUM(COALESCE(l.amount_base, 0)) " \
                "FROM personal_base_account a " \
                    "LEFT JOIN personal_base_account_entry_line l " \
                    "ON (a.id=l.account_id) " \
                "WHERE l.state = 'confirmed' " \
                    "AND a.id IN (%s) " \
                "GROUP BY a.id") % (','.join(map(str,ids)),))
        for id in ids:
            res[id] = 0
        for account_id, sum in cr.fetchall():
            account = self.browse(cr, uid, account_id)
            res[account_id] = currency_pool.round(cr, uid, account.currency_id,
                                                  sum * account.type_id.sign)

        #line_pool = self.pool.get('personal.base.account.entry.line')
        #for id in ids:
        #    account = self.browse(cr, uid, id)
        #    res[id] = 0.0
        #    for search_line_id in line_pool.search(cr, uid,
        #            [('account_id', '=', id),
        #             ('state', '=', 'confirmed'),]
        #    ):
        #        line = line_pool.browse(cr, uid, search_line_id)
        #        res[id] = res[id] + (line.amount_base * account.type_id.sign)
        return res

    _columns = {
        'user_id':
        fields.many2one('res.users', 'User', required=True),
        'name':
        fields.char('Name', size=128, required=True, select=True),
        'currency_id':
        fields.many2one('res.currency', 'Currency', required=True),
        'type_id':
        fields.many2one('personal.base.account.type',
                        'Account Type',
                        required=True),
        'parent_id':
        fields.many2one('personal.base.account', 'Parent Code', select=True),
        'child_ids':
        fields.one2many('personal.base.account', 'parent_id', 'Child Codes'),
        'note':
        fields.text('Note'),
        'balance':
        fields.function(_get_balance_fnc,
                        method=True,
                        type="float",
                        digits=(10, 2),
                        string='Balance'),

        #fields for unit_test
        'unit_test':
        fields.boolean(string='unit_test')
    }

    _defaults = {
        'user_id':
        lambda self, cr, uid, context: uid,
        'currency_id':
        lambda self, cr, uid, context: base_get_default_currency(
            cr, uid, context),
        'unit_test':
        lambda *a: False,
    }

    def search(self,
               cr,
               uid,
               args,
               offset=0,
               limit=2000,
               order=None,
               context=None,
               count=False):
        args.append(('user_id', '=', uid))
        return osv.orm.orm.search(self,
                                  cr,
                                  uid,
                                  args,
                                  offset,
                                  limit,
                                  order,
                                  context=context)

    #for unit tests
    def try_create_litas(self, cr, uid):
        cur_pool = self.pool.get('res.currency')
        cur_rate_pool = self.pool.get('res.currency.rate')
        if cur_pool.search(cr, uid, [('code', '=', 'LTL')]) == []:
            cur_id = cur_pool.create(cr, uid, {
                'code': 'LTL',
                'name': 'Litas',
                'rounding': 0.01,
                'accuracy': 4
            })
            cur_rate_pool.create(
                cr, uid, {
                    'currency_id': cur_id,
                    'rate': 3.4528,
                    'name': datetime.date(2002, 2, 2)
                })

    def delete_unit_test_records(self, cr, uid):
        base_delete_unit_test_records(self, cr, uid)
示例#26
0
class delivery_carrier(osv.osv):
    _name = "delivery.carrier"
    _description = "Carrier"

    def name_get(self, cr, uid, ids, context=None):
        if not len(ids):
            return []
        if context is None:
            context = {}
        order_id = context.get('order_id', False)
        if not order_id:
            res = super(delivery_carrier, self).name_get(cr,
                                                         uid,
                                                         ids,
                                                         context=context)
        else:
            order = self.pool.get('sale.order').browse(cr,
                                                       uid,
                                                       order_id,
                                                       context=context)
            currency = order.pricelist_id.currency_id.name or ''
            res = [
                (r['id'],
                 r['name'] + ' (' + (str(r['price'])) + ' ' + currency + ')')
                for r in self.read(cr, uid, ids, ['name', 'price'], context)
            ]
        return res

    def get_price(self, cr, uid, ids, field_name, arg=None, context=None):
        res = {}
        if context is None:
            context = {}
        sale_obj = self.pool.get('sale.order')
        grid_obj = self.pool.get('delivery.grid')
        for carrier in self.browse(cr, uid, ids, context=context):
            order_id = context.get('order_id', False)
            price = False
            if order_id:
                order = sale_obj.browse(cr, uid, order_id, context=context)
                carrier_grid = self.grid_get(cr, uid, [carrier.id],
                                             order.partner_shipping_id.id,
                                             context)
                if carrier_grid:
                    price = grid_obj.get_price(cr, uid, carrier_grid, order,
                                               time.strftime('%Y-%m-%d'),
                                               context)
                else:
                    price = 0.0
            res[carrier.id] = price
        return res

    _columns = {
        'name':
        fields.char('Carrier', size=64, required=True),
        'partner_id':
        fields.many2one('res.partner', 'Carrier Partner', required=True),
        'product_id':
        fields.many2one('product.product', 'Delivery Product', required=True),
        'grids_id':
        fields.one2many('delivery.grid', 'carrier_id', 'Delivery Grids'),
        'price':
        fields.function(get_price, method=True, string='Price'),
        'active':
        fields.boolean(
            'Active',
            help=
            "If the active field is set to False, it will allow you to hide the delivery carrier without removing it."
        )
    }
    _defaults = {'active': lambda *args: 1}

    def grid_get(self, cr, uid, ids, contact_id, context=None):
        contact = self.pool.get('res.partner.address').browse(cr,
                                                              uid,
                                                              contact_id,
                                                              context=context)
        for carrier in self.browse(cr, uid, ids, context=context):
            for grid in carrier.grids_id:
                get_id = lambda x: x.id
                country_ids = map(get_id, grid.country_ids)
                state_ids = map(get_id, grid.state_ids)
                if country_ids and not contact.country_id.id in country_ids:
                    continue
                if state_ids and not contact.state_id.id in state_ids:
                    continue
                if grid.zip_from and (contact.zip or '') < grid.zip_from:
                    continue
                if grid.zip_to and (contact.zip or '') > grid.zip_to:
                    continue
                return grid.id
        return False
示例#27
0
class product_product(osv.osv):
    def view_header_get(self, cr, uid, view_id, view_type, context=None):
        if context is None:
            context = {}
        res = super(product_product, self).view_header_get(cr, uid, view_id, view_type, context)
        if (context.get('categ_id', False)):
            return _('Products: ')+self.pool.get('product.category').browse(cr, uid, context['categ_id'], context=context).name
        return res

    def _product_price(self, cr, uid, ids, name, arg, context=None):
        res = {}
        if context is None:
            context = {}
        quantity = context.get('quantity') or 1.0
        pricelist = context.get('pricelist', False)
        partner = context.get('partner', False)
        if pricelist:
            for id in ids:
                try:
                    price = self.pool.get('product.pricelist').price_get(cr,uid,[pricelist], id, quantity, partner=partner, context=context)[pricelist]
                except:
                    price = 0.0
                res[id] = price
        for id in ids:
            res.setdefault(id, 0.0)
        return res

    def _get_product_available_func(states, what):
        def _product_available(self, cr, uid, ids, name, arg, context=None):
            return {}.fromkeys(ids, 0.0)
        return _product_available

    _product_qty_available = _get_product_available_func(('done',), ('in', 'out'))
    _product_virtual_available = _get_product_available_func(('confirmed','waiting','assigned','done'), ('in', 'out'))
    _product_outgoing_qty = _get_product_available_func(('confirmed','waiting','assigned'), ('out',))
    _product_incoming_qty = _get_product_available_func(('confirmed','waiting','assigned'), ('in',))

    def _product_lst_price(self, cr, uid, ids, name, arg, context=None):
        res = {}
        product_uom_obj = self.pool.get('product.uom')
        for id in ids:
            res.setdefault(id, 0.0)
        for product in self.browse(cr, uid, ids, context=context):
            if 'uom' in context:
                uom = product.uos_id or product.uom_id
                res[product.id] = product_uom_obj._compute_price(cr, uid,
                        uom.id, product.list_price, context['uom'])
            else:
                res[product.id] = product.list_price
            res[product.id] =  (res[product.id] or 0.0) * (product.price_margin or 1.0) + product.price_extra
        return res

    def _get_partner_code_name(self, cr, uid, ids, product, partner_id, context=None):
        for supinfo in product.seller_ids:
            if supinfo.name.id == partner_id:
                return {'code': supinfo.product_code or product.default_code, 'name': supinfo.product_name or product.name, 'variants': ''}
        res = {'code': product.default_code, 'name': product.name, 'variants': product.variants}
        return res

    def _product_code(self, cr, uid, ids, name, arg, context=None):
        res = {}
        if context is None:
            context = {}
        for p in self.browse(cr, uid, ids, context=context):
            res[p.id] = self._get_partner_code_name(cr, uid, [], p, context.get('partner_id', None), context=context)['code']
        return res

    def _product_partner_ref(self, cr, uid, ids, name, arg, context=None):
        res = {}
        if context is None:
            context = {}
        for p in self.browse(cr, uid, ids, context=context):
            data = self._get_partner_code_name(cr, uid, [], p, context.get('partner_id', None), context=context)
            if not data['variants']:
                data['variants'] = p.variants
            if not data['code']:
                data['code'] = p.code
            if not data['name']:
                data['name'] = p.name
            res[p.id] = (data['code'] and ('['+data['code']+'] ') or '') + \
                    (data['name'] or '') + (data['variants'] and (' - '+data['variants']) or '')
        return res

    _defaults = {
        'active': lambda *a: 1,
        'price_extra': lambda *a: 0.0,
        'price_margin': lambda *a: 1.0,
        'color': 0,
    }

    _name = "product.product"
    _description = "Product"
    _table = "product_product"
    _inherits = {'product.template': 'product_tmpl_id'}
    _order = 'default_code,name_template'
    _columns = {
        'qty_available': fields.function(_product_qty_available, type='float', string='Quantity On Hand'),
        'virtual_available': fields.function(_product_virtual_available, type='float', string='Quantity Available'),
        'incoming_qty': fields.function(_product_incoming_qty, type='float', string='Incoming'),
        'outgoing_qty': fields.function(_product_outgoing_qty, type='float', string='Outgoing'),
        'price': fields.function(_product_price, type='float', string='Pricelist', digits_compute=dp.get_precision('Sale Price')),
        'lst_price' : fields.function(_product_lst_price, type='float', string='Public Price', digits_compute=dp.get_precision('Sale Price')),
        'code': fields.function(_product_code, type='char', string='Reference'),
        'partner_ref' : fields.function(_product_partner_ref, type='char', string='Customer ref'),
        'default_code' : fields.char('Reference', size=64, select=True),
        'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the product without removing it."),
        'variants': fields.char('Variants', size=64),
        'product_tmpl_id': fields.many2one('product.template', 'Product Template', required=True, ondelete="cascade"),
        'ean13': fields.char('EAN13', size=13),
        'packaging' : fields.one2many('product.packaging', 'product_id', 'Logistical Units', help="Gives the different ways to package the same product. This has no impact on the picking order and is mainly used if you use the EDI module."),
        'price_extra': fields.float('Variant Price Extra', digits_compute=dp.get_precision('Sale Price')),
        'price_margin': fields.float('Variant Price Margin', digits_compute=dp.get_precision('Sale Price')),
        'pricelist_id': fields.dummy(string='Pricelist', relation='product.pricelist', type='many2one'),
        'name_template': fields.related('product_tmpl_id', 'name', string="Name", type='char', size=128, store=True, select=True),
        'color': fields.integer('Color Index'),
        'product_image': fields.binary('Image'),
    }
    
    def unlink(self, cr, uid, ids, context=None):
        unlink_ids = []
        unlink_product_tmpl_ids = []
        for product in self.browse(cr, uid, ids, context=context):
            tmpl_id = product.product_tmpl_id.id
            # Check if the product is last product of this template
            other_product_ids = self.search(cr, uid, [('product_tmpl_id', '=', tmpl_id), ('id', '!=', product.id)], context=context)
            if not other_product_ids:
                 unlink_product_tmpl_ids.append(tmpl_id)
            unlink_ids.append(product.id)
        self.pool.get('product.template').unlink(cr, uid, unlink_product_tmpl_ids, context=context)
        return super(product_product, self).unlink(cr, uid, unlink_ids, context=context)

    def onchange_uom(self, cursor, user, ids, uom_id,uom_po_id):
        if uom_id and uom_po_id:
            uom_obj=self.pool.get('product.uom')
            uom=uom_obj.browse(cursor,user,[uom_id])[0]
            uom_po=uom_obj.browse(cursor,user,[uom_po_id])[0]
            if uom.category_id.id != uom_po.category_id.id:
                return {'value': {'uom_po_id': uom_id}}
        return False

    def _check_ean_key(self, cr, uid, ids, context=None):
        for product in self.browse(cr, uid, ids, context=context):
            res = check_ean(product.ean13)
        return res

    _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]

    def on_order(self, cr, uid, ids, orderline, quantity):
        pass

    def name_get(self, cr, user, ids, context=None):
        if context is None:
            context = {}
        if not len(ids):
            return []
        def _name_get(d):
            name = d.get('name','')
            code = d.get('default_code',False)
            if code:
                name = '[%s] %s' % (code,name)
            if d.get('variants'):
                name = name + ' - %s' % (d['variants'],)
            return (d['id'], name)

        partner_id = context.get('partner_id', False)

        result = []
        for product in self.browse(cr, user, ids, context=context):
            sellers = filter(lambda x: x.name.id == partner_id, product.seller_ids)
            if sellers:
                for s in sellers:
                    mydict = {
                              'id': product.id,
                              'name': s.product_name or product.name,
                              'default_code': s.product_code or product.default_code,
                              'variants': product.variants
                              }
                    result.append(_name_get(mydict))
            else:
                mydict = {
                          'id': product.id,
                          'name': product.name,
                          'default_code': product.default_code,
                          'variants': product.variants
                          }
                result.append(_name_get(mydict))
        return result

    def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
        if not args:
            args = []
        if name:
            ids = self.search(cr, user, [('default_code','=',name)]+ args, limit=limit, context=context)
            if not ids:
                ids = self.search(cr, user, [('ean13','=',name)]+ args, limit=limit, context=context)
            if not ids:
                # Do not merge the 2 next lines into one single search, SQL search performance would be abysmal
                # on a database with thousands of matching products, due to the huge merge+unique needed for the
                # OR operator (and given the fact that the 'name' lookup results come from the ir.translation table
                # Performing a quick memory merge of ids in Python will give much better performance
                ids = set()
                ids.update(self.search(cr, user, args + [('default_code',operator,name)], limit=limit, context=context))
                if len(ids) < limit:
                    # we may underrun the limit because of dupes in the results, that's fine
                    ids.update(self.search(cr, user, args + [('name',operator,name)], limit=(limit-len(ids)), context=context))
                ids = list(ids)
            if not ids:
                ptrn = re.compile('(\[(.*?)\])')
                res = ptrn.search(name)
                if res:
                    ids = self.search(cr, user, [('default_code','=', res.group(2))] + args, limit=limit, context=context)
        else:
            ids = self.search(cr, user, args, limit=limit, context=context)
        result = self.name_get(cr, user, ids, context=context)
        return result

    #
    # Could be overrided for variants matrices prices
    #
    def price_get(self, cr, uid, ids, ptype='list_price', context=None):
        if context is None:
            context = {}

        if 'currency_id' in context:
            pricetype_obj = self.pool.get('product.price.type')
            price_type_id = pricetype_obj.search(cr, uid, [('field','=',ptype)])[0]
            price_type_currency_id = pricetype_obj.browse(cr,uid,price_type_id).currency_id.id

        res = {}
        product_uom_obj = self.pool.get('product.uom')
        for product in self.browse(cr, uid, ids, context=context):
            res[product.id] = product[ptype] or 0.0
            if ptype == 'list_price':
                res[product.id] = (res[product.id] * (product.price_margin or 1.0)) + \
                        product.price_extra
            if 'uom' in context:
                uom = product.uom_id or product.uos_id
                res[product.id] = product_uom_obj._compute_price(cr, uid,
                        uom.id, res[product.id], context['uom'])
            # Convert from price_type currency to asked one
            if 'currency_id' in context:
                # Take the price_type currency from the product field
                # This is right cause a field cannot be in more than one currency
                res[product.id] = self.pool.get('res.currency').compute(cr, uid, price_type_currency_id,
                    context['currency_id'], res[product.id],context=context)

        return res

    def copy(self, cr, uid, id, default=None, context=None):
        if context is None:
            context={}

        if not default:
            default = {}

        # Craft our own `<name> (copy)` in en_US (self.copy_translation()
        # will do the other languages).
        context_wo_lang = context.copy()
        context_wo_lang.pop('lang', None)
        product = self.read(cr, uid, id, ['name'], context=context_wo_lang)
        default = default.copy()
        default['name'] = product['name'] + ' (copy)'

        if context.get('variant',False):
            fields = ['product_tmpl_id', 'active', 'variants', 'default_code',
                    'price_margin', 'price_extra']
            data = self.read(cr, uid, id, fields=fields, context=context)
            for f in fields:
                if f in default:
                    data[f] = default[f]
            data['product_tmpl_id'] = data.get('product_tmpl_id', False) \
                    and data['product_tmpl_id'][0]
            del data['id']
            return self.create(cr, uid, data)
        else:
            return super(product_product, self).copy(cr, uid, id, default=default,
                    context=context)
示例#28
0
class hr_evaluation(osv.osv):
    _name = "hr_evaluation.evaluation"
    _description = "Employee Appraisal"
    _rec_name = 'employee_id'
    _columns = {
        'date':
        fields.date("Appraisal Deadline", required=True, select=True),
        'employee_id':
        fields.many2one('hr.employee', "Employee", required=True),
        'note_summary':
        fields.text('Appraisal Summary'),
        'note_action':
        fields.text(
            'Action Plan',
            help=
            "If the evaluation does not meet the expectations, you can propose"
            + "an action plan"),
        'rating':
        fields.selection(
            [
                ('0', 'Significantly bellow expectations'),
                ('1', 'Did not meet expectations'),
                ('2', 'Meet expectations'),
                ('3', 'Exceeds expectations'),
                ('4', 'Significantly exceeds expectations'),
            ],
            "Appreciation",
            help="This is the appreciation on that summarize the evaluation"),
        'survey_request_ids':
        fields.one2many('hr.evaluation.interview', 'evaluation_id',
                        'Appraisal Forms'),
        'plan_id':
        fields.many2one('hr_evaluation.plan', 'Plan', required=True),
        'state':
        fields.selection([
            ('draft', 'New'),
            ('wait', 'Plan In Progress'),
            ('progress', 'Waiting Appreciation'),
            ('done', 'Done'),
            ('cancel', 'Cancelled'),
        ],
                         'State',
                         required=True,
                         readonly=True),
        'date_close':
        fields.date('Ending Date', select=True),
        'progress':
        fields.float("Progress"),
    }
    _defaults = {
        'date':
        lambda *a: (parser.parse(datetime.now().strftime('%Y-%m-%d')) +
                    relativedelta(months=+1)).strftime('%Y-%m-%d'),
        'state':
        lambda *a: 'draft',
    }

    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        reads = self.browse(cr, uid, ids, context=context)
        res = []
        for record in reads:
            name = record.plan_id.name
            res.append((record['id'], name))
        return res

    def onchange_employee_id(self, cr, uid, ids, employee_id, context=None):
        evaluation_plan_id = False
        if employee_id:
            employee_obj = self.pool.get('hr.employee')
            for employee in employee_obj.browse(cr,
                                                uid, [employee_id],
                                                context=context):
                if employee and employee.evaluation_plan_id and employee.evaluation_plan_id.id:
                    evaluation_plan_id = employee.evaluation_plan_id.id
        return {'value': {'plan_id': evaluation_plan_id}}

    def button_plan_in_progress(self, cr, uid, ids, context=None):
        mail_message = self.pool.get('mail.message')
        hr_eval_inter_obj = self.pool.get('hr.evaluation.interview')
        if context is None:
            context = {}
        for evaluation in self.browse(cr, uid, ids, context=context):
            wait = False
            for phase in evaluation.plan_id.phase_ids:
                children = []
                if phase.action == "bottom-up":
                    children = evaluation.employee_id.child_ids
                elif phase.action in ("top-down", "final"):
                    if evaluation.employee_id.parent_id:
                        children = [evaluation.employee_id.parent_id]
                elif phase.action == "self":
                    children = [evaluation.employee_id]
                for child in children:
                    #                    if not child.user_id:
                    #                        continue

                    int_id = hr_eval_inter_obj.create(
                        cr,
                        uid, {
                            'evaluation_id':
                            evaluation.id,
                            'survey_id':
                            phase.survey_id.id,
                            'date_deadline':
                            (parser.parse(datetime.now().strftime('%Y-%m-%d'))
                             + relativedelta(months=+1)).strftime('%Y-%m-%d'),
                            'user_id':
                            child.user_id.id,
                            'user_to_review_id':
                            evaluation.employee_id.id
                        },
                        context=context)
                    if phase.wait:
                        wait = True
                    if not wait:
                        hr_eval_inter_obj.survey_req_waiting_answer(
                            cr, uid, [int_id], context=context)

                    if (not wait) and phase.mail_feature:
                        body = phase.mail_body % {
                            'employee_name': child.name,
                            'user_signature': child.user_id.signature,
                            'eval_name': phase.survey_id.title,
                            'date': time.strftime('%Y-%m-%d'),
                            'time': time
                        }
                        sub = phase.email_subject
                        dest = [child.work_email]
                        if dest:
                            mail_message.schedule_with_attach(
                                cr,
                                uid,
                                evaluation.employee_id.work_email,
                                dest,
                                sub,
                                body,
                                context=context)

        self.write(cr, uid, ids, {'state': 'wait'}, context=context)
        return True

    def button_final_validation(self, cr, uid, ids, context=None):
        request_obj = self.pool.get('hr.evaluation.interview')
        self.write(cr, uid, ids, {'state': 'progress'}, context=context)
        for id in self.browse(cr, uid, ids, context=context):
            if len(id.survey_request_ids) != len(
                    request_obj.search(cr,
                                       uid,
                                       [('evaluation_id', '=', id.id),
                                        ('state', 'in', ['done', 'cancel'])],
                                       context=context)):
                raise osv.except_osv(
                    _('Warning !'),
                    _("You cannot change state, because some appraisal in waiting answer or draft state"
                      ))
        return True

    def button_done(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'progress': 1 * 100}, context=context)
        self.write(cr,
                   uid,
                   ids, {
                       'state': 'done',
                       'date_close': time.strftime('%Y-%m-%d')
                   },
                   context=context)
        return True

    def button_cancel(self, cr, uid, ids, context=None):
        interview_obj = self.pool.get('hr.evaluation.interview')
        evaluation = self.browse(cr, uid, ids[0], context)
        interview_obj.survey_req_cancel(
            cr, uid, [r.id for r in evaluation.survey_request_ids])
        self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
        return True

    def button_draft(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'draft'}, context=context)
        return True

    def write(self, cr, uid, ids, vals, context=None):
        if 'date' in vals:
            new_vals = {'date_deadline': vals.get('date')}
            obj_hr_eval_iterview = self.pool.get('hr.evaluation.interview')
            for evalutation in self.browse(cr, uid, ids, context=context):
                for survey_req in evalutation.survey_request_ids:
                    obj_hr_eval_iterview.write(cr,
                                               uid, [survey_req.id],
                                               new_vals,
                                               context=context)
        return super(hr_evaluation, self).write(cr,
                                                uid,
                                                ids,
                                                vals,
                                                context=context)
class l10n_es_aeat_mod340(osv.osv):
    def button_calculate(self, cr, uid, ids, args, context=None):

        if not context:
            context = {}

        calculate_obj = self.pool.get('l10n.es.aeat.mod340.calculate_records')
        calculate_obj._wkf_calculate_records(cr, uid, ids, context)

        return True

    def button_recalculate(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        calculate_obj = self.pool.get('l10n.es.aeat.mod340.calculate_records')
        calculate_obj._calculate_records(cr, uid, ids, context)

        return True

    def button_export(self, cr, uid, ids, context=None):
        #FUNCION CALCADA DEL MODELO 347, inoperativa de momento

        #raise osv.except_osv(_('No disponible:'), _('En desarrollo'))

        if context is None:
            context = {}

        export_obj = self.pool.get("l10n.es.aeat.mod340.export_to_boe")
        export_obj._export_boe_file(cr, uid, ids,
                                    self.browse(cr, uid, ids and ids[0]))

        return True

    def _name_get(self, cr, uid, ids, field_name, arg, context={}):
        """
        Returns the report name
        """
        result = {}
        for report in self.browse(cr, uid, ids, context):
            result[report.id] = report.number
        return result

    def _get_number_records(self, cr, uid, ids, field_name, args, context):

        result = {}
        for id in ids:
            result[id] = {}.fromkeys(
                ['number_records', 'total_taxable', 'total_sharetax', 'total'],
                0.0)

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

            for issue in model.issued:
                result[model.id]['number_records'] += len(issue.tax_line_ids)
                result[model.id]['total_taxable'] += issue.base_tax
                result[model.id]['total_sharetax'] += issue.amount_tax
                result[model.id]['total'] += issue.base_tax + issue.amount_tax

            for issue in model.received:
                result[model.id]['number_records'] += len(issue.tax_line_ids)
                result[model.id]['total_taxable'] += issue.base_tax
                result[model.id]['total_sharetax'] += issue.amount_tax
                result[model.id]['total'] += issue.base_tax + issue.amount_tax

        return result

    _inherit = "l10n.es.aeat.report"
    _name = 'l10n.es.aeat.mod340'
    _description = 'Model 340'
    _columns = {
        'name':
        fields.function(_name_get,
                        method=True,
                        type="char",
                        size="64",
                        string="Name"),
        'contact_phone':
        fields.char("Phone", size=9),
        'phone_contact':
        fields.char('Phone Contact', size=9),
        'name_contact':
        fields.char('Name And Surname Contact', size=40),
        'period':
        fields.selection([('1T', 'First quarter'), ('2T', 'Second quarter'),
                          ('3T', 'Third quarter'), ('4T', 'Fourth quarter'),
                          ('01', 'January'), ('02', 'February'),
                          ('03', 'March'), ('04', 'April'), ('05', 'May'),
                          ('06', 'June'), ('07', 'July'), ('08', 'August'),
                          ('09', 'September'), ('10', 'October'),
                          ('11', 'November'), ('12', 'December')], 'Period'),
        'issued':
        fields.one2many('l10n.es.aeat.mod340.issued', 'mod340_id',
                        'Invoices Issued'),
        'received':
        fields.one2many('l10n.es.aeat.mod340.received', 'mod340_id',
                        'Invoices Received'),
        'investment':
        fields.one2many('l10n.es.aeat.mod340.investment', 'mod340_id',
                        'Property Investment'),
        'intracomunitarias':
        fields.one2many('l10n.es.aeat.mod340.intracomunitarias', 'mod340_id',
                        'Operations Intracomunitarias'),
        'ean13':
        fields.char('Electronic Code VAT reverse charge', size=16),
        'total_taxable':
        fields.function(
            _get_number_records,
            method=True,
            type='float',
            string='Total Taxable',
            multi='recalc',
            help=
            "The declaration will include partners with the total of operations over this limit"
        ),
        'total_sharetax':
        fields.function(
            _get_number_records,
            method=True,
            type='float',
            string='Total Share Tax',
            multi='recalc',
            help=
            "The declaration will include partners with the total of operations over this limit"
        ),
        'number_records':
        fields.function(
            _get_number_records,
            method=True,
            type='integer',
            string='Records',
            multi='recalc',
            help=
            "The declaration will include partners with the total of operations over this limit"
        ),
        'total':
        fields.function(
            _get_number_records,
            method=True,
            type='float',
            string="Total",
            multi='recalc',
            help=
            "The declaration will include partners with the total of operations over this limit"
        ),
        'calculation_date':
        fields.date('Calculation date', readonly=True),
    }
    _defaults = {
        'support_type': lambda *a: 'Telemático',
        'number': lambda *a: '340',
        'type': lambda *a: 'Normal'
    }

    def set_done(self, cr, uid, id, *args):
        self.write(cr, uid, id, {
            'calculation_date': time.strftime('%Y-%m-%d'),
            'state': 'done',
        })
        wf_service = netsvc.LocalService("workflow")
        wf_service.trg_validate(uid, 'l10n.es.aeat.mod340', id, 'done', cr)
        return True

    def _check_report_lines(self, cr, uid, ids, context=None):
        """checks report lines"""
        #                if context is None: context = {}

        #        for item in self.browse(cr, uid, ids, context):
        #            ## Browse partner record lines to check if all are correct (all fields filled)
        #            for partner_record in item.partner_record_ids:
        #                if not partner_record.partner_state_code:
        #                    raise osv.except_osv(_('Error!'), _("All partner state code field must be filled."))
        #                if not partner_record.partner_vat:
        #                    raise osv.except_osv(_('Error!'), _("All partner vat number field must be filled."))
        #
        #            for real_state_record in item.real_state_record_ids:
        #                if not real_state_record.state_code:
        #                    raise osv.except_osv(_('Error!'), _("All real state records state code field must be filled."))

        return True

    def check_report(self, cr, uid, ids, context=None):
        """Different check out in report"""
        if context is None: context = {}

        self._check_report_lines(cr, uid, ids, context)

        return True

    def action_confirm(self, cr, uid, ids, context=None):
        """set to done the report and check its records"""
        if context is None: context = {}

        self.check_report(cr, uid, ids, context)
        self.write(cr, uid, ids, {'state': 'done'})

        return True

    def confirm(self, cr, uid, ids, context=None):
        """set to done the report and check its records"""

        self.write(cr, uid, ids, {'state': 'done'})

        return True

    def cancel(self, cr, uid, ids, context=None):
        """set to done the report and check its records"""

        self.write(cr, uid, ids, {'state': 'canceled'})

        return True
示例#30
0
class mrp_bom(osv.osv):
    _inherit = "mrp.bom"
    _columns = {
        'history_ids': fields.one2many('bom.history', 'bom_id', 'History'),
    }
    def _get_total_duration(self, cr, uid, ids, field_names, arg, context=None):
        res = {}
        try:            
            duration = 0
            for sheet in self.browse(cr, uid, ids, context=context):            
                for overtime in sheet.overtime_ids:
                    duration += overtime.duration
                log.info("duration=%s" % duration)    
                res[sheet.id] = duration         
        except Exception, e:
            raise osv.except_osv(_('Variable Error !'), _('Variable Error: %s') % (e))
        
        return res
    
    _columns = {        
        'overtime_ids': fields.one2many('hr_timesheet_sheet.sheet.overtime', 'sheet_id', 'Overtime lines', readonly=False),
        'total_overtimes': fields.function(_get_total_duration, method=True, store=True, type='float', size=64, string='Total Duration', readonly=True),            
    }
    __defaults = {
        #'source': 'manual',    
    }
    

hr_timesheet_sheet()

class hr_timesheet_sheet_sheet_overtime(osv.osv):
    _name = "hr_timesheet_sheet.sheet.overtime"
    _description = "Overtimes"
    _order='date'    
    
    _columns = {
示例#32
0
class asset_pact_order(osv.osv):
      """
      Asset Pact record including basic information of the Pact."""

      def create(self, cr, user, vals, context=None):
        """
        
        """
        if ('name' not in vals) or (vals.get('name') == '/'):
            seq = self.pool.get('ir.sequence').get(cr, user, 'asset.pact.order')
            vals['name'] = seq and seq or '/'
            if not seq:
                raise  osv.except_osv(_('Warning'), _('No sequence defined!\nPleas contact administartor to configue sequence with code \'asset.pact.order\'') )
        new_id = super(asset_pact_order, self).create(cr, user, vals, context)
        return new_id


      def copy(self, cr, uid, id, default=None, context=None):
        """
        Override copy function to edit default value.

        @param default : default vals dict 
        @return: id of the newly created record  
        """
        if default is None:
            default = {}
        if context is None:
            context = {}
        default.update({
            'name': self.pool.get('ir.sequence').get(cr, uid, 'asset.pact.order'),
            'categories_ids':[],
            'pact_line_ids':[],
        })
        return super(asset_pact_order, self).copy(cr, uid, id, default, context)





      def action_create_custody_order(self ,cr ,uid ,ids ,order={},context=None):
          """This Function For Create Custody Order
              
              @para order : is a dictionary holds order data,

              @return order_id"""
          



          order_id =  self.create( cr , uid , order ,context=context)

          return order_id
              
                        
 







      def unlink(self, cr, uid, ids, context=None):
		"""
		
		"""
		pact_orders = self.read(cr, uid, ids, ['state'], context=context)
		unlink_ids = []
		for pact_order in pact_orders:
		    if pact_order['state'] in ['draft', 'cancel']:
		        unlink_ids.append(pact_order['id'])
		    else:
		        raise osv.except_osv(_('Invalid action !'), _('In order to delete a Pact Order(s), it must be cancelled first!'))
		wf_service = netsvc.LocalService("workflow")
		for id in unlink_ids:
		    wf_service.trg_validate(uid, 'asset.pact.order', id, 'cancel', cr)
		return super(asset_pact_order, self).unlink(cr, uid, unlink_ids, context=context)


      






      _name = 'asset.pact.order'
      _description = 'Custody Request'
      _inherit = ['mail.thread']
      _track = {
        'state': {
            'asset_pact_order.mt_custody_order_state_change': lambda self, cr, uid, obj, ctx=None: True,
        },}



      _columns = {
         'name' : fields.char('Name' , size=32),
         'department_id' : fields.many2one('hr.department','Department', ),
         'user':  fields.many2one('res.users', 'Responsible', readonly=True,),
         'order_date' : fields.date('Date' ,),
         'purpose' : fields.char('Purpose',size=64, ),
         'source_document' : fields.many2one('stock.picking' , 'Source Document' ,),
         'custody_type' : fields.selection([('department','Administrative'),('personal' , 'Personal')], 'Custody Type',),
         'period_type' : fields.selection([('temp','Temparory'),('const' , 'Constant')], 'Period Type',),
         'expacted_return_date' : fields.date('Expected Date',),
         'categories_ids' : fields.one2many('custody.order.items' , 'custody_order_id' , 'Categories') ,
         'pact_line_ids' : fields.one2many('pact.order.line' , 'pact_order_id' , 'Pact Lines') ,
         
         'notes': fields.text('Notes'),
         'state' : fields.selection([('draft','Draft'),
                                     ('confirmed','Confirmed'),
                                     ('approved','Approved from Section Manager'),
                                     ('approve_dept','Approved from Department Manager'),
                                     ('approve_support','Approved from Techincal Manager'),
                                     ('assigned' , 'Assigned'),
                                     ('cancel','Cancelled')] , 'State' ),
                 
                 }

      _defaults = {
              'name':'/',
              'order_date': lambda *a: time.strftime('%Y-%m-%d'),
              'user': lambda self, cr, uid, context: uid,
              'state' : 'draft',
              


                 }
      _order = "order_date desc,name desc"



      _sql_constraints = [

                   ('check_expacted_return_date',"CHECK(expacted_return_date >= order_date)",_("Expacted Return Date must be bigger than Order Date!")) ,
                   ]   




      def confirm(self,cr,uid,ids,context=None):
          """ 
        Workflow function changes order state to confirmed.

            
        @return: Boolean True
        """
          for order in self.browse(cr, uid, ids, context=context): 
              
              if not order.categories_ids:  
                 raise osv.except_osv(_('Error !'), _('Please Fill the Categories'))
           
          self.write(cr,uid,ids,{'state' : 'confirmed' },context=context)
          return True

      def approve(self,cr,uid,ids,context=None):
          """ 
        Workflow function changes order state to approved.

            
        @return: Boolean True
        """
          self.write(cr,uid,ids,{'state' : 'approved' },context=context)
          return True
      def approve_dept(self,cr,uid,ids,context=None):
          """ 
        Workflow function changes order state to approve_dept.

            
        @return: Boolean True
        """
          self.write(cr,uid,ids,{'state' : 'approve_dept' },context=context)
          return True
      
      def approve_support(self,cr,uid,ids,context=None):
          """ 
        Workflow function changes order state to approve_suport.

            
        @return: Boolean True
        """ 
          if not isinstance(ids, list):
             ids = [ids] 
          pact_line_obj = self.pool.get('pact.order.line')
          emp_obj = self.pool.get('hr.employee')
          

          for order in self.browse(cr, uid, ids, context=context): 
              user_id = order.user.id
              user_name = order.user.name
              if not order.categories_ids:  
                 raise osv.except_osv(_('Error !'), _('Please Fill the Assets or Assign the Assets to Users.'))

                  
              
              if order.custody_type == 'personal':
                 emp_id = emp_obj.search(cr ,uid ,[('user_id', '=' , user_id ),('name','=',user_name)]  )
                 if not emp_id:
                       emp_id = [False]
              else :
                 emp_id = [False]

              for line in order.categories_ids:
                  for custody in range(line.quantity):
                      custody_id = pact_line_obj.create(cr ,uid , {'category_id' : line.category_id.id,
                                                                   'custody_type' : order.custody_type,
                                                                   'employee_id' : emp_id[0],
                                                                   'pact_order_id' : order.id ,} ,context=context)

          self.write(cr,uid,ids,{'state' : 'approve_support' },context=context)
          return True





      def assign(self,cr,uid,ids,context=None):
          employee_obj = self.pool.get('hr.employee')
          user_obj = self.pool.get('res.users')
          custody_obj = self.pool.get('account.asset.asset')
          asset_obj = self.pool.get('account.asset.asset')
          asset_log_obj = self.pool.get('asset.logs')
          parent_res = { }
          lines_res = { }
          for order in self.browse(cr, uid, ids, context=context): 
              

              if not order.categories_ids:  
                 raise osv.except_osv(_('Error !'), _('Please Fill the Assets or Assign the Assets to Users.'))

              if not order.pact_line_ids:  
                 raise osv.except_osv(_('Error !'), _('Please Fill the Assets or Assign the Assets to Users.'))

              #desire_quantity = 0 
 
              #for categ in order.categories_ids:
              #    desire_quantity += categ.quantity


              #if len(order.pact_line_ids) !=  desire_quantity :
              #   raise osv.except_osv(_('Error !'), _('The Desire Quantities and The Number of Assign Quantities Not Equal .'))



              for line in order.pact_line_ids:

                  custody_id = custody_obj.search(cr,uid,[('id' , '=' , line.custody_id.id )])
                  parent_res = {

                   'state' : 'open',
                   'custody_type' : order.custody_type ,
                   'current_employee' : line.employee_id.id ,
                   'period_type' : order.period_type,
                   'expacted_return_date' : order.expacted_return_date or False,
                   'department_id' : order.department_id.id,
                   'custody_location_id' : line.custody_location_id.id ,
                   'user_id' : line.employee_id.user_id.id,
                                }
                
                 
                  lines_res = {
                      'custody_log_id' : custody_id[0] ,
                      'department_id' : order.department_id.id,
                      'action_type' : 'recieve' ,
                      'action_date' : order.order_date ,
                      'employee_id' : line.employee_id.id or False,
                         }
                  
                  log_id = asset_log_obj.create(cr,uid,lines_res)
                  custody_obj.write(cr,uid,custody_id, parent_res ,context=context)
              self.write(cr,uid,ids,{'state' : 'assigned' },context=context)
          return True

      def cancel(self,cr,uid,ids,context=None):
		""" 
		Workflow function changes order state to cancel.

		    
		@return: Boolean True
		"""
	      
		self.write(cr, uid, ids, {'state':'cancel'}, context=context)
		return True


      def ir_action_cancel_draft(self, cr, uid, ids, context=None):
        """ 
        Changes state to Draft and reset the workflow.

        @return: Boolean True 
        """
        if not len(ids):
            return False
        self.write(cr, uid, ids, {'state':'draft'}, context=context)
        wf_service = netsvc.LocalService("workflow")
        for s_id in ids:            
            # Deleting the existing instance of workflow for Internal requestion
            wf_service.trg_delete(uid, 'asset.pact.order', s_id, cr)            
            wf_service.trg_create(uid, 'asset.pact.order', s_id, cr)
        return True    
示例#33
0
        else:
                 raise osv.except_osv(_('Warning !'),'No products found on Amazon as per your search query. Please try again')
        return True
    _columns = {
        'amazon_sku': fields.char('Amazon SKU', size=126),
        'amazon_asin': fields.char('ASIN', size=16,readonly=True),
        'orderitemid': fields.char('Orderitemid', size=16),
        'product_order_item_id': fields.char('Order_item_id', size=256),
        'amazon_export':fields.boolean('Exported to Amazon'),
        'amazon_category':fields.many2one('amazon.category','Amazon Category'),
        'amz_type': fields.selection([('',''),('IBSN','IBSN'),('UPC','UPC'),('EAN','EAN'),('ASIN','ASIN')],'Type'),
        'amz_type_value': fields.char('Amazon Type Value', size=126),
        'amzn_condtn': fields.selection([('',''),('New','New'),('UsedLikeNew','Used Like New'),('UsedVeryGood','Used Very Good'),('UsedGood','UsedGood')
        ,('UsedAcceptable','Used Acceptable'),('CollectibleLikeNew','Collectible Like New'),('CollectibleVeryGood','Collectible Very Good'),('CollectibleGood','Collectible Good')
        ,('CollectibleAcceptable','Collectible Acceptable'),('Refurbished','Refurbished'),('Club','Club')],'Amazon Condition'),
        'prod_query': fields.char('Product Search Query', size=200, help="A search string with the same support as that is provided on Amazon marketplace websites."),
        'prod_query_contextid': fields.selection(_amazon_browse_node_get,'Query ContextId', help="An identifier for the context within which the given search will be performed."),
        'amazon_instance_id': fields.selection(_amazon_instance_get,'Amazon Instance', help="Select the Amazon instance where you want to perform search."),
        'amazon_products_ids': fields.one2many('amazon.products.master', 'product_id', 'Amazon Searched Products'),
        'amazon_prod_status':  fields.selection([('active','Active'),('fail','Failure')],'Status',readonly="True"),
        'operation_performed': fields.char('Operation Performed', size=126),
        'submit_feed_result' : fields.text('Submit Feed Result',readonly=True),
        'amazon_updated_price':fields.float('Amazon Updated Price',digits=(16,2)),
        'condition_note' : fields.text('Condition Note'),
    }
    _defaults = {
        'amzn_condtn':'',
        'amazon_instance_id': _assign_default_amazon_instance
    }
product_product()
示例#34
0
class oehealth_borderaux(osv.Model):
    _name = 'oehealth.borderaux'
    _description = "Borderaux"

    def _compute_create_uid(self, cr, uid, ids, field_name, arg, context={}):
        result = {}
        for r in self.browse(cr, uid, ids, context=context):
            perms = self.perm_read(cr, uid, ids)
            create_uid = perms[0].get('create_uid', 'n/a')
            result[r.id] = create_uid
        return result

    def _compute_create_date(self, cr, uid, ids, field_name, arg, context={}):
        result = {}
        for r in self.browse(cr, uid, ids, context=context):
            perms = self.perm_read(cr, uid, ids)
            create_date = perms[0].get('create_date', 'n/a')
            result[r.id] = create_date
        return result

    def _compute_write_uid(self, cr, uid, ids, field_name, arg, context={}):
        result = {}
        for r in self.browse(cr, uid, ids, context=context):
            perms = self.perm_read(cr, uid, ids)
            write_uid = perms[0].get('write_uid', 'n/a')
            result[r.id] = write_uid
        return result

    def _compute_write_date(self, cr, uid, ids, field_name, arg, context={}):
        result = {}
        for r in self.browse(cr, uid, ids, context=context):
            perms = self.perm_read(cr, uid, ids)
            write_date = perms[0].get('write_date', 'n/a')
            result[r.id] = write_date
        return result

    _columns = {
        'name':
        fields.char(string='Borderaux', size=64, required=True),
        'pharmacy':
        fields.char('Pharmacy Name', size=254),
        'pharmacy_id':
        fields.many2one('oehealth.pharmacy', 'Pharmacy'),
        'authorizations':
        fields.integer('Authorizations'),
        'refund_value':
        fields.float('Refund Value'),
        'refund_data':
        fields.date('Refund Data'),
        'borderaux_total':
        fields.float('Borderaux Total'),
        'category_ids':
        fields.many2many('oehealth.borderaux.category',
                         'oehealth_borderaux_category_rel', 'borderaux_id',
                         'category_id', 'Categories'),
        'tag_ids':
        fields.many2many('oehealth.tag', 'oehealth_borderaux_tag_rel',
                         'borderaux_id', 'tag_id', 'Tags'),
        'borderaux_info':
        fields.text(string='Info'),
        'annotation_ids':
        fields.one2many('oehealth.annotation', 'borderaux_id', 'Annotations'),
        'state':
        fields.selection([('new', 'New'), ('revised', 'Revised'),
                          ('waiting', 'Waiting'), ('okay', 'Okay')],
                         'Stage',
                         readonly=True),
        'active':
        fields.boolean(
            'Active',
            help=
            "The active field allows you to hide the borderaux without removing it."
        ),
        'create_uid':
        fields.function(
            _compute_create_uid,
            method=True,
            type='char',
            string='Create User',
        ),
        'create_date':
        fields.function(
            _compute_create_date,
            method=True,
            type='datetime',
            string='Create Date',
        ),
        'write_uid':
        fields.function(
            _compute_write_uid,
            method=True,
            type='char',
            string='Write User',
        ),
        'write_date':
        fields.function(
            _compute_write_date,
            method=True,
            type='datetime',
            string='Write Date',
        ),
    }

    _order = 'name'

    _sql_constraints = [('name_uniq', 'unique(name)', u'Duplicated Borderaux!')
                        ]

    _defaults = {
        'active': 1,
        'state': 'new',
    }

    def oehealth_borderaux_new(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'new'})
        return True

    def oehealth_borderaux_revised(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'revised'})
        return True

    def oehealth_borderaux_waiting(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'waiting'})
        return True

    def oehealth_borderaux_okay(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'okay'})
        return True
示例#35
0
                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),
        
        'msg_ids_tmp':fields.text('List of temporary ids of message to be pulled'),
        'version': fields.integer('version'),
        'last_sequence': fields.integer('Last update sequence pulled',
            readonly=True),
    }
    _defaults = {
示例#36
0
class account_invoice(osv.osv):
    _inherit = "account.invoice"

    _columns = {
        'invoice_taxform_ids': fields.one2many('account.invoice.tax', 'invoice_id', 'Tax Forms'),
    }
示例#37
0
                                                         cr, 
                                                         uid, 
                                                         {'interval_type':interval}
                                                     )
     compagnies =  self.search(cr, uid, [])
     for comp in compagnies :
         self.write(cr, uid, comp,{'interval_type':interval})
     return {}
     
 _inherit = "res.company"
 _columns = {
     ### activate the currency update
     'auto_currency_up': fields.boolean('Automatical update of the currency this company'),
     'services_to_use' : fields.one2many(
                                         'currency.rate.update.service', 
                                         'company_id',
                                         'Currency update services' 
                                         ),
     ###predifine cron frequence
     'interval_type': fields.selection(
                                             [
                                                 ('days','Day(s)'), 
                                                 ('weeks', 'Week(s)'), 
                                                 ('months', 'Month(s)')
                                             ],
                                             'Currency update frequence',
                                             help="""changing this value will
                                              also affect other compagnies"""
                                         ),
     ###function field that allows to know the
     ###mutli company currency implementation
示例#38
0
class Pembelian_Barang(osv.osv):

    STATES = [('draft', 'Draft'), ('confirm', 'Check'),
              ('confirm2', 'Confirm'), ('purchase', 'Purchase'),
              ('done', 'Done'), ('cancel', 'Cancel'), ('edit', 'Edit PB')]

    # FOR STATE FIELD
    def _getParentState(self, cr, uid, ids, field_name, args, context={}):
        res = {}
        for data in self.browse(cr, uid, ids, context):

            line = [x.id for x in data.detail_pb_ids]
            state_done = [
                y.id for y in data.detail_pb_ids if y.state == "done"
            ]

            operation = context.get('operation', False)
            action_state = context.get('action_state', False)

            if line == state_done:
                res[data.id] = "done"

            if operation == "create":
                res[data.id] = "draft"
            elif action_state == "submit":
                res[data.id] = "confirm"
            elif action_state == "confirm":
                res[data.id] = "confirm2"
            elif action_state == "confirm2":
                res[data.id] = "purchase"
            elif action_state == "draft":
                res[data.id] = "draft"

        return res

    def _get_cek_state_detail_pb(self, cr, uid, ids, context=None):
        result = {}
        for line in self.pool.get('detail.pb').browse(cr,
                                                      uid,
                                                      ids,
                                                      context=context):
            result[line.detail_pb_id.id] = True
        return result.keys()

    def _get_cek_state_delivery_line(self, cr, uid, ids, context=None):
        result = {}
        for line in self.pool.get('order.requisition.delivery.line').browse(
                cr, uid, ids, context=context):
            result[line.purchase_requisition_line_id.detail_pb_id.id] = True
        return result.keys()

    _name = 'pembelian.barang'
    _columns = {
        'name':
        fields.char('No.PB',
                    required=True,
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'edit': [('readonly', False)]
                    }),
        'spk_no':
        fields.char('SPK No / PO No',
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'edit': [('readonly', False)]
                    },
                    track_visibility='onchange'),
        'tanggal':
        fields.date('Date',
                    required=True,
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'edit': [('readonly', False)]
                    }),
        'duedate':
        fields.date('Due Date',
                    required=True,
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'edit': [('readonly', False)]
                    }),
        'employee_id':
        fields.many2one('hr.employee',
                        "Employee",
                        required=True,
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'edit': [('readonly', False)]
                        }),
        'department_id':
        fields.many2one('hr.department',
                        'Department',
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'edit': [('readonly', False)]
                        }),
        'customer_id':
        fields.many2one('res.partner',
                        'Customer',
                        domain=[('customer', '=', True)],
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'edit': [('readonly', False)]
                        }),
        'detail_pb_ids':
        fields.one2many('detail.pb',
                        'detail_pb_id',
                        'Detail PB',
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'edit': [('readonly', False)]
                        },
                        track_visibility='onchange'),
        'ref_pb':
        fields.char('Ref No',
                    required=True,
                    select=True,
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'edit': [('readonly', False)]
                    },
                    track_visibility='onchange'),
        'notes':
        fields.text('Terms and Conditions',
                    readonly=True,
                    states={
                        'draft': [('readonly', False)],
                        'edit': [('readonly', False)]
                    }),
        'cancel_reason':
        fields.text('Cancel Reason'),
        'product_id':
        fields.related('detail_pb_ids',
                       'name',
                       type='many2one',
                       relation='product.product',
                       string='Product'),
        'source_location_request_id':
        fields.many2one('stock.location',
                        "Source Location",
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'edit': [('readonly', False)]
                        }),
        'destination_location_request_id':
        fields.many2one('stock.location',
                        "Destination Location",
                        required=True,
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'edit': [('readonly', False)]
                        }),
        'state':
        fields.function(_getParentState,
                        method=True,
                        string="State",
                        type="selection",
                        selection=STATES,
                        store={
                            'pembelian.barang':
                            (lambda self, cr, uid, ids, c={}: ids, ['state'],
                             20),
                            'detail.pb':
                            (_get_cek_state_detail_pb, ['state'], 20),
                            'order.requisition.delivery.line':
                            (_get_cek_state_delivery_line, ['state'], 20),
                        }),
    }
    _inherit = ['mail.thread']

    _track = {
        'state': {
            'sbm_purchase.pb_confirmed':
            lambda self, cr, uid, obj, ctx=None: obj['state'] == 'confirm',
            'sbm_purchase.pb_checked':
            lambda self, cr, uid, obj, ctx=None: obj['state'] == 'confirm2',
            'sbm_purchase.pb_canceled':
            lambda self, cr, uid, obj, ctx=None: obj['state'] == 'cancel',
            'sbm_purchase.pb_draft':
            lambda self, cr, uid, obj, ctx=None: obj['state'] == 'draft',
        },
    }

    def _employee_get(obj, cr, uid, context=None):
        if context is None:
            context = {}

        cek = obj.pool.get('hr.employee').search(cr, uid,
                                                 [('user_id', '=', uid)])
        hasil = obj.pool.get('hr.employee').browse(cr, uid, cek)

        if hasil:
            ids = obj.pool.get('hr.employee').search(cr,
                                                     uid,
                                                     [('user_id', '=', uid)],
                                                     context=context)
            if ids:
                return ids[0]
        else:
            return uid

    _defaults = {
        'name': '/',
        'tanggal': time.strftime('%Y-%m-%d'),
        'employee_id': _employee_get,
        'state': 'draft',
        'source_location_request_id': 12,
    }

    _order = 'id DESC'

    def action_cancel_item(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        dummy, view_id = self.pool.get('ir.model.data').get_object_reference(
            cr, uid, 'sbm_purchase', 'wizard_pr_cancel_form')

        context.update({
            'active_model': self._name,
            'active_ids': ids,
            'active_id': len(ids) and ids[0] or False
        })
        return {
            'view_mode': 'form',
            'view_id': view_id,
            'view_type': 'form',
            'view_name': 'wizard_pr_cancel_form',
            'res_model': 'pembelian.barang',
            'type': 'ir.actions.act_window',
            'target': 'new',
            'context': context,
            'nodestroy': True,
        }

    def setDeuDate(self, cr, uid, ids, tanggal):
        setDueDateValue = datetime.strptime(tanggal,
                                            "%Y-%m-%d") + timedelta(days=4)
        return {'value': {'duedate': setDueDateValue.strftime('%Y-%m-%d')}}

    def setTanggal(self, cr, uid, ids, tanggal, duedate):
        setDueDateValue = datetime.strptime(tanggal,
                                            "%Y-%m-%d") + timedelta(days=4)
        cektanggal = setDueDateValue.strftime("%Y-%m-%d")
        if duedate < cektanggal:
            return {'value': {'duedate': cektanggal}}
        else:
            return {'value': {'duedate': duedate}}

    def create(self, cr, uid, vals, context={}):
        # vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'pembelian.barang')
        context.update(action_state='confirm')
        return super(Pembelian_Barang, self).create(cr,
                                                    uid,
                                                    vals,
                                                    context=context)

    def setDept(self, cr, uid, ids, pid):
        employee_id = self.pool.get('hr.employee').browse(cr, uid, pid)
        dept_id = employee_id.department_id.id
        return {'value': {'department_id': dept_id}}

    def submit(self, cr, uid, ids, context={}):
        context.update(action_state='submit')
        val = self.browse(cr, uid, ids)[0]
        code = val.destination_location_request_id.code
        no = self.pool.get('ir.sequence').get(
            cr, uid,
            'pembelian.barang') + 'PB/SBM/' + code + '/' + time.strftime(
                '%y') + '/' + time.strftime('%m')
        return self.write(cr,
                          uid,
                          ids, {
                              'state': 'confirm',
                              'name': no
                          },
                          context=context)

    def edit(self, cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state': 'edit'})

    def setdraft(self, cr, uid, ids, context={}):
        context.update(action_state='draft')
        # print '============',data
        return self.write(cr, uid, ids, {'state': 'draft'}, context=context)

    def confirm3(self, cr, uid, ids, context={}):
        val = self.browse(cr, uid, ids)[0]
        obj_detail_pb = self.pool.get('detail.pb')
        for detail in val.detail_pb_ids:
            if detail.state == 'draft':
                cr.execute('Update detail_pb Set state=%s Where id=%s',
                           ('onproses', detail.id))
        return self.write(cr, uid, ids, {'state': 'purchase'})

    def confirm(self, cr, uid, ids, context={}):
        #		val = self.browse(cr, uid, ids)[0]
        #		usermencet = self.pool.get('res.user')
        #		if val.employee_id.parent_id.id != uid :
        #			raise osv.except_osv(('Perhatian..!!'), ('Harus Atasannya langsung ..'))
        context.update(action_state='confirm')
        return self.write(cr, uid, ids, {'state': 'confirm2'}, context=context)

    def confirm2(self, cr, uid, ids, context={}):
        #		val = self.browse(cr, uid, ids)[0]
        #		usermencet = self.pool.get('res.user')
        #		if val.employee_id.parent_id.id != uid :
        #			raise osv.except_osv(('Perhatian..!!'), ('Harus Atasannya langsung ..'))
        context.update(action_state='confirm2')
        cr.execute('Update detail_pb Set state=%s Where detail_pb_id=%s',
                   ('onproses', ids[0]))
        return self.write(cr, uid, ids, {'state': 'purchase'}, context=context)

    def purchase(self, cr, uid, ids, context={}):
        return self.write(cr, uid, ids, {'state': 'done'})

    def reportpb(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        datas['model'] = 'pembelian.barang'
        datas['form'] = self.read(cr, uid, ids)[0]

        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'print.pb',
            'report_type': 'webkit',
            'datas': datas,
        }
示例#39
0
            try:
                file_data = image_file.read()
                self._logo_image = base64.encodestring(file_data)
                return self._logo_image
            finally:
                image_file.close()
        else:
            self._logo_image = base64.encodestring(im.read())
            return self._logo_image

    def _get_image_fn(self, cr, uid, ids, name, args, context=None):
        image = self._get_image(cr, uid, context)
        return dict.fromkeys(ids, image) # ok to use .fromkeys() as the image is same for all 

    _columns = {
        'printer_ids':fields.one2many('aeroo.printers.temp', 'install_id', 'Printers'),
        'config_logo': fields.function(_get_image_fn, string='Image', type='binary', method=True),
        'state':fields.selection([
            ('init','Init'),
            ('done','Done'),
            
        ],'State', select=True, readonly=True),
    }

    def default_get(self, cr, uid, fields, context=None):
        printers_obj = self.pool.get('aeroo.printers')
        data = super(aeroo_printer_installer, self).default_get(cr, uid, fields, context=context)
        conn = cups.Connection()
        printers = conn.getPrinters()
        installed_ids = printers_obj.search(cr, 1, ['|',('active','=',False),('active','=',True)], context=context)
        printers_installed = printers_obj.read(cr, uid, installed_ids, context=context)
示例#40
0
 #   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),
 'url':
 fields.char('URL', size=128, readonly=True),
 'sequence':
 fields.integer('Sequence'),
 'dependencies_id':
 fields.one2many('ir.module.module.dependency',
                 'module_id',
                 'Dependencies',
                 readonly=True),
 'auto_install':
 fields.boolean(
     'Automatic Installation',
     help='An auto-installable module is automatically installed by the '
     'system when all its dependencies are satisfied. '
     'If the module has no dependency, it is always installed.'),
 'state':
 fields.selection([('uninstallable', 'Not Installable'),
                   ('uninstalled', 'Not Installed'),
                   ('installed', 'Installed'),
                   ('to upgrade', 'To be upgraded'),
                   ('to remove', 'To be removed'),
                   ('to install', 'To be installed')],
                  string='State',
            [("not_started", "Not Started"), ("failed", "Failed"), ("succeeded", "Succeeded"), ("skipped", "Skipped")],
            "Functional Certification",
        ),
        "sale_ids": fields.many2many(
            "sale.order", "maintenance_module_sale_rel", "module_id", "sale_id", "Sale orders"
        ),
        "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):
示例#42
0
class res_partner(osv.osv):
    _inherit = "res.partner"
    _columns = {
        'tenant_ids': fields.one2many('chricar.tenant', 'partner_id',
                                      'Tenant'),
    }
示例#43
0
     #Warranty
     'warranty_start_date':fields.date('Start Date', help="The date the warranty commences"),
     'warranty_finish_date':fields.date('Finish Date', help="The date the warranty expires"),
     'warranty_completion_date':fields.date('Completion Date'),
     'warranty_duration':fields.selection([
               ('no_warranty', 'No Warranty'),
               ('30_days','30 Days'),
               ('60_days','60 Days'),
               ('90_days','90 Days'),
               ('180_days','180 Days'),
               ('1_year','1 Year'),
               ('2_years','2 Years'),
               ('3_years','3 Years'),
               ('4_years','4 Years'),
               ('5_years','5 Years')], 'Duration', help="Duration of the Warranty"),
     'warranty_history':fields.one2many('mttl.warranty.history','serial_id', 'Warranty Claims History'),
     #+++ HoangTK - 02/18/2016 : Link warranty module to serials
     'warranty_ids': fields.one2many('warranty.cases','serial_id','Warranty Cases'),
     #Notes
     'notes':fields.text('Notes'),
     
     'image':fields.text('Images'),
     #attachments
     'attachment_lines': fields.one2many('ir.attachment', 'mttl_serials_id', 'Attachment'),
 }
 
 _defaults = {
     'serial_number':_generate_serial_number,
     'serial':'New Number',
 }
 
示例#44
0
class chricar_top(osv.osv):
    _inherit = "chricar.top"

    def _lease_current_m2(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        price = 0.0
        for p in self.browse(cr, uid, ids, context):
            now = time.strftime('%Y-%m-%d %H:%M:%S')
            tenant_obj = self.pool.get('chricar.tenant')
            tenant_ids = tenant_obj.search(cr, uid, [
                '|', ('to_date', '=', False), ('to_date', '>', now),
                ('name', '<=', now), ('top_id', '=', p.id)
            ])
            for lease in tenant_obj.browse(cr, uid, tenant_ids, context):
                price = lease.price
            result[p.id] = price
        return result

    def _lease_current(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for p in self.browse(cr, uid, ids, context):
            now = time.strftime('%Y-%m-%d %H:%M:%S')
            tenant_obj = self.pool.get('chricar.tenant')
            tenant_ids = tenant_obj.search(cr, uid, [
                '|', ('to_date', '=', False), ('to_date', '>', now),
                ('name', '<=', now), ('top_id', '=', p.id)
            ])
            lease_cur = 0.0
            for lease in tenant_obj.browse(cr, uid, tenant_ids, context):
                lease_cur = lease.lease
            result[p.id] = lease_cur
        return result

    def _lease_potential(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        potential = 0.0
        for p in self.browse(cr, uid, ids, context):
            now = time.strftime('%Y-%m-%d %H:%M:%S')
            tenant_obj = self.pool.get('chricar.tenant')
            tenant_ids = tenant_obj.search(cr, uid, [
                '|', ('to_date', '=', False), ('to_date', '>', now),
                ('name', '<=', now), ('top_id', '=', p.id)
            ])
            price = 0.0
            for lease in tenant_obj.browse(cr, uid, tenant_ids, context):
                price = lease.price
            potential = 0.0
            if p.lease_target and p.surface:
                potential = p.surface * (p.lease_target - price)
            if not p.surface and p.lease_target:
                potential = round(p.lease_target - p.lease_current, 0)
            result[p.id] = potential
        return result

    def _unpaid_rate(self, cr, uid, ids, field_name, arg, context=None):
        _logger = logging.getLogger(__name__)
        result = {}
        for leases in self.browse(cr, uid, ids, context):
            # days
            unpaid = 0
            total = 0
            for lease in leases.tenant_ids:
                to_day = time.strftime('%Y-%m-%d')
                to_date = datetime.strptime(
                    min(lease.to_date or to_day, to_day), '%Y-%m-%d')
                #to_date = datetime.strptime(lease.to_date or time.strftime('%Y-%m-%d'),'%Y-%m-%d')
                from_date = datetime.strptime(lease.name, '%Y-%m-%d')
                days = to_date - from_date
                total += days.days
                if lease.partner_id and lease.partner_id.name == _(
                        'Leerstehung'):
                    unpaid += days.days
                self._logger.info('FGF unpaid %s %s %s %s %s' %
                                  (leases.name, lease.partner_id.name,
                                   days.days, total, unpaid))
            if total > 0:
                result[leases.id] = float(unpaid) / float(total) * 100
            else:
                result[leases.id] = None
        return result

    def _tenant_current(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for p in self.browse(cr, uid, ids, context):
            partner_id = False
            now = time.strftime('%Y-%m-%d %H:%M:%S')
            tenant_obj = self.pool.get('chricar.tenant')
            tenant_ids = tenant_obj.search(cr, uid, [
                '|', ('to_date', '=', False), ('to_date', '>', now),
                ('name', '<=', now), ('top_id', '=', p.id)
            ])
            if tenant_ids:
                for lease in tenant_obj.browse(cr, uid, tenant_ids, context):
                    partner_id = lease.partner_id.id
            if not partner_id:
                tenant_ids = tenant_obj.search(cr, uid,
                                               [('name', '>', now),
                                                ('top_id', '=', p.id)])
                if tenant_ids:
                    for lease in tenant_obj.browse(cr, uid, tenant_ids,
                                                   context):
                        partner_id = lease.partner_id.id
            result[p.id] = partner_id
        return result

    _columns = {
        'lease_current':
        fields.function(_lease_current,
                        method=True,
                        string="Current Lease",
                        type='float',
                        digits=(16, 0)),
        'lease_current_m2':
        fields.function(_lease_current_m2,
                        method=True,
                        string="Current/m²",
                        type='float',
                        digits=(16, 2)),
        'lease_potential':
        fields.function(_lease_potential,
                        method=True,
                        string="Potential Lease",
                        type='float',
                        digits=(16, 0)),
        'unpaid_rate':
        fields.function(_unpaid_rate,
                        method=True,
                        string="Unpaid Rate",
                        type='float',
                        digits=(3, 0),
                        help="Percentage not rented days until today"),
        'tenant_id':
        fields.function(_tenant_current,
                        method=True,
                        type='many2one',
                        relation='res.partner',
                        string='Tenant'),
        'tenant_ids':
        fields.one2many('chricar.tenant', 'top_id', 'Tenant'),
        #'tenant_id'          : fields.function(_tenant_current, method=True, string='Tenant',type='char', size=128 ),
    }
示例#45
0
        '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),

        'url': fields.char('URL', size=128, readonly=True),
        'sequence': fields.integer('Sequence'),
        'dependencies_id': fields.one2many('ir.module.module.dependency',
            'module_id', 'Dependencies', readonly=True),
        'auto_install': fields.boolean('Automatic Installation',
            help='An auto-installable module is automatically installed by the '
            'system when all its dependencies are satisfied. '
            'If the module has no dependency, it is always installed.'),
        'state': fields.selection([
            ('uninstallable','Not Installable'),
            ('uninstalled','Not Installed'),
            ('installed','Installed'),
            ('to upgrade','To be upgraded'),
            ('to remove','To be removed'),
            ('to install','To be installed')
        ], string='State', readonly=True, select=True),
        'demo': fields.boolean('Demo data', readonly=True),
        'license': fields.selection([
                ('GPL-2', 'GPL Version 2'),
示例#46
0
     #Warranty
     'warranty_start_date':fields.date('Start Date', help="The date the warranty commences"),
     'warranty_finish_date':fields.date('Finish Date', help="The date the warranty expires"),
     'warranty_completion_date':fields.date('Completion Date'),
     'warranty_duration':fields.selection([
               ('no_warranty', 'No Warranty'),
               ('30_days','30 Days'),
               ('60_days','60 Days'),
               ('90_days','90 Days'),
               ('180_days','180 Days'),
               ('1_year','1 Year'),
               ('2_years','2 Years'),
               ('3_years','3 Years'),
               ('4_years','4 Years'),
               ('5_years','5 Years')], 'Duration', help="Duration of the Warranty"),
     'warranty_history':fields.one2many('mttl.warranty.history','serial_id', 'Warranty Claims History'),
     
     #Notes
     'notes':fields.text('Notes'),
     
     'image':fields.text('Images'),
     
 }
 
 _defaults = {
     'serial_number':_generate_serial_number,
     'serial':'New Number',
 }