예제 #1
0
 def view_init(self, cr, uid, fields_list, context=None):
     """
      Creates view dynamically and adding fields at runtime.
      @param self: The object pointer.
      @param cr: A database cursor
      @param uid: ID of the user currently logged in
      @param context: A standard dictionary
      @return: New arch of view with new columns.
     """
     res = super(AccountProfitAndLossLedgerWizard, self).view_init(cr, uid, fields_list, context=context)
     for index in range(LEVEL_STYLES):
         # create columns for each comparison page
         self._columns.update({
             "level%s_print" % (index,):
                 fields.boolean('Print'),
             "level%s_size" % (index,):
                 fields.integer('Size', required=True),
             "level%s_bold" % (index,):
                 fields.boolean('Bold'),
             "level%s_italic" % (index,):
                 fields.boolean('Italic'),
             "level%s_underline" % (index,):
                 fields.boolean('Underline'),
             "level%s_uppercase" % (index,):
                 fields.boolean('Uppercase'),
         })
     return res
    def __init__(self, pool, cr):
        """ Dynamically add columns
        """

        super(report_prompt_class, self).__init__(pool, cr)

        for counter in range(0, MAX_PARAMS):
            field_name = PARAM_XXX_STRING_VALUE % counter
            self._columns[field_name] = fields.char('String Value', size=64)

            field_name = PARAM_XXX_BOOLEAN_VALUE % counter
            self._columns[field_name] = fields.boolean('Boolean Value')

            field_name = PARAM_XXX_INTEGER_VALUE % counter
            self._columns[field_name] = fields.integer('Integer Value')

            field_name = PARAM_XXX_NUMBER_VALUE % counter
            self._columns[field_name] = fields.float('Number Value')

            field_name = PARAM_XXX_DATE_VALUE % counter
            self._columns[field_name] = fields.date('Date Value')

            field_name = PARAM_XXX_TIME_VALUE % counter
            self._columns[field_name] = fields.datetime('Time Value')

        self.paramfile = False
    def action_compute(self, cr, uid, ids, properties=None, context=None):
        """ Computes bills of material of a product.
        @param properties: List containing dictionaries of properties.
        @return: No. of products.
        """
        if properties is None:
            properties = []
        results = []
        bom_obj = self.pool.get('mrp.bom')
        uom_obj = self.pool.get('product.uom')
        prod_line_obj = self.pool.get('mrp.production.product.line')
        workcenter_line_obj = self.pool.get('mrp.production.workcenter.line')
        for production in self.browse(cr, uid, ids):
            cr.execute('delete from mrp_production_product_line where production_id=%s', (production.id,))
            cr.execute('delete from mrp_production_workcenter_line where production_id=%s', (production.id,))
            bom_point = production.bom_id
            bom_id = production.bom_id.id
            if not bom_point:
                bom_id = bom_obj._bom_find(cr, uid, production.product_id.id, production.product_uom.id, properties)
                if bom_id:
                    bom_point = bom_obj.browse(cr, uid, bom_id)
                    routing_id = bom_point.routing_id.id or False
                    self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id})

            if not bom_id:
                raise osv.except_osv(_('Error!'), _("Cannot find a bill of material for this product."))
            factor = uom_obj._compute_qty(cr, uid, production.product_uom.id, production.product_qty, bom_point.product_uom.id)
            res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, properties, routing_id=production.routing_id.id)
            results = res[0]
            results2 = res[1]
            for line in results:
                line['production_id'] = production.id
                prod_line_obj.create(cr, uid, line)
            for line in results2:
                line['production_id'] = production.id
                workcenter_line_obj.create(cr, uid, line)
        return len(results)
	_columns = {
		'pallet_stack_id': fields.many2one('pallet.stack.layout','Pallet Stack'), #TODO Filter to ids returned by product.product.pallet_stack_layers for the product
		'num_layers': fields.many2one('pallet.stack.layers', 'Number of layers') #TODO Filter to ids returned by field above, and pre-enter default number of layers as a default.
		'num_pallets': fields.integer('Quantity of pallets')
		}
예제 #4
0
        '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 = {
        'version': lambda *a: 0,
        'last_sequence': lambda *a: 0,
    }
    def unlink(self, cr, uid, ids, context=None):
        for rec in self.browse(cr, uid, ids, context=context):
            if rec.parent_id:
                raise osv.except_osv(_("Error!"), _("Can not delete an instance that have children!"))
