Beispiel #1
0
class res_partner_tags(osv.Model):
    _description = 'Partner Tags - These tags can be used on website to find customers by sector, or ... '
    _name = 'res.partner.tag'
    _inherit = 'website.published.mixin'

    def get_selection_class(self, cr, uid, context=None):
        classname = ['default', 'primary', 'success', 'warning', 'danger']
        return [(x, str.title(x)) for x in classname]

    _columns = {
        'name':
        fields.char('Category Name', required=True, translate=True),
        'partner_ids':
        fields.many2many('res.partner',
                         'res_partner_res_partner_tag_rel',
                         id1='tag_id',
                         id2='partner_id',
                         string='Partners'),
        'classname':
        fields.selection(get_selection_class,
                         'Class',
                         help="Bootstrap class to customize the color",
                         required=True),
        'active':
        fields.boolean('Active'),
    }
    _defaults = {
        'active': True,
        'website_published': True,
        'classname': 'default',
    }
Beispiel #2
0
class restaurant_printer(osv.osv):
    _name = 'restaurant.printer'

    _columns = {
        'name':
        fields.char('Printer Name',
                    size=32,
                    required=True,
                    help='An internal identification of the printer'),
        'proxy_ip':
        fields.char(
            'Proxy IP Address',
            size=32,
            help="The IP Address or hostname of the Printer's hardware proxy"),
        'product_categories_ids':
        fields.many2many('pos.category',
                         'printer_category_rel',
                         'printer_id',
                         'category_id',
                         string='Printed Product Categories'),
    }

    _defaults = {
        'name': 'Printer',
    }
Beispiel #3
0
class CountryGroup(osv.osv):
    _description = "Country Group"
    _name = 'res.country.group'
    _columns = {
        'name': fields.char('Name', required=True),
        'country_ids': fields.many2many('res.country', 'res_country_res_country_group_rel', 'res_country_group_id', 'res_country_id', string='Countries'),
    }
Beispiel #4
0
class MailComposeMessage(osv.TransientModel):
    """Add concept of mass mailing campaign to the mail.compose.message wizard
    """
    _inherit = 'mail.compose.message'

    _columns = {
        'mass_mailing_campaign_id': fields.many2one(
            'mail.mass_mailing.campaign', 'Mass Mailing Campaign'
        ),
        'mass_mailing_id': fields.many2one(
            'mail.mass_mailing', 'Mass Mailing', ondelete='cascade'
        ),
        'mass_mailing_name': fields.char('Mass Mailing'),
        'mailing_list_ids': fields.many2many(
            'mail.mass_mailing.list', string='Mailing List'
        ),
    }

    def get_mail_values(self, cr, uid, ids, res_ids, context=None):
        """ Override method that generated the mail content by creating the
        mail.mail.statistics values in the o2m of mail_mail, when doing pure
        email mass mailing. """
        res = super(MailComposeMessage, self).get_mail_values(cr, uid, ids, res_ids, context=context)
        # TDE: arg was wiards, not ids - but new API -> multi with ensure_one
        wizard = self.browse(cr, uid, ids[0], context=context)
        # use only for allowed models in mass mailing
        if wizard.composition_mode == 'mass_mail' and \
                (wizard.mass_mailing_name or wizard.mass_mailing_id) and \
                wizard.model in [item[0] for item in self.pool['mail.mass_mailing']._get_mailing_model(cr, uid, context=context)]:
            mass_mailing = wizard.mass_mailing_id
            if not mass_mailing:
                reply_to_mode = wizard.no_auto_thread and 'email' or 'thread'
                reply_to = wizard.no_auto_thread and wizard.reply_to or False
                mass_mailing_id = self.pool['mail.mass_mailing'].create(
                    cr, uid, {
                        'mass_mailing_campaign_id': wizard.mass_mailing_campaign_id and wizard.mass_mailing_campaign_id.id or False,
                        'name': wizard.mass_mailing_name,
                        'template_id': wizard.template_id and wizard.template_id.id or False,
                        'state': 'done',
                        'reply_to_mode': reply_to_mode,
                        'reply_to': reply_to,
                        'sent_date': fields.datetime.now(),
                        'body_html': wizard.body,
                        'mailing_model': wizard.model,
                        'mailing_domain': wizard.active_domain,
                    }, context=context)
                mass_mailing = self.pool['mail.mass_mailing'].browse(cr, uid, mass_mailing_id, context=context)
            for res_id in res_ids:
                res[res_id].update({
                    'mailing_id':  mass_mailing.id,
                    'statistics_ids': [(0, 0, {
                        'model': wizard.model,
                        'res_id': res_id,
                        'mass_mailing_id': mass_mailing.id,
                    })],
                    # email-mode: keep original message for routing
                    'notification': mass_mailing.reply_to_mode == 'thread',
                    'auto_delete': not mass_mailing.keep_archives,
                })
        return res
class hr_holidays_summary_dept(osv.osv_memory):
    _name = 'hr.holidays.summary.dept'
    _description = 'HR Leaves Summary Report By Department'
    _columns = {
        'date_from':
        fields.date('From', required=True),
        'depts':
        fields.many2many('hr.department', 'summary_dept_rel', 'sum_id',
                         'dept_id', 'Department(s)'),
        'holiday_type':
        fields.selection([('Approved', 'Approved'), ('Confirmed', 'Confirmed'),
                          ('both', 'Both Approved and Confirmed')],
                         'Leave Type',
                         required=True)
    }

    _defaults = {
        'date_from': lambda *a: time.strftime('%Y-%m-01'),
        'holiday_type': 'Approved'
    }

    def print_report(self, cr, uid, ids, context=None):
        data = self.read(cr, uid, ids, context=context)[0]
        if not data['depts']:
            raise UserError(
                _('You have to select at least one Department. And try again.')
            )
        datas = {'ids': [], 'model': 'hr.department', 'form': data}
        return self.pool['report'].get_action(
            cr,
            uid,
            data['depts'],
            'hr_holidays.report_holidayssummary',
            data=datas,
            context=context)
Beispiel #6
0
class pos_config(osv.osv):
    _inherit = 'pos.config'
    _columns = {
        'iface_splitbill':
        fields.boolean('Bill Splitting',
                       help='Enables Bill Splitting in the Point of Sale'),
        'iface_printbill':
        fields.boolean('Bill Printing',
                       help='Allows to print the Bill before payment'),
        'iface_orderline_notes':
        fields.boolean('Orderline Notes',
                       help='Allow custom notes on Orderlines'),
        'floor_ids':
        fields.one2many(
            'restaurant.floor',
            'pos_config_id',
            'Restaurant Floors',
            help='The restaurant floors served by this point of sale'),
        'printer_ids':
        fields.many2many('restaurant.printer',
                         'pos_config_printer_rel',
                         'config_id',
                         'printer_id',
                         string='Order Printers'),
    }
    _defaults = {
        'iface_splitbill': False,
        'iface_printbill': False,
    }
Beispiel #7
0
class account_budget_post(osv.osv):
    _name = "account.budget.post"
    _description = "Budgetary Position"
    _columns = {
        'name':
        fields.char('Name', required=True),
        'account_ids':
        fields.many2many('account.account',
                         'account_budget_rel',
                         'budget_id',
                         'account_id',
                         'Accounts',
                         domain=[('deprecated', '=', False)]),
        'crossovered_budget_line':
        fields.one2many('crossovered.budget.lines', 'general_budget_id',
                        'Budget Lines'),
        'company_id':
        fields.many2one('res.company', 'Company', required=True),
    }
    _defaults = {
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.company').
        _company_default_get(cr, uid, 'account.budget.post', context=c)
    }
    _order = "name"
Beispiel #8
0
class ir_model_fields_anonymization_history(osv.osv):
    _name = 'ir.model.fields.anonymization.history'
    _order = "date desc"

    _columns = {
        'date':
        fields.datetime('Date', required=True, readonly=True),
        'field_ids':
        fields.many2many('ir.model.fields.anonymization',
                         'anonymized_field_to_history_rel',
                         'field_id',
                         'history_id',
                         'Fields',
                         readonly=True),
        'state':
        fields.selection(selection=ANONYMIZATION_HISTORY_STATE,
                         string='Status',
                         required=True,
                         readonly=True),
        'direction':
        fields.selection(selection=ANONYMIZATION_DIRECTION,
                         string='Direction',
                         size=20,
                         required=True,
                         readonly=True),
        'msg':
        fields.text('Message', readonly=True),
        'filepath':
        fields.char(string='File path', readonly=True),
    }
Beispiel #9
0
class hr_holidays_summary_employee(osv.osv_memory):
    _name = 'hr.holidays.summary.employee'
    _description = 'HR Leaves Summary Report By Employee'
    _columns = {
        'date_from':
        fields.date('From', required=True),
        'emp':
        fields.many2many('hr.employee', 'summary_emp_rel', 'sum_id', 'emp_id',
                         'Employee(s)'),
        'holiday_type':
        fields.selection([('Approved', 'Approved'), ('Confirmed', 'Confirmed'),
                          ('both', 'Both Approved and Confirmed')],
                         'Select Leave Type',
                         required=True)
    }

    _defaults = {
        'date_from': lambda *a: time.strftime('%Y-%m-01'),
        'holiday_type': 'Approved',
    }

    def print_report(self, cr, uid, ids, context=None):
        data = self.read(cr, uid, ids, context=context)[0]
        data['emp'] = context.get('active_ids', [])
        datas = {'ids': [], 'model': 'hr.employee', 'form': data}
        return self.pool['report'].get_action(
            cr,
            uid,
            data['emp'],
            'hr_holidays.report_holidayssummary',
            data=datas,
            context=context)
class hr_salary_employee_bymonth(osv.osv_memory):

    _name = 'hr.salary.employee.month'
    _description = 'Hr Salary Employee By Month Report'
    _columns = {
        'start_date':
        fields.date('Start Date', required=True),
        'end_date':
        fields.date('End Date', required=True),
        'employee_ids':
        fields.many2many('hr.employee',
                         'payroll_year_rel',
                         'payroll_year_id',
                         'employee_id',
                         'Employees',
                         required=True),
        'category_id':
        fields.many2one('hr.salary.rule.category', 'Category', required=True),
    }

    def _get_default_category(self, cr, uid, context=None):
        category_ids = self.pool.get('hr.salary.rule.category').search(
            cr, uid, [('code', '=', 'NET')], context=context)
        return category_ids and category_ids[0] or False

    _defaults = {
        'start_date': lambda *a: time.strftime('%Y-01-01'),
        'end_date': lambda *a: time.strftime('%Y-%m-%d'),
        'category_id': _get_default_category
    }

    def print_report(self, cr, uid, ids, context=None):
        """
         To get the date and print the report
         @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: return report
        """
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}

        res = self.read(cr, uid, ids, context=context)
        res = res and res[0] or {}
        datas.update({'form': res})
        return self.pool['report'].get_action(
            cr,
            uid,
            ids,
            'l10n_in_hr_payroll.report_hrsalarybymonth',
            data=datas,
            context=context)