예제 #5
0
 _columns = {
     "email_from": fields.char("From", size=64),
     "email_to": fields.char("Recipient (To)", size=250),
     "email_cc": fields.char("CC", size=250),
     "email_bcc": fields.char("BCC", size=250),
     "reply_to": fields.char("Reply-To", size=250),
     "message_id": fields.char("Message-ID", size=250),
     "subject": fields.char("Subject", size=200),
     "body_text": fields.text("Standard Body (Text)"),
     "body_html": fields.text("Body (Rich Text Clients Only)"),
     "attachments_ids": fields.many2many(
         "ir.attachment", "mail_attachments_rel", "mail_id", "att_id", "Attachments"
     ),
     "account_id": fields.many2one("email_template.account", "User account", required=True),
     "user": fields.related("account_id", "user", type="many2one", relation="res.users", string="User"),
     "server_ref": fields.integer("Server Reference of mail", help="Applicable for inward items only"),
     "mail_type": fields.selection(
         [
             ("multipart/mixed", "Has Attachments"),
             ("multipart/alternative", "Plain Text & HTML with no attachments"),
             ("multipart/related", "Intermixed content"),
             ("text/plain", "Plain Text"),
             ("text/html", "HTML Body"),
         ],
         "Mail Contents",
     ),
     # I like GMAIL which allows putting same mail in many folders
     # Lets plan it for 0.9
     "folder": fields.selection(
         [("drafts", "Drafts"), ("outbox", "Outbox"), ("trash", "Trash"), ("sent", "Sent Items")],
         "Folder",
예제 #6
0
class report_account_analytic_planning(osv.osv):
    _name = "report_account_analytic.planning"
    _description = "Planning"

    def emp_to_users(self, cr, uid, ids, context=None):
        employees = self.pool.get('hr.employee').browse(cr,
                                                        uid,
                                                        ids,
                                                        context=context)
        user_ids = [e.user_id.id for e in employees if e.user_id]
        return user_ids

    def _child_compute(self, cr, uid, ids, name, args, context=None):
        obj_dept = self.pool.get('hr.department')
        obj_user = self.pool.get('res.users')
        result = {}
        for user_id in ids:
            child_ids = []
            cr.execute(
                """SELECT dept.id FROM hr_department AS dept
                LEFT JOIN hr_employee AS emp ON dept.manager_id = emp.id
                WHERE emp.id IN
                    (SELECT emp.id FROM hr_employee
                        JOIN resource_resource r ON r.id = emp.resource_id WHERE r.user_id = %s)
                """, (user_id, ))
            mgnt_dept_ids = [x[0] for x in cr.fetchall()]
            ids_dept = obj_dept.search(cr,
                                       uid,
                                       [('id', 'child_of', mgnt_dept_ids)],
                                       context=context)
            if ids_dept:
                data_dept = obj_dept.read(cr,
                                          uid,
                                          ids_dept, ['member_ids'],
                                          context=context)
                emp_children = map(lambda x: x['member_ids'], data_dept)
                emp_children = tools.flatten(emp_children)
                children = self.emp_to_users(cr,
                                             uid,
                                             emp_children,
                                             context=context)
                children = obj_user.search(cr,
                                           uid, [('id', 'in', children),
                                                 ('active', '=', True)],
                                           context=context)
                if user_id in children:
                    children.remove(user_id)
                child_ids = list(set(child_ids + children))
            result[user_id] = child_ids
        return result

    def _get_total_planned(self, cr, uid, ids, name, args, context=None):
        result = {}
        for plan in self.browse(cr, uid, ids, context=context):
            plan_hrs = 0.0
            for p in plan.planning_user_ids:
                if not p.plan_open: p.plan_open = 0.0
                if not p.plan_tasks: p.plan_tasks = 0.0
                plan_hrs = plan_hrs + p.plan_open + p.plan_tasks
            result[plan.id] = plan_hrs
        return result

    def _get_total_free(self, cr, uid, ids, name, args, context=None):
        result = {}
        for plan in self.browse(cr, uid, ids, context=context):
            total_free = 0.0
            for p in plan.planning_user_ids:
                if p.free:
                    total_free = total_free + p.free
            result[plan.id] = total_free
        return result

    def _check_planning_responsible(self, cr, uid, ids, context=None):
        for obj_plan in self.browse(cr, uid, ids, context=context):
            cr.execute(
                """
                SELECT id FROM report_account_analytic_planning plan
                WHERE (   (%(date_from)s BETWEEN date_from AND date_to)
                                OR (%(date_to)s BETWEEN date_from AND date_to)
                                OR (%(date_from)s < date_from AND %(date_to)s > date_to)
                               )  AND user_id = %(uid)s AND id <> %(id)s""", {
                    "date_from": obj_plan.date_from,
                    "date_to": obj_plan.date_to,
                    "uid": obj_plan.user_id.id,
                    "id": obj_plan.id
                })

            res = cr.fetchone()
            if res:
                return False
        return True

    _columns = {
        'name':
        fields.char('Planning Name',
                    required=True,
                    size=32,
                    states={'done': [('readonly', True)]}),
        'code':
        fields.char('Code', size=32, states={'done': [('readonly', True)]}),
        'user_id':
        fields.many2one('res.users',
                        'Responsible',
                        required=True,
                        states={'done': [('readonly', True)]}),
        'date_from':
        fields.date('Start Date',
                    required=True,
                    states={'done': [('readonly', True)]}),
        'date_to':
        fields.date('End Date',
                    required=True,
                    states={'done': [('readonly', True)]}),
        'line_ids':
        fields.one2many('report_account_analytic.planning.line',
                        'planning_id',
                        'Planning lines',
                        states={'done': [('readonly', True)]}),
        'stat_ids':
        fields.one2many('report_account_analytic.planning.stat',
                        'planning_id',
                        'Planning analysis',
                        readonly=True),
        'state':
        fields.selection([('draft', 'Draft'), ('open', 'Open'),
                          ('done', 'Done'), ('cancel', 'Cancelled')],
                         'Status',
                         required=True),
        'business_days':
        fields.integer(
            'Business Days',
            required=True,
            states={'done': [('readonly', True)]},
            help=
            'Set here the number of working days within this planning for one person full time'
        ),
        'planning_user_ids':
        one2many_mod3('report_account_analytic.planning.user', 'planning_id',
                      'Planning By User'),
        'planning_account':
        fields.one2many('report_account_analytic.planning.account',
                        'planning_id', 'Planning By Account'),
        'total_planned':
        fields.function(_get_total_planned, string='Total Planned'),
        'total_free':
        fields.function(_get_total_free, string='Total Free'),
    }
    _defaults = {
        'date_from':
        lambda self, cr, uid, ctx: fields.date.context_today(
            self,
            cr,
            uid,
            timestamp=(datetime.now() + relativedelta(day=1)),
            context=ctx),
        'date_to':
        lambda self, cr, uid, ctx: fields.date.context_today(
            self,
            cr,
            uid,
            timestamp=(datetime.now() + relativedelta(months=1, day=1, days=-1)
                       ),
            context=ctx),
        'user_id':
        lambda self, cr, uid, c: uid,
        'state':
        'draft',
        'business_days':
        20,
    }
    _order = 'date_from desc'

    _constraints = [(
        _check_planning_responsible,
        'Invalid planning ! Planning dates can\'t overlap for the same responsible. ',
        ['user_id'])]

    def action_open(self, cr, uid, id, context=None):
        self.write(cr, uid, id, {'state': 'open'}, context=context)
        return True

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

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

    def action_done(self, cr, uid, id, context=None):
        self.write(cr, uid, id, {'state': 'done'}, context=context)
        return True
예제 #7
0
class OeMedicalPrescriptionLine(osv.Model):
    _name = 'oemedical.prescription.line'

    def _get_medicament(self, cr, uid, ids, name, args, context=None):
        print '_get_medicament', name, args, context, ids
        medication_obj = self.pool.get('oemedical.medication.template')
        result = {}

        #        if name == 'form':
        #            result = {'value': {
        #                        'form' : medication_obj.browse(cr, uid, medication, context = None).form.id ,
        #                         } }
        return result


#    def _get_dose(self, cr, uid, ids, field_name, arg, context=None):
#        res = {}
#        for record in self.browse(cr, uid, ids, context=context):
#            res[record.id] = record.template.dose
#        return res

#    def _get_frecuency(self, cr, uid, ids, field_name, arg, context=None):
#        res = {}
#        for record in self.browse(cr, uid, ids, context=context):
#            res[record.id] = 1
#        return res

#    def _get_duration(self, cr, uid, ids, field_name, arg, context=None):
#        res = {}
#        for record in self.browse(cr, uid, ids, context=context):
#            res[record.id] = 1
#        return res

#    def _get_qty(self, cr, uid, ids, field_name, arg, context=None):
#        res = {}
#        for record in self.browse(cr, uid, ids, context=context):
#            res[record.id] = 1
#        return res

#    def _get_frecuency_unit(self, cr, uid, ids, field_name, arg, context=None):
#        res = {}
#        return res

#    def _get_admin_times(self, cr, uid, ids, name, args, context=None):
#        res = {}
#        return res

#    def _get_start_treatment(self, cr, uid, ids, field_name, arg, context=None):
#        ops = self.browse(cr, uid, ids, context=context)
#        res = {}
#        for op in ops:
#            res[op.id] = False
#        return res

#    def _get_end_treatment(self, cr, uid, ids, field_name, arg, context=None):
#        ops = self.browse(cr, uid, ids, context=context)
#        res = {}
#        for op in ops:
#            res[op.id] = False
#        return res

#    def _get_duration_period(self, cr, uid, ids, field_name, arg, context=None):
#        res = {}
#        for line in self.browse(cr, uid, ids, context=context):
#            res[line.id] = 'days'
#        return res

    def onchange_template(self, cr, uid, ids, medication, context=None):
        medication_obj = self.pool.get('oemedical.medication.template')
        res = {}
        res = {
            'value': {
                'indication':
                medication_obj.browse(cr, uid, medication,
                                      context=None).indication.id,
                'form':
                medication_obj.browse(cr, uid, medication,
                                      context=None).form.id,
                'route':
                medication_obj.browse(cr, uid, medication,
                                      context=None).route.id,
                'dose':
                medication_obj.browse(cr, uid, medication, context=None).dose,
                'dose_unit':
                medication_obj.browse(cr, uid, medication,
                                      context=None).dose_unit.id,
                'qty':
                medication_obj.browse(cr, uid, medication, context=None).qty,
                'admin_times':
                medication_obj.browse(cr, uid, medication,
                                      context=None).admin_times,
                'common_dosage':
                medication_obj.browse(cr, uid, medication,
                                      context=None).common_dosage.id,
                'frequency':
                medication_obj.browse(cr, uid, medication,
                                      context=None).frequency,
                'frequency_unit':
                medication_obj.browse(cr, uid, medication,
                                      context=None).frequency_unit,
            }
        }
        return res


    _columns = {
        'name': fields.many2one('oemedical.prescription.order', string='Prescription ID', ),
        'template': fields.many2one('oemedical.medication.template', string='Medication', ),
        'indication': fields.many2one('oemedical.pathology', string='Indication', help='Choose a disease for this medicament from the disease list. It'\
                        ' can be an existing disease of the patient or a prophylactic.'),
        'allow_substitution': fields.boolean(string='Allow substitution'),
        'prnt': fields.boolean(string='Print', help='Check this box to print this line of the prescription.'),
        'quantity': fields.integer(string='Units',  help="Number of units of the medicament. Example : 30 capsules of amoxicillin"),
        'active_component': fields.char(size=256, string='Active component', help='Active Component'),
        'start_treatment': fields.datetime(string='Start'),
        'end_treatment': fields.datetime(string='End'),
        'dose' : fields.float('Dose', digits=(16, 2), help="Amount of medication (eg, 250 mg) per dose"),
        'dose_unit': fields.many2one('product.uom', string='Dose Unit', help='Amount of medication (eg, 250 mg) per dose'),
        'qty' : fields.integer('x'),
        'form': fields.many2one('oemedical.drug.form', string='Form', help='Drug form, such as tablet or gel'),
        'route': fields.many2one('oemedical.drug.route', string='Route', help='Drug form, such as tablet or gel'),
        'common_dosage': fields.many2one('oemedical.medication.dosage', string='Frequency', help='Drug form, such as tablet or gel'),
     'admin_times' : fields.char('Admin Hours', size=255),
        'frequency' : fields.integer('Frequency'),
        'frequency_unit': fields.selection([
                                (None, ''),
                                ('seconds', 'seconds'),
                                ('minutes', 'minutes'),
                                ('hours', 'hours'),
                                ('days', 'days'),
                                ('weeks', 'weeks'),
                                ('wr', 'when required'),
                                    ],'Unit'),
        'frequency_prn': fields.boolean(string='Frequency prn', help=''),
        'duration' : fields.integer('Treatment duration'),
        'duration_period': fields.selection([
                                (None, ''),
                                ('minutes', 'minutes'),
                                ('hours', 'hours'),
                                ('days', 'days'),
                                ('months', 'months'),
                                ('years', 'years'),
                                ('indefinite', 'indefinite'),
                                    ],'Treatment period'),
        'refills': fields.integer(string='Refills #'),
        'review': fields.datetime(string='Review'),
        'short_comment': fields.char(size=256, string='Comment', help='Short comment on the specific drug'),

    }

    _defaults = {
        'prnt': True,
    }
예제 #8
0
class account_fstr_category(osv.osv):
    _name = "account_fstr.category"
    _description = "Financial Statement template category"
    _order = "sequence, id"

    def __compute(self,
                  cr,
                  uid,
                  ids,
                  field_names,
                  arg=None,
                  context=None,
                  query='',
                  query_params=()):
        res = {}
        for category_obj in self.browse(cr, uid, ids, context=context):
            res.update({
                category_obj.id:
                self.__compute_balance_for_caregory(cr,
                                                    uid,
                                                    category_obj,
                                                    context=context)
            })
        return res

    def __compute_balance_for_caregory(self,
                                       cr,
                                       uid,
                                       category_obj,
                                       context={}):
        result = 0
        if category_obj.state == 'normal':
            for account_obj in category_obj.account_ids:
                result += account_obj.balance
        else:
            for child_category_obj in category_obj.child_id:
                result += self.__compute_balance_for_caregory(
                    cr, uid, child_category_obj, context=context)
        return result

    def _get_progenitor_id(self,
                           cr,
                           uid,
                           ids,
                           field_names,
                           arg=None,
                           context={}):
        res = {}
        for category_obj in self.browse(cr, uid, ids, context=context):
            res.update({
                category_obj.id:
                self._get_progenitor_id_in_recurse(cr,
                                                   uid,
                                                   category_obj,
                                                   context=context)
            })
        return res

    def _get_progenitor_id_in_recurse(self, cr, uid, category_obj, context={}):
        result = None
        if not (category_obj.parent_id and category_obj.parent_id.id):
            result = category_obj.id
        else:
            result = self._get_progenitor_id_in_recurse(cr,
                                                        uid,
                                                        category_obj.parent_id,
                                                        context=context)
        return result

    def _get_childs(self, cr, uid, ids, context={}):
        return self.search(cr, uid, [('id', 'child_of', ids)], context=context)

    _columns = {
        'name':
        fields.char(
            'Category Title name',
            size=128,
            required=True,
            select=True,
        ),
        'digits_round':
        fields.integer('Digits round', required=True),
        'company_id':
        fields.many2one(
            'res.company',
            'Company',
            ondelete='set null',
        ),
        'name_end':
        fields.char(
            'Category End/Total name',
            size=128,
        ),
        'display_total':
        fields.boolean('Display End/Total'),
        'parent_id':
        fields.many2one(
            'account_fstr.category',
            'Parent node',
            ondelete='cascade',
            select=True,
        ),
        'sequence':
        fields.integer('Sequence'),
        'consolidate_total':
        fields.boolean(
            'Consolidate total',
            help=
            "Selecting Consolidate total will print this category total as a single summed figure and will not list out each individual account"
        ),
        'display_heading':
        fields.boolean('Display title'),
        'bold_title':
        fields.boolean('Bold'),
        'italic_title':
        fields.boolean('Italic'),
        'underline_title':
        fields.boolean('Unnderline'),
        'bold_end':
        fields.boolean('Bold'),
        'italic_end':
        fields.boolean('Italic'),
        'underline_end':
        fields.boolean('Unnderline'),
        'inversed_sign':
        fields.boolean('Inversed sign'),
        'child_id':
        fields.one2many(
            'account_fstr.category',
            'parent_id',
            'Consolidated Children',
            select=True,
        ),
        'account_ids':
        fields.many2many(
            'account.account',
            'account_fstr_category_account',
            'account_id',
            'category_id',
            'Accounts',
            select=True,
        ),
        'indent_title':
        fields.integer('Indent Title, (pt)'),
        'indent_end':
        fields.integer('Indent End, (pt)'),
        'top_spacing_title':
        fields.integer('Top spacing Title, (pt)'),
        'top_spacing_end':
        fields.integer('Top spacing End, (pt)'),
        'bottom_spacing_title':
        fields.integer('Bottom spacing Title, (pt)'),
        'bottom_spacing_end':
        fields.integer('Bottom spacing End, (pt)'),
        'state':
        fields.selection(
            [('view', 'View'), ('root', 'Root'), ('normal', 'Normal')],
            'Type',
            select=True,
        ),
        'balance':
        fields.function(__compute,
                        digits_compute=dp.get_precision('Account'),
                        method=True,
                        string='Balance',
                        store=False,
                        type='float'),
        'printable':
        fields.boolean(
            'Printable',
            help="Select to allow category to display in print list"),
        'progenitor_id':
        fields.function(
            _get_progenitor_id,
            method=True,
            string='Root',
            type='many2one',
            obj='account_fstr.category',
            store={'account_fstr.category': (_get_childs, ['parent_id'], 1)},
            select=True,
        ),
    }

    _defaults = {
        'state': 'normal',
        'indent_title': 10,
        'indent_end': 10,
        'top_spacing_title': 0,
        'digits_round': 0,
    }

    def print_template(self, cr, uid, ids, context={}):
        return account_fstr_wizard.account_fstr_wizard.print_template(
            cr, uid, ids, context={})

    def _get_selected_accounts(self,
                               cr,
                               uid,
                               progenitor_id,
                               current_category_id,
                               context={}):
        result = []
        category_ids = self.search(cr,
                                   uid,
                                   [('progenitor_id', '=', progenitor_id)],
                                   context=context)
        for category_obj in self.browse(cr, uid, category_ids,
                                        context=context):
            if category_obj.id != current_category_id[0]:
                result.extend(
                    [category.id for category in category_obj.account_ids])
        return result

    def test_account_list(self, cr, uid, ids, progenitor_id, account_ids):
        warning = {}
        warning_account_names = []
        current_account_ids = []
        all_account_ids_for_template = self._get_selected_accounts(
            cr, uid, progenitor_id, ids)
        updated_account_ids = account_ids[0][2]
        for account_obj in self.pool.get('account.account').browse(
                cr, uid, updated_account_ids):
            if not (account_obj.id in all_account_ids_for_template):
                current_account_ids.append(account_obj.id)
            else:
                warning_account_names.append(account_obj.name)
        if warning_account_names:
            warning.update({
                'title':
                'Alert',
                'message':
                "Accounts %s already exist in current template" %
                (", ".join(warning_account_names)),
            })
        return {
            'value': {
                'account_ids': current_account_ids,
            },
            'warning': warning
        }

    def view_exception_accounts(self, cr, uid, ids, context={}):
        account_list = self._get_selected_accounts(cr,
                                                   uid,
                                                   ids[0],
                                                   ids,
                                                   context=context)
        model_data_pool = self.pool.get('ir.model.data')
        model_data_ids = model_data_pool.search(
            cr,
            uid, [('model', '=', 'ir.ui.view'),
                  ('name', '=', 'view_account_list')],
            context=context)
        resource_id = model_data_pool.read(cr,
                                           uid,
                                           model_data_ids,
                                           fields=['res_id'],
                                           context=context)[0]['res_id']
        return {
            'name': "Exception Accounts",
            'view_mode': 'tree,form',
            'view_type': 'form',
            'res_model': 'account.account',
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'domain': [('type', '!=', 'view'), ('id', 'not in', account_list)]
        }
예제 #9
0
            if res[1]:
                user_id = res[0]
        elif conf['create_user']:
            _logger.debug("Creating new OpenERP user \"%s\" from LDAP" % login)
            user_obj = self.pool.get('res.users')
            values = self.map_ldap_attributes(cr, uid, conf, login, ldap_entry)
            if conf['user']:
                user_id = user_obj.copy(cr, SUPERUSER_ID, conf['user'],
                                        default={'active': True})
                user_obj.write(cr, SUPERUSER_ID, user_id, values)
            else:
                user_id = user_obj.create(cr, SUPERUSER_ID, values)
        return user_id

    _columns = {
        'sequence': fields.integer('Sequence'),
        'company': fields.many2one('res.company', 'Company', required=True,
            ondelete='cascade'),
        'ldap_server': fields.char('LDAP Server address', size=64, required=True),
        'ldap_server_port': fields.integer('LDAP Server port', required=True),
        'ldap_binddn': fields.char('LDAP binddn', size=64,
            help=("The user account on the LDAP server that is used to query "
                  "the directory. Leave empty to connect anonymously.")),
        'ldap_password': fields.char('LDAP password', size=64,
            help=("The password of the user account on the LDAP server that is "
                  "used to query the directory.")),
        'ldap_filter': fields.char('LDAP filter', size=256, required=True),
        'ldap_base': fields.char('LDAP base', size=64, required=True),
        'user': fields.many2one('res.users', 'Model User',
            help="Model used for user creation"),
        'create_user': fields.boolean('Create user',
예제 #10
0
                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 = {
        'host': fields.char('Host', size=64, required=True),
        'port': fields.integer('Port', required=True),
        'ooo_restart_cmd': fields.char('OOO restart command', size=256, \
            help='Enter the shell command that will be executed to restart the LibreOffice/OpenOffice background process.'+ \
                'The command will be executed as the user of the OpenERP server process,'+ \
                'so you may need to prefix it with sudo and configure your sudoers file to have this command executed without password.'),
        'state':fields.selection([
            ('init','Init'),
            ('error','Error'),
            ('done','Done'),
            
        ], 'State', select=True, readonly=True),
        'msg': fields.text('Message', readonly=True),
        'error_details': fields.text('Error Details', readonly=True),
        'link':fields.char('Installation Manual', size=128, help='Installation (Dependencies and Base system setup)', readonly=True),
        'config_logo': fields.function(_get_image_fn, string='Image', type='binary', method=True),
        
class auction_lots_make_invoice_buyer(osv.osv_memory):
    """Make Invoice for Buyer"""

    _name = "auction.lots.make.invoice.buyer"
    _description = __doc__
    _columns = {
        'amount':
        fields.float('Invoiced Amount',
                     required=True,
                     readonly=True,
                     help="Buyer Price"),
        'objects':
        fields.integer('# of objects', required=True, readonly=True),
        'number':
        fields.char('Invoice Number', size=64),
        'buyer_id':
        fields.many2one('res.partner', 'Buyer', required=True),
    }
    _defaults = {
        'number': lambda *a: False,
    }

    def default_get(self, cr, uid, fields, context=None):
        """ 
         To get default values for the object.
         @param self: The object pointer.
         @param cr: A database cursor
         @param uid: ID of the user currently logged in
         @param fields: List of fields for which we want default values 
         @param context: A standard dictionary 
         @return: A dictionary which of fields with values. 
        """
        if context is None:
            context = {}
        res = super(auction_lots_make_invoice_buyer,
                    self).default_get(cr, uid, fields, context=context)
        lots_obj = self.pool.get('auction.lots')
        for lot in lots_obj.browse(cr,
                                   uid,
                                   context.get('active_ids', []),
                                   context=context):
            if 'amount' in fields:
                res.update({'amount': lot.buyer_price})
            if 'buyer_id' in fields:
                res.update(
                    {'buyer_id': lot.ach_uid and lot.ach_uid.id or False})
            if 'objects' in fields:
                res.update({'objects': len(context.get('active_ids', []))})
        return res

    def makeInvoices(self, cr, uid, ids, context=None):
        """
        Create an invoice for selected lots (IDS) to BUYER_ID .
        @param cr: the current row, from the database cursor.
        @param uid: the current user’s ID for security checks.
        @param ids: List of Auction lots make invoice buyer’s IDs
        @return: dictionary of  account invoice form.
        """
        order_obj = self.pool.get('auction.lots')
        mod_obj = self.pool.get('ir.model.data')
        result = mod_obj._get_id(cr, uid, 'account',
                                 'view_account_invoice_filter')
        id = mod_obj.read(cr, uid, result, ['res_id'])
        lots = order_obj.browse(cr,
                                uid,
                                context.get('active_ids', []),
                                context=context)
        for current in self.browse(cr, uid, ids, context=context):
            invoice_number = current.number
            for lot in lots:
                up_auction = order_obj.write(cr, uid, [lot.id],
                                             {'ach_uid': current.buyer_id.id})
            lots_ids = order_obj.lots_invoice(cr, uid,
                                              context.get('active_ids', []),
                                              context, current.number)
            return {
                'domain':
                "[('id','in', [" + ','.join(map(str, lots_ids)) + "])]",
                'name': 'Buyer invoices',
                'view_type': 'form',
                'view_mode': 'tree,form',
                'res_model': 'account.invoice',
                'view_id': False,
                'context': "{'type':'in_refund'}",
                'type': 'ir.actions.act_window',
                'search_view_id': id['res_id']
            }
class report_membership(osv.osv):
    '''Membership Analysis'''

    _name = 'report.membership'
    _description = __doc__
    _auto = False
    _rec_name = 'year'
    _columns = {
        'year': fields.char('Year', size=4, readonly=True, select=1),
        'month': fields.selection([('01', 'January'), ('02', 'February'), \
                                  ('03', 'March'), ('04', 'April'),\
                                  ('05', 'May'), ('06', 'June'), \
                                  ('07', 'July'), ('08', 'August'),\
                                  ('09', 'September'), ('10', 'October'),\
                                  ('11', 'November'), ('12', 'December')], 'Month', readonly=True),
        'date_from': fields.datetime('Start Date', readonly=True, help="Start membership date"),
        'date_to': fields.datetime('End Date', readonly=True, help="End membership date"),
        'num_waiting': fields.integer('# Waiting', readonly=True),
        'num_invoiced': fields.integer('# Invoiced', readonly=True),
        'num_paid': fields.integer('# Paid', readonly=True),
        'tot_pending': fields.float('Pending Amount', digits_compute= dp.get_precision('Account'), readonly=True),
        'tot_earned': fields.float('Earned Amount', digits_compute= dp.get_precision('Account'), readonly=True),
        'partner_id': fields.many2one('res.partner', 'Member', readonly=True),
        'associate_member_id': fields.many2one('res.partner', 'Associate Member', readonly=True),
        'membership_id': fields.many2one('product.product', 'Membership Product', readonly=True),
        'membership_state': fields.selection(STATE, 'Current Membership State', readonly=True),
        'user_id': fields.many2one('res.users', 'Salesperson', readonly=True),
        'company_id': fields.many2one('res.company', 'Company', readonly=True)
        }

    def init(self, cr):
        '''Create the view'''
        tools.drop_view_if_exists(cr, 'report_membership')
        cr.execute("""
        CREATE OR REPLACE VIEW report_membership AS (
        SELECT
        MIN(id) AS id,
        partner_id,
        user_id,
        membership_state,
        associate_member_id,
        membership_amount,
        date_from,
        date_to,
        year,
        month,
        COUNT(num_waiting) AS num_waiting,
        COUNT(num_invoiced) AS num_invoiced,
        COUNT(num_paid) AS num_paid,
        SUM(tot_pending) AS tot_pending,
        SUM(tot_earned) AS tot_earned,
        membership_id,
        company_id
        FROM
        (SELECT
            MIN(p.id) AS id,
            p.id AS partner_id,
            p.user_id AS user_id,
            p.membership_state AS membership_state,
            p.associate_member AS associate_member_id,
            p.membership_amount AS membership_amount,
            TO_CHAR(p.membership_start, 'YYYY-MM-DD') AS date_from,
            TO_CHAR(p.membership_stop, 'YYYY-MM-DD') AS date_to,
            TO_CHAR(p.membership_start, 'YYYY') AS year,
            TO_CHAR(p.membership_start,'MM') AS month,
            CASE WHEN ml.state = 'waiting'  THEN ml.id END AS num_waiting,
            CASE WHEN ml.state = 'invoiced' THEN ml.id END AS num_invoiced,
            CASE WHEN ml.state = 'paid'     THEN ml.id END AS num_paid,
            CASE WHEN ml.state IN ('waiting', 'invoiced') THEN SUM(il.price_subtotal) ELSE 0 END AS tot_pending,
            CASE WHEN ml.state = 'paid' OR p.membership_state = 'old' THEN SUM(il.price_subtotal) ELSE 0 END AS tot_earned,
            ml.membership_id AS membership_id,
            p.company_id AS company_id
            FROM res_partner p
            LEFT JOIN membership_membership_line ml ON (ml.partner = p.id)
            LEFT JOIN account_invoice_line il ON (ml.account_invoice_line = il.id)
            LEFT JOIN account_invoice ai ON (il.invoice_id = ai.id)
            WHERE p.membership_state != 'none' and p.active = 'true'
            GROUP BY
              p.id,
              p.user_id,
              p.membership_state,
              p.associate_member,
              p.membership_amount,
              TO_CHAR(p.membership_start, 'YYYY-MM-DD'),
              TO_CHAR(p.membership_stop, 'YYYY-MM-DD'),
              TO_CHAR(p.membership_start, 'YYYY'),
              TO_CHAR(p.membership_start,'MM'),
              ml.membership_id,
              p.company_id,
              ml.state,
              ml.id
        ) AS foo
        GROUP BY
            year,
            month,
            date_from,
            date_to,
            partner_id,
            user_id,
            membership_id,
            company_id,
            membership_state,
            associate_member_id,
            membership_amount
        )""")
예제 #13
0
class procurement_order_run_wizard(osv.osv_memory):
    _name = "procurement.order.orderpoint.run.wizard"
    _description = "Run Procurement scheduler from orderpoint multiple times"

    def _get_status(self, cr, uid, context):
        return self.pool.get('bakery.process').process_running(cr,
                                                               uid,
                                                               '30',
                                                               context=None)

    _columns = {
        'repeat_number':
        fields.integer('Repeat Number'),
        'status':
        fields.char('Status', size=128, readonly=True),
        'override':
        fields.boolean(
            'Override running process',
            help='Run the process, even if there is another one running'),
    }
    _defaults = {
        'repeat_number': lambda *a: 0,
        'status': _get_status,
    }

    def _group_manufacturing_orders(self, cr, uid, context=None):

        man_order_obj = self.pool.get('mrp.production')
        picking_obj = self.pool.get('stock.picking')
        procurement_obj = self.pool.get('procurement.order')
        mrp_obj = self.pool.get('mrp.procurement.qty')
        stock_move_obj = self.pool.get('stock.move')

        ready_ids = man_order_obj.search(
            cr,
            uid, [
                ('state', 'in', ['ready', 'confirmed', 'in_production']),
                ('status_izdelki', '=', 3),
            ],
            order='product_id')

        qty_produced = 0
        qty_scrap = 0
        qty_scrap_phantom = 0
        qty_product_qty = 0
        qty_produced_stock = 0
        qty_produced_phantom = 0
        PR_ID = -1
        OR_ID = -1

        for order in man_order_obj.browse(cr, uid, ready_ids):
            if order.product_id != PR_ID:
                qty_produced = order.produced
                qty_scrap = order.scrap
                qty_scrap_phantom = order.scrap_phantom
                qty_product_qty = order.product_qty
                qty_produced_stock = order.produced_stock
                qty_produced_phantom = order.produced_phantom
                PR_ID = order.product_id
                OR_ID = order.id
            else:  #produkt na liniji je enak kot na zgornji -> sestejemo vrednosti
                qty_produced = qty_produced + order.produced
                qty_scrap = qty_scrap + order.scrap
                qty_scrap_phantom = qty_scrap_phantom + order.scrap_phantom
                qty_product_qty = qty_product_qty + order.product_qty
                qty_produced_stock = qty_produced_stock + order.produced_stock
                qty_produced_phantom = qty_produced_phantom + order.produced_phantom

                #Spremenimo kolicino na D.N.
                mrp_obj.change_prod_qty(cr, uid, OR_ID, qty_product_qty,
                                        context)

                #vrednosti zapisemo na prvi D.N. s tem produktom
                man_order_obj.write(
                    cr,
                    uid,
                    [OR_ID],
                    {
                        'scrap': qty_scrap,
                        'produced': qty_produced,
                        'scrap_phantom': qty_scrap_phantom,
                        #'product_qty':qty_product_qty,
                        'produced_stock': qty_produced_stock,
                        'produced_phantom': qty_produced_phantom,
                        'status_izdelki': 0,
                        'status_testo': 0,
                    })

                picking_obj.action_cancel(cr, uid, [order.picking_id.id],
                                          context)  #najprej preklicemo picking
                man_order_obj.action_cancel(
                    cr, uid, [order.id],
                    context)  #nato preklicemo manufacturing order
                stock_move_obj.action_cancel(
                    cr, uid, [order.move_prod_id.id],
                    context)  #preklicemo se stock move
                #Preklicemo procurement_order
                procurement_id = procurement_obj.search(
                    cr, uid, [('production_id', '=', order.id)])
                procurement_obj.action_cancel(cr, uid, procurement_id)

        return 0

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

        sale_override = self.browse(cr, uid, ids)[0].override
        proc_obj = self.pool.get('procurement.order')
        #        proc_jour_obj = self.pool.get('procurement.order.journal')

        #Preverimo ali obstaja aktiven zapis in nezakljucene dobavnice----------------------------------------
        production_id, production_status = self.pool.get(
            'bakery.production').production_running(cr, uid, '30')
        if production_status:  #dobavnice so ze potrjene
            raise osv.except_osv(_('Warning!'), production_status)
        if production_id == []:  #se ne obstaja aktiven zapis
            raise osv.except_osv(
                _('Warning!'),
                _('Sale orders have today not been confirmed yet!'))
        else:
            production_id = production_id[0]

        #Preverimo je lansiranje ze zagnano
        process_status = self.pool.get('bakery.process').process_running(
            cr, uid, '30')
        if not sale_override and process_status:
            raise osv.except_osv('Warning!', process_status)
        else:
            process_id = self.pool.get('bakery.process').process_start(
                cr, uid, '30')
        #------------------------------------------------------------------------------------------------------
        #Nastavimo da zacasna lokacija zaloge ni aktivna
        ir_config_parameter = self.pool.get('ir.config_parameter')
        ir_config_parameter.set_param(cr, uid, 'stock.empty_location_active',
                                      '0')

        #Ce je stevilo ponovitev != 0 potem tolikokrat, drugace 4x
        repeat_number = self.browse(cr, uid, ids)[0].repeat_number
        if repeat_number == 0:
            repeat_number = 4
        elif repeat_number == -1:
            repeat_number = 0

        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S") +
              ' - Start from OP')

        cr.commit()
        use_new_cursor = cr.dbname
        for x in range(0, repeat_number):
            try:
                #proc_obj.run_scheduler(new_cr, uid, automatic=False, use_new_cursor=new_cr.dbname, context=context)
                produrement_ids = proc_obj.search(
                    cr, uid, [('state', '=', 'confirmed'),
                              ('procure_method', '=', 'make_to_stock')])
                proc_obj._procure_confirm(cr,
                                          uid,
                                          ids=produrement_ids,
                                          use_new_cursor=use_new_cursor,
                                          context=context)
                proc_obj._procure_orderpoint_confirm(
                    cr,
                    uid,
                    automatic=False,
                    use_new_cursor=use_new_cursor,
                    context=context)

                self.pool.get('bakery.process').write(cr, uid, [process_id],
                                                      {'misc': str(x + 1)})
                cr.commit()

            except Exception, e:
                self.pool.get('bakery.process').write(cr, uid, [process_id],
                                                      {'error': str(e)})
                cr.commit()
                raise osv.except_osv(
                    'Opozorilo!',
                    u'Napaka lansiranja iz OP v %s. krogu. Err: %s' %
                    (str(x), str(e)))
                return {}
            print(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' - Close: ' +
                  str(x + 1))
        #------------------------------------------------------------------------------------------------------------------------
        cr.commit()  #Da si nalozimo sprememb
        self._group_manufacturing_orders(cr, uid, context)
        #raise osv.except_osv('Opozorilo!', 'Napaka pri zdruzevanju d.n.:' + str(e))
        #-------------------------------------------------------------------------------------------
        _sql_string1 = """update mrp_production
                            SET status_testo = 0, status_izdelki = 0, created_from_op = True
                            WHERE status_testo = 3 or status_izdelki = 3;"""
        cr.execute(_sql_string1)
        cr.commit()
        #raise osv.except_osv('Opozorilo!', 'Napaka pri zagonu query-ja: status_testo; ' +str(e))

        _sql_string2 = """update stock_move
                            SET basket_status = 2
                            WHERE basket_status = 3 AND state = 'done';"""
        cr.execute(_sql_string2)
        cr.commit()
        #raise osv.except_osv('Opozorilo!', 'Napaka pri zagonu query-ja: basket_status_2_done; ' +str(e))

        _sql_string3 = """update stock_move
                            SET basket_status = 0
                            WHERE basket_status = 3;"""
        cr.execute(_sql_string3)
        cr.commit()
        #raise osv.except_osv('Opozorilo!', 'Napaka pri zagonu query-ja: basket_status_0; ' +str(e))

        _sql_string4 = """update stock_move upd 
                                set basket_status = 2
                                where 
                                not upd.id in
                                (
                                
                                    select id from stock_move mov
                                    where mov.basket_status <> 2 and mov.location_id = 12
                                    and exists(
                                        select * from stock_picking pic 
                                        where
                                        pic.id = mov.picking_id and 
                                        pic.type = 'out'
                                    )

                                ) and basket_status != 2;"""
        cr.execute(_sql_string4)
        cr.commit()
        #raise osv.except_osv('Opozorilo!', 'Napaka pri zagonu query-ja: basket_status2; ' +str(e))

        self.pool.get('stock.move').get_qty_delivery_available(cr, uid)
        #raise osv.except_osv('Opozorilo!', 'Napaka pri zagonu query-ja delivery_available' + str(e))

        self.pool.get('bakery.process').process_end(cr, uid, '30', process_id,
                                                    production_id)
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S") +
              ' - KONEC Lansiranja')
        return {}
class analytic_entries_report(osv.osv):
    _name = "analytic.entries.report"
    _description = "Analytic Entries Statistics"
    _auto = False
    _columns = {
        'date':
        fields.date('Date', readonly=True),
        'year':
        fields.char('Year', size=4, readonly=True),
        'day':
        fields.char('Day', size=128, readonly=True),
        'month':
        fields.selection([('01', 'January'), ('02', 'February'),
                          ('03', 'March'), ('04', 'April'), ('05', 'May'),
                          ('06', 'June'), ('07', 'July'), ('08', 'August'),
                          ('09', 'September'), ('10', 'October'),
                          ('11', 'November'), ('12', 'December')],
                         'Month',
                         readonly=True),
        'user_id':
        fields.many2one('res.users', 'User', readonly=True),
        'name':
        fields.char('Description', size=64, readonly=True),
        'partner_id':
        fields.many2one('res.partner', 'Partner'),
        'company_id':
        fields.many2one('res.company', 'Company', required=True),
        'currency_id':
        fields.many2one('res.currency', 'Currency', required=True),
        'account_id':
        fields.many2one('account.analytic.account', 'Account', required=False),
        'general_account_id':
        fields.many2one('account.account', 'General Account', required=True),
        'journal_id':
        fields.many2one('account.analytic.journal', 'Journal', required=True),
        'move_id':
        fields.many2one('account.move.line', 'Move', required=True),
        'product_id':
        fields.many2one('product.product', 'Product', required=True),
        'product_uom_id':
        fields.many2one('product.uom',
                        'Product Unit of Measure',
                        required=True),
        'amount':
        fields.float('Amount', readonly=True),
        'unit_amount':
        fields.float('Quantity', readonly=True),
        'nbr':
        fields.integer('#Entries', readonly=True),
    }

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'analytic_entries_report')
        cr.execute("""
            create or replace view analytic_entries_report as (
                 select
                     min(a.id) as id,
                     count(distinct a.id) as nbr,
                     a.date as date,
                     to_char(a.date, 'YYYY') as year,
                     to_char(a.date, 'MM') as month,
                     to_char(a.date, 'YYYY-MM-DD') as day,
                     a.user_id as user_id,
                     a.name as name,
                     analytic.partner_id as partner_id,
                     a.company_id as company_id,
                     a.currency_id as currency_id,
                     a.account_id as account_id,
                     a.general_account_id as general_account_id,
                     a.journal_id as journal_id,
                     a.move_id as move_id,
                     a.product_id as product_id,
                     a.product_uom_id as product_uom_id,
                     sum(a.amount) as amount,
                     sum(a.unit_amount) as unit_amount
                 from
                     account_analytic_line a, account_analytic_account analytic
                 where analytic.id = a.account_id
                 group by
                     a.date, a.user_id,a.name,analytic.partner_id,a.company_id,a.currency_id,
                     a.account_id,a.general_account_id,a.journal_id,
                     a.move_id,a.product_id,a.product_uom_id
            )
        """)
예제 #15
0
class chricar_application_columns(osv.osv):
    _name = "chricar.application_columns"

    _columns = {
        'application_tables_id':
        fields.many2one('chricar.application_tables',
                        'Source Table Name',
                        select=True,
                        required=True),
        'char_size':
        fields.float('Size', digits=(4, 0)),
        'column_fk':
        fields.char('Column FK', size=64),
        'column_list_show':
        fields.boolean('List Show', required=True),
        'defaults':
        fields.char('Defaults', size=256),
        'extra_tab':
        fields.boolean('Extra Tab', required=True),
        'help':
        fields.char('Help', size=256),
        'inherits_columns':
        fields.boolean('Inherits Columns', required=True),
        'is_name':
        fields.boolean('is Name', required=True),
        'many2one':
        fields.boolean('Many2one', required=True),
        'migrate':
        fields.boolean('Migrate', required=True),
        'name_column':
        fields.char('Column Name Display', size=64, required=True),
        'name_column_source':
        fields.char('Source Column Name', size=64, required=True),
        'name':
        fields.char('Column Name', size=64, required=True),
        'num_precision':
        fields.float('Num Precision', digits=(4, 0)),
        'num_scale':
        fields.float('Num Scale', digits=(4, 0)),
        'one2many_col_name':
        fields.char('One2many Col Name', size=64),
        'read_only':
        fields.boolean('Read Only', required=True),
        'required':
        fields.boolean('Required', required=True),
        'search':
        fields.char('Search', size=8),
        'sequence':
        fields.float('Sequence', digits=(4, 0)),
        'sort_form':
        fields.float('Form Sort', digits=(4, 0)),
        'sort_list':
        fields.integer('List Sort'),
        'source_pk':
        fields.float('Source PK', digits=(4, 0)),
        'state':
        fields.char('State', size=16),
        'suppress_in_form':
        fields.boolean('Form Suppress', required=True),
        'table_fk':
        fields.char('Table FK', size=64),
        'table_fk_source':
        fields.char('Source Table Foreign Key', size=64),
        'tiny_column_english':
        fields.char('Column Name English', size=64),
        'translate':
        fields.boolean('Translate', required=True),
        'type':
        fields.char('Type', size=16, required=True),
    }
    _defaults = {
        'column_list_show': lambda *a: True,
        'extra_tab': lambda *a: False,
        'inherits_columns': lambda *a: False,
        'is_name': lambda *a: False,
        'many2one': lambda *a: False,
        'migrate': lambda *a: True,
        'read_only': lambda *a: False,
        'required': lambda *a: False,
        'suppress_in_form': lambda *a: False,
        'translate': lambda *a: False,
    }
예제 #16
0
class external_report_lines(osv.osv):
    _name = 'external.report.line'
    _description = 'External Report Lines'
    _rec_name = 'res_id'
    _order = 'date desc'

    _columns = {
        'res_model':
        fields.char('Resource Object', size=64, required=True, readonly=True),
        'res_id':
        fields.integer('Resource Id', readonly=True),
        'action':
        fields.char('Action', size=32, required=True, readonly=True),
        'date':
        fields.datetime('Date', required=True, readonly=True),
        'external_id':
        fields.char('External ID', size=64, readonly=True),
        'error_message':
        fields.text('Error Message', readonly=True),
        'traceback':
        fields.text('Traceback', readonly=True),
        'exception_type':
        fields.char('Exception Type', size=128, readonly=True),
        'data_record':
        fields.serialized('External Data', readonly=True),
        'origin_defaults':
        fields.serialized('Defaults', readonly=True),
        'origin_context':
        fields.serialized('Context', readonly=True),
        'referential_id':
        fields.many2one('external.referential',
                        'External Referential',
                        required=True,
                        readonly=True)
    }

    _defaults = {
        "date": lambda *a: time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
    }

    def _prepare_log_vals(self,
                          cr,
                          uid,
                          model,
                          action,
                          res_id,
                          external_id,
                          referential_id,
                          data_record,
                          context=None):
        return {
            'res_model': model,
            'action': action,
            'res_id': res_id,
            'external_id': external_id,
            'referential_id': referential_id,
            'data_record': data_record,
        }

    def _prepare_log_info(self,
                          cr,
                          uid,
                          origin_defaults,
                          origin_context,
                          context=None):
        exc_type, exc_value, exc_traceback = sys.exc_info()
        return {
            'date':
            time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
            'origin_defaults':
            origin_defaults,
            'origin_context':
            origin_context,
            'exception_type':
            exc_type,
            'error_message':
            exc_value,
            'traceback':
            ''.join(
                traceback.format_exception(exc_type, exc_value,
                                           exc_traceback)),
        }

    def log_failed(self,
                   cr,
                   uid,
                   model,
                   action,
                   referential_id,
                   res_id=None,
                   external_id=None,
                   data_record=None,
                   defaults=None,
                   context=None):
        defaults = defaults or {}
        context = context or {}
        existing_line_id = context.get('retry_report_line_id', False)

        # if the log was a fail, we raise to not let the import continue
        # This ensure a backward compatibility, synchro will continue to
        # work exactly the same way if use_external_log is not in context
        if not (existing_line_id or context.get('use_external_log', False)):
            raise

        log_cr = pooler.get_db(cr.dbname).cursor()

        try:
            origin_defaults = defaults.copy()
            origin_context = context.copy()
            # connection object can not be kept in text indeed
            # FIXME : see if we have some problem with other objects
            # and maybe remove from the conect all objects
            # which are not string, boolean, list, dict, integer, float or ?
            if origin_context.get('conn_obj', False):
                del origin_context['conn_obj']
            info = self._prepare_log_info(log_cr,
                                          uid,
                                          origin_defaults,
                                          origin_context,
                                          context=context)
            if existing_line_id:
                self.write(log_cr,
                           uid,
                           existing_line_id,
                           info,
                           context=context)
            else:
                vals = self._prepare_log_vals(log_cr,
                                              uid,
                                              model,
                                              action,
                                              res_id,
                                              external_id,
                                              referential_id,
                                              data_record,
                                              context=context)
                vals.update(info)
                existing_line_id = self.create(log_cr,
                                               uid,
                                               vals,
                                               context=context)
        except:
            log_cr.rollback()
            raise
        else:
            log_cr.commit()
        finally:
            log_cr.close()
        return existing_line_id

    def log_success(self,
                    cr,
                    uid,
                    model,
                    action,
                    referential_id,
                    res_id=None,
                    external_id=None,
                    context=None):
        if res_id is None and external_id is None:
            raise ValueError('Missing ext_id or external_id')
        domain = [
            ('res_model', '=', model),
            ('action', '=', action),
            ('referential_id', '=', referential_id),
        ]
        if res_id is not None:
            domain += ('res_id', '=', res_id),
        if external_id is not None:
            domain += ('external_id', '=', external_id),
        log_cr = pooler.get_db(cr.dbname).cursor()
        try:
            log_ids = self.search(log_cr, uid, domain, context=context)
            self.unlink(log_cr, uid, log_ids, context=context)
        except:
            log_cr.rollback()
            raise
        else:
            log_cr.commit()
        finally:
            log_cr.close()
        return True

    def retry(self, cr, uid, ids, context=None):
        if isinstance(ids, (int, long)):
            ids = [ids]

        for log in self.browse(cr, uid, ids, context=context):
            mapping = self.pool.get(log.res_model).\
            report_action_mapping(cr, uid, context=context)

            method = mapping.get(log.action, False)
            if not method:
                raise Exception("No python method defined for action %s" %
                                (log.action, ))

            kwargs = {}
            for field, value in method['fields'].items():
                kwargs[field] = safe_eval(value, {'log': log, 'self': self})

            if not kwargs.get('context', False):
                kwargs['context'] = {}

            # keep the id of the line to update it with the result
            kwargs['context']['retry_report_line_id'] = log.id
            # force export of the resource
            kwargs['context']['force_export'] = True
            kwargs['context']['force'] = True

            method['method'](cr, uid, **kwargs)
        return True
class account_aged_trial_balance(osv.osv_memory):
    _inherit = 'account.common.partner.report'
    _name = 'account.aged.trial.balance'
    _description = 'Account Aged Trial balance Report'

    _columns = {
        'period_length':
        fields.integer('Period length (days)', required=True),
        'direction_selection':
        fields.selection([('past', 'Past'), ('future', 'Future')],
                         'Analysis Direction',
                         required=True),
    }
    _defaults = {
        'period_length': 30,
        'date_from': lambda *a: time.strftime('%Y-%m-%d'),
        'direction_selection': 'past',
    }

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

        data = self.pre_print_report(cr, uid, ids, data, context=context)
        data['form'].update(
            self.read(cr, uid, ids,
                      ['period_length', 'direction_selection'])[0])

        period_length = data['form']['period_length']
        if period_length <= 0:
            raise osv.except_osv(
                _('UserError'),
                _('You must enter a period length that cannot be 0 or below !')
            )
        if not data['form']['date_from']:
            raise osv.except_osv(_('UserError'), _('Enter a Start date !'))

        start = datetime.strptime(data['form']['date_from'], "%Y-%m-%d")

        if data['form']['direction_selection'] == 'past':
            for i in range(5)[::-1]:
                stop = start - relativedelta(days=period_length)
                res[str(i)] = {
                    'name': (i != 0 and (str(
                        (5 - (i + 1)) * period_length) + '-' + str(
                            (5 - i) * period_length))
                             or ('+' + str(4 * period_length))),
                    'stop':
                    start.strftime('%Y-%m-%d'),
                    'start': (i != 0 and stop.strftime('%Y-%m-%d') or False),
                }
                start = stop - relativedelta(days=1)
        else:
            for i in range(5):
                stop = start + relativedelta(days=period_length)
                res[str(5 - (i + 1))] = {
                    'name': (i != 4 and str((i) * period_length) + '-' + str(
                        (i + 1) * period_length)
                             or ('+' + str(4 * period_length))),
                    'start':
                    start.strftime('%Y-%m-%d'),
                    'stop': (i != 4 and stop.strftime('%Y-%m-%d') or False),
                }
                start = stop + relativedelta(days=1)
        data['form'].update(res)
        if data.get('form', False):
            data['ids'] = [data['form'].get('chart_account_id', False)]
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'account.aged_trial_balance',
            'datas': data
        }
예제 #18
0
class tcv_mrp_finished_slab_output_wizard_line(osv.osv_memory):

    _name = 'tcv.mrp.finished.slab.output.wizard.line'

    _description = ''

    ##-------------------------------------------------------------------------

    ##------------------------------------------------------- _internal methods

    def _fill_data(self, cr, uid, ids, context):
        return True

    ##--------------------------------------------------------- function fields

    _columns = {
        'line_id':
        fields.many2one('tcv.mrp.finished.slab.output.wizard',
                        'Parent',
                        required=True,
                        ondelete='cascade'),
        'input_id':
        fields.many2one('tcv.mrp.finished.slab.inputs',
                        'Origin',
                        required=True,
                        readonly=False,
                        ondelete='cascade'),
        'prod_lot_ref':
        fields.char('Lot reference', size=24, readonly=False),
        'location_id':
        fields.many2one('stock.location',
                        'Location',
                        required=True,
                        select=True,
                        ondelete='restrict',
                        help=""),
        'pieces':
        fields.integer('Pieces', readonly=False),
        'length':
        fields.float(string='Length (m)',
                     digits_compute=dp.get_precision('Extra UOM data'),
                     readonly=False),
        'heigth':
        fields.float(string='heigth (m)',
                     digits_compute=dp.get_precision('Extra UOM data'),
                     readonly=False),
        'thickness':
        fields.integer('Thickness', readonly=False),
        'product_id':
        fields.many2one('product.product',
                        'Product',
                        ondelete='restrict',
                        required=True,
                        help="The finised output product",
                        domain=[('sale_ok', '=', True),
                                ('stock_driver', '=', 'slab')]),
        'first_num':
        fields.integer(
            'First slab #',
            required=True,
            help="The first number for sequence this set of slabs (to " +
            "complete the label number)"),
    }

    _defaults = {}

    _sql_constraints = [
        ('first_num_gt_zero', 'CHECK (first_num>0)',
         'The first_num must be > 0!'),
    ]

    ##-----------------------------------------------------

    ##----------------------------------------------------- public methods

    ##----------------------------------------------------- buttons (object)

    ##----------------------------------------------------- on_change...

    ##----------------------------------------------------- create write unlink

    def write(self, cr, uid, ids, vals, context=None):
        readonly_fields = ('input_id', 'prod_lot_ref', 'pieces', 'length',
                           'heigth', 'thickness')
        for f in readonly_fields:
            if f in vals:
                vals.pop(f)
        res = super(tcv_mrp_finished_slab_output_wizard_line, self).\
            write(cr, uid, ids, vals, context)
        return res
예제 #19
0
        ],'Template source', select=True),
        'parser_def': fields.text('Parser Definition'),
        'parser_loc':fields.char('Parser location', size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}"),
        'parser_state':fields.selection([
            ('default',_('Default')),
            ('def',_('Definition')),
            ('loc',_('Location')),
        ],'State of Parser', select=True),
        'in_format': fields.selection(_get_in_mimetypes, 'Template Mime-type'),
        'out_format':fields.many2one('report.mimetypes', 'Output Mime-type'),
        'report_sxw_content': fields.function(_report_content,
            fnct_inv=_report_content_inv, method=True,
            type='binary', string='SXW content',),
        'active':fields.boolean('Active'),
        'report_wizard':fields.boolean('Report Wizard'),
        'copies': fields.integer('Number of copies'),
        'fallback_false':fields.boolean('Disable format fallback'),
        'xml_id': fields.function(_get_xml_id, type='char', size=128, string="XML ID",
                                  method=True, help="ID of the report defined in xml file"),
        
    }

    def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
        ##### check new model fields, that while not exist in database #####
        cr.execute("SELECT name FROM ir_model_fields WHERE model = 'ir.actions.report.xml'")
        true_fields = [val[0] for val in cr.fetchall()]
        true_fields.append(self.CONCURRENCY_CHECK_FIELD)
        if fields:
            exclude_fields = set(fields).difference(set(true_fields))
            fields = filter(lambda f: f not in exclude_fields, fields)
        else:
예제 #20
0
        'author': fields.char("Author", size=128, readonly=True),
        'maintainer': fields.char('Maintainer', size=128, readonly=True),
        'contributors': fields.text('Contributors', readonly=True),
        'website': fields.char("Website", size=256, readonly=True),

        # attention: Incorrect field names !!
        #   installed_version refer the latest version (the one on disk)
        #   latest_version refer the installed version (the one in database)
        #   published_version refer the version available on the repository
        'installed_version': fields.function(_get_latest_version, 
            string='Latest version', type='char'),
        'latest_version': fields.char('Installed version', size=64, readonly=True),
        'published_version': fields.char('Published Version', size=64, readonly=True),

        '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),
예제 #21
0
         size=128,
         help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}",
     ),
     "parser_state": fields.selection(
         [("default", _("Default")), ("def", _("Definition")), ("loc", _("Location"))],
         "State of Parser",
         select=True,
     ),
     "in_format": fields.selection(_get_in_mimetypes, "Template Mime-type"),
     "out_format": fields.many2one("report.mimetypes", "Output Mime-type"),
     "report_sxw_content": fields.function(
         _report_content, fnct_inv=_report_content_inv, method=True, type="binary", string="SXW content"
     ),
     "active": fields.boolean("Active"),
     "report_wizard": fields.boolean("Report Wizard"),
     "copies": fields.integer("Number of copies"),
     "fallback_false": fields.boolean("Disable format fallback"),
     "xml_id": fields.function(
         _get_xml_id,
         type="char",
         size=128,
         string="XML ID",
         method=True,
         help="ID of the report defined in xml file",
     ),
     "page_count": fields.char(
         "Page Count",
         size=128,
         help="Line count on each page, in format 'first_last_page, first_page, middle_page,last_page', for example,'17,22,26,21'. ",
     ),
 }
예제 #22
0
class mrp_production_order(osv.osv):
    _name = "mrp.production.order"
    _description = "Production Order Report"
    _auto = False
    _columns = {
        'year':
        fields.char('Year', size=64, readonly=True),
        'month':
        fields.selection([('01', 'January'), ('02', 'February'),
                          ('03', 'March'), ('04', 'April'), ('05', 'May'),
                          ('06', 'June'), ('07', 'July'), ('08', 'August'),
                          ('09', 'September'), ('10', 'October'),
                          ('11', 'November'), ('12', 'December')],
                         'Month',
                         readonly=True),
        'day':
        fields.char('Day', size=64, readonly=True),
        'origin':
        fields.char('Source Document', size=64),
        'nbr':
        fields.integer('# of Lines', readonly=True),
        'products_to_consume':
        fields.integer('Products to Consume', readonly=True),
        'consumed_products':
        fields.integer('Consumed Products', readonly=True),
        'date':
        fields.date('Date', readonly=True),
        'product_id':
        fields.many2one('product.product', 'Product', readonly=True),
        'product_id2':
        fields.many2one('product.product', 'Product Consumed', readonly=True),
        'product_qty':
        fields.float('Product Qty', readonly=True),
        'state':
        fields.selection([('draft', 'Draft'),
                          ('picking_except', 'Picking Exception'),
                          ('confirmed', 'Waiting Goods'),
                          ('ready', 'Ready to Produce'),
                          ('in_production', 'In Production'),
                          ('cancel', 'Cancelled'), ('done', 'Done')],
                         'State',
                         readonly=True),
        'date_planned':
        fields.date('Scheduled Date'),
        'location_src_id':
        fields.many2one('stock.location',
                        'Raw Materials Location',
                        readonly=True),
        'date_start':
        fields.datetime('Start Date', readonly=True),
        'date_finished':
        fields.datetime('End Date', readonly=True),
        'location_dest_id':
        fields.many2one('stock.location',
                        'Finished Products Location',
                        readonly=True),
        'company_id':
        fields.many2one('res.company', 'Company', readonly=True),
        'bom_id':
        fields.many2one('mrp.bom', 'Bill of Material', readonly=True),
        'routing_id':
        fields.many2one('mrp.routing', string='Routing', readonly=True),
        'picking_id':
        fields.many2one('stock.picking', 'Picking list', readonly=True),
        'product_uom':
        fields.many2one('product.uom', 'Product UOM', readonly=True),
        'priority':
        fields.selection([('0', 'Not urgent'), ('1', 'Normal'),
                          ('2', 'Urgent'), ('3', 'Very Urgent')],
                         'Priority',
                         readonly=True),
    }

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'mrp_production_order')
        cr.execute("""
            create or replace view mrp_production_order as (
                select
                     min(l.id) as id,
                     to_date(to_char(s.create_date, 'MM-dd-YYYY'),'MM-dd-YYYY') as date,
                     to_char(s.create_date, 'YYYY') as year,
                     to_char(s.create_date, 'MM') as month,
                     to_char(s.create_date, 'YYYY-MM-DD') as day,
                     s.product_id as product_id,
                     l.product_id as product_id2,
                     l.product_uom,
                     sum(l.product_qty * u.factor) as product_qty,
                     s.company_id as company_id,
                     (select 1) as nbr,
                     (select sum(sm.product_qty) from stock_move as sm
                        left join mrp_production_move_ids as mv on (sm.id=mv.move_id)
                        left join mrp_production_product_line as ll on (ll.production_id=mv.production_id)
                        where sm.product_id=ll.product_id and ll.id=l.id
                        and sm.state not in ('done','cancel')
                        group by sm.product_id) as products_to_consume,
                    (select sum(sm.product_qty)/2 from stock_move as sm
                        left join mrp_production_move_ids as mv on (sm.id=mv.move_id)
                        left join mrp_production_product_line as ll on (ll.production_id=mv.production_id)
                        where sm.product_id=ll.product_id and ll.id=l.id
                        and sm.state in ('done','cancel')
                        group by sm.product_id) as consumed_products,
                     s.location_src_id,
                     s.location_dest_id,
                     s.bom_id,
                     s.routing_id,
                     s.picking_id,
                     s.date_start,
                     s.date_finished,
                     to_date(to_char(s.date_planned, 'dd-MM-YYYY'),'dd-MM-YYYY') as date_planned,
                     s.origin,
                     s.priority,
                     s.state
                 from mrp_production_product_line l
                 left join mrp_production s on (s.id=l.production_id)
                 left join product_uom u on (u.id=l.product_uom)
                 group by
                     to_char(s.create_date, 'YYYY'),
                     to_char(s.create_date, 'MM'),
                     to_char(s.create_date, 'YYYY-MM-DD'),
                     to_date(to_char(s.create_date, 'MM-dd-YYYY'),'MM-dd-YYYY'),
                     l.product_id,
                     s.product_id,
                     l.product_uom,
                     s.id,
                     l.id,
                     s.bom_id,
                     s.routing_id,
                     s.picking_id,
                     s.priority,
                     s.location_src_id,
                     s.location_dest_id,
                     s.state,
                     to_date(to_char(s.date_planned, 'dd-MM-YYYY'),'dd-MM-YYYY'),
                     s.origin,
                     s.date_start,
                     s.date_finished,
                     s.company_id
            )""")
예제 #23
0
class tcv_mrp_gangsaw_params(osv.osv):

    _name = 'tcv.mrp.gangsaw.params'

    _description = ''

    ##-------------------------------------------------------------------------

    ##------------------------------------------------------- _internal methods

    ##--------------------------------------------------------- function fields

    _columns = {
        'name':
        fields.char('Name', size=64, required=False, readonly=False),
        'template_id':
        fields.many2one('tcv.mrp.template',
                        'Task template',
                        required=True,
                        readonly=False,
                        ondelete='restrict',
                        domain=[('res_model', '=', 'tcv.mrp.gangsaw')]),
        'whell_amp':
        fields.integer('Whell amp', help="Max. whell amp"),
        'pump_amp':
        fields.integer('Pump amp', help="Max. pump amp"),
        'tens_preasure':
        fields.float('Tensors preasure',
                     digits_compute=dp.get_precision('Account'),
                     help="Tensors preasure in tons"),
        'viscosity':
        fields.float('Viscosity',
                     digits_compute=dp.get_precision('Account'),
                     help="Fluid viscosity"),
        'max_length':
        fields.float('Max length (m)',
                     digits_compute=dp.get_precision('Product UoM'),
                     help="Max block length"),
        'max_heigth':
        fields.float('Max heigth (m)',
                     digits_compute=dp.get_precision('Product UoM'),
                     help="Max block heigth"),
        'max_width':
        fields.float('Max width (m)',
                     digits_compute=dp.get_precision('Product UoM'),
                     help="Max block width"),
        'min_steel_grit':
        fields.float('Min steel grit',
                     digits_compute=dp.get_precision('Product UoM'),
                     help="Min dry steel grit"),
        'max_steel_grit':
        fields.float('Max steel grit',
                     digits_compute=dp.get_precision('Product UoM'),
                     help="Max dry steel grit"),
        'params_ids':
        fields.one2many('tcv.mrp.gangsaw.params.extra', 'gangsaw_params_id',
                        'Extra params'),
        'narration':
        fields.text('Notes', readonly=False),
    }

    _defaults = {}

    _sql_constraints = [
        ('template_uniq', 'UNIQUE(template_id)',
         'The template must be unique!'),
    ]

    ##-------------------------------------------------------------------------

    ##---------------------------------------------------------- public methods

    ##-------------------------------------------------------- buttons (object)

    ##------------------------------------------------------------ on_change...

    def on_change_size(self, cr, uid, ids, length, heigth, width):
        obj_uom = self.pool.get('product.uom')
        length, heigth, width = obj_uom.adjust_sizes(length, heigth, width)
        res = {
            'value': {
                'max_length': length,
                'max_heigth': heigth,
                'max_width': width,
            }
        }
        return res
예제 #24
0
class report_auction_estimation_adj_category1(osv.osv):
    _name = "report.auction.estimation.adj.category1"
    _description = "comparison estimate/adjudication "
    _auto = False
    _columns = {
        'auction_id':
        fields.many2one('auction.dates', 'Auction Date'),
        'bord_vnd_id':
        fields.many2one('auction.deposit',
                        'Depositer Inventory',
                        required=True),
        'name':
        fields.char('Short Description', size=64, required=True),
        'lot_type':
        fields.selection(_type_get, 'Object Type', size=64, select=True),
        'lot_est1':
        fields.float('Minimum Estimation', select=True),
        'lot_est2':
        fields.float('Maximum Estimation', select=True),
        'obj_desc':
        fields.text('Object Description', select=True),
        'obj_num':
        fields.integer('Catalog Number'),
        'obj_ret':
        fields.float('Price retired'),
        'obj_comm':
        fields.boolean('Commission'),
        'obj_price':
        fields.float('Adjudication price'),
        'state':
        fields.selection((('draft', 'Draft'), ('unsold', 'Unsold'),
                          ('paid', 'Paid'), ('invoiced', 'Invoiced')),
                         'State',
                         required=True,
                         select=True),
        'date':
        fields.char('Name', size=64, required=True, select=True),
        'lot_num':
        fields.integer('Quantity', required=True),
        'lot_type':
        fields.selection(_type_get, 'Object Type', size=64),
        'adj_total':
        fields.float('Total Adjudication', select=True),
    }

    def init(self, cr):
        cr.execute("""
            create or replace view report_auction_estimation_adj_category1 as (
                select
                    min(l.id) as id,
                   to_char(l.create_date, 'YYYY-MM-01') as date,
                   l.state as state,
                   l.lot_type as lot_type,
                   sum(l.lot_est1) as lot_est1,
                   sum(l.lot_est2) as lot_est2,
                   sum(l.obj_price) as adj_total
                from
                    auction_lots l,auction_dates m
                where l.auction_id=m.id
                group by
                    to_char(l.create_date, 'YYYY-MM-01'),l.state,lot_type
            )
        """)