Beispiel #11
0
class res_partner(osv.Model):
    _inherit = 'res.partner'

    _columns = {
        'website_tag_ids':
        fields.many2many('res.partner.tag',
                         id1='partner_id',
                         id2='tag_id',
                         string='Website tags',
                         oldname="tag_ids"),
    }
Beispiel #12
0
class product_template(osv.Model):
    _inherit = "product.template"

    _columns = {
        'optional_product_ids':
        fields.many2many('product.template',
                         'product_optional_rel',
                         'src_id',
                         'dest_id',
                         string='Optional Products',
                         help="Products to propose when add to cart."),
    }
Beispiel #13
0
class sale_order(osv.osv):
    _name = "sale.order"
    _inherit = ['sale.order', 'utm.mixin']
    _columns = {
        'tag_ids':
        fields.many2many('crm.lead.tag', 'sale_order_tag_rel', 'order_id',
                         'tag_id', 'Tags'),
        'opportunity_id':
        fields.many2one('crm.lead',
                        'Opportunity',
                        domain="[('type', '=', 'opportunity')]")
    }
Beispiel #14
0
class res_company(osv.osv):
    """Override company to add Header object link a company can have many header and logos"""

    _inherit = "res.company"
    _columns = {
        'header_image':
        fields.many2many(
            'ir.header_img',
            'company_img_rel',
            'company_id',
            'img_id',
            'Available Images',
        ),
        'header_webkit':
        fields.many2many(
            'ir.header_webkit',
            'company_html_rel',
            'company_id',
            'html_id',
            'Available html',
        ),
    }
Beispiel #15
0
class Country(osv.osv):
    _name = 'res.country'
    _description = 'Country'
    _columns = {
        'name': fields.char('Country Name',
                            help='The full name of the country.', required=True, translate=True),
        'code': fields.char('Country Code', size=2,
                            help='The ISO country code in two chars.\n'
                            'You can use this field for quick search.'),
        'address_format': fields.text('Address Format', help="""You can state here the usual format to use for the \
addresses belonging to this country.\n\nYou can use the python-style string patern with all the field of the address \
(for example, use '%(street)s' to display the field 'street') plus
            \n%(state_name)s: the name of the state
            \n%(state_code)s: the code of the state
            \n%(country_name)s: the name of the country
            \n%(country_code)s: the code of the country"""),
        'currency_id': fields.many2one('res.currency', 'Currency'),
        'image': fields.binary("Image", attachment=True),
        'phone_code': fields.integer('Country Calling Code'),
        'country_group_ids': fields.many2many('res.country.group', 'res_country_res_country_group_rel', 'res_country_id', 'res_country_group_id', string='Country Groups'),
        'state_ids': fields.one2many('res.country.state', 'country_id', string='States'),
    }
    _sql_constraints = [
        ('name_uniq', 'unique (name)',
            'The name of the country must be unique !'),
        ('code_uniq', 'unique (code)',
            'The code of the country must be unique !')
    ]
    _defaults = {
        'address_format': "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s",
    }
    _order = 'name'

    name_search = location_name_search

    def create(self, cursor, user, vals, context=None):
        if vals.get('code'):
            vals['code'] = vals['code'].upper()
        return super(Country, self).create(cursor, user, vals, context=context)

    def write(self, cursor, user, ids, vals, context=None):
        if vals.get('code'):
            vals['code'] = vals['code'].upper()
        return super(Country, self).write(cursor, user, ids, vals, context=context)

    def get_address_fields(self, cr, uid, ids, context=None):
        res = {}
        for country in self.browse(cr, uid, ids, context=context):
            res[country.id] = re.findall('\((.+?)\)', country.address_format)
        return res
Beispiel #16
0
class test_uninstall_model(Model):
    """
    This model uses different types of columns to make it possible to test
    the uninstall feature of eCore.
    """
    _name = 'test_uninstall.model'

    _columns = {
        'name': fields.char('Name'),
        'ref': fields.many2one('res.users', string='User'),
        'rel': fields.many2many('res.users', string='Users'),
    }

    _sql_constraints = [('name_uniq', 'unique (name)',
                         'Each name must be unique.')]
Beispiel #17
0
class BlogTag(osv.Model):
    _name = 'blog.tag'
    _description = 'Blog Tag'
    _inherit = ['website.seo.metadata']
    _order = 'name'
    _columns = {
        'name': fields.char('Name', required=True),
        'post_ids': fields.many2many(
            'blog.post',
            string='Posts',
        ),
    }
    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Tag name already exists !"),
    ]
Beispiel #18
0
class hr_employee_category(osv.Model):

    _name = "hr.employee.category"
    _description = "Employee Category"
    _columns = {
        'name':
        fields.char("Employee Tag", required=True),
        'color':
        fields.integer('Color Index'),
        'employee_ids':
        fields.many2many('hr.employee', 'employee_category_rel', 'category_id',
                         'emp_id', 'Employees'),
    }
    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Tag name already exists !"),
    ]