예제 #25
0
class project_issue_report(osv.osv):
    _name = "project.issue.report"
    _auto = False

    _columns = {
        'name': fields.char('Year', size=64, required=False, readonly=True),
        'section_id':fields.many2one('crm.case.section', 'Sale Team', readonly=True),
        'state': fields.selection(AVAILABLE_STATES, 'State', size=16, readonly=True),
        'month':fields.selection([('01', 'January'), ('02', 'February'), \
                                  ('03', 'March'), ('04', 'April'),\
                                  ('05', 'May'), ('06', 'June'), \
                                  ('07', 'July'), ('08', 'August'),\
                                  ('09', 'September'), ('10', 'October'),\
                                  ('11', 'November'), ('12', 'December')], 'Month', readonly=True),
        'company_id': fields.many2one('res.company', 'Company', readonly=True),
        'day': fields.char('Day', size=128, readonly=True),
        'opening_date': fields.date('Date of Opening', readonly=True),
        'creation_date': fields.date('Creation Date', readonly=True),
        'date_closed': fields.date('Date of Closing', readonly=True),
        'categ_id': fields.many2one('crm.case.categ', 'Category', domain="['&',('section_id','=',section_id),('object_id.model', '=', 'project.issue')]"),
        'type_id': fields.many2one('project.task.type', 'Stage'),
        'nbr': fields.integer('# of Issues', readonly=True),
        'working_hours_open': fields.float('Avg. Working Hours to Open', readonly=True, group_operator="avg"),
        'working_hours_close': fields.float('Avg. Working Hours to Close', readonly=True, group_operator="avg"),
        'delay_open': fields.float('Avg. Delay to Open', digits=(16,2), readonly=True, group_operator="avg",
                                       help="Number of Days to open the project issue"),
        'delay_close': fields.float('Avg. Delay to Close', digits=(16,2), readonly=True, group_operator="avg",
                                       help="Number of Days to close the project issue"),
        'company_id' : fields.many2one('res.company', 'Company'),
        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
        'project_id':fields.many2one('project.project', 'Project',readonly=True),
        'version_id': fields.many2one('project.issue.version', 'Version'),
        'user_id' : fields.many2one('res.users', 'Assigned to',readonly=True),
        'partner_id': fields.many2one('res.partner','Partner'),
        'channel_id': fields.many2one('crm.case.channel', 'Channel',readonly=True),
        'task_id': fields.many2one('project.task', 'Task'),
        'email': fields.integer('# Emails', size=128, readonly=True),
    }

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'project_issue_report')
        cr.execute("""
            CREATE OR REPLACE VIEW project_issue_report AS (
                SELECT
                    c.id as id,
                    to_char(c.create_date, 'YYYY') as name,
                    to_char(c.create_date, 'MM') as month,
                    to_char(c.create_date, 'YYYY-MM-DD') as day,
                    to_char(c.date_open, 'YYYY-MM-DD') as opening_date,
                    to_char(c.create_date, 'YYYY-MM-DD') as creation_date,
                    c.state,
                    c.user_id,
                    c.working_hours_open,
                    c.working_hours_close,
                    c.section_id,
                    c.categ_id,
                    c.type_id,
                    to_char(c.date_closed, 'YYYY-mm-dd') as date_closed,
                    c.company_id as company_id,
                    c.priority as priority,
                    c.project_id as project_id,
                    c.version_id as version_id,
                    1 as nbr,
                    c.partner_id,
                    c.channel_id,
                    c.task_id,
                    date_trunc('day',c.create_date) as create_date,
                    c.day_open as  delay_open,
                    c.day_close as  delay_close,
                    (SELECT count(id) FROM mail_message WHERE model='project.issue' AND res_id=c.id) AS email

                FROM
                    project_issue c
                WHERE c.active= 'true' and c.categ_id IN (select id from crm_case_categ where object_id in (select id from ir_model where model = 'project.issue'))
            )""")
예제 #26
0
파일: autobus.py 프로젝트: jmucero97/Albus
class autobus(osv.Model):
    def _check_asientos(self, cr, uid, ids):
        # Los servicios tienen que tener almenos 0.1 KM para poder registrarse
        bus = self.browse(cr, uid, ids[0], context=None)
        if bus.numAsientos <= 11:
            return False
        return True

    def _numero_servicios(self, cr, uid, ids, field, args, context=None):
        servicios = 0

        for autobus in self.browse(cr, uid, ids, context=context):
            servicios = len(autobus.servicio_id)

        return servicios

    def onchange_consumo(self, cr, uid, ids, consum, context=None):
        consumoMinimo = 1.00
        if consum < consumoMinimo:
            res = {'value': {'consumo': consumoMinimo}}
        elif consum > consumoMinimo:
            res = {'value': {'consumo': consum}}
        return res

    _name = 'autobus'
    _description = 'Informacion sobre autobus'

    _columns = {
        'name':
        fields.char('Matricula', size=8, required=True, readonly=False),
        'numAsientos':
        fields.integer('Numero de Plazas', required=True),
        'modelo':
        fields.char('Modelo de Autobus',
                    size=32,
                    required=False,
                    readonly=False),
        'consumo':
        fields.float('Consumo (L/Km)', required=True),
        'revisado':
        fields.boolean(
            'Necesita Revision'),  #Cada mes este atributo pasara a FALSE
        'mantenimiento_id':
        fields.one2many("mantenimiento", "matricula_id", "Mantenimientos"),
        'servicio_id':
        fields.one2many("servicio", "matricula_id", "Servicios"),
        'numServicios':
        fields.function(_numero_servicios,
                        type='integer',
                        string="Número de Servicios",
                        store=True)
    }

    _constraints = [
        (_check_asientos, 'El numero de asientos no pueden ser negativos',
         ['numAsientos'])
    ]
    _sql_constraints = [
        ('matricula_uniq', 'unique (name)',
         'Ya existe un autobus con esa matricula'),
    ]
class ea_import_template_line(osv.osv):

    _name = 'ea_import.template.line'
    _rec_name = 'target_field'

    def _get_related_field_model(self, cr, uid, ids, name, args, context=None):
        if not ids:
            return {}
        result = {}
        for template_line in self.browse(cr, uid, ids, context=context):
            result[template_line.id] = template_line.target_field.relation
        return result

    def _get_next_sequence(self, cr, uid, context={}):
        template_id = context.get('template_id')
        if template_id:
            cr.execute(
                """
                SELECT MAX(sequence) + 1
                FROM ea_import_template_line
                WHERE template_id = %s
                      """, (template_id, ))
            for (next_sequence, ) in cr.fetchall():
                return next_sequence or 1
        return 1

    _columns = {
        'target_field':
        fields.many2one('ir.model.fields', string="Field Name", select=True),
        'template_id':
        fields.many2one('ea_import.template', 'Template', select=True),
        'target_model_id':
        fields.related(
            'template_id',
            'target_model_id',
            type='many2one',
            relation='ir.model',
            string='Target Object',
            readonly=True,
            store=False,
        ),
        'related_field':
        fields.many2one('ir.model.fields', string="Related Field",
                        select=True),
        'related_field_model':
        fields.char(
            'related_field_model',
            size=512,
        ),
        'sequence':
        fields.integer('Sequence', required=True, select=True),
        'real_field_type':
        fields.related(
            'target_field',
            'ttype',
            type='char',
            relation='ir.model.fields',
            string='Field type',
            readonly=True,
            store=False,
        ),
        'test_result_field':
        fields.char(
            'Test Result',
            size=512,
        ),
        'default_value':
        fields.char(
            'Default Value',
            size=512,
        ),
        'use_only_defaults':
        fields.boolean('Use only defaults', ),
        'test_result_record_number':
        fields.integer('Record Number'),
        'key_field':
        fields.boolean('Key field for updating', select=True),
        'required':
        fields.boolean('Required for creating new', select=True),
        'calculated':
        fields.boolean('Calculated', select=True),
        'calc_field_ids':
        fields.one2many(
            'ea_import.template.line.calc_field',
            'template_line_id',
            'Calculated Field',
        ),
        'boolean_field_ids':
        fields.one2many(
            'ea_import.template.line.boolean_field',
            'template_line_id',
            'Boolean Fields',
        ),
        'replace':
        fields.boolean('Replace field before processing', select=True),
        'regexp_field_ids':
        fields.one2many(
            'ea_import.template.line.regexp_field',
            'template_line_id',
            'Regexp Fields',
        ),
        'header_column_name':
        fields.char(
            'Header Column Name',
            size=64,
        ),
        'time_format':
        fields.char('Time Format',
                    size=128,
                    help="""DIRECTIVE       MEANING
%a	Locale’s abbreviated weekday name.
%A	Locale’s full weekday name.
%b	Locale’s abbreviated month name.
%B	Locale’s full month name.
%c	Locale’s appropriate date and time representation.
%d	Day of the month as a decimal number [01,31].
%H	Hour (24-hour clock) as a decimal number [00,23].
%I	Hour (12-hour clock) as a decimal number [01,12].
%j	Day of the year as a decimal number [001,366].
%m	Month as a decimal number [01,12].
%M	Minute as a decimal number [00,59].
%p	Locale’s equivalent of either AM or PM.
%S	Second as a decimal number [00,61].
%U	Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w	Weekday as a decimal number [0(Sunday),6].
%W	Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x	Locale’s appropriate date representation.
%X	Locale’s appropriate time representation.
%y	Year without century as a decimal number [00,99].
%Y	Year with century as a decimal number.
%Z	Time zone name (no characters if no time zone exists).
%%	A literal '%' character.),"""),
        'field_type':
        fields.selection([
            ('char', 'char'),
            ('text', 'text'),
            ('boolean', 'boolean'),
            ('integer', 'integer'),
            ('date', 'date'),
            ('datetime', 'datetime'),
            ('float', 'float'),
            ('selection', 'selection'),
            ('binary', 'binary'),
            ('many2one', 'many2one'),
        ], 'Field Type'),
        'many2one_rel_type':
        fields.selection(
            [('dbid', 'Database ID'), ('subfield', 'Subfield'),
             ('template', 'Template')],
            'Relation type',
        ),
        'related_template_id':
        fields.many2one('ea_import.template', 'Related Template', select=True),
    }

    _defaults = {
        'time_format':
        '%d/%m/%Y',
        'sequence':
        lambda self, cr, uid, context: self._get_next_sequence(
            cr, uid, context=context),
        'many2one_rel_type':
        'subfield',
        'default_value':
        None,
    }

    def name_get(self, cr, uid, ids, context={}):
        result = []
        for template_line in self.browse(cr, uid, ids, context=context):
            template_line_name = "%s/%s" % (template_line.target_model_id.name,
                                            template_line.related_field.name)
            result.append((template_line.id, template_line_name))
        return result

    def default_get(self, cr, uid, fields, context={}):
        result = super(ea_import_template_line,
                       self).default_get(cr, uid, fields, context=context)
        template_id = context.get('template_id')
        target_model_id = context.get('target_model_id')
        result.update({
            'template_id': template_id,
            'target_model_id': target_model_id
        })
        return result

    def onchange_target_field(self, cr, uid, ids, field_id, context={}):
        if field_id:
            model_fields_pool = self.pool.get('ir.model.fields')
            field_obj = model_fields_pool.browse(cr,
                                                 uid,
                                                 field_id,
                                                 context=context)
            return {
                'value': {
                    'field_type': field_obj.ttype,
                    'related_field_model': field_obj.relation
                }
            }
        else:
            return {'value': {}}

    def get_field(self, cr, uid, ids, input_list, context={}, testing=False):
        template_line_boolean_field_pool = self.pool.get(
            'ea_import.template.line.boolean_field')
        template_line_regxp_field_pool = self.pool.get(
            'ea_import.template.line.regexp_field')

        def test_many2one_result(result_list, template_line, target_string):
            if len(result_list) > 1:
                raise osv.except_osv(
                    _('Error !'),
                    _("For %s/%s relation there more then 1 record." %
                      (template_line.target_field.field_description,
                       template_line.related_field.field_description)))
            elif not result and template_line.target_field.required:
                raise osv.except_osv(
                    _('Error !'),
                    _("""Model - %s\nField - %s\nThere no related field '%s' in %s/%s relation (field is required)"""
                      % (template_line.template_id.name,
                         template_line.target_field.model, target_string,
                         template_line.target_field.model,
                         template_line.related_field.model)))

        for template_line in self.browse(cr, uid, ids, context=context):
            if not all([bool(field_str) == False for field_str in input_list]):
                if template_line.use_only_defaults:
                    target_string = template_line.default_value
                else:
                    target_string = input_list[template_line.sequence - 1]
                    if not target_string.strip(
                    ) and template_line.default_value:
                        target_string = template_line.default_value
                if template_line.replace:
                    target_string = template_line_regxp_field_pool.replace_string(
                        cr,
                        uid, [
                            regexp_field.id
                            for regexp_field in template_line.regexp_field_ids
                        ],
                        target_string,
                        context=context)
                template_line_type = template_line.field_type
                if template_line.calculated and template_line_type in [
                        'integer', 'float'
                ]:
                    calc_fields = sorted(template_line.calc_field_ids,
                                         key=lambda k: k.sequence)
                    result = float(
                        input_list[calc_fields.pop(0).column_number -
                                   1].strip() or "0")
                    for calc_field in calc_fields:
                        result = calc_field.calculate(result, input_list)
                    return result
                elif template_line_type in ['text', 'char']:
                    return target_string
                if template_line_type == 'selection':
                    return template_line.get_selection_from_name(target_string)
                if template_line_type == 'binary':
                    return base64.b32encode(target_string)
                elif template_line_type == 'integer':
                    return int(target_string)
                elif template_line_type == 'float':
                    return float(target_string)
                elif template_line_type == 'boolean':
                    if template_line.boolean_field_ids:
                        return template_line_boolean_field_pool.get_value(
                            cr,
                            uid, [
                                boolean_field.id for boolean_field in
                                template_line.boolean_field_ids
                            ],
                            target_string,
                            context=context)
                    else:
                        return bool(target_string)
                elif template_line_type == 'date':
                    try:
                        target_time = datetime.datetime.strptime(
                            target_string, template_line.time_format)
                        return target_time.strftime("%Y-%m-%d")
                    except ValueError:
                        return None
                elif template_line_type == 'datetime':
                    try:
                        target_time = datetime.datetime.strptime(
                            target_string, template_line.time_format)
                        return target_time.strftime("%Y-%m-%d %H:%M:%S")
                    except ValueError:
                        return None
                elif template_line_type == 'time':
                    try:
                        target_time = datetime.datetime.strptime(
                            target_string, template_line.time_format)
                        return target_time.strftime("%H:%M:%S")
                    except ValueError:
                        return None
                elif template_line_type == 'many2one':
                    target_obj_pool = self.pool.get(
                        template_line.target_field.relation)
                    if template_line.many2one_rel_type == 'dbid':
                        return int(target_string)
                    elif template_line.many2one_rel_type == 'subfield':
                        result = target_obj_pool.search(
                            cr,
                            uid, [(template_line.related_field.name, '=',
                                   target_string)],
                            context=context)
                        if testing:
                            test_many2one_result(result, template_line,
                                                 target_string)
                            return result and result[0] or False
                        elif not result:
                            return None
                        else:
                            return result[0]
                    elif template_line.many2one_rel_type == 'template':
                        result = template_line.related_template_id.get_related_id(
                            input_list)
                        if testing:
                            test_many2one_result(result, template_line,
                                                 target_string)
                        return result[0]
            else:
                continue

    def get_selection_from_name(self, cr, uid, ids, target_string, context={}):
        for template_line in self.browse(cr, uid, ids, context=context):
            target_model_pool = self.pool.get(
                template_line.target_model_id.model)
            selection_dict = dict(target_model_pool._columns[
                template_line.target_field.name].selection)
            revrese_selection_dict = dict(
                (v, k) for k, v in selection_dict.iteritems())
            return revrese_selection_dict.get(target_string)
예제 #28
0
class print_quotation_feedback(osv.osv_memory):
    _name = 'print.quotation.feedback'
    _description = 'feedback print quotation'
    _columns = {
        'type': fields.selection(WARNING_TYPES, string='Type', readonly=True),
        'title': fields.char(string="Title", size=100, readonly=True),
        'message': fields.text(string="Message", readonly=True),
        'sale_order_id': fields.integer(readonly=True),
    }
    _req_name = 'title'

    def _get_view_id(self, cr, uid):
        """Get the view id
        @return: view id, or False if no view found
        """
        res = self.pool.get('ir.model.data').get_object_reference(
            cr, uid, 'natuurpunt_sale_cmis', 'print_quotation_feedback_view')
        return res and res[1] or False

    def message(self, cr, uid, id, context):
        message = self.browse(cr, uid, id)
        message_type = [t[1] for t in WARNING_TYPES if message.type == t[0]][0]
        print '%s: %s' % (_(message_type), _(message.title))
        res = {
            'name': '%s: %s' % (_(message_type), _(message.title)),
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': self._get_view_id(cr, uid),
            'res_model': 'print.quotation.feedback',
            'domain': [],
            'context': context,
            'type': 'ir.actions.act_window',
            'target': 'new',
            'res_id': message.id
        }
        return res

    def print_quotation(self, cr, uid, ids, context=None):
        for message in self.browse(cr, uid, ids):
            sale_order_id = message.sale_order_id
            return self.pool.get('sale.order').create_print_quotation(
                cr, uid, [sale_order_id])

    def warning(self, cr, uid, title, message, sale_order_id, context=None):
        id = self.create(
            cr, uid, {
                'title': title,
                'message': message,
                'type': 'warning',
                'sale_order_id': sale_order_id
            })
        res = self.message(cr, uid, id, context)
        return res

    def info(self, cr, uid, title, message, sale_order_id, context=None):
        id = self.create(
            cr, uid, {
                'title': title,
                'message': message,
                'type': 'info',
                'sale_order_id': sale_order_id
            })
        res = self.message(cr, uid, id, context)
        return res

    def error(self, cr, uid, title, message, sale_order_id, context=None):
        id = self.create(
            cr, uid, {
                'title': title,
                'message': message,
                'type': 'error',
                'sale_order_id': sale_order_id
            })
        res = self.message(cr, uid, id, context)
        return res
예제 #29
0
class tcv_balance(osv.osv_memory):

    _name = 'tcv.balance'

    _description = ''

    ##-------------------------------------------------------------------------

    ##------------------------------------------------------- _internal methods

    def default_get(self, cr, uid, fields, context=None):
        data = super(tcv_balance, self).\
            default_get(cr, uid, fields, context)
        year = datetime.now().year
        if not data.get('date_from'):
            data['date_from'] = '%s-01-01' % (year)
        if not data.get('date_to'):
            data['date_to'] = time.strftime('%Y-%m-%d')
        data.update({'loaded': False})
        return data

    def _compute_result(self, atype, lines):
        res = 0
        for l in lines:
            if l.account_id.level == 1:
                if atype == 'balance':
                    res += l.balance
                else:
                    res += l.amount_period
        return res

    def _add_account(self, account, balance, level):
        res = []
        if account.type == 'view' and \
                account.level < level:
            res.append({
                'code': account.code,
                'account_id': account.id,
            })
            code_tot = '%s%s' % (account.code, __TOTAL_CODE__)
            res.append({
                'code': code_tot,
                'account_id': account.id,
                'total': True,
                'debit': balance if balance >= 0 else 0,
                'credit': abs(balance) if balance < 0 else 0,
            })
        else:
            res.append({
                'code': account.code,
                'account_id': account.id,
                'debit': balance if balance >= 0 else 0,
                'credit': abs(balance) if balance < 0 else 0,
            })
        return res

    def _add_result_accounts(self, cr, uid, acc_id, result, level, balance_id):
        result_acc_ids = []
        result_codes = []
        res = []
        obj_tbl = self.pool.get('tcv.trial.balance.lines')
        obj_acc = self.pool.get('account.account')
        acc = obj_acc.browse(cr, uid, acc_id, context=None)
        while acc.parent_id and acc.parent_id.level >= 0:
            result_acc_ids.append(acc.id)
            acc = acc.parent_id
        for acc_id in result_acc_ids:
            acc = obj_acc.browse(cr, uid, acc_id, context=None)
            if not obj_tbl.search(cr, uid, [('account_id', '=', acc_id),
                                            ('line_id', '=', balance_id)]):
                if acc.level <= level:
                    lines = self._add_account(acc, 0, level)
                    result_codes.append(lines[-1]['code'])
                    res.extend(lines)
            else:
                if acc.level < level:
                    result_codes.append(acc.code + __TOTAL_CODE__)
                elif acc.level == level:
                    result_codes.append(acc.code)
        return res, result_codes

    ##--------------------------------------------------------- function fields

    _columns = {
        'type':
        fields.selection([('balance', 'Situational balance'),
                          ('profit_loss', 'Result balance')],
                         string='Type',
                         required=True,
                         readonly=False),
        'date_from':
        fields.date('Date from', required=False),
        'date_to':
        fields.date('Date to', required=True),
        'line_ids':
        fields.one2many('tcv.balance.lines',
                        'line_id',
                        'Account balance',
                        readonly=True),
        'loaded':
        fields.boolean('Loaded'),
        'non_zero':
        fields.boolean('No zero lines', help="Hide 0 balance accounts"),
        'show_code':
        fields.boolean('Show code', help="Show accounts code"),
        'use_ident':
        fields.boolean('Use ident', help="Use identation"),
        'level':
        fields.integer('Account level', help="0=All levels"),
        'print_cols':
        fields.selection([(1, '1'), (2, '2')],
                         string='Print columns',
                         required=True),
        'company_id':
        fields.many2one('res.company',
                        'Company',
                        required=True,
                        readonly=True,
                        ondelete='restrict'),
    }

    _defaults = {
        'type':
        lambda *a: 'balance',
        'loaded':
        lambda *a: False,
        'non_zero':
        lambda *ad: True,
        'show_code':
        lambda *a: False,
        'use_ident':
        lambda *a: True,
        'print_cols':
        lambda *a: 1,
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.company').
        _company_default_get(cr, uid, self._name, context=c),
    }

    _sql_constraints = [
        ('level_range', 'CHECK(level between 0 and 9)',
         'The level must be in 0-9 range!'),
        ('print_cols_range', 'CHECK(print_cols between 1 and 2)',
         'The Print columns must be 1 or 2!'),
        ('date_to_gt_date_from', 'CHECK (date_to>=date_from)',
         'The from date must be < the to date'),
    ]

    ##-------------------------------------------------------------------------

    ##---------------------------------------------------------- public methods

    def clear_wizard_lines(self, cr, uid, item, context):
        unlink_ids = []
        for l in item.line_ids:
            unlink_ids.append(l.id)
        obj_lin = self.pool.get('tcv.balance.lines')
        if unlink_ids:
            obj_lin.unlink(cr, uid, unlink_ids, context=context)
        return unlink_ids

    ##-------------------------------------------------------- buttons (object)

    def load_wizard_lines(self, cr, uid, ids, context):
        ids = isinstance(ids, (int, long)) and [ids] or ids
        obj_per = self.pool.get('account.period')
        obj_tba = self.pool.get('tcv.trial.balance')
        obj_tbl = self.pool.get('tcv.trial.balance.lines')
        obj_acc = self.pool.get('account.account')
        #~ tot_23 = 0
        lines = []
        for item in self.browse(cr, uid, ids, context={}):
            self.clear_wizard_lines(cr, uid, item, context)
            period_id = obj_per.find(cr, uid, item.date_to)[0]
            period = obj_per.browse(cr, uid, period_id, context=context)
            # Create trial balance
            values = {
                'date_from':
                period.date_start
                if item.type == 'balance' else item.date_from,
                'date_to':
                item.date_to,
                'non_zero':
                item.non_zero,
                'total_view':
                True,
                'level':
                item.level or None,
            }
            tba_id = obj_tba.create(cr, uid, values, context=None)
            obj_tba.load_wizard_lines(cr, uid, tba_id, context=None)
            level = item.level or 99
            # Get ids from trial balance lines
            balance_acc_ids = obj_acc.search(cr, uid, [('code', '<', '4')])
            balance_ids = obj_tbl.search(
                cr, uid, [('account_id', 'in', balance_acc_ids),
                          ('line_id', '=', tba_id)])
            result_ids = obj_tbl.search(
                cr, uid, [('account_id', 'not in', balance_acc_ids),
                          ('line_id', '=', tba_id)])
            # Add trial balance & totals lines
            report_ids = balance_ids if item.type == 'balance' else result_ids
            for l in obj_tbl.browse(cr, uid, report_ids, context=None):
                amount = l.balance if item.type == 'balance' else \
                    l.amount_period
                lines.extend(self._add_account(l.account_id, amount, level))

            # Add extra lines
            result_acc_id = obj_acc.search(
                cr, uid, [('type', '=', 'consolidation'),
                          ('company_id', '=', item.company_id.id)])[0]
            result = self._compute_result(
                item.type, obj_tbl.browse(cr, uid, result_ids, context=None))
            if item.type == 'balance':
                if result or not item.non_zero:
                    result_lines, result_codes = self._add_result_accounts(
                        cr, uid, result_acc_id, result, level, tba_id)
                    lines.extend(result_lines)
                    if level == 1:
                        tot_23_codes = ('2', '3')
                    else:
                        tot_23_codes = ('2' + __TOTAL_CODE__,
                                        '3' + __TOTAL_CODE__)
                    tot_23 = 0
                    for l in lines:
                        if l['code'] in result_codes:
                            balance = l['debit'] - l['credit'] + result
                            l.update({
                                'debit':
                                balance if balance >= 0 else 0,
                                'credit':
                                abs(balance) if balance < 0 else 0,
                            })
                        if l['code'] in tot_23_codes:
                            tot_23 += l['debit'] - l['credit']
                    lines.append({
                        'code': __TOTAL_CODE__ + __TOTAL_CODE__,
                        'total': True,
                        'debit': tot_23 if tot_23 >= 0 else 0,
                        'credit': abs(tot_23) if tot_23 < 0 else 0,
                    })
            else:
                lines.append({
                    'code': __TOTAL_CODE__,
                    'total': True,
                    'debit': result if result >= 0 else 0,
                    'credit': abs(result) if result < 0 else 0,
                })
            line_ids = sorted(lines, key=lambda k: k['code'])
            self.write(cr,
                       uid, [item.id], {
                           'line_ids': [(0, 0, x) for x in line_ids],
                           'loaded': True
                       },
                       context=None)
        return True

    ##------------------------------------------------------------ on_change...

    def on_change_data(self, cr, uid, ids, loaded):
        res = {}
        res.update({'loaded': False})
        return {'value': res}
예제 #30
0
class purchase(osv.osv):
    """
    Modify purchase order to fit foreign purchase order """
    def _calculate_bills_amount(self, cr, uid, ids):
        """
        To calculate bills total amouunt

        @return: True
        """
        for purchase in self.browse(cr, uid, ids):
            bill_amount_sum = 0.0
            for bills in purchase.purchase_bills:
                bill_amount_sum += bills.bill_amount
            self.write(cr, uid, purchase.id, {
                'bills_amoun_total': bill_amount_sum,
            })
        return True

    def _amount_all(self, cr, uid, ids, field_name, arg, context=None):
        """
        Functional field function to calculate the amount_total,amount_untaxed,
        amount_tax and written_total of purchase order to add exstra amount to the 
        purchase order.

        @return: Dictionary of fields value
        """
        res = super(purchase, self)._amount_all(cr, uid, ids, field_name, arg,
                                                context)
        for order in self.browse(cr, uid, ids, context=context):
            freight_all = 0.0
            packing_all = 0.0
            for line in order.order_line:
                freight_all += line.price_unit_freight * line.product_qty
                packing_all += line.price_unit_packing * line.product_qty
            self.write(cr, uid, order.id, {
                'freight': (freight_all),
                'packing': (packing_all)
            })
            res[order.id]['amount_total'] = res[
                order.id]['amount_untaxed'] + res[order.id]['amount_tax'] + (
                    freight_all) + (packing_all)
            currency_format = order.company_id.currency_format
            total = res[order.id]['amount_total']
            if currency_format == 'ar':
                res[order.id]['written_total'] = amount_to_text_ar(
                    total, currency_format, order.currency_id['units_name'],
                    order.currency_id['cents_name'])
            else:
                res[order.id]['written_total'] = amount_to_text_ar(total)
        return res

    def _get_order(self, cr, uid, ids, context=None):
        """
        Override to calling the function from purchase order object.

        @return: super _get_order method 
        """
        line = self.pool.get('purchase.order')
        return super(purchase, line)._get_order(cr, uid, ids, context)

    DELIVERY_SELECTION = [
        ('air_freight', 'Air Freight'),
        ('sea_freight', 'Sea Freight'),
        ('land_freight', 'Land Freight'),
        ('free_zone', 'Free Zone'),
    ]

    TYPE_SELECTION = [
        ('internal', 'Internal Purchase'),
        ('foreign', 'Foreign Purchase'),
    ]

    _inherit = 'purchase.order'
    _columns = {
        'account_voucher_ids':
        fields.many2many('account.voucher', 'purchase_order_voucher',
                         'purchase_id', 'voucher_id', 'Account voucher'),
        'purchase_bills':
        fields.one2many('purchase.bills', 'purchase_id', 'Other Cost'),
        'bills_amoun_total':
        fields.float('Billing Total amount', digits=(16, 2)),
        'purchase_type':
        fields.selection(TYPE_SELECTION, 'Purchase Type', select=True),
        'final_invoice_no':
        fields.integer('Final Invoice No',
                       size=64,
                       states={'done': [('readonly', True)]}),
        'final_invoice_date':
        fields.date('Final Invoice Date',
                    states={'done': [('readonly', True)]}),
        'delivery_method':
        fields.selection(DELIVERY_SELECTION,
                         'Method of dispatch',
                         select=True,
                         required=False,
                         states={'done': [('readonly', True)]}),
        'freight':
        fields.float('Freight', digits=(16, 2)),
        'packing':
        fields.float('Packing', digits=(16, 2)),
        'written_total':
        fields.function(_amount_all,
                        method=True,
                        string='written Total',
                        type='char',
                        size=128,
                        store={
                            'purchase.order':
                            (lambda self, cr, uid, ids, c={}: ids,
                             ['order_line', 'taxes_id'], 10),
                            'purchase.order.line': (_get_order, None, 10),
                        },
                        multi="sums",
                        help="The total written amount"),
        'amount_untaxed':
        fields.function(_amount_all,
                        method=True,
                        digits_compute=dp.get_precision('Purchase Price'),
                        string='Untaxed Amount',
                        store={
                            'purchase.order':
                            (lambda self, cr, uid, ids, c={}: ids,
                             ['order_line', 'taxes_id'], 10),
                            'purchase.order.line': (_get_order, None, 10),
                        },
                        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':
                            (lambda self, cr, uid, ids, c={}: ids,
                             ['order_line', 'taxes_id'], 10),
                            'purchase.order.line': (_get_order, None, 10),
                        },
                        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':
                            (lambda self, cr, uid, ids, c={}: ids,
                             ['order_line', 'taxes_id'], 10),
                            'purchase.order.line': (_get_order, None, 10),
                        },
                        multi="sums",
                        help="The total amount"),
    }
    _defaults = {
        'bills_amoun_total': 0.0,
        'freight': 0.0,
        'packing': 0.0,
        'purchase_type': 'internal',
    }

    def wkf_sign_order(self, cr, uid, ids, context=None):
        """
        Workflow function override to create voucher with the 
        extra cost prices.

        @return: True
        """
        company_obj = self.pool.get('res.users').browse(cr, uid,
                                                        uid).company_id
        for po in self.browse(cr, uid, ids, context=context):
            if not po.location_id:
                raise osv.except_osv(
                    _('NO Stock Location !'),
                    _('Please chose stock location then make Confirmation.'))
        self.write(cr, uid, ids, {
            'state': 'sign',
        })
        voucher_obj = self.pool.get('account.voucher')
        voucher_line_obj = self.pool.get('account.voucher.line')
        purchase_obj = self.pool.get('purchase.order').browse(cr, uid, ids)
        if not company_obj:
            company_obj = purchase_obj.company_id
        list = []
        for purchase in purchase_obj:
            if purchase.purchase_bills:
                for bill in purchase.purchase_bills:
                    journal = bill.type.property_type_journal
                    account = bill.type.property_type_account
                    voucher_id = voucher_obj.create(
                        cr, uid, {
                            'amount': bill.bill_amount,
                            'type': 'purchase',
                            'date': time.strftime('%Y-%m-%d'),
                            'partner_id': bill.partner_id.id,
                            'journal_id': journal.id,
                            'reference': purchase.name,
                            'reference': purchase.name,
                        })
                    list.append(voucher_id)
                    vocher_line_id = voucher_line_obj.create(
                        cr, uid, {
                            'amount': bill.bill_amount,
                            'voucher_id': voucher_id,
                            'account_id': account.id,
                            'type': 'dr',
                            'name': bill.description,
                        })
                self.write(cr, uid, ids,
                           {'account_voucher_ids': [(6, 0, list)]})
            purchase._calculate_bills_amount()
        self.write(cr, uid, ids, {
            'state': 'sign',
        })
        return True

    def wkf_confirm_order(self, cr, uid, ids, context=None):
        """
        Workflow function override to force calculate the extra price amount.

        @return: super wkf_confirm_order method
        """
        #for purchases in self.browse(cr, uid, ids):
        #purchases._calculate_bills_amount()
        #for line in purchases.order_line:
        #line._calculate_extra_amount(purchases)
        return super(purchase, self).wkf_confirm_order(cr, uid, ids, context)

    def create_supplier_invoive(self, cr, uid, ids, context=None):
        """
        Function For create Invoice From Button add check whether it created before.

        @return: True
        """
        order_obj = self.browse(cr, uid, ids)[0]
        invoice_obj = self.pool.get('account.invoice')
        invoice_line_obj = self.pool.get('account.invoice.line')
        invoice_record = invoice_obj.search(cr, uid,
                                            [('origin', '=', order_obj.name)])
        if invoice_record:
            raise osv.except_osv(
                _('Duplicated Invoices !'),
                _('You are Already Create Invoice for this order before.'))
        invoice_id = super(purchase,
                           self).action_invoice_create(cr, uid, ids, context)
        self.write(cr, uid, ids, {'invoice_method': 'manual'})
        return True

    def action_invoice_create(self, cr, uid, ids, context=None):
        """
        Override to add invoice lines to manage freight and packing prices.

        @return: invoice id
        """
        invoice_obj = self.pool.get('account.invoice')
        invoice_line_obj = self.pool.get('account.invoice.line')
        invoice_id = super(purchase,
                           self).action_invoice_create(cr, uid, ids, context)
        for order in self.browse(cr, uid, ids):
            company_obj = order.company_id
            invoice_obj.write(cr, uid, invoice_id,
                              {'currency_id': order.currency_id.id})
            line_id = invoice_line_obj.search(
                cr, uid, [('invoice_id', '=', invoice_id)], limit=1)
            account_id = invoice_line_obj.browse(cr, uid,
                                                 line_id)[0].account_id.id
            if order.freight > 0.0:
                invoice_line_id = invoice_line_obj.create(
                    cr, uid, {
                        'name': 'Freight',
                        'origin': order.name,
                        'invoice_id': invoice_id,
                        'uos_id': 0,
                        'product_id': 0,
                        'account_id': account_id,
                        'price_unit': order.freight,
                        'discount': 0,
                        'quantity': 1,
                        'invoice_line_tax_id': 0,
                        'account_analytic_id': 0,
                    })
            if order.packing > 0.0:
                invoice_line_id = invoice_line_obj.create(
                    cr, uid, {
                        'name': 'Packing',
                        'origin': order.name,
                        'invoice_id': invoice_id,
                        'uos_id': 0,
                        'product_id': 0,
                        'account_id': account_id,
                        'price_unit': order.packing,
                        'discount': 0,
                        'quantity': 1,
                        'invoice_line_tax_id': 0,
                        'account_analytic_id': 0,
                    })
            if order.purchase_type == 'foreign':
                account_from_company = company_obj.purchase_foreign_account
                journal_id = company_obj.purchase_foreign_journal
                if not account_from_company:
                    raise osv.except_osv(
                        _('NO Account !'),
                        _('no account defined for purchase foreign.'))
                if not journal_id:
                    raise osv.except_osv(
                        _('NO Journal !'),
                        _('no journal defined for purchase foreign.'))
                invoice = invoice_obj.browse(cr, uid, invoice_id)
                invoice_obj.write(cr, uid, invoice_id,
                                  {'journal_id': journal_id.id})
                for line in invoice.invoice_line:
                    invoice_line_obj.write(
                        cr, uid, line.id,
                        {'account_id': account_from_company.id})
        #print"invoice_id %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",invoice_id
        return invoice_id

    def action_picking_create(self, cr, uid, ids, *args):
        """
        Override to read account of purchase foreign from the company,
        and add foreign purchase price to picking.

        @return: picking id
        """
        res = {}
        picking_obj = self.pool.get('stock.picking')
        picking_id = super(purchase,
                           self).action_picking_create(cr, uid, ids, *args)
        move_obj = self.pool.get('stock.move')
        currency_obj = self.pool.get('res.currency')
        for purchase_obj in self.browse(cr, uid, ids):
            company_obj = purchase_obj.company_id
            if purchase_obj.purchase_type == 'foreign':
                account_from_company = company_obj.purchase_foreign_account
                if not account_from_company:
                    raise osv.except_osv(
                        _('NO Account !'),
                        _('no account defined for purchase foreign.'))
                else:
                    res = {
                        'account_id': account_from_company.id or False,
                        'company_id': company_obj.id,
                    }
            picking_obj.write(cr, uid, picking_id, res)
            move = {}
            total_amount = 0.0
            for order_line in purchase_obj.order_line:
                stock_move_obj = move_obj.search(
                    cr, uid, [('purchase_line_id', '=', order_line.id)])
                total_amount = order_line.price_unit_freight + order_line.price_unit_packing + order_line.price_unit
                new_price = currency_obj.compute(
                    cr, uid, order_line.order_id.currency_id.id,
                    order_line.order_id.company_id.currency_id.id,
                    total_amount, purchase_obj.date_order)
                price = new_price
                if purchase_obj.purchase_type == 'internal':
                    price = order_line.price_unit + order_line.price_unit_freight + order_line.price_unit_packing + order_line.price_unit_tax
                move = {
                    'price_unit': price,
                }
                move_obj.write(cr, uid, stock_move_obj, move)
        return picking_id
예제 #31
0
            filename = random_name()
            fname = os.path.join(path, flag, filename)
            fp = file(fname,'wb')
            v = base64.decodestring(value)
            fp.write(v)
            filesize = os.stat(fname).st_size
            cr.execute('update ir_attachment set store_fname=%s,store_method=%s,file_size=%s where id=%s', (os.path.join(flag,filename),'fs',len(v),id))
            return True
        except Exception,e :
            raise except_orm(_('Error!'), str(e))

    _columns = {
        'user_id': fields.many2one('res.users', 'Owner', select=1),
        'group_ids': fields.many2many('res.groups', 'document_directory_group_rel', 'item_id', 'group_id', 'Groups'),
        'parent_id': fields.many2one('document.directory', 'Directory', select=1),
        'file_size': fields.integer('File Size', required=True),
        'file_type': fields.char('Content Type', size=32),
        'index_content': fields.text('Indexed Content'),
        'write_date': fields.datetime('Date Modified', readonly=True),
        'write_uid':  fields.many2one('res.users', 'Last Modification User', readonly=True),
        'create_date': fields.datetime('Date Created', readonly=True),
        'create_uid':  fields.many2one('res.users', 'Creator', readonly=True),
        'store_method': fields.selection([('db','Database'),('fs','Filesystem'),('link','Link')], "Storing Method"),
        'datas': fields.function(_data_get,method=True,fnct_inv=_data_set,string='File Content',type="binary"),
        'store_fname': fields.char('Stored Filename', size=200),
        'res_model': fields.char('Attached Model', size=64), #res_model
        'res_id': fields.integer('Attached ID'), #res_id
        'partner_id':fields.many2one('res.partner', 'Partner', select=1),
        'title': fields.char('Resource Title',size=64),
    }