Beispiel #19
0
class yearly_salary_detail(osv.osv_memory):

    _name = 'yearly.salary.detail'
    _description = 'Hr Salary Employee By Category Report'
    _columns = {
        'employee_ids':
        fields.many2many('hr.employee',
                         'payroll_emp_rel',
                         'payroll_id',
                         'employee_id',
                         'Employees',
                         required=True),
        'date_from':
        fields.date('Start Date', required=True),
        'date_to':
        fields.date('End Date', required=True),
    }

    _defaults = {
        'date_from': lambda *a: time.strftime('%Y-01-01'),
        'date_to': lambda *a: time.strftime('%Y-%m-%d'),
    }

    def print_report(self, cr, uid, ids, context=None):
        """
         To get the date and print the report
         @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: return report
        """
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}

        res = self.read(cr, uid, ids, context=context)
        res = res and res[0] or {}
        datas.update({'form': res})
        return self.pool['report'].get_action(
            cr,
            uid,
            ids,
            'l10n_in_hr_payroll.report_hryearlysalary',
            data=datas,
            context=context)
Beispiel #20
0
class pos_details(osv.osv_memory):
    _name = 'pos.details'
    _description = 'Sales Details'

    _columns = {
        'date_start':
        fields.date('Date Start', required=True),
        'date_end':
        fields.date('Date End', required=True),
        'user_ids':
        fields.many2many('res.users', 'pos_details_report_user_rel', 'user_id',
                         'wizard_id', 'Salespeople'),
    }
    _defaults = {
        'date_start': fields.date.context_today,
        'date_end': fields.date.context_today,
    }

    def print_report(self, cr, uid, ids, context=None):
        """
         To get the date and print the report
         @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 : retrun report
        """
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        res = self.read(cr,
                        uid,
                        ids, ['date_start', 'date_end', 'user_ids'],
                        context=context)
        res = res and res[0] or {}
        datas['form'] = res
        if res.get('id', False):
            datas['ids'] = [res['id']]
        return self.pool['report'].get_action(
            cr,
            uid, [],
            'point_of_sale.report_detailsofsales',
            data=datas,
            context=context)
Beispiel #21
0
class groups_implied(osv.osv):
    _inherit = 'res.groups'

    def _get_trans_implied(self, cr, uid, ids, field, arg, context=None):
        "computes the transitive closure of relation implied_ids"
        memo = {}           # use a memo for performance and cycle avoidance
        def computed_set(g):
            if g not in memo:
                memo[g] = cset(g.implied_ids)
                for h in g.implied_ids:
                    computed_set(h).subsetof(memo[g])
            return memo[g]

        res = {}
        for g in self.browse(cr, SUPERUSER_ID, ids, context):
            res[g.id] = map(int, computed_set(g))
        return res

    _columns = {
        'implied_ids': fields.many2many('res.groups', 'res_groups_implied_rel', 'gid', 'hid',
            string='Inherits', help='Users of this group automatically inherit those groups'),
        'trans_implied_ids': fields.function(_get_trans_implied,
            type='many2many', relation='res.groups', string='Transitively inherits'),
    }

    def create(self, cr, uid, values, context=None):
        users = values.pop('users', None)
        gid = super(groups_implied, self).create(cr, uid, values, context)
        if users:
            # delegate addition of users to add implied groups
            self.write(cr, uid, [gid], {'users': users}, context)
        return gid

    def write(self, cr, uid, ids, values, context=None):
        res = super(groups_implied, self).write(cr, uid, ids, values, context)
        if values.get('users') or values.get('implied_ids'):
            # add all implied groups (to all users of each group)
            for g in self.browse(cr, uid, ids, context=context):
                gids = map(int, g.trans_implied_ids)
                vals = {'users': [(4, u.id) for u in g.users]}
                super(groups_implied, self).write(cr, uid, gids, vals, context)
        return res
Beispiel #22
0
class purchase_requisition_partner(osv.osv_memory):
    _name = "purchase.requisition.partner"
    _description = "Purchase Requisition Partner"
    _columns = {
        'partner_ids':
        fields.many2many('res.partner',
                         'purchase_requisition_supplier_rel',
                         'requisition_id',
                         'partner_id',
                         string='Vendors',
                         required=True,
                         domain=[('supplier', '=', True)])
    }

    def view_init(self, cr, uid, fields_list, context=None):
        if context is None:
            context = {}
        res = super(purchase_requisition_partner,
                    self).view_init(cr, uid, fields_list, context=context)
        record_id = context and context.get('active_id', False) or False
        tender = self.pool.get('purchase.requisition').browse(cr,
                                                              uid,
                                                              record_id,
                                                              context=context)
        if not tender.line_ids:
            raise UserError(
                _('Define product(s) you want to include in the call for tenders.'
                  ))
        return res

    def create_order(self, cr, uid, ids, context=None):
        active_ids = context and context.get('active_ids', [])
        purchase_requisition = self.pool.get('purchase.requisition')
        for wizard in self.browse(cr, uid, ids, context=context):
            for partner_id in wizard.partner_ids:
                purchase_requisition.make_purchase_order(cr,
                                                         uid,
                                                         active_ids,
                                                         partner_id.id,
                                                         context=context)
        return {'type': 'ir.actions.act_window_close'}
Beispiel #23
0
class website_pricelist(osv.Model):
    _name = 'website_pricelist'
    _description = 'Website Pricelist'

    def _get_display_name(self, cr, uid, ids, name, arg, context=None):
        result = {}
        for o in self.browse(cr, uid, ids, context=context):
            result[o.id] = _("Website Pricelist for %s") % o.pricelist_id.name
        return result

    _columns = {
        'name': fields.function(_get_display_name, string='Pricelist Name', type="char"),
        'website_id': fields.many2one('website', string="Website", required=True),
        'selectable': fields.boolean('Selectable', help="Allow the end user to choose this price list"),
        'pricelist_id': fields.many2one('product.pricelist', string='Pricelist'),
        'country_group_ids': fields.many2many('res.country.group', 'res_country_group_website_pricelist_rel',
                                              'website_pricelist_id', 'res_country_group_id', string='Country Groups'),
    }

    def clear_cache(self):
        # website._get_pl() is cached to avoid to recompute at each request the
        # list of available pricelists. So, we need to invalidate the cache when
        # we change the config of website price list to force to recompute.
        website = self.pool['website']
        website._get_pl.clear_cache(website)

    def create(self, cr, uid, data, context=None):
        res = super(website_pricelist, self).create(cr, uid, data, context=context)
        self.clear_cache()
        return res

    def write(self, cr, uid, ids, data, context=None):
        res = super(website_pricelist, self).write(cr, uid, ids, data, context=context)
        self.clear_cache()
        return res

    def unlink(self, cr, uid, ids, context=None):
        res = super(website_pricelist, self).unlink(cr, uid, ids, context=context)
        self.clear_cache()
        return res
Beispiel #24
0
class base_language_install(osv.osv_memory):
    _inherit = "base.language.install"
    _columns = {
        'website_ids': fields.many2many('website',
                                        string='Websites to translate'),
    }

    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        defaults = super(base_language_install,
                         self).default_get(cr, uid, fields, context)
        website_id = context.get('params', {}).get('website_id')
        if website_id:
            if 'website_ids' not in defaults:
                defaults['website_ids'] = []
            defaults['website_ids'].append(website_id)
        return defaults

    def lang_install(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        action = super(base_language_install,
                       self).lang_install(cr, uid, ids, context)
        language_obj = self.browse(cr, uid, ids)[0]
        website_ids = [website.id for website in language_obj['website_ids']]
        lang_id = self.pool['res.lang'].search(
            cr, uid, [('code', '=', language_obj['lang'])])
        if website_ids and lang_id:
            data = {'language_ids': [(4, lang_id[0])]}
            self.pool['website'].write(cr, uid, website_ids, data)
        params = context.get('params', {})
        if 'url_return' in params:
            return {
                'url': params['url_return'].replace('[lang]',
                                                    language_obj['lang']),
                'type': 'ir.actions.act_url',
                'target': 'self'
            }
        return action
Beispiel #25
0
class wkf_instance(osv.osv):
    _table = "wkf_instance"
    _name = "workflow.instance"
    _rec_name = 'res_type'
    _log_access = False
    _columns = {
        'uid':
        fields.integer('User'),  # FIXME no constraint??
        'wkf_id':
        fields.many2one('workflow',
                        'Workflow',
                        ondelete='cascade',
                        select=True),
        'res_id':
        fields.integer('Resource ID'),
        'res_type':
        fields.char('Resource Object'),
        'state':
        fields.char('Status'),
        'transition_ids':
        fields.many2many('workflow.transition', 'wkf_witm_trans', 'inst_id',
                         'trans_id'),
    }

    def _auto_init(self, cr, context=None):
        super(wkf_instance, self)._auto_init(cr, context)
        cr.execute(
            'SELECT indexname FROM pg_indexes WHERE indexname = \'wkf_instance_res_type_res_id_state_index\''
        )
        if not cr.fetchone():
            cr.execute(
                'CREATE INDEX wkf_instance_res_type_res_id_state_index ON wkf_instance (res_type, res_id, state)'
            )
        cr.execute(
            'SELECT indexname FROM pg_indexes WHERE indexname = \'wkf_instance_res_id_wkf_id_index\''
        )
        if not cr.fetchone():
            cr.execute(
                'CREATE INDEX wkf_instance_res_id_wkf_id_index ON wkf_instance (res_id, wkf_id)'
            )
Beispiel #26
0
class mrp_repair_fee(osv.osv, ProductChangeMixin):
    _name = 'mrp.repair.fee'
    _description = 'Repair Fees Line'

    def _amount_line(self, cr, uid, ids, field_name, arg, context=None):
        """ Calculates amount.
        @param field_name: Name of field.
        @param arg: Argument
        @return: Dictionary of values.
        """
        res = {}
        tax_obj = self.pool.get('account.tax')
        cur_obj = self.pool.get('res.currency')
        for line in self.browse(cr, uid, ids, context=context):
            if line.to_invoice:
                cur = line.repair_id.pricelist_id.currency_id
                taxes = tax_obj.compute_all(cr, uid, line.tax_id, line.price_unit, cur.id, line.product_uom_qty, line.product_id.id, line.repair_id.partner_id.id)
                res[line.id] = taxes['total_included']
            else:
                res[line.id] = 0
        return res

    _columns = {
        'repair_id': fields.many2one('mrp.repair', 'Repair Order Reference', required=True, ondelete='cascade', select=True),
        'name': fields.char('Description', select=True, required=True),
        'product_id': fields.many2one('product.product', 'Product'),
        'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
        'price_unit': fields.float('Unit Price', required=True),
        'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
        'price_subtotal': fields.function(_amount_line, string='Subtotal', digits=0),
        'tax_id': fields.many2many('account.tax', 'repair_fee_line_tax', 'repair_fee_line_id', 'tax_id', 'Taxes'),
        'invoice_line_id': fields.many2one('account.invoice.line', 'Invoice Line', readonly=True, copy=False),
        'to_invoice': fields.boolean('To Invoice'),
        'invoiced': fields.boolean('Invoiced', readonly=True, copy=False),
    }

    _defaults = {
        'to_invoice': lambda *a: True,
    }
Beispiel #27
0
class crm_claim_stage(osv.osv):
    """ Model for claim stages. This models the main stages of a claim
        management flow. Main CRM objects (leads, opportunities, project
        issues, ...) will now use only stages, instead of state and stages.
        Stages are for example used to display the kanban view of records.
    """
    _name = "crm.claim.stage"
    _description = "Claim stages"
    _rec_name = 'name'
    _order = "sequence"

    _columns = {
        'name':
        fields.char('Stage Name', required=True, translate=True),
        'sequence':
        fields.integer('Sequence',
                       help="Used to order stages. Lower is better."),
        'team_ids':
        fields.many2many(
            'crm.team',
            'crm_team_claim_stage_rel',
            'stage_id',
            'team_id',
            string='Teams',
            help=
            "Link between stages and sales teams. When set, this limitate the current stage to the selected sales teams."
        ),
        'case_default':
        fields.boolean(
            'Common to All Teams',
            help=
            "If you check this field, this stage will be proposed by default on each sales team. It will not assign this stage to existing teams."
        ),
    }

    _defaults = {
        'sequence': lambda *args: 1,
    }
Beispiel #28
0
class product_category(osv.osv):
    _inherit = 'product.category'

    def calculate_total_routes(self, cr, uid, ids, name, args, context=None):
        res = {}
        for categ in self.browse(cr, uid, ids, context=context):
            categ2 = categ
            routes = [x.id for x in categ.route_ids]
            while categ2.parent_id:
                categ2 = categ2.parent_id
                routes += [x.id for x in categ2.route_ids]
            res[categ.id] = routes
        return res

    _columns = {
        'route_ids':
        fields.many2many('stock.location.route',
                         'stock_location_route_categ',
                         'categ_id',
                         'route_id',
                         'Routes',
                         domain="[('product_categ_selectable', '=', True)]"),
        'removal_strategy_id':
        fields.many2one(
            'product.removal',
            'Force Removal Strategy',
            help=
            "Set a specific removal strategy that will be used regardless of the source location for this product category"
        ),
        'total_route_ids':
        fields.function(calculate_total_routes,
                        relation='stock.location.route',
                        type='many2many',
                        string='Total routes',
                        readonly=True),
    }
Beispiel #29
0
    ('integer', fields.integer()),
    ('float', fields.float()),
    ('decimal', fields.float(digits=(16, 3))),
    ('string.bounded', fields.char('unknown', size=16)),
    ('string.required', fields.char('unknown', size=None, required=True)),
    ('string', fields.char('unknown', size=None)),
    ('date', fields.date()),
    ('datetime', fields.datetime()),
    ('text', fields.text()),
    ('selection', fields.selection([(1, "Foo"), (2, "Bar"), (3, "Qux"), (4, '')])),
    # here use size=-1 to store the values as integers instead of strings
    ('selection.function', fields.selection(selection_fn, size=-1)),
    # just relate to an integer
    ('many2one', fields.many2one('export.integer')),
    ('one2many', fields.one2many('export.one2many.child', 'parent_id')),
    ('many2many', fields.many2many('export.many2many.other')),
    ('function', fields.function(function_fn, fnct_inv=function_fn_write, type="integer")),
    # related: specialization of fields.function, should work the same way
    # TODO: reference
]