예제 #32
0
class oebase_event_category(osv.osv):
    _name = 'oebase.event.category'

    def name_get(self, cr, uid, ids, context=None):
        """Return the category's display name, including their direct
           parent by default.

        :param dict context: the ``event_category_display`` key can be
                             used to select the short version of the
                             category (without the direct parent),
                             when set to ``'short'``. The default is
                             the long version."""
        if context is None:
            context = {}
        if context.get('event_category_display') == 'short':
            return super(oebase_event_category, self).name_get(cr,
                                                               uid,
                                                               ids,
                                                               context=context)
        if isinstance(ids, (int, long)):
            ids = [ids]
        reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['parent_id']:
                name = record['parent_id'][1] + ' / ' + name
            res.append((record['id'], name))
        return res

    def name_search(self,
                    cr,
                    uid,
                    name,
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        if not context:
            context = {}
        if name:
            name = name.split(' / ')[-1]
            ids = self.search(cr,
                              uid, [('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)

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)

    _columns = {
        'name':
        fields.char('Event Category', required=True, size=64, translate=True),
        'parent_id':
        fields.many2one('oebase.event.category',
                        'Parent Category',
                        select=True,
                        ondelete='restrict'),
        'description':
        fields.text(string='Description'),
        'notes':
        fields.text(string='Notes'),
        'complete_name':
        fields.function(_name_get_fnc,
                        type="char",
                        string='Event Category',
                        store=True),
        'child_ids':
        fields.one2many('oebase.event.category', 'parent_id',
                        'Child Categories'),
        'active':
        fields.boolean(
            'Active',
            help=
            "If unchecked, it will allow you to hide the category without removing it."
        ),
        'parent_left':
        fields.integer('Left parent', select=True),
        'parent_right':
        fields.integer('Right parent', select=True),
        'event_ids':
        fields.many2many('oebase.event', 'oebase_event_category_rel',
                         'category_id', 'event_id', 'Events'),
    }

    _constraints = [
        (osv.osv._check_recursion,
         'Error! You can not create recursive categories.', ['parent_id'])
    ]

    _defaults = {
        'active': 1,
    }

    _parent_store = True
    _parent_order = 'name'
    _order = 'parent_left'
예제 #33
0
            #
            statement_facade.write(cr, uid, [statement_id], {
                                    'date': st_data['fecha_fin'],
                                    'balance_start': st_data['saldo_ini'],
                                    'balance_end_real': st_data['saldo_fin'],
                                }, context=context)

            # Attach the C43 file to the current statement
            data = base64.encodestring( c43_wizard.file )
            res = statement_facade._attach_file_to_statement(cr, uid, data, statement_id, _('Bank Statement'), _('bank-statement.txt') )

        return {}


    _name = 'l10n.es.bank.statement.import.c43.wizard'

    _columns = {
        'file': fields.binary('Bank Statements File', required=True, filename='file_name'),
        'file_name': fields.char('Bank Statements File', size=64, readonly=True),
        'reco_reference_and_amount': fields.boolean('Reconcile by reference and amount'),
        'reco_vat_and_amount' : fields.boolean('Reconcile by VAT number and amount'),
        'reco_amount' : fields.boolean('Reconcile by amount'),
        'reco_rules' : fields.boolean('Statement Line Rules'),
        'reco_payment_order': fields.boolean('Reconcile payment orders by total amount'),
        'reco_max_days' : fields.integer('Max. days from statement date',help='Maximum difference in days, between the maturity date of the entry to reconcile and the bank statement entry')
        }

l10n_es_bank_statement_import_c43_wizard()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
예제 #34
0
class create_transformation(osv.osv_memory):
    _name = 'create.transformation'
    _description = 'Wizard to create transformation'

    _columns = {
        'prod_trans_tmpl_id':
        fields.many2one(
            'product.transformation.template',
            'Transformation Template',
            help=
            'Template based on which you need to create Product Transformation'
        ),
        'quantity':
        fields.integer(
            '#Transformations',
            help=
            'No of transformations to be created based on the selected template'
        )
    }

    _defaults = {
        'prod_trans_tmpl_id':
        lambda self, cr, uid, context: context.get('active_id', False),
        'quantity':
        lambda *a: 1
    }

    def create_transformation(self, cr, uid, ids, context=None):
        """
        This method creates transformations based on the product transformation
        """
        # It is assumed that only 1 wizard exist at any point of time for each session
        wiz = self.browse(cr, uid, ids[0], context=context)

        # Get the Vals for Transformation
        _ptt = wiz.prod_trans_tmpl_id
        trans_vals = _ptt.prepare_instance(context=context).get(_ptt.id, {})

        _pt_pool = self.pool.get('product.transformation')
        _pcl_pool = self.pool.get('product.consume.line')
        _fgl_pool = self.pool.get('finish.goods.line')
        for i in range(int(wiz.quantity)):
            _to_write = trans_vals.copy()
            # Create Transformation
            _consume_line_ids = []
            if 'consume_line_ids' in _to_write:
                _consume_line_ids = _to_write.pop('consume_line_ids')
            _finish_goods_line_ids = []
            if 'finish_goods_line_ids' in _to_write:
                _finish_goods_line_ids = _to_write.pop('finish_goods_line_ids')
            trans_id = _pt_pool.create(cr, uid, _to_write, context=context)

            # Add Products to Consume Lines in Transformation
            for c_line in _consume_line_ids:
                _c_line_to_write = c_line.copy()
                _c_line_to_write.update({'prod_trans_id': trans_id})
                _pcl_pool.create(cr, uid, _c_line_to_write, context=context)

            # Add Finished Goods Products in Trnansformation
            for f_line in _finish_goods_line_ids:
                _f_line_to_write = f_line.copy()
                _f_line_to_write.update({'prod_trans_id': trans_id})
                _ctx = context.copy()
                _ctx.update({'recalculate_mp': False})
                _fgl_pool.create(cr, uid, _f_line_to_write, context=_ctx)
        return {'type': 'ir.actions.act_window_close'}
		'weight': fields.integer('Weight (kg)')
		'product_id': fields.many2one('product.product', 'Pallet Product'),
		}
	_defaults = {
		'active': lambda *a, 1,
		}
	_sql_constraints = [('name_uniq', 'unique(name)', 'Pallet names must be unique!')]
pallet_types()

class pallet_stack_layout(osv.osv):

	_name = 'pallet.stack.layout'
    _columns = {
		'name': fields.char('Description', size=128, required=True),
		'active': fields.boolean('Active'),
		'program': fields.integer('Program Number', help='If this is stacked on a palletiser, this is the palletiser program number'),
		'pallet_type_id': fields.many2one('pallet.types','Pallet Type', ondelete='set null'),
		'layout_diagram': fields.binary('Layout diagram', filters='*.bmp,*.jpg,*.gif')
		'slipsheeted': fields.boolean('Slipsheeted', help='If product is stacked onto slipsheets, this box should be ticked.'),
		'layer_qty': fields.integer('Packages per layer'),
		'layer_height': fields.integer('Height per layer (mm)'),
		'layer_ids': fields.one2many('pallet_stack_layers', 'layout_id','Layer options'),
        }
	_defaults = {
		'active': lambda *a, 1,
		}
pallet_stack_layout()

class pallet_stack_layers(osv.osv):
	_name = 'pallet.stack.layers'
	#TODO This needs to calculate sum height of each layer and add the pallet height to come up with an overall height.
예제 #36
0
class tcv_sigesic_csv_export(osv.osv):

    _name = 'tcv.sigesic.csv.export'

    _description = ''

    ##-------------------------------------------------------------------------

    ##------------------------------------------------------- _internal methods

    ##--------------------------------------------------------- function fields

    _columns = {
        'name':
        fields.char('Filename', 64, readonly=True),
        'data_year':
        fields.integer('Year',
                       required=True,
                       help="El año al que corresponden los datos"),
        'csv_file':
        fields.binary('TXT file',
                      readonly=True,
                      filters='*.csv',
                      help="CSV file name"),
        'type':
        fields.selection([
            ('tcv.sigesic.0901',
             '0901 - Inputs and/or raw materials required'),
            ('tcv.sigesic.0902', '0902 - Goods produced'),
            ('tcv.sigesic.0903', '0903 - Raw materials / Goods relation'),
            ('tcv.sigesic.1001', '1001 - Machinery (unavaible)'),
            ('tcv.sigesic.1101', '1101 - Suppliers'),
            ('tcv.sigesic.1201',
             '1201 - Marketed Goods not produced by the Economic Unit'),
        ],
                         string='Model',
                         required=True),
    }

    _defaults = {
        'data_year': lambda *a: int(time.strftime('%Y')) - 1,
    }

    _sql_constraints = []

    ##-----------------------------------------------------

    ##----------------------------------------------------- public methods

    ##----------------------------------------------------- buttons (object)

    def button_create_csv(self, cr, uid, ids, context):
        ids = isinstance(ids, (int, long)) and [ids] or ids
        context = context or {}
        for item in self.browse(cr, uid, ids, context={}):
            if item.data_year < 2012 or item.data_year > 2099:
                raise osv.except_osv(_('Error!'),
                                     _('The year must be in 2012-2099 range.'))
            res = []
            obj_data = self.pool.get(item.type)
            context.update({'data_year': item.data_year})
            header = ';'.join(obj_data._csv_header(cr, uid, ids, context))
            res.append(header)
            line_ids = obj_data.get_data_lines_ids(cr, uid, ids,
                                                   item.data_year, context)
            if not line_ids:
                raise osv.except_osv(_('Error!'), _('Can\'t find any data.'))
            for line_id in line_ids:
                line = obj_data.get_data_line(cr, uid, line_id, context)
                res.append(';'.join(line))
            data = '\n'.join(res)
            buf = cStringIO.StringIO()
            buf.write(data.encode('utf-8'))
            output_file = base64.encodestring(buf.getvalue())
            buf.close()
            return self.write(
                cr,
                uid,
                ids, {
                    'csv_file': output_file,
                    'name': obj_data._csv_file_name % item.data_year
                },
                context=context)
예제 #37
0
                 'mail_attachments_rel',
                 'mail_id',
                 'att_id',
                 'Attachments'),
 'pem_account_id' :fields.many2one(
                 'poweremail.core_accounts',
                 'User account',
                 required=True),
 'pem_user':fields.related(
                 'pem_account_id',
                 'user',
                 type="many2one",
                 relation="res.users",
                 string="User"),
 'server_ref':fields.integer(
                 'Server Reference of mail',
                 help="Applicable for inward items only."),
 'pem_recd':fields.char('Received at', size=50),
 'mail_type':fields.selection([
                 ('multipart/mixed',
                  'Has Attachments'),
                 ('multipart/alternative',
                  'Plain Text & HTML with no attachments'),
                 ('multipart/related',
                  'Intermixed content'),
                 ('text/plain',
                  'Plain Text'),
                 ('text/html',
                  'HTML Body'),
                 ], 'Mail Contents'),
 #I like GMAIL which allows putting same mail in many folders
예제 #38
0
class external_referential(magerp_osv.magerp_osv):
    #This class stores instances of magento to which the ERP will connect, so you can connect OpenERP to multiple Magento installations (eg different Magento databases)
    _inherit = "external.referential"

    _logger = logging.getLogger(__name__)
    SYNC_PRODUCT_FILTERS = {'status': {'=': 1}}
    SYNC_PARTNER_FILTERS = {}
    SYNC_PARTNER_STEP = 500

    def _is_magento_referential(self,
                                cr,
                                uid,
                                ids,
                                field_name,
                                arg,
                                context=None):
        """If at least one shop is magento, we consider that the external
        referential is a magento referential
        """
        res = {}
        for referential in self.browse(cr, uid, ids, context):
            res[referential.id] = False
            for group in referential.shop_group_ids:
                for shop in group.shop_ids:
                    if shop.magento_shop:
                        res[referential.id] = True
                        break
                if res[referential.id]:
                    break
        return res

    _columns = {
        'attribute_sets':
        fields.one2many('magerp.product_attribute_set', 'referential_id',
                        'Attribute Sets'),
        'default_pro_cat':
        fields.many2one(
            'product.category',
            'Default Product Category',
            help=
            "Products imported from magento may have many categories.\nOpenERP requires a specific category for a product to facilitate invoicing etc."
        ),
        'default_lang_id':
        fields.many2one(
            'res.lang',
            'Default Language',
            help=
            "Choose the language which will be used for the Default Value in Magento"
        ),
        'active':
        fields.boolean('Active'),
        'magento_referential':
        fields.function(_is_magento_referential,
                        type="boolean",
                        method=True,
                        string="Magento Referential"),
        'last_imported_product_id':
        fields.integer(
            'Last Imported Product Id',
            help=
            "Product are imported one by one. This is the magento id of the last product imported. If you clear it all product will be imported"
        ),
        'last_imported_partner_id':
        fields.integer(
            'Last Imported Partner Id',
            help=
            "Partners are imported one by one. This is the magento id of the last partner imported. If you clear it all partners will be imported"
        ),
        'import_all_attributs':
        fields.boolean(
            'Import all attributs',
            help=
            "If the option is uncheck only the attributs that doesn't exist in OpenERP will be imported"
        ),
        'import_image_with_product':
        fields.boolean(
            'With image',
            help=
            "If the option is check the product's image and the product will be imported at the same time and so the step '7-import images' is not needed"
        ),
        'import_links_with_product':
        fields.boolean(
            'With links',
            help=
            "If the option is check the product's links (Up-Sell, Cross-Sell, Related) and the product will be imported at the same time and so the step '8-import links' is not needed"
        ),
    }

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

    def external_connection(self, cr, uid, id, DEBUG=False, context=None):
        if isinstance(id, list):
            id = id[0]
        referential = self.browse(cr, uid, id)
        if 'magento' in referential.type_id.name.lower():
            attr_conn = Connection(referential.location,
                                   referential.apiusername,
                                   referential.apipass, DEBUG)
            return attr_conn.connect() and attr_conn or False
        else:
            return super(external_referential,
                         self).external_connection(cr,
                                                   uid,
                                                   id,
                                                   DEBUG=DEBUG,
                                                   context=context)

    def connect(self, cr, uid, id, context=None):
        if isinstance(id, (list, tuple)):
            if not len(id) == 1:
                raise osv.except_osv(
                    _("Error"), _("Connect should be only call with one id"))
            else:
                id = id[0]
            core_imp_conn = self.external_connection(cr,
                                                     uid,
                                                     id,
                                                     DEBUG,
                                                     context=context)
            if core_imp_conn.connect():
                return core_imp_conn
            else:
                raise osv.except_osv(
                    _("Connection Error"),
                    _("Could not connect to server\nCheck location, username & password."
                      ))

        return False

    def core_sync(self, cr, uid, ids, context=None):
        filter = []
        for referential_id in ids:
            core_imp_conn = self.external_connection(cr,
                                                     uid,
                                                     referential_id,
                                                     DEBUG,
                                                     context=context)
            self.pool.get('external.shop.group').mage_import_base(
                cr,
                uid,
                core_imp_conn,
                referential_id,
                defaults={'referential_id': referential_id})
            self.pool.get('sale.shop').mage_import_base(
                cr, uid, core_imp_conn, referential_id, {
                    'magento_shop':
                    True,
                    'company_id':
                    self.pool.get('res.users').browse(cr, uid,
                                                      uid).company_id.id
                })
            self.pool.get('magerp.storeviews').mage_import_base(cr,
                                                                uid,
                                                                core_imp_conn,
                                                                referential_id,
                                                                defaults={})
        return True

    def sync_categs(self, cr, uid, ids, context=None):
        for referential_id in ids:
            pro_cat_conn = self.external_connection(cr,
                                                    uid,
                                                    referential_id,
                                                    DEBUG,
                                                    context=context)
            confirmation = pro_cat_conn.call('catalog_category.currentStore',
                                             [0])  #Set browse to root store
            if confirmation:
                categ_tree = pro_cat_conn.call(
                    'catalog_category.tree')  #Get the tree
                self.pool.get('product.category').record_entire_tree(
                    cr, uid, referential_id, pro_cat_conn, categ_tree, DEBUG)
                #exp_ids = self.pool.get('product.category').search(cr,uid,[('exportable','=',True)])
                #self.pool.get('product.category').ext_export(cr,uid,exp_ids,[referential_id],{},{'conn_obj':pro_cat_conn})
        return True

    def sync_attribs(self, cr, uid, ids, context=None):
        attr_obj = self.pool.get('magerp.product_attributes')
        attr_set_obj = self.pool.get('magerp.product_attribute_set')
        for referential in self.browse(cr, uid, ids, context=context):
            attr_conn = referential.external_connection(DEBUG, context=context)
            attrib_set_ids = attr_set_obj.search(
                cr, uid, [('referential_id', '=', referential.id)])
            attrib_sets = attr_set_obj.read(cr, uid, attrib_set_ids,
                                            ['magento_id'])
            #Get all attribute set ids to get all attributes in one go
            all_attr_set_ids = attr_set_obj.get_all_extid_from_referential(
                cr, uid, referential.id, context=context)
            #Call magento for all attributes
            if referential.import_all_attributs:
                attributes_imported = []
            else:
                attributes_imported = attr_obj.get_all_extid_from_referential(
                    cr, uid, referential.id, context=context)
            import_cr = pooler.get_db(cr.dbname).cursor()
            try:
                for attr_set_id in all_attr_set_ids:
                    mage_inp = attr_conn.call(
                        'ol_catalog_product_attribute.list',
                        [attr_set_id])  #Get the tree
                    attribut_to_import = []
                    for attribut in mage_inp:
                        ext_id = attribut['attribute_id']
                        if not ext_id in attributes_imported:
                            attributes_imported.append(ext_id)
                            attr_obj.ext_import(
                                import_cr,
                                uid, [attribut],
                                referential.id,
                                defaults={'referential_id': referential.id},
                                context={'referential_id': referential.id})
                            import_cr.commit()
                    self._logger.info(
                        "All attributs for the attributs set id %s was succesfully imported"
                        % (attr_set_id))
                #Relate attribute sets & attributes
                mage_inp = {}
                #Pass in {attribute_set_id:{attributes},attribute_set_id2:{attributes}}
                #print "Attribute sets are:", attrib_sets
                #TODO find a solution in order to import the relation in a incremental way (maybe splitting this function in two)
                for each in attrib_sets:
                    mage_inp[each['magento_id']] = attr_conn.call(
                        'ol_catalog_product_attribute.relations',
                        [each['magento_id']])
                if mage_inp:
                    attr_set_obj.relate(import_cr, uid, mage_inp,
                                        referential.id, DEBUG)
                import_cr.commit()
            finally:
                import_cr.close()
        return True

    def sync_attrib_sets(self, cr, uid, ids, context=None):
        for referential_id in ids:
            attr_conn = self.external_connection(cr,
                                                 uid,
                                                 referential_id,
                                                 DEBUG,
                                                 context=context)
            filter = []
            self.pool.get('magerp.product_attribute_set').mage_import_base(
                cr, uid, attr_conn, referential_id,
                {'referential_id': referential_id}, {'ids_or_filter': filter})
        return True

    def sync_attrib_groups(self, cr, uid, ids, context=None):
        for referential_id in ids:
            attr_conn = self.external_connection(cr,
                                                 uid,
                                                 referential_id,
                                                 DEBUG,
                                                 context=context)
            attrset_ids = self.pool.get(
                'magerp.product_attribute_set').get_all_mage_ids(
                    cr, uid, [], referential_id)
            filter = [{'attribute_set_id': {'in': attrset_ids}}]
            self.pool.get('magerp.product_attribute_groups').mage_import_base(
                cr, uid, attr_conn, referential_id,
                {'referential_id': referential_id}, {'ids_or_filter': filter})
        return True

    def sync_customer_groups(self, cr, uid, ids, context=None):
        for referential_id in ids:
            attr_conn = self.external_connection(cr,
                                                 uid,
                                                 referential_id,
                                                 DEBUG,
                                                 context=context)
            filter = []
            self.pool.get('res.partner.category').mage_import_base(
                cr, uid, attr_conn, referential_id, {},
                {'ids_or_filter': filter})
        return True

    def sync_customer_addresses(self, cr, uid, ids, context=None):
        for referential_id in ids:
            attr_conn = self.external_connection(cr,
                                                 uid,
                                                 referential_id,
                                                 DEBUG,
                                                 context=context)
            filter = []
            #self.pool.get('res.partner').mage_import(cr, uid, filter, attr_conn, referential_id, DEBUG)
            #TODO fix by retrieving customer list first
            self.pool.get('res.partner.address').mage_import_base(
                cr, uid, attr_conn, referential_id, {},
                {'ids_or_filter': filter})
        return True

    def _sync_product_storeview(self,
                                cr,
                                uid,
                                referential_id,
                                mag_connection,
                                ext_product_id,
                                storeview,
                                context=None):
        if context is None: context = {}
        #we really need to clean all magento call and give the posibility to force everythere to use the id as identifier
        product_info = mag_connection.call(
            'catalog_product.info',
            [ext_product_id, storeview.code, False, 'id'])
        ctx = context.copy()
        ctx.update({'magento_sku': product_info['sku']})
        defaults = {'magento_exportable': True}
        return self.pool.get('product.product').ext_import(cr,
                                                           uid, [product_info],
                                                           referential_id,
                                                           defaults=defaults,
                                                           context=ctx)

    def sync_products(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        prod_obj = self.pool.get('product.product')
        #        context.update({'dont_raise_error': True})
        for referential in self.browse(cr, uid, ids, context):
            attr_conn = referential.external_connection(DEBUG)
            filter = []
            if referential.last_imported_product_id:
                filters = {
                    'product_id': {
                        'gt': referential.last_imported_product_id
                    }
                }
                filters.update(self.SYNC_PRODUCT_FILTERS)
                filter = [filters]
            #TODO call method should be not harcoded. Need refactoring
            ext_product_ids = attr_conn.call('ol_catalog_product.search',
                                             filter)
            ext_product_ids = [x['product_id'] for x in ext_product_ids]
            storeview_obj = self.pool.get('magerp.storeviews')

            #get all instance storeviews
            storeview_ids = []
            for website in referential.shop_group_ids:
                for shop in website.shop_ids:
                    for storeview in shop.storeview_ids:
                        storeview_ids += [storeview.id]

            lang_2_storeview = {}
            for storeview in storeview_obj.browse(cr, uid, storeview_ids,
                                                  context):
                #get lang of the storeview
                lang_id = storeview.lang_id
                if lang_id:
                    lang = lang_id.code
                else:
                    osv.except_osv(
                        _('Warning!'),
                        _('The storeviews have no language defined'))
                    lang = referential.default_lang_id.code
                if not lang_2_storeview.get(lang, False):
                    lang_2_storeview[lang] = storeview

            if referential.import_links_with_product:
                link_types = self.get_magento_product_link_types(
                    cr, uid, referential.id, attr_conn, context=context)

            import_cr = pooler.get_db(cr.dbname).cursor()
            try:
                for ext_product_id in ext_product_ids:
                    for lang, storeview in lang_2_storeview.iteritems():
                        ctx = context.copy()
                        ctx.update({'lang': lang})
                        res = self._sync_product_storeview(import_cr,
                                                           uid,
                                                           referential.id,
                                                           attr_conn,
                                                           ext_product_id,
                                                           storeview,
                                                           context=ctx)
                    product_id = (res.get('create_ids')
                                  or res.get('write_ids'))[0]
                    if referential.import_image_with_product:
                        prod_obj.import_product_image(import_cr,
                                                      uid,
                                                      product_id,
                                                      referential.id,
                                                      attr_conn,
                                                      ext_id=ext_product_id,
                                                      context=context)
                    if referential.import_links_with_product:
                        prod_obj.mag_import_product_links_types(
                            import_cr,
                            uid,
                            product_id,
                            link_types,
                            referential.id,
                            attr_conn,
                            context=context)
                    self.write(
                        import_cr,
                        uid,
                        referential.id,
                        {'last_imported_product_id': int(ext_product_id)},
                        context=context)
                    import_cr.commit()
            finally:
                import_cr.close()
        return True

    def get_magento_product_link_types(self,
                                       cr,
                                       uid,
                                       ids,
                                       conn=None,
                                       context=None):
        if not conn:
            conn = self.external_connection(cr,
                                            uid,
                                            ids,
                                            DEBUG,
                                            context=context)
        return conn.call('catalog_product_link.types')

    def sync_images(self, cr, uid, ids, context=None):
        product_obj = self.pool.get('product.product')
        image_obj = self.pool.get('product.images')
        import_cr = pooler.get_db(cr.dbname).cursor()
        try:
            for referential_id in ids:
                conn = self.external_connection(cr,
                                                uid,
                                                referential_id,
                                                DEBUG,
                                                context=context)
                product_ids = product_obj.get_all_oeid_from_referential(
                    cr, uid, referential_id, context=context)
                for product_id in product_ids:
                    product_obj.import_product_image(import_cr,
                                                     uid,
                                                     product_id,
                                                     referential_id,
                                                     conn,
                                                     context=context)
                    import_cr.commit()
        finally:
            import_cr.close()
        return True

    def sync_product_links(self, cr, uid, ids, context=None):
        if context is None: context = {}
        for referential in self.browse(cr, uid, ids, context):
            conn = referential.external_connection(DEBUG)
            exportable_product_ids = []
            for shop_group in referential.shop_group_ids:
                for shop in shop_group.shop_ids:
                    exportable_product_ids.extend([
                        product.id for product in shop.exportable_product_ids
                    ])
            exportable_product_ids = list(set(exportable_product_ids))
            self.pool.get('product.product').mag_import_product_links(
                cr,
                uid,
                exportable_product_ids,
                referential.id,
                conn,
                context=context)
        return True

    def export_products(self, cr, uid, ids, context=None):
        if context is None: context = {}
        shop_ids = self.pool.get('sale.shop').search(cr, uid, [])
        for referential_id in ids:
            for shop in self.pool.get('sale.shop').browse(
                    cr, uid, shop_ids, context):
                context['conn_obj'] = self.external_connection(cr,
                                                               uid,
                                                               referential_id,
                                                               context=context)
                #shop.export_catalog
                tools.debug((
                    cr,
                    uid,
                    shop,
                    context,
                ))
                shop.export_products(cr, uid, shop, context)
        return True

    def sync_partner(self, cr, uid, ids, context=None):
        def next_partners(connection, start, step):
            filters = {'customer_id': {'in': range(start, start + step)}}
            filters.update(self.SYNC_PARTNER_FILTERS)
            filter = [filters]
            return attr_conn.call('customer.list', filter)

        for referential in self.browse(cr, uid, ids, context):
            attr_conn = referential.external_connection(DEBUG)
            last_imported_id = 0
            if referential.last_imported_partner_id:
                last_imported_id = referential.last_imported_partner_id

            ext_customer_ids = next_partners(attr_conn, last_imported_id + 1,
                                             self.SYNC_PARTNER_STEP)
            import_cr = pooler.get_db(cr.dbname).cursor()
            try:
                while ext_customer_ids:
                    for ext_customer_id in ext_customer_ids:
                        customer_info = attr_conn.call(
                            'customer.info', [ext_customer_id['customer_id']])
                        customer_address_info = attr_conn.call(
                            'customer_address.list',
                            [ext_customer_id['customer_id']])

                        address_info = False
                        if customer_address_info:
                            address_info = customer_address_info[0]
                            address_info['customer_id'] = ext_customer_id[
                                'customer_id']
                            address_info['email'] = customer_info['email']

                        self.pool.get('res.partner').ext_import(
                            import_cr,
                            uid, [customer_info],
                            referential.id,
                            context=context)
                        if address_info:
                            self.pool.get('res.partner.address').ext_import(
                                import_cr,
                                uid, [address_info],
                                referential.id,
                                context=context)

                        last_imported_id = int(ext_customer_id['customer_id'])
                        self.write(
                            import_cr,
                            uid,
                            referential.id,
                            {'last_imported_partner_id': last_imported_id},
                            context=context)
                        import_cr.commit()
                    ext_customer_ids = next_partners(attr_conn,
                                                     last_imported_id + 1,
                                                     self.SYNC_PARTNER_STEP)
            finally:
                import_cr.close()
        return True

    def sync_newsletter(self, cr, uid, ids, context=None):
        #update first all customer
        self.sync_partner(cr, uid, ids, context)

        partner_obj = self.pool.get('res.partner')

        for referential_id in ids:
            attr_conn = self.external_connection(cr,
                                                 uid,
                                                 referential_id,
                                                 DEBUG,
                                                 context=context)
            filter = []
            list_subscribers = attr_conn.call('ol_customer_subscriber.list')
            result = []
            for each in list_subscribers:
                each_subscribers_info = attr_conn.call(
                    'ol_customer_subscriber.info', [each])

                # search this customer. If exist, update your newsletter subscription
                partner_ids = partner_obj.search(
                    cr, uid, [('emailid', '=',
                               each_subscribers_info[0]['subscriber_email'])])
                if partner_ids:
                    #unsubscriber magento value: 3
                    if int(each_subscribers_info[0]['subscriber_status']) == 1:
                        subscriber_status = 1
                    else:
                        subscriber_status = 0
                    partner_obj.write(cr, uid, partner_ids[0],
                                      {'mag_newsletter': subscriber_status})
        return True

    def sync_newsletter_unsubscriber(self, cr, uid, ids, context=None):
        partner_obj = self.pool.get('res.partner')

        for referential_id in ids:
            attr_conn = self.external_connection(cr,
                                                 uid,
                                                 referential_id,
                                                 DEBUG,
                                                 context=context)
            partner_ids = partner_obj.search(cr, uid,
                                             [('mag_newsletter', '!=', 1),
                                              ('emailid', '!=', '')])

            print partner_ids

            for partner in partner_obj.browse(cr, uid, partner_ids):
                print partner.emailid
                if partner.emailid:
                    attr_conn.call('ol_customer_subscriber.delete',
                                   [partner.emailid])

        return True

    # Schedules functions ============ #
    def run_import_newsletter_scheduler(self, cr, uid, context=None):
        if context is None:
            context = {}

        referential_ids = self.search(cr, uid, [('active', '=', 1)])

        if referential_ids:
            self.sync_newsletter(cr, uid, referential_ids, context)
        if DEBUG:
            print "run_import_newsletter_scheduler: %s" % referential_ids

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

        referential_ids = self.search(cr, uid, [('active', '=', 1)])

        if referential_ids:
            self.sync_newsletter_unsubscriber(cr, uid, referential_ids,
                                              context)
        if DEBUG:
            print "run_import_newsletter_unsubscriber_scheduler: %s" % referential_ids
예제 #39
0
    _columns = {
        'active':fields.function(_get_active, method=True,type='boolean', store=False),
        'ask_id': fields.many2one('openstc.ask', 'Demande', ondelete='set null', select="1"),
        'project_id': fields.many2one('project.project', 'Intervention', ondelete='set null'),
        'equipment_ids':fields.many2many('openstc.equipment', 'openstc_equipment_task_rel', 'task_id', 'equipment_id', 'Equipments'),
        'consumable_ids':fields.many2many('openbase.consumable', 'openbase_consumable_task_rel', 'task_id', 'consumable_id', 'Fournitures'),
        'parent_id': fields.many2one('project.task', 'Parent Task'),
        'intervention_assignement_id':fields.many2one('openstc.intervention.assignement', 'Assignement'),
        'absent_type_id':fields.many2one('openstc.absent.type', 'Type d''abscence'),
        'category_id':fields.many2one('openstc.task.category', 'Category'),
        'state': fields.selection([('absent', 'Absent'),('draft', 'New'),('open', 'In Progress'),('pending', 'Pending'), ('done', 'Done'), ('cancelled', 'Cancelled')], 'State', readonly=True, required=True,
                                  help='If the task is created the state is \'Draft\'.\n If the task is started, the state becomes \'In Progress\'.\n If review is needed the task is in \'Pending\' state.\
                                  \n If the task is over, the states is set to \'Done\'.'),
        'team_id': fields.many2one('openstc.team', 'Team'),

        'km': fields.integer('Km', select=1),
        'oil_qtity': fields.float('oil quantity', select=1),
        'oil_price': fields.float('oil price', select=1),
        'site1':fields.related('project_id','site1',type='many2one',relation='openstc.site', string='Site',store={'project.task':[lambda self,cr,uid,ids,ctx={}:ids, ['project_id'], 10],
                                                                                                                  'project.project':[_get_task_from_inter, ['site1'],11]}),
        'inter_desc': fields.related('project_id', 'description', type='char'),
        'inter_equipment': fields.related('project_id', 'equipment_id', type='many2one',relation='openstc.equipment'),
        'cancel_reason': fields.text('Cancel reason'),
        'agent_or_team_name':fields.function(_get_agent_or_team_name, type='char', method=True, store=False),
        'cost':fields.float('Cost', type='float', digits=(5,2)),
        'hr_cost':fields.float('Cost', type='float', digits=(5,2)),
        'equipment_cost':fields.float('Cost', type='float', digits=(5,2)),
        'consumable_cost':fields.float('Cost', type='float', digits=(5,2)),
    }

    _defaults = {'active': lambda *a: True, 'user_id':None}
예제 #40
0
class tcv_sigesic_1201(osv.osv):

    _name = 'tcv.sigesic.1201'

    _description = 'Marketed Goods\n' + \
                   'Bienes Comercializados No producidos por la U.E.'

    _csv_file_name = 'bienes_comercializacion_%s.csv'

    def _csv_header(self, cr, uid, ids, context):
        return (
            'CODIGO ARANCELARIO',
            'NOMBRE DEL BIEN',
            'ESPECIFICACIONES TECNICAS',
            'MARCA',
            'UNIDAD DE MEDIDA',
            'ORIGEN NACIONAL (SI/NO)',
            'PESO UNITARIO (KG/U)',
            'CANTIDAD VENDIDA ANHO CONCLUIDO',
            'MONTO TOTAL FACTURADO ANHO CONCLUIDO (Bs.)'
            )

    ##-------------------------------------------------------------------------

    ##------------------------------------------------------- _internal methods

    ##--------------------------------------------------------- function fields

    _columns = {
        'hs_code_id': fields.many2one('tcv.sigesic.9901', 'HS Code',
                                      ondelete='restrict'),
        'name': fields.char('Name', size=64, required=False, readonly=False,
                            help="Denominación o nombre comercial del " +
                            "producto"),
        'product_id': fields.many2one('product.product', 'Product',
                                      ondelete='restrict', required=True),
        'tech_specs': fields.related('product_id', 'tech_specs', type='text',
                                     string='Tech specs', store=False,
                                     readonly=True,
                                     help="Composición o características " +
                                     "físicas y/o químicas del producto"),
        'uom_id': fields.related('product_id', 'uom_id', type='many2one',
                                 relation='product.uom', string='Uom',
                                 store=False, readonly=True),
        'local_good': fields.selection([('yes', 'Si'),
                                        ('no', 'No')], string='Local good'),
        'weight': fields.related('product_id', 'weight', type='float',
                                 string='Gross weight', store=False,
                                 readonly=True),
        'sale_qty': fields.float('Sale qty', digits=(15, 2), readonly=False,
                                 help="Cantidad total vendida del bien, " +
                                 "para el año inmediatamente concluido, de " +
                                 "acuerdo a la Udm"),
        'sale_amount': fields.float('Sale amount', digits=(15, 2),
                                    readonly=False,
                                    help="Monto total facturado del bien " +
                                    "expresado en Bs., para el año " +
                                    "inmediatamente concluido."),
        'data_year': fields.integer(
            'Year', required=True,
            help="El año al que corresponden los datos"),
        }

    _defaults = {
        }

    _sql_constraints = [
        ('product_id_uniq', 'UNIQUE(data_year, product_id)',
         'The product must be unique!'),
        ]

    ##-------------------------------------------------------------------------

    ##---------------------------------------------------------- public methods

    def get_data_lines_ids(self, cr, uid, line_id, data_year, context):
        return self.search(
            cr, uid, [('data_year', '=', data_year)])

    def get_data_line(self, cr, uid, line_id, context):
        def str_uom(uom):
            uoms = {'m2': u'm²',
                    'm3': u'm³',
                    'Unidad': u'unid',
                    'ml': u'm',
                    }
            return uom and uoms.get(uom, uom) or ''

        def str_line(line):
            return line and line.replace(';', ',').strip() or ''

        line = self.browse(cr, uid, line_id, context=context)
        return (str_line(line.hs_code_id and line.hs_code_id.code),
                str_line(line.name),
                str_line(line.tech_specs),
                str_line(line.product_id and line.product_id.name),
                str_uom(line.uom_id and line.uom_id.name),
                str_uom('SI' if line.local_good == 'yes' else 'NO'),
                str_line('%.2f' % line.weight),
                str_line('%.2f' % line.sale_qty),
                str_line('%.2f' % line.sale_amount),
                )

    ##-------------------------------------------------------- buttons (object)

    ##------------------------------------------------------------ on_change...

    def on_change_hs_code_id(self, cr, uid, ids, hs_code_id, product_id):
        if product_id and hs_code_id:
            obj_prd = self.pool.get('product.product')
            prd = obj_prd.browse(cr, uid, product_id, context=None)
            if not prd.hs_code or hs_code_id != prd.hs_code:
                obj_hsc = self.pool.get('tcv.sigesic.9901')
                hsc = obj_hsc.browse(cr, uid, hs_code_id, context=None)
                obj_prd.write(cr, uid, prd.id, {'hs_code': hsc.code},
                              context=None)
        return {'value': {}}

    def on_change_product_id(self, cr, uid, ids, product_id):
        res = {}
        if product_id:
            obj_prd = self.pool.get('product.product')
            prd = obj_prd.browse(cr, uid, product_id, context=None)
            cntry = prd.origin_country_id and prd.origin_country_id.code or ''
            res.update({'tech_specs': prd.tech_specs,
                        'uom_id': prd.uom_id.id,
                        'weight': prd.weight,
                        'local_good': 'yes' if cntry == 'VE' else 'no'})
            if prd.hs_code:
                ids = self.pool.get('tcv.sigesic.9901').\
                    search(cr, uid, [('code', '=', prd.hs_code)])
                if ids and len(ids) == 1:
                    res.update({'hs_code_id': ids[0]})
        return {'value': res}
class sale_product_multistep_configurator_configurator_step(osv.osv):
    _name = "sale_product_multistep_configurator.configurator.step"
    _columns = {
        'name':
        fields.char('Value Name', size=64, select=1),  #TODO related?
        'model_id':
        fields.many2one('ir.model', 'Object ID', required=True, select=True),
        'sequence':
        fields.integer('Sequence',
                       help="Determine in which order step are executed"),
    }
    _order = 'sequence'

    def update_context_before_step(self, cr, user, context={}):
        """Hook to allow a configurator step module to update the context before running, for instance to skip this step."""
        return context

    def next_step(self, cr, user, context={}):
        context = self.update_context_before_step(cr, user, context)
        index = context.get('next_step', 0)
        context.update({'next_step': index + 1})
        model_list = context.get('step_list', False)
        if index and model_list and index < len(model_list):
            return {
                'view_type': 'form',
                "view_mode": 'form',
                'res_model': model_list[index],
                'type': 'ir.actions.act_window',
                'target': 'new',
                'context': context,
            }
        else:
            if context.get('active_id_object_type',
                           False) == 'sale.order.line':
                return {
                    'type': 'ir.actions.act_window_close',
                }
            else:

                #fake the product_id_change event occuring when manually selecting the product
                uid = user
                order_line = self.pool.get('sale.order.line').browse(
                    cr, uid, context.get('sol_id', False), {})
                sale_order = order_line.order_id
                pricelist = sale_order.pricelist_id.id
                date_order = sale_order.date_order
                fiscal_position = sale_order.fiscal_position.id
                qty_uos = order_line.product_uos_qty
                uos = order_line.product_uos.id
                partner_id = sale_order.partner_id.id
                packaging = order_line.product_packaging.id
                product = order_line.product_id.id
                qty = order_line.product_uom_qty
                uom = order_line.product_uom.id
                qty_uos = order_line.product_uos_qty
                uos = order_line.product_uos.id
                name = order_line.name
                lang = context.get('lang', False)
                update_tax = True
                flag = True  #TODO sure?

                on_change_result = self.pool.get(
                    'sale.order.line').product_id_change(
                        cr, uid, [order_line.id], pricelist, product, qty, uom,
                        qty_uos, uos, name, partner_id, lang, update_tax,
                        date_order, packaging, fiscal_position, flag)

                on_change_result['value']['tax_id'] = [
                    (6, 0, on_change_result['value']['tax_id'])
                ]  #deal with many2many and sucking geek Tiny API
                self.pool.get('sale.order.line').write(
                    cr, uid, [order_line.id], on_change_result['value'])

                return {
                    'view_type': 'form',
                    "view_mode": 'form',
                    'res_model': 'sale.order.line',
                    'type': 'ir.actions.act_window',
                    'target': 'new',
                    'res_id': context.get('sol_id', False),
                    'buttons': True,
                    'context': context,
                }
예제 #42
0
        ],'Template source', select=True),
        'parser_def': fields.text('Parser Definition'),
        'parser_loc':fields.char('Parser location', size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}"),
        'parser_state':fields.selection([
            ('default',_('Default')),
            ('def',_('Definition')),
            ('loc',_('Location')),
        ],'State of Parser', select=True),
        'in_format': fields.selection(_get_in_mimetypes, 'Template Mime-type'),
        'out_format':fields.many2one('report.mimetypes', 'Output Mime-type'),
        'report_sxw_content': fields.function(_report_content,
            fnct_inv=_report_content_inv, method=True,
            type='binary', string='SXW content',),
        'active':fields.boolean('Active'),
        'report_wizard':fields.boolean('Report Wizard'),
        'copies': fields.integer('Number of copies'),
        'fallback_false':fields.boolean('Disable format fallback'),
        
    }

    def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
        ##### check new model fields, that while not exist in database #####
        cr.execute("SELECT name FROM ir_model_fields WHERE model = 'ir.actions.report.xml'")
        true_fields = [val[0] for val in cr.fetchall()]
        true_fields.append(self.CONCURRENCY_CHECK_FIELD)
        if fields:
            exclude_fields = set(fields).difference(set(true_fields))
            fields = filter(lambda f: f not in exclude_fields, fields)
        else:
            exclude_fields = []
        ####################################################################
     "version": fields.char("Versions", size=64, readonly=False),
     "certificate": fields.char("Certificate Code", size=42, required=False, readonly=False),
     "path": fields.function(_get_module_path, method=True, string="Path", type="char", size=512, readonly=True),
     "technical_certificate": fields.selection(
         [("not_started", "Not Started"), ("failed", "Failed"), ("succeeded", "Succeeded"), ("skipped", "Skipped")],
         "Technical Certification",
     ),
     "functional_certificate": fields.selection(
         [("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"),
 }
예제 #44
0
class account_invoice_report(osv.osv):
    _name = "account.invoice.report"
    _description = "Invoices Statistics"
    _auto = False
    _rec_name = 'date'
    _columns = {
        'date':
        fields.date('Date', readonly=True),
        'year':
        fields.char('Year', size=4, readonly=True),
        'day':
        fields.char('Day', size=128, readonly=True),
        'month':
        fields.selection([('01', 'January'), ('02', 'February'),
                          ('03', 'March'), ('04', 'April'), ('05', 'May'),
                          ('06', 'June'), ('07', 'July'), ('08', 'August'),
                          ('09', 'September'), ('10', 'October'),
                          ('11', 'November'), ('12', 'December')],
                         'Month',
                         readonly=True),
        'product_id':
        fields.many2one('product.product', 'Product', readonly=True),
        'product_qty':
        fields.float('Qty', readonly=True),
        'uom_name':
        fields.char('Reference UoM', size=128, readonly=True),
        'payment_term':
        fields.many2one('account.payment.term', 'Payment Term', readonly=True),
        'period_id':
        fields.many2one('account.period',
                        'Force Period',
                        domain=[('state', '<>', 'done')],
                        readonly=True),
        'fiscal_position':
        fields.many2one('account.fiscal.position',
                        'Fiscal Position',
                        readonly=True),
        'currency_id':
        fields.many2one('res.currency', 'Currency', readonly=True),
        'categ_id':
        fields.many2one('product.category',
                        'Category of Product',
                        readonly=True),
        'journal_id':
        fields.many2one('account.journal', 'Journal', readonly=True),
        'partner_id':
        fields.many2one('res.partner', 'Partner', readonly=True),
        'company_id':
        fields.many2one('res.company', 'Company', readonly=True),
        'user_id':
        fields.many2one('res.users', 'Salesman', readonly=True),
        'price_total':
        fields.float('Total Without Tax', readonly=True),
        'price_total_tax':
        fields.float('Total With Tax', readonly=True),
        'price_average':
        fields.float('Average Price', readonly=True, group_operator="avg"),
        'currency_rate':
        fields.float('Currency Rate', readonly=True),
        'nbr':
        fields.integer('# of Lines', readonly=True),
        'type':
        fields.selection([
            ('out_invoice', 'Customer Invoice'),
            ('in_invoice', 'Supplier Invoice'),
            ('out_refund', 'Customer Refund'),
            ('in_refund', 'Supplier Refund'),
        ],
                         'Type',
                         readonly=True),
        'state':
        fields.selection([('draft', 'Draft'), ('proforma', 'Pro-forma'),
                          ('proforma2', 'Pro-forma'), ('open', 'Open'),
                          ('paid', 'Done'), ('cancel', 'Cancelled')],
                         'Invoice State',
                         readonly=True),
        'date_due':
        fields.date('Due Date', readonly=True),
        'address_contact_id':
        fields.many2one('res.partner.address',
                        'Contact Address Name',
                        readonly=True),
        'address_invoice_id':
        fields.many2one('res.partner.address',
                        'Invoice Address Name',
                        readonly=True),
        'account_id':
        fields.many2one('account.account', 'Account', readonly=True),
        'partner_bank_id':
        fields.many2one('res.partner.bank', 'Bank Account', readonly=True),
        'residual':
        fields.float('Total Residual', readonly=True),
        'delay_to_pay':
        fields.float('Avg. Delay To Pay', readonly=True, group_operator="avg"),
        'due_delay':
        fields.float('Avg. Due Delay', readonly=True, group_operator="avg"),
    }
    _order = 'date desc'

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'account_invoice_report')
        cr.execute("""
            create or replace view account_invoice_report as (
                 select min(ail.id) as id,
                    ai.date_invoice as date,
                    to_char(ai.date_invoice, 'YYYY') as year,
                    to_char(ai.date_invoice, 'MM') as month,
                    to_char(ai.date_invoice, 'YYYY-MM-DD') as day,
                    ail.product_id,
                    ai.partner_id as partner_id,
                    ai.payment_term as payment_term,
                    ai.period_id as period_id,
                    (case when u.uom_type not in ('reference') then
                        (select name from product_uom where uom_type='reference' and category_id=u.category_id)
                    else
                        u.name
                    end) as uom_name,
                    ai.currency_id as currency_id,
                    ai.journal_id as journal_id,
                    ai.fiscal_position as fiscal_position,
                    ai.user_id as user_id,
                    ai.company_id as company_id,
                    count(ail.*) as nbr,
                    ai.type as type,
                    ai.state,
                    pt.categ_id,
                    ai.date_due as date_due,
                    ai.address_contact_id as address_contact_id,
                    ai.address_invoice_id as address_invoice_id,
                    ai.account_id as account_id,
                    ai.partner_bank_id as partner_bank_id,
                    sum(case when ai.type in ('out_refund','in_invoice') then
                         ail.quantity / u.factor * -1
                        else
                         ail.quantity / u.factor
                        end) as product_qty,
                    sum(case when ai.type in ('out_refund','in_invoice') then
                         ail.quantity*ail.price_unit * -1
                        else
                         ail.quantity*ail.price_unit
                        end) / cr.rate as price_total,
                    sum(case when ai.type in ('out_refund','in_invoice') then
                         ai.amount_total * -1
                        else
                         ai.amount_total
                         end) / (CASE WHEN 
                              (select count(l.id) from account_invoice_line as l
                               left join account_invoice as a ON (a.id=l.invoice_id)
                               where a.id=ai.id) <> 0 
                            THEN 
                              (select count(l.id) from account_invoice_line as l
                               left join account_invoice as a ON (a.id=l.invoice_id)
                               where a.id=ai.id) 
                            ELSE 1 
                            END) / cr.rate as price_total_tax,
                    (case when ai.type in ('out_refund','in_invoice') then
                      sum(ail.quantity*ail.price_unit*-1)
                    else
                      sum(ail.quantity*ail.price_unit)
                    end) / (CASE WHEN
                         (case when ai.type in ('out_refund','in_invoice') 
                          then sum(ail.quantity/u.factor*-1)
                          else sum(ail.quantity/u.factor) end) <> 0 
                       THEN 
                         (case when ai.type in ('out_refund','in_invoice') 
                          then sum(ail.quantity/u.factor*-1)
                          else sum(ail.quantity/u.factor) end) 
                       ELSE 1 
                       END)
                     / cr.rate as price_average,

                    cr.rate as currency_rate,
                    sum((select extract(epoch from avg(date_trunc('day',aml.date_created)-date_trunc('day',l.create_date)))/(24*60*60)::decimal(16,2)
                        from account_move_line as aml
                        left join account_invoice as a ON (a.move_id=aml.move_id)
                        left join account_invoice_line as l ON (a.id=l.invoice_id)
                        where a.id=ai.id)) as delay_to_pay,
                    sum((select extract(epoch from avg(date_trunc('day',a.date_due)-date_trunc('day',a.date_invoice)))/(24*60*60)::decimal(16,2)
                        from account_move_line as aml
                        left join account_invoice as a ON (a.move_id=aml.move_id)
                        left join account_invoice_line as l ON (a.id=l.invoice_id)
                        where a.id=ai.id)) as due_delay,
                    (case when ai.type in ('out_refund','in_invoice') then
                      ai.residual * -1
                    else
                      ai.residual
                    end)/ (CASE WHEN 
                        (select count(l.id) from account_invoice_line as l
                         left join account_invoice as a ON (a.id=l.invoice_id)
                         where a.id=ai.id) <> 0 
                       THEN
                        (select count(l.id) from account_invoice_line as l
                         left join account_invoice as a ON (a.id=l.invoice_id)
                         where a.id=ai.id) 
                       ELSE 1 
                       END) / cr.rate as residual
                from account_invoice_line as ail
                left join account_invoice as ai ON (ai.id=ail.invoice_id)
                left join product_template pt on (pt.id=ail.product_id)
                left join product_uom u on (u.id=ail.uos_id),
                res_currency_rate cr
                where cr.id in (select id from res_currency_rate cr2  where (cr2.currency_id = ai.currency_id)
                and ((ai.date_invoice is not null and cr.name <= ai.date_invoice) or (ai.date_invoice is null and cr.name <= NOW())) limit 1)
                group by ail.product_id,
                    ai.date_invoice,
                    ai.id,
                    cr.rate,
                    to_char(ai.date_invoice, 'YYYY'),
                    to_char(ai.date_invoice, 'MM'),
                    to_char(ai.date_invoice, 'YYYY-MM-DD'),
                    ai.partner_id,
                    ai.payment_term,
                    ai.period_id,
                    u.name,
                    ai.currency_id,
                    ai.journal_id,
                    ai.fiscal_position,
                    ai.user_id,
                    ai.company_id,
                    ai.type,
                    ai.state,
                    pt.categ_id,
                    ai.date_due,
                    ai.address_contact_id,
                    ai.address_invoice_id,
                    ai.account_id,
                    ai.partner_bank_id,
                    ai.residual,
                    ai.amount_total,
                    u.uom_type,
                    u.category_id
            )
        """)