for name, field in models:
    class NewModel(orm.Model):
        _name = 'export.%s' % name
        _columns = {
            'const': fields.integer(),
            'value': field,
        }
        _defaults = {
            'const': 4,
        }
Beispiel #30
0
class gamification_badge(osv.Model):
    """Badge object that users can send and receive"""

    CAN_GRANT = 1
    NOBODY_CAN_GRANT = 2
    USER_NOT_VIP = 3
    BADGE_REQUIRED = 4
    TOO_MANY = 5

    _name = 'gamification.badge'
    _description = 'Gamification badge'
    _inherit = ['mail.thread']

    def _get_owners_info(self, cr, uid, ids, name, args, context=None):
        """Return:
            the list of unique res.users ids having received this badge
            the total number of time this badge was granted
            the total number of users this badge was granted to
        """
        result = dict((res_id, {'stat_count': 0, 'stat_count_distinct': 0, 'unique_owner_ids': []}) for res_id in ids)

        cr.execute("""
            SELECT badge_id, count(user_id) as stat_count,
                count(distinct(user_id)) as stat_count_distinct,
                array_agg(distinct(user_id)) as unique_owner_ids
            FROM gamification_badge_user
            WHERE badge_id in %s
            GROUP BY badge_id
            """, (tuple(ids),))
        for (badge_id, stat_count, stat_count_distinct, unique_owner_ids) in cr.fetchall():
            result[badge_id] = {
                'stat_count': stat_count,
                'stat_count_distinct': stat_count_distinct,
                'unique_owner_ids': unique_owner_ids,
            }
        return result

    def _get_badge_user_stats(self, cr, uid, ids, name, args, context=None):
        """Return stats related to badge users"""
        result = dict.fromkeys(ids, False)
        badge_user_obj = self.pool.get('gamification.badge.user')
        first_month_day = date.today().replace(day=1).strftime(DF)
        for bid in ids:
            result[bid] = {
                'stat_my': badge_user_obj.search(cr, uid, [('badge_id', '=', bid), ('user_id', '=', uid)], context=context, count=True),
                'stat_this_month': badge_user_obj.search(cr, uid, [('badge_id', '=', bid), ('create_date', '>=', first_month_day)], context=context, count=True),
                'stat_my_this_month': badge_user_obj.search(cr, uid, [('badge_id', '=', bid), ('user_id', '=', uid), ('create_date', '>=', first_month_day)], context=context, count=True),
                'stat_my_monthly_sending': badge_user_obj.search(cr, uid, [('badge_id', '=', bid), ('create_uid', '=', uid), ('create_date', '>=', first_month_day)], context=context, count=True)
            }
        return result

    def _remaining_sending_calc(self, cr, uid, ids, name, args, context=None):
        """Computes the number of badges remaining the user can send

        0 if not allowed or no remaining
        integer if limited sending
        -1 if infinite (should not be displayed)
        """
        result = dict.fromkeys(ids, False)
        for badge in self.browse(cr, uid, ids, context=context):
            if self._can_grant_badge(cr, uid, badge.id, context) != 1:
                # if the user cannot grant this badge at all, result is 0
                result[badge.id] = 0
            elif not badge.rule_max:
                # if there is no limitation, -1 is returned which means 'infinite'
                result[badge.id] = -1
            else:
                result[badge.id] = badge.rule_max_number - badge.stat_my_monthly_sending
        return result

    _columns = {
        'name': fields.char('Badge', required=True, translate=True),
        'description': fields.text('Description', translate=True),
        'image': fields.binary("Image", attachment=True,
            help="This field holds the image used for the badge, limited to 256x256"),
        'rule_auth': fields.selection([
                ('everyone', 'Everyone'),
                ('users', 'A selected list of users'),
                ('having', 'People having some badges'),
                ('nobody', 'No one, assigned through challenges'),
            ],
            string="Allowance to Grant",
            help="Who can grant this badge",
            required=True),
        'rule_auth_user_ids': fields.many2many('res.users', 'rel_badge_auth_users',
            string='Authorized Users',
            help="Only these people can give this badge"),
        'rule_auth_badge_ids': fields.many2many('gamification.badge',
            'gamification_badge_rule_badge_rel', 'badge1_id', 'badge2_id',
            string='Required Badges',
            help="Only the people having these badges can give this badge"),

        'rule_max': fields.boolean('Monthly Limited Sending',
            help="Check to set a monthly limit per person of sending this badge"),
        'rule_max_number': fields.integer('Limitation Number',
            help="The maximum number of time this badge can be sent per month per person."),
        'stat_my_monthly_sending': fields.function(_get_badge_user_stats,
            type="integer",
            string='My Monthly Sending Total',
            multi='badge_users',
            help="The number of time the current user has sent this badge this month."),
        'remaining_sending': fields.function(_remaining_sending_calc, type='integer',
            string='Remaining Sending Allowed', help="If a maxium is set"),

        'challenge_ids': fields.one2many('gamification.challenge', 'reward_id',
            string="Reward of Challenges"),

        'goal_definition_ids': fields.many2many('gamification.goal.definition', 'badge_unlocked_definition_rel',
            string='Rewarded by',
            help="The users that have succeeded theses goals will receive automatically the badge."),

        'owner_ids': fields.one2many('gamification.badge.user', 'badge_id',
            string='Owners', help='The list of instances of this badge granted to users'),
        'active': fields.boolean('Active'),
        'unique_owner_ids': fields.function(_get_owners_info,
            string='Unique Owners',
            help="The list of unique users having received this badge.",
            multi='unique_users',
            type="many2many", relation="res.users"),

        'stat_count': fields.function(_get_owners_info, string='Total',
            type="integer",
            multi='unique_users',
            help="The number of time this badge has been received."),
        'stat_count_distinct': fields.function(_get_owners_info,
            type="integer",
            string='Number of users',
            multi='unique_users',
            help="The number of time this badge has been received by unique users."),
        'stat_this_month': fields.function(_get_badge_user_stats,
            type="integer",
            string='Monthly total',
            multi='badge_users',
            help="The number of time this badge has been received this month."),
        'stat_my': fields.function(_get_badge_user_stats, string='My Total',
            type="integer",
            multi='badge_users',
            help="The number of time the current user has received this badge."),
        'stat_my_this_month': fields.function(_get_badge_user_stats,
            type="integer",
            string='My Monthly Total',
            multi='badge_users',
            help="The number of time the current user has received this badge this month."),
    }

    _defaults = {
        'rule_auth': 'everyone',
        'active': True,
    }

    def check_granting(self, cr, uid, badge_id, context=None):
        """Check the user 'uid' can grant the badge 'badge_id' and raise the appropriate exception
        if not

        Do not check for SUPERUSER_ID
        """
        status_code = self._can_grant_badge(cr, uid, badge_id, context=context)
        if status_code == self.CAN_GRANT:
            return True
        elif status_code == self.NOBODY_CAN_GRANT:
            raise UserError(_('This badge can not be sent by users.'))
        elif status_code == self.USER_NOT_VIP:
            raise UserError(_('You are not in the user allowed list.'))
        elif status_code == self.BADGE_REQUIRED:
            raise UserError(_('You do not have the required badges.'))
        elif status_code == self.TOO_MANY:
            raise UserError(_('You have already sent this badge too many time this month.'))
        else:
            _logger.exception("Unknown badge status code: %d" % int(status_code))
        return False

    def _can_grant_badge(self, cr, uid, badge_id, context=None):
        """Check if a user can grant a badge to another user

        :param uid: the id of the res.users trying to send the badge
        :param badge_id: the granted badge id
        :return: integer representing the permission.
        """
        if uid == SUPERUSER_ID:
            return self.CAN_GRANT

        badge = self.browse(cr, uid, badge_id, context=context)

        if badge.rule_auth == 'nobody':
            return self.NOBODY_CAN_GRANT

        elif badge.rule_auth == 'users' and uid not in [user.id for user in badge.rule_auth_user_ids]:
            return self.USER_NOT_VIP

        elif badge.rule_auth == 'having':
            all_user_badges = self.pool.get('gamification.badge.user').search(cr, uid, [('user_id', '=', uid)], context=context)
            for required_badge in badge.rule_auth_badge_ids:
                if required_badge.id not in all_user_badges:
                    return self.BADGE_REQUIRED

        if badge.rule_max and badge.stat_my_monthly_sending >= badge.rule_max_number:
            return self.TOO_MANY

        # badge.rule_auth == 'everyone' -> no check
        return self.CAN_GRANT

    def check_progress(self, cr, uid, context=None):
        try:
            model, res_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'gamification', 'badge_hidden')
        except ValueError:
            return True
        badge_user_obj = self.pool.get('gamification.badge.user')
        if not badge_user_obj.search(cr, uid, [('user_id', '=', uid), ('badge_id', '=', res_id)], context=context):
            values = {
                'user_id': uid,
                'badge_id': res_id,
            }
            badge_user_obj.create(cr, SUPERUSER_ID, values, context=context)
        return True
Beispiel #31
0
class make_procurement(osv.osv_memory):
    _name = 'make.procurement'
    _description = 'Make Procurements'
    
    def onchange_product_id(self, cr, uid, ids, prod_id, context=None):
        product = self.pool.get('product.product').browse(cr, uid, prod_id, context=context)
        return {'value': {
            'uom_id': product.uom_id.id,
            'product_tmpl_id': product.product_tmpl_id.id,
            'product_variant_count': product.product_tmpl_id.product_variant_count
        }}
    
    _columns = {
        'qty': fields.float('Quantity', digits=(16,2), required=True),
        'res_model': fields.char('Res Model'),
        'product_id': fields.many2one('product.product', 'Product', required=True),
        'product_tmpl_id': fields.many2one('product.template', 'Template', required=True),
        'product_variant_count': fields.related('product_tmpl_id', 'product_variant_count', type='integer', string='Variant Number'),
        'uom_id': fields.many2one('product.uom', 'Unit of Measure', required=True),
        'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True),
        'date_planned': fields.date('Planned Date', required=True),
        'route_ids': fields.many2many('stock.location.route', string='Preferred Routes'),
    }

    _defaults = {
        'date_planned': fields.date.context_today,
        'qty': lambda *args: 1.0,
    }

    def make_procurement(self, cr, uid, ids, context=None):
        """ Creates procurement order for selected product. """
        user = self.pool.get('res.users').browse(cr, uid, uid, context=context).login
        wh_obj = self.pool.get('stock.warehouse')
        procurement_obj = self.pool.get('procurement.order')
        data_obj = self.pool.get('ir.model.data')

        for proc in self.browse(cr, uid, ids, context=context):
            wh = wh_obj.browse(cr, uid, proc.warehouse_id.id, context=context)
            procure_id = procurement_obj.create(cr, uid, {
                'name':'INT: '+str(user),
                'date_planned': proc.date_planned,
                'product_id': proc.product_id.id,
                'product_qty': proc.qty,
                'product_uom': proc.uom_id.id,
                'warehouse_id': proc.warehouse_id.id,
                'location_id': wh.lot_stock_id.id,
                'company_id': wh.company_id.id,
                'route_ids': [(6, 0, proc.route_ids.ids)],
            })
            procurement_obj.signal_workflow(cr, uid, [procure_id], 'button_confirm')

        id2 = data_obj._get_id(cr, uid, 'procurement', 'procurement_tree_view')
        id3 = data_obj._get_id(cr, uid, 'procurement', 'procurement_form_view')

        if id2:
            id2 = data_obj.browse(cr, uid, id2, context=context).res_id
        if id3:
            id3 = data_obj.browse(cr, uid, id3, context=context).res_id

        return {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'procurement.order',
            'res_id' : procure_id,
            'views': [(id3,'form'),(id2,'tree')],
            'type': 'ir.actions.act_window',
         }

    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        record_id = context.get('active_id')

        if context.get('active_model') == 'product.template':
            product_ids = self.pool.get('product.product').search(cr, uid, [('product_tmpl_id', '=', context.get('active_id'))], context=context)
            if product_ids:
                record_id = product_ids[0]

        res = super(make_procurement, self).default_get(cr, uid, fields, context=context)

        if record_id and 'product_id' in fields:
            proxy = self.pool.get('product.product')
            product_ids = proxy.search(cr, uid, [('id', '=', record_id)], context=context, limit=1)
            if product_ids:
                product_id = product_ids[0]

                product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
                res['product_id'] = product.id
                res['uom_id'] = product.uom_id.id

        if 'warehouse_id' in fields:
            warehouse_id = self.pool.get('stock.warehouse').search(cr, uid, [], context=context)
            res['warehouse_id'] = warehouse_id[0] if warehouse_id else False

        return res

    def create(self, cr, uid, values, context=None):
        if values.get('product_id'):
            values.update(self.onchange_product_id(cr, uid, None, values['product_id'], context=context)['value'])
        return super(make_procurement, self).create(cr, uid, values, context=context)