예제 #45
0
                # ignored, just a consequence of the previous exception
                pass
        raise osv.except_osv("Connection Test Succeeded!", "Everything seems properly set up!")

    _name = 'vehicle.config'
    _description = 'Configuration for Vehicle Fits ftp link'
    _table = 'vehiclefits_config'
    _columns = {

        'name': fields.char('Name', size=20),
        'vf_url': fields.char('Url', size=30, help="Url to Magento Web"),
        'sftp_user': fields.char('Ftp user', size=20, required=True),
        'sftp_password': fields.char('Ftp password', size=20, required=False),
        'sftp_pem': fields.binary('RSA Key', required=True),
        'sftp_host': fields.char('FTP IP host', size=15, required=True),
        'sftp_port': fields.integer('Ftp Port', help='Port of the connection'),
        'sftp_local_file': fields.char('Full path to local csv file'),
        'sftp_remote_file': fields.char('Name of remote file', help="Default name for import is"
                                                                    " product-fitments-import.csv"),
        'sftp_remote_dir': fields.char('Full remote path'),
        'erp_host': fields.char('Erp host', size=20, required=True),
        'erp_user': fields.char('Erp DB user', size=15, required=True),
        'erp_password': fields.char('Erp password', size=20, required=True),
        'erp_db': fields.char('Erp DB', size=20, required=True)

    }


vehicle_config()

예제 #46
0
class tree_node(osv.osv):
    _name = 'via.reporting.tree.node'
    _description = 'VIA Reporting Tree Node'
    __doc__ = (
        'A VIA Reporting Tree Node object is used to construct a tree of'
        ' objects of this class, each of which is associated with zero'
        ' or more objects of the same model.')
    _order = 'sequence'
    _parent_order = _order
    _parent_store = True

    def _auto_init(self, cr, context=None):
        super(tree_node, self)._auto_init(cr, context=context)
        create_composite_type(cr, 'via_tree_node', [('id', 'BIGINT'),
                                                    ('parent_id', 'BIGINT')])
        create_composite_type(cr, 'via_tree_node_unrolled',
                              [('id', 'BIGINT'), ('parent_id', 'BIGINT'),
                               ('level', 'BIGINT'), ('parent_left', 'BIGINT'),
                               ('parent_right', 'BIGINT')])
        create_composite_type(cr, 'via_tree_node_level_tagger_datum',
                              [('id', 'BIGINT'), ('parent_id', 'BIGINT'),
                               ('level', 'BIGINT'),
                               ('unrolling_pid', 'BIGINT'),
                               ('unique_id', 'BIGINT'),
                               ('unique_parent_id', 'BIGINT')])
        create_composite_type(cr, 'via_tree_node_child_count',
                              [('id', 'BIGINT'), ('parent_id', 'BIGINT'),
                               ('level', 'BIGINT'), ('unique_id', 'BIGINT'),
                               ('unique_parent_id', 'BIGINT'),
                               ('child_count', 'BIGINT')])
        create_plpgsql_proc(cr, 'via_tree_node_unroller',
                            [('IN', 'tree_nodes', 'VIA_TREE_NODE[]')],
                            'SETOF VIA_TREE_NODE_LEVEL_TAGGER_DATUM',
                            via_tree_node_unroller_def)
        create_plpgsql_proc(cr, 'via_tree_node_count_children', [
            ('IN', 'unrolled_tree_nodes', 'VIA_TREE_NODE_LEVEL_TAGGER_DATUM[]')
        ], 'SETOF VIA_TREE_NODE_CHILD_COUNT', via_tree_node_count_children_def)
        create_plpgsql_proc(cr, 'via_tree_node_parent_left_right_tagger', [
            ('IN', 'unrolled_tree_nodes', 'VIA_TREE_NODE_CHILD_COUNT[]')
        ], 'SETOF VIA_TREE_NODE_UNROLLED',
                            via_tree_node_parent_left_right_tagger_def)
        create_plpgsql_proc(cr, 'via_tree_node_level_tagger',
                            [('IN', 'tree_nodes', 'VIA_TREE_NODE[]')],
                            'SETOF VIA_TREE_NODE_UNROLLED',
                            via_tree_node_level_tagger_def)

    def copy(self, cr, uid, src_id, default=None, context=None):
        raise NotImplementedError(
            _('The copy method is not implemented on this'
              ' object !'))

    def copy_data(self, cr, uid, src_id, default=None, context=None):
        raise NotImplementedError(
            _('The copy_data method is not implemented on'
              ' this object !'))

    def _get_level(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        nodes = self.browse(cr, uid, ids, context=context)
        for node in nodes:
            level = 0
            if node.parent_id:
                obj = self.browse(cr, uid, node.parent_id.id)
                level = obj.level + 1
            res[node.id] = level
        return res

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

        tree_node_types = []
        tree_node_type = context.get(
            'via_reporting_tree.tree_node_specialization_name', False)
        if tree_node_type is False:
            tree_id = context.get('via_reporting_tree.tree_id', False)
            if tree_id is not False:
                tree_pool = self.pool.get('via.reporting.tree')
                tree = tree_pool.browse(cr, uid, tree_id, context)
                tree_node_types = [tree.tree_type_id.tree_node_type]
            else:
                # This happens when importing CSV data through the web client
                tree_node_types = list(
                    self._specialization_registry.iterkeys())
        else:
            tree_node_types = [tree_node_type]

        available_calcs = set()
        for type_ in tree_node_types:
            calcs = self._specialization_registry[type_].calculators
            for k in calcs.iterkeys():
                available_calcs.add(k)

        return [(calc, calc.capitalize()) for calc in available_calcs]

    _columns = {
        'company_id':
        fields.related('tree_id',
                       'company_id',
                       type='many2one',
                       relation='res.company',
                       string='Company',
                       store=True,
                       readonly=True),
        'tree_id':
        fields.many2one('via.reporting.tree', 'Tree', required=True),
        'tree_type_name':
        fields.related('tree_id',
                       'tree_type_id',
                       'name',
                       type='text',
                       string='Tree Type Name',
                       readonly=True),
        'tree_node_type':
        fields.related('tree_id',
                       'tree_type_id',
                       'tree_node_type',
                       type='char',
                       string='Tree Node Type',
                       readonly=True,
                       size=64),
        'sequence':
        fields.integer('Sequence', required=True),
        'name':
        fields.char('Name', size=128, required=True, select=True),
        'parent_id':
        fields.many2one('via.reporting.tree.node',
                        'Parent',
                        ondelete='cascade',
                        domain="[('tree_id','=',tree_id)]"),
        'parent_left':
        fields.integer('Parent Left', select=1),
        'parent_right':
        fields.integer('Parent Right', select=1),
        'level':
        fields.function(_get_level,
                        string='Level',
                        method=True,
                        store=True,
                        type='integer'),
        'children':
        fields.one2many('via.reporting.tree.node', 'parent_id', 'Children'),
        'calculation':
        fields.selection(_get_available_calculation, 'Method', required=True),
        'dummy_node':
        fields.boolean('Dummy Node'),
        'associated_node_ids':
        fields.many2many('via.reporting.tree.node',
                         'via_reporting_tree_node_rel', 'node_id',
                         'associate_id', 'Associated Nodes'),
        # Formatting attributes
        'bold':
        fields.boolean('Bold'),
        'italic':
        fields.boolean('Italic'),
        'underline':
        fields.boolean('Underline'),
        'blank_line':
        fields.boolean('Blank Line'),
        'title_line':
        fields.boolean('Title Line'),
    }

    def get_rtype(self, cr, uid, ids, context=None):
        def _get_rtype(bold=False,
                       italic=False,
                       underline=False,
                       blank_line=False,
                       title_line=False):
            return '%s-%s-%s-%s-%s' % (
                str(bold).lower(), str(italic).lower(), str(underline).lower(),
                str(blank_line).lower(), str(title_line).lower())

        if isinstance(ids, (int, long)) or len(ids) == 1:
            if type(ids) == list:
                ids = ids[0]
            o = self.browse(cr, uid, ids, context=context)
            return _get_rtype(o.bold, o.italic, o.underline, o.blank_line,
                              o.title_line)

        res = dict.fromkeys(ids, _get_rtype())
        for o in self.browse(cr, uid, ids, context=context):
            res[o.id] = _get_rtype(o.bold, o.italic, o.underline, o.blank_line,
                                   o.title_line)
        return res

    def default_get_tree_id(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('via_reporting_tree.tree_id', None)

    def default_get_tree_type_name(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('via_reporting_tree.tree_type_name', None)

    def default_get_tree_node_type(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('via_reporting_tree.tree_node_specialization_name',
                           None)

    def default_get_calculation(self, cr, uid, context=None):
        if context is None:
            context = {}
        tree_node_type = context.get(
            'via_reporting_tree.tree_node_specialization_name', False)
        if tree_node_type is False:
            tree_id = context.get('via_reporting_tree.tree_id', False)
            if tree_id is not False:
                t = self.pool.get('via.reporting.tree').browse(cr,
                                                               uid,
                                                               tree_id,
                                                               context=context)
                tree_node_type = t.tree_node_type

        if tree_node_type is False:
            return 'none'

        return tree_node._specialization_registry[
            tree_node_type].default_calculation

    _defaults = {
        'tree_id': default_get_tree_id,
        'tree_type_name': default_get_tree_type_name,
        'tree_node_type': default_get_tree_node_type,
        'calculation': default_get_calculation,
        'dummy_node': False,
        'bold': False,
        'italic': False,
        'underline': False,
        'blank_line': False,
        'title_line': False,
    }

    def _check_single_root_node(self, cr, uid, ids, context=None):
        nodes = self.browse(cr, uid, ids, context=context)
        for node in nodes:
            if node.parent_id and node.parent_id.id:
                continue
            root_node_ids = self.search(cr,
                                        uid,
                                        [('tree_id', '=', node.tree_id.id),
                                         ('parent_id', '=', False)],
                                        context=context)
            if len(root_node_ids) > 1:
                return False
        return True

    def _non_dummy_no_associated_nodes(self, cr, uid, ids, context=None):
        nodes = self.browse(cr, uid, ids, context=context)
        for node in nodes:
            if not node.dummy_node and len(node.associated_node_ids) != 0:
                return False
        return True

    def _calculation_none_no_associated_node(self, cr, uid, ids, context=None):
        nodes = self.browse(cr, uid, ids, context=context)
        for node in nodes:
            if node.calculation == 'none' and len(
                    node.associated_node_ids) != 0:
                return False
        return True

    def _calculation_sum_dummy_has_associated_node(self,
                                                   cr,
                                                   uid,
                                                   ids,
                                                   context=None):
        nodes = self.browse(cr, uid, ids, context=context)
        for node in nodes:
            if node.calculation == 'sum' and node.dummy_node and len(
                    node.associated_node_ids) == 0:
                return False
        return True

    _constraints = [
        (_check_single_root_node, 'You cannot have more than one root node !',
         ['parent_id']),
        (_non_dummy_no_associated_nodes,
         'A non-dummy node cannot have an associated node !',
         ['associated_node_ids', 'dummy_node']),
        (_calculation_none_no_associated_node,
         'Calculation NONE must have no associated node !',
         ['associated_node_ids', 'calculation']),
        (_calculation_sum_dummy_has_associated_node,
         'Calculation SUM on a dummy node must have at least one associated node !',
         ['associated_node_ids', 'calculation', 'dummy_node']),
    ]

    _sql_constraints = [
        ('sequence_tree_uniq', 'unique (sequence, tree_id)',
         'The sequence of a tree node must be unique per tree !'),
    ]

    _specialization_registry = {}

    @classmethod
    def register_specialization(cls,
                                tree_node_type,
                                link_type,
                                calculators,
                                default_calculation='none'):
        if tree_node_type in cls._specialization_registry:
            raise osv.except_osv(
                _('Error !'),
                _('Tree node specialization "%s" already'
                  ' exists !') % tree_node_type)

        link = None
        if link_type == 'one2many':
            link = one2many_link(tree_node_type)
        else:
            raise osv.except_osv(
                _('Error !'),
                _('Unrecognized node specialization link type'
                  ' "%s" !') % link_type)

        class registry_entry(object):
            def __init__(self, tree_node_type, link, calculators,
                         default_calculation):
                self.tree_node_type = tree_node_type
                self.link = link
                self.calculators = calculators
                self.calculators.update(
                    {'none': (lambda parent_datum, child_datum: None)})
                self.default_calculation = default_calculation
                if self.default_calculation not in self.calculators:
                    raise osv.except_osv(
                        _('Error !'),
                        _('Default calculation is not in calculators'))

        entry = registry_entry(tree_node_type, link, calculators,
                               default_calculation)
        cls._specialization_registry[tree_node_type] = entry

        cls._columns.update(link.get_columns())

    def fields_get(self, cr, uid, fields=None, context=None):
        if context is None:
            context = {}
        res = super(tree_node, self).fields_get(cr, uid, fields, context)

        name = context.get('via_reporting_tree.tree_node_specialization_name',
                           False)
        if name is False:
            return res

        field_defs = self._specialization_registry[name].link.get_field_defs()
        needed_fields = []
        if (fields and not context.get(
                'via_reporting_tree.tree_node_fields_view_get', False)):
            for f in field_defs.iterkeys():
                if f in fields:
                    needed_fields.append(f)
        else:
            needed_fields = list(field_defs.iterkeys())

        for f in needed_fields:
            res[f] = field_defs[f]

        return res

    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):
        if context is None:
            context = {}
        context['via_reporting_tree.tree_node_fields_view_get'] = True
        return super(tree_node,
                     self).fields_view_get(cr, uid, view_id, view_type,
                                           context, toolbar, submenu)

    def read(self,
             cr,
             uid,
             ids,
             fields=None,
             context=None,
             load='_classic_read'):
        if type(ids) != list:
            ids = [ids]
        res = super(tree_node, self).read(cr, uid, ids, fields, context, load)

        if fields is None:
            fields = []
        if not fields or not res:
            return res

        unread_fields = set(fields)
        for k in res[0].iterkeys():
            try:
                unread_fields.remove(k)
            except KeyError:
                pass  # Some extra keys are included (e.g., id)
        if len(unread_fields) == 0:
            return res
        else:
            unread_fields = list(unread_fields)

        if context is None:
            context = {}

        names = {}
        for node in self.browse(cr, uid, ids, context=context):
            l = names.setdefault(node.tree_id.tree_node_type, [])
            l.append(node.id)

        for (name, _ids) in names.iteritems():
            reader = self._specialization_registry[name].link.reader
            update_data = reader(cr, uid, _ids, unread_fields, context)
            for record in res:
                tree_node_id = record['id']
                record.update(update_data[tree_node_id])

        return res

    def write(self, cr, uid, ids, vals, context=None):
        if type(ids) != list:
            ids = [ids]

        if context is None:
            context = {}

        names = {}
        for node in self.browse(cr, uid, ids, context=context):
            l = names.setdefault(node.tree_id.tree_node_type, [])
            l.append(node.id)
            if vals.get('tree_id', node.tree_id.id) != node.tree_id.id:
                raise osv.except_osv(_('Error !'), _('Cannot change tree !'))

        specific_name_vals = {}
        for name in names:
            field_defs = self._specialization_registry[
                name].link.get_field_defs()
            for f in field_defs.iterkeys():
                if f not in vals:
                    continue
                d = specific_name_vals.setdefault(name, {})
                d[f] = vals[f]
                del vals[f]

        if vals:
            super(tree_node, self).write(cr, uid, ids, vals, context)

        for (name, specific_vals) in specific_name_vals.iteritems():
            writer = self._specialization_registry[name].link.writer
            writer(cr, uid, ids, specific_vals, context)

        return True
예제 #47
0
        'engine_serial':fields.char('Engine Serial',size=20),

        'chassis_1st_fa':fields.char("Chassis 1st FA", size=10, help="1st Front Axle Weight (without wrecker)"),
        'chassis_2nd_fa':fields.char("Chassis 2nd FA", size=10, help="2nd Front Axle Weight (without wrecker)"),
        'chassis_1st_ra':fields.char("Chassis 1st RA", size=10, help="1st Rear Axle Weight (without wrecker)"),
        'chassis_2nd_ra':fields.char("Chassis 2nd RA", size=10, help="2nd Rear Axle Weight (without wrecker)"),
        'chassis_3rd_ra':fields.char("Chassis 3rd RA", size=10, help="3rd Rear Axle Weight (without wrecker)"),
        'installed_1st_fa':fields.char("Installed 1st FA", size=10, help="1st Front Axle Weight (with wrecker)"),
        'installed_2nd_fa':fields.char("Installed 2nd FA", size=10, help="2nd Front Axle Weight (with wrecker)"),
        'installed_1st_ra':fields.char("Installed 1st RA", size=10, help="1st Rear Axle Weight (with wrecker)"),
        'installed_2nd_ra':fields.char("Installed 2nd RA", size=10, help="2nd Rear Axle Weight (with wrecker)"),
        'installed_3rd_ra':fields.char("Installed 3rd RA", size=10, help="3rd Rear Axle Weight (with wrecker)"),
        'installed_height':fields.char("Installed Height", size=10, help="Highest Point on the Installed Wrecker"),
        'installed_length':fields.char("Installed Length", size=10, help="Overall Length of the Installed Wrecker"),
        'installed_width':fields.char("Installed Width", size=10, help="Overall Width of the Installed Wrecker"),
        'chassis_1st_fa_rating':fields.integer("Chassis 1st FA Rating", size=10, help="1st Front Axle Rating"),
        'chassis_2nd_fa_rating':fields.integer("Chassis 2nd FA Rating", size=10, help="2nd Front Axle Rating"),
        'chassis_1st_ra_rating':fields.integer("Chassis 1st RA Rating", size=10, help="1st Rear Axle Rating"),
        'chassis_2nd_ra_rating':fields.integer("Chassis 2nd RA Rating", size=10, help="2nd Rear Axle Rating"),
        'chassis_3rd_ra_rating':fields.integer("Chassis 3rd RA Rating", size=10, help="3rd Rear Axle Rating"),
        
        #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'),
예제 #48
0
class Detail_expenses_dinas(osv.osv):
    _name = 'hr.expense.dinas'
    _columns = {
        'name':
        fields.char('Refference',
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'no_spk':
        fields.char('No SPK',
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'employee_id':
        fields.many2one('hr.employee',
                        "Employee",
                        required=True,
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'department_id':
        fields.many2one('hr.department',
                        'Department',
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'golongan':
        fields.selection([('1', 'Golongan 1'), ('2', 'Golongan 2'),
                          ('3', 'Golongan 3'), ('4', 'Golongan 4'),
                          ('5', 'Golongan 5')],
                         'Golongan',
                         readonly=True,
                         states={'draft': [('readonly', False)]}),
        'lama_perjalanan':
        fields.integer('Lama Perjalanan (Hari)',
                       size=2,
                       readonly=True,
                       states={'draft': [('readonly', False)]}),
        'lokasi_dinas':
        fields.selection([('1', 'Sumatera, Jawa , Bali , Bangka'),
                          ('2', 'Kalimantan, Sulawesi, Kepulan Maluku'),
                          ('3', 'NTB, NTT, Kepulan Timor'),
                          ('4', 'Duri, Batam, Kepulan Riau'),
                          ('5', 'Papua, Kepulan Papua'), ('6', 'Luar Negeri')],
                         'Lokasi Dinas',
                         required=True,
                         readonly=True,
                         states={'draft': [('readonly', False)]}),
        'tanggal_keberangkatan':
        fields.date('Tanggal Keberangkatan',
                    required=True,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'tanggal_kepulangan':
        fields.date('Tanggal Kepulangan',
                    required=True,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'maksud_perjalanan_dinas':
        fields.char('Tujuan Perjalanan Dinas',
                    size=200,
                    required=True,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'customer_id':
        fields.many2one('res.partner',
                        'Customer',
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'status':
        fields.selection(
            [('1', 'Tidak Menginap'), ('2', 'Menginap')],
            'Status',
            required=True,
            states={
                'confirm': [('readonly', True)],
                'done': [('readonly', True)],
                'ticketing': [('readonly', True)]
            }),
        'dibebankan':
        fields.char('Akan Di Bebankan',
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'state':
        fields.selection([
            ('draft', 'Draft'),
            ('confirm', 'Confirm'),
            ('ticketing', 'Ticketing'),
            ('done', 'Done'),
        ], 'Status'),
        'real_lokasi':
        fields.char('Real Lokasi', states={'draft': [('readonly', True)]}),
        'tunjangan_transport_ids':
        fields.one2many('tunjangan.transport',
                        'tunjangan_transport_id',
                        'Transport',
                        readonly=True,
                        states={
                            'draft': [('readonly', True)],
                            'ticketing': [('readonly', False)]
                        }),
        'tunjangan_meal_hotel_ids':
        fields.one2many('tunjangan.meal.hotel',
                        'tunjangan_meal_hotel_id',
                        'Meal dan Hotel',
                        readonly=True,
                        states={
                            'draft': [('readonly', False)],
                            'ticketing': [('readonly', True)]
                        }),
    }

    def _employee_get(obj, cr, uid, context=None):
        if context is None:
            context = {}
        ids = obj.pool.get('hr.employee').search(cr,
                                                 uid, [('user_id', '=', uid)],
                                                 context=context)
        if ids:
            return ids[0]
        return False

    def _golongan_get(obj, cr, uid, context=None):
        if context is None:
            context = {}
        ids = obj.pool.get('hr.employee').search(cr,
                                                 uid, [('user_id', '=', uid)],
                                                 context=context)
        if ids:
            golid = obj.pool.get('hr.employee').browse(cr, uid,
                                                       ids[0]).golongan
            return golid
        return False

    def _department_get(obj, cr, uid, context=None):
        if context is None:
            context = {}
        ids = obj.pool.get('hr.employee').search(cr,
                                                 uid, [('user_id', '=', uid)],
                                                 context=context)
        if ids:
            depds = obj.pool.get('hr.employee').browse(cr, uid,
                                                       ids[0]).department_id.id
            return depds
        return False

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

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

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

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

    _defaults = {
        'name': '/',
        'state': 'draft',
        'employee_id': _employee_get,
        'department_id': _department_get,
        'golongan': _golongan_get,
        'lama_perjalanan': 1,
    }

    def create(self, cr, uid, vals, context=None):
        vals['name'] = self.pool.get('ir.sequence').get(
            cr, uid, 'hr.expense.dinas')
        return super(Detail_expenses_dinas, self).create(cr,
                                                         uid,
                                                         vals,
                                                         context=context)

    def hitung_tunjangan(self, cr, uid, ids, idLJ, idEP, idLP, ST):
        if idLP:
            id_employee = self.pool.get('hr.employee').browse(cr, uid, idEP)

            golongan = id_employee.golongan
            cek = self.pool.get('tunjangan.expense').search(
                cr, uid, [('golongan', '=', golongan),
                          ('lokasi_dinas', '=', idLJ), ('status', '=', ST)])
            if cek:
                data = []
                hasil = self.pool.get('tunjangan.expense').browse(
                    cr, uid, cek)[0]
                for x in hasil.tunjangan_detail_dinas_ids:
                    data.append({
                        'name': x.name.name,
                        'harga': x.jumlah_tunjangan,
                        'qty': idLP,
                        'subtotal': x.jumlah_tunjangan * idLP,
                    })
                return {'value': {'tunjangan_meal_hotel_ids': data}}
            return True

    def reportexspense(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        datas['model'] = 'hr.expense.dinas'
        datas['form'] = self.read(cr, uid, ids)[0]

        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'hr.expense.dinas',
            'report_type': 'webkit',
            'datas': datas,
        }
예제 #49
0
        ],'Template source', select=True),
        'parser_def': fields.text('Parser Definition'),
        'parser_loc':fields.char('Parser location', size=128, help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}"),
        'parser_state':fields.selection([
            ('default',_('Default')),
            ('def',_('Definition')),
            ('loc',_('Location')),
        ],'State of Parser', select=True),
        'in_format': fields.selection(_get_in_mimetypes, 'Template Mime-type'),
        'out_format':fields.many2one('report.mimetypes', 'Output Mime-type'),
        'report_sxw_content': fields.function(_report_content,
            fnct_inv=_report_content_inv, method=True,
            type='binary', string='SXW content',),
        'active':fields.boolean('Active', help='Disables the report if unchecked.'),
        'report_wizard':fields.boolean('Report Wizard'),
        'copies': fields.integer('Number of Copies'),
        'fallback_false':fields.boolean('Disable Format Fallback'),
        'xml_id': fields.function(_get_xml_id, type='char', size=128, string="XML ID",
                                  method=True, help="ID of the report defined in xml file"),
        'extras': fields.function(_get_extras, method=True, type='char', size='256', string='Extra options'),
        'deferred':fields.selection([
            ('off',_('Off')),
            ('adaptive',_('Adaptive')),
            
        ],'Deferred', help='Deferred (aka Batch) reporting, for reporting on large amount of data.'),
        'deferred_limit': fields.integer('Deferred Records Limit', help='Records limit at which you are invited to start the deferred process.'),
        'replace_report_id':fields.many2one('ir.actions.report.xml', 'Replace Report'),
        'wizard_id':fields.many2one('ir.actions.act_window', 'Wizard Action'),
        
    }
예제 #50
0
            if res[1]:
                user_id = res[0]
        elif conf["create_user"]:
            logger = logging.getLogger("orm.ldap")
            logger.debug('Creating new OpenERP user "%s" from LDAP' % login)
            user_obj = self.pool.get("res.users")
            values = self.map_ldap_attributes(cr, uid, conf, login, ldap_entry)
            if conf["user"]:
                user_id = user_obj.copy(cr, SUPERUSER_ID, conf["user"], default={"active": True})
                user_obj.write(cr, SUPERUSER_ID, user_id, values)
            else:
                user_id = user_obj.create(cr, SUPERUSER_ID, values)
        return user_id

    _columns = {
        "sequence": fields.integer("Sequence"),
        "company": fields.many2one("res.company", "Company", required=True, ondelete="cascade"),
        "ldap_server": fields.char("LDAP Server address", size=64, required=True),
        "ldap_server_port": fields.integer("LDAP Server port", required=True),
        "ldap_binddn": fields.char(
            "LDAP binddn",
            size=64,
            help=(
                "The user account on the LDAP server that is used to query "
                "the directory. Leave empty to connect anonymously."
            ),
        ),
        "ldap_password": fields.char(
            "LDAP password",
            size=64,
            help=("The password of the user account on the LDAP server that is " "used to query the directory."